-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcommon.js
61 lines (47 loc) · 1.51 KB
/
common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// @ts-check
import * as acorn from 'acorn';
import { tsPlugin } from '@sveltejs/acorn-typescript';
import { walk } from 'zimmerframe';
/** @import { TSESTree } from '@typescript-eslint/types' */
/** @import { NodeWithComments } from '../src/types' */
// @ts-expect-error
export const acornTs = acorn.Parser.extend(tsPlugin({ allowSatisfies: true }));
/** @param {string} input */
export function load(input) {
/** @type {any[]} */
const comments = [];
const ast = acornTs.parse(input, {
ecmaVersion: 'latest',
sourceType: 'module',
locations: true,
onComment: (block, value, start, end) => {
if (block && /\n/.test(value)) {
let a = start;
while (a > 0 && input[a - 1] !== '\n') a -= 1;
let b = a;
while (/[ \t]/.test(input[b])) b += 1;
const indentation = input.slice(a, b);
value = value.replace(new RegExp(`^${indentation}`, 'gm'), '');
}
comments.push({ type: block ? 'Block' : 'Line', value, start, end });
}
});
walk(ast, null, {
_(node, { next }) {
let comment;
const commentNode = /** @type {NodeWithComments} */ (/** @type {any} */ (node));
while (comments[0] && comments[0].start < node.start) {
comment = comments.shift();
(commentNode.leadingComments ??= []).push(comment);
}
next();
if (comments[0]) {
const slice = input.slice(node.end, comments[0].start);
if (/^[,) \t]*$/.test(slice)) {
commentNode.trailingComments = [comments.shift()];
}
}
}
});
return /** @type {TSESTree.Program} */ (/** @type {any} */ (ast));
}