sfmc-language-lsp 4.4.0 → 4.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -0
- package/dist/cjs/package-version.cjs +1 -1
- package/dist/cjs/typescript/index.cjs +16 -0
- package/dist/cjs/typescript/index.d.ts +11 -0
- package/dist/cjs/typescript/index.d.ts.map +1 -0
- package/dist/cjs/typescript/index.js.map +1 -0
- package/dist/cjs/typescript/orchestration.cjs +108 -0
- package/dist/cjs/typescript/orchestration.d.ts +59 -0
- package/dist/cjs/typescript/orchestration.d.ts.map +1 -0
- package/dist/cjs/typescript/orchestration.js.map +1 -0
- package/dist/cjs/typescript/service.cjs +810 -0
- package/dist/cjs/typescript/service.d.ts +52 -0
- package/dist/cjs/typescript/service.d.ts.map +1 -0
- package/dist/cjs/typescript/service.js.map +1 -0
- package/dist/cjs/typescript/source-analysis.cjs +582 -0
- package/dist/cjs/typescript/source-analysis.d.ts +110 -0
- package/dist/cjs/typescript/source-analysis.d.ts.map +1 -0
- package/dist/cjs/typescript/source-analysis.js.map +1 -0
- package/dist/cjs/utils/regions.cjs +15 -4
- package/dist/cjs/utils/regions.d.ts +3 -1
- package/dist/cjs/utils/regions.d.ts.map +1 -1
- package/dist/cjs/utils/regions.js.map +1 -1
- package/dist/esm/package-version.js +1 -1
- package/dist/esm/typescript/index.d.ts +11 -0
- package/dist/esm/typescript/index.d.ts.map +1 -0
- package/dist/esm/typescript/index.js +9 -0
- package/dist/esm/typescript/index.js.map +1 -0
- package/dist/esm/typescript/orchestration.d.ts +59 -0
- package/dist/esm/typescript/orchestration.d.ts.map +1 -0
- package/dist/esm/typescript/orchestration.js +103 -0
- package/dist/esm/typescript/orchestration.js.map +1 -0
- package/dist/esm/typescript/service.d.ts +52 -0
- package/dist/esm/typescript/service.d.ts.map +1 -0
- package/dist/esm/typescript/service.js +774 -0
- package/dist/esm/typescript/service.js.map +1 -0
- package/dist/esm/typescript/source-analysis.d.ts +110 -0
- package/dist/esm/typescript/source-analysis.d.ts.map +1 -0
- package/dist/esm/typescript/source-analysis.js +572 -0
- package/dist/esm/typescript/source-analysis.js.map +1 -0
- package/dist/esm/utils/regions.d.ts +3 -1
- package/dist/esm/utils/regions.d.ts.map +1 -1
- package/dist/esm/utils/regions.js +15 -4
- package/dist/esm/utils/regions.js.map +1 -1
- package/dist/types/typescript/index.d.ts +11 -0
- package/dist/types/typescript/index.d.ts.map +1 -0
- package/dist/types/typescript/orchestration.d.ts +59 -0
- package/dist/types/typescript/orchestration.d.ts.map +1 -0
- package/dist/types/typescript/service.d.ts +52 -0
- package/dist/types/typescript/service.d.ts.map +1 -0
- package/dist/types/typescript/source-analysis.d.ts +110 -0
- package/dist/types/typescript/source-analysis.d.ts.map +1 -0
- package/dist/types/utils/regions.d.ts +3 -1
- package/dist/types/utils/regions.d.ts.map +1 -1
- package/package.json +14 -1
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Text-only analysis of SSJS source for the embedded TypeScript service: ESLint-style global
|
|
4
|
+
* comments, prototype/static polyfills and the comment ranges used to filter diagnostics and
|
|
5
|
+
* remap definitions. Nothing here depends on TypeScript or on the runtime environment.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.parseGlobalCommentDeclarations = parseGlobalCommentDeclarations;
|
|
9
|
+
exports.parsePolyfillDeclarations = parsePolyfillDeclarations;
|
|
10
|
+
exports.jsdocCommentRanges = jsdocCommentRanges;
|
|
11
|
+
exports.isInsideJsdoc = isInsideJsdoc;
|
|
12
|
+
exports.prototypePolyfillBodyRanges = prototypePolyfillBodyRanges;
|
|
13
|
+
exports.prototypeMethodNameFor = prototypeMethodNameFor;
|
|
14
|
+
exports.isOffsetInsideComment = isOffsetInsideComment;
|
|
15
|
+
exports.findPrototypeAssignmentSpan = findPrototypeAssignmentSpan;
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// ESLint global comment parser
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
/**
|
|
20
|
+
* Parses ESLint-style global comments from SSJS source text and returns a
|
|
21
|
+
* TypeScript ambient declaration string for all declared names.
|
|
22
|
+
*
|
|
23
|
+
* Supported forms:
|
|
24
|
+
* /* global DEBUG, deKey * /
|
|
25
|
+
* /* globals DEBUG, deKey * /
|
|
26
|
+
* /* global DEBUG:readonly, deKey:writable * /
|
|
27
|
+
*
|
|
28
|
+
* Qualifiers (`:readonly`, `:writable`) are accepted for ESLint compatibility
|
|
29
|
+
* but ignored — all names are declared as `any` for the TS checker.
|
|
30
|
+
*
|
|
31
|
+
* Returns an empty string when no global comments are present.
|
|
32
|
+
* @param text - SSJS source text to scan
|
|
33
|
+
* @returns TypeScript `declare var` statements, or an empty string
|
|
34
|
+
*/
|
|
35
|
+
function parseGlobalCommentDeclarations(text) {
|
|
36
|
+
// Matches: /* global[s] <body> */ — non-greedy, allows multiline bodies.
|
|
37
|
+
const GLOBAL_COMMENT = /\/\*\s*globals?\s+([\s\S]*?)\*\//g;
|
|
38
|
+
// Conservative ASCII JS identifier — rejects anything that looks like a
|
|
39
|
+
// qualifier fragment or punctuation that slipped through the split.
|
|
40
|
+
const IDENT = /^[$A-Z_a-z][\w$]*$/;
|
|
41
|
+
const names = new Set();
|
|
42
|
+
let match;
|
|
43
|
+
while ((match = GLOBAL_COMMENT.exec(text)) !== null) {
|
|
44
|
+
// Body may use commas and/or whitespace as separators.
|
|
45
|
+
const parts = match[1].split(/[\s,]+/);
|
|
46
|
+
for (const part of parts) {
|
|
47
|
+
// Strip optional :readonly / :writable qualifier.
|
|
48
|
+
const name = part ? part.split(':', 1)[0].trim() : '';
|
|
49
|
+
if (name && IDENT.test(name)) {
|
|
50
|
+
names.add(name);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return names.size === 0
|
|
55
|
+
? ''
|
|
56
|
+
: [...names].map((n) => `declare var ${n}: any;`).join('\n') + '\n';
|
|
57
|
+
}
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
// Prototype polyfill parser
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
/**
|
|
62
|
+
* Built-in constructors whose `.prototype` can be polyfilled in SSJS, mapped to
|
|
63
|
+
* the TypeScript interface that `sfmc-globals.d.ts` declares for instances of
|
|
64
|
+
* that type. `Array` is generic (`interface Array<T>`) so it carries its type
|
|
65
|
+
* parameter; the rest are non-generic.
|
|
66
|
+
*/
|
|
67
|
+
const POLYFILL_INTERFACE_BY_CTOR = {
|
|
68
|
+
Array: { iface: 'Array', typeParams: '<T>' },
|
|
69
|
+
String: { iface: 'String', typeParams: '' },
|
|
70
|
+
Number: { iface: 'Number', typeParams: '' },
|
|
71
|
+
Boolean: { iface: 'Boolean', typeParams: '' },
|
|
72
|
+
Object: { iface: 'Object', typeParams: '' },
|
|
73
|
+
Date: { iface: 'Date', typeParams: '' },
|
|
74
|
+
Function: { iface: 'Function', typeParams: '' },
|
|
75
|
+
RegExp: { iface: 'RegExp', typeParams: '' },
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Scans SSJS source for prototype polyfills of the form
|
|
79
|
+
* `Ctor.prototype.method = ...` and returns TypeScript interface-merge
|
|
80
|
+
* declarations that add each polyfilled method to the matching built-in
|
|
81
|
+
* interface from `sfmc-globals.d.ts`.
|
|
82
|
+
*
|
|
83
|
+
* Because the bundled `sfmc-globals.d.ts` intentionally declares only the
|
|
84
|
+
* SSJS-supported subset of built-in methods (no `Array.prototype.forEach`,
|
|
85
|
+
* `String.prototype.startsWith`, …), polyfilling an unsupported method would
|
|
86
|
+
* otherwise raise `Property 'X' does not exist` on both the assignment and
|
|
87
|
+
* every later call. Merging the polyfilled members back into the interface
|
|
88
|
+
* teaches the checker that those methods now exist for this document.
|
|
89
|
+
*
|
|
90
|
+
* Each polyfilled member is emitted as a *method signature* (not a bare
|
|
91
|
+
* `: any` property) so hover reports `(method) String.startsWith(...)` rather
|
|
92
|
+
* than `(property) … : any`. When the polyfill is assigned a function
|
|
93
|
+
* expression, the function's own parameter names are reused — typed from the
|
|
94
|
+
* polyfill's `@param {Type}` / `@returns {Type}` JSDoc when present, otherwise
|
|
95
|
+
* `any` — and any JSDoc block immediately preceding the assignment is forwarded
|
|
96
|
+
* so the checker surfaces the documented `@param` / `@returns` text on hover.
|
|
97
|
+
* The polyfill's body is still type-checked normally and unrelated diagnostics
|
|
98
|
+
* are preserved.
|
|
99
|
+
*
|
|
100
|
+
* Returns an empty string when no prototype polyfills are present.
|
|
101
|
+
* @param text - SSJS source text to scan
|
|
102
|
+
* @returns TypeScript interface-merge statements, or an empty string
|
|
103
|
+
*/
|
|
104
|
+
function parsePolyfillDeclarations(text) {
|
|
105
|
+
// Match `Ctor.prototype.method = function (params) {` where Ctor is a known
|
|
106
|
+
// built-in. Captures the constructor, the method name, and — when the value
|
|
107
|
+
// is a function expression — its parameter list. The trailing function part
|
|
108
|
+
// is optional so non-function polyfills still register the member.
|
|
109
|
+
// The canonical polyfill form ssjs-data ships uses a self-guard —
|
|
110
|
+
// `String.prototype.trim = String.prototype.trim || function (…)` — so
|
|
111
|
+
// tolerate an optional `<expr> ||` prefix between `=` and `function`.
|
|
112
|
+
const POLYFILL = /\b(Array|String|Number|Boolean|Object|Date|Function|RegExp)\s*\.\s*prototype\s*\.\s*([$A-Z_a-z][\w$]*)\s*(?:=\s*(?:[$A-Z_a-z][\w$.]*\s*\|\|\s*)?function\s*\*?\s*[$A-Z_a-z]*\s*\(([^)]*)\))?/g;
|
|
113
|
+
const membersByIface = new Map();
|
|
114
|
+
let match;
|
|
115
|
+
while ((match = POLYFILL.exec(text)) !== null) {
|
|
116
|
+
const ctor = match[1];
|
|
117
|
+
const method = match[2];
|
|
118
|
+
const rawParameters = match[3];
|
|
119
|
+
const target = POLYFILL_INTERFACE_BY_CTOR[ctor];
|
|
120
|
+
if (!target)
|
|
121
|
+
continue;
|
|
122
|
+
const parameters = rawParameters === undefined
|
|
123
|
+
? []
|
|
124
|
+
: rawParameters
|
|
125
|
+
.split(',')
|
|
126
|
+
.map((p) => p.trim())
|
|
127
|
+
// Strip default values / rest syntax — only the name matters.
|
|
128
|
+
.map((p) => p
|
|
129
|
+
.replace(/^\.\.\./, '')
|
|
130
|
+
.split('=', 1)[0]
|
|
131
|
+
.trim())
|
|
132
|
+
.filter((p) => /^[$A-Z_a-z][\w$]*$/.test(p));
|
|
133
|
+
const rawJsdoc = extractPrecedingJsdoc(text, match.index);
|
|
134
|
+
const { paramTypes, optionalParams, returnType } = parseJsdocTypes(rawJsdoc);
|
|
135
|
+
// Strip JSDoc type annotations before forwarding: in a `.d.ts` TypeScript
|
|
136
|
+
// type-checks `@param {Type}` / `@property {Type}` / `@typedef` tags, so an
|
|
137
|
+
// undeclared or duplicate type name (e.g. a user `@typedef Client`) would
|
|
138
|
+
// raise spurious diagnostics and break the interface merge. The synthesized
|
|
139
|
+
// signature already carries the (sanitized) types.
|
|
140
|
+
const jsdoc = stripJsdocTypeAnnotations(rawJsdoc);
|
|
141
|
+
let bucket = membersByIface.get(target.iface);
|
|
142
|
+
if (!bucket) {
|
|
143
|
+
bucket = { typeParams: target.typeParams, methods: new Map() };
|
|
144
|
+
membersByIface.set(target.iface, bucket);
|
|
145
|
+
}
|
|
146
|
+
// First declaration with a function signature wins; a later bare
|
|
147
|
+
// reference must not overwrite captured params/jsdoc.
|
|
148
|
+
const existing = bucket.methods.get(method);
|
|
149
|
+
if (!existing || (existing.params.length === 0 && parameters.length > 0)) {
|
|
150
|
+
bucket.methods.set(method, {
|
|
151
|
+
params: parameters,
|
|
152
|
+
jsdoc,
|
|
153
|
+
paramTypes,
|
|
154
|
+
optionalParams,
|
|
155
|
+
returnType,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const staticBlocks = parseStaticPolyfillDeclarations(text);
|
|
160
|
+
if (membersByIface.size === 0)
|
|
161
|
+
return staticBlocks;
|
|
162
|
+
const blocks = [];
|
|
163
|
+
for (const [iface, { typeParams, methods }] of membersByIface) {
|
|
164
|
+
const memberLines = [];
|
|
165
|
+
// The instance type of the interface being merged (e.g. `Array<T>`,
|
|
166
|
+
// `String`). Emitted as an explicit `this` parameter on each method so
|
|
167
|
+
// that under `noLib:true` a polyfill body reading `this.length` or doing
|
|
168
|
+
// `return this` (e.g. `Array.prototype.copyWithin` / `fill`) type-checks
|
|
169
|
+
// against the array/string instance rather than the function object.
|
|
170
|
+
const thisType = `${iface}${typeParams}`;
|
|
171
|
+
for (const [name, { params, jsdoc, paramTypes, optionalParams, returnType }] of methods) {
|
|
172
|
+
if (jsdoc)
|
|
173
|
+
memberLines.push(indentLines(jsdoc, ' '.repeat(4)));
|
|
174
|
+
// Use the JSDoc `@param {Type}` / `@returns {Type}` annotations when
|
|
175
|
+
// present so hover reports the documented types instead of `any`.
|
|
176
|
+
// A parameter marked optional in JSDoc (`[name]`) emits `name?: type`;
|
|
177
|
+
// every parameter after an optional one must also be optional in TS.
|
|
178
|
+
let isSawOptional = false;
|
|
179
|
+
const parameterString = params
|
|
180
|
+
.map((p) => {
|
|
181
|
+
const optional = isSawOptional || optionalParams.has(p);
|
|
182
|
+
if (optional)
|
|
183
|
+
isSawOptional = true;
|
|
184
|
+
return `${p}${optional ? '?' : ''}: ${paramTypes.get(p) ?? 'any'}`;
|
|
185
|
+
})
|
|
186
|
+
.join(', ');
|
|
187
|
+
const signatureParameters = parameterString
|
|
188
|
+
? `this: ${thisType}, ${parameterString}`
|
|
189
|
+
: `this: ${thisType}`;
|
|
190
|
+
memberLines.push(` ${name}(${signatureParameters}): ${returnType};`);
|
|
191
|
+
}
|
|
192
|
+
blocks.push(`interface ${iface}${typeParams} {\n${memberLines.join('\n')}\n}`);
|
|
193
|
+
}
|
|
194
|
+
return blocks.join('\n') + '\n' + staticBlocks;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Built-in constructors whose STATIC members can be polyfilled in SSJS, mapped to
|
|
198
|
+
* the declaration target that the merge must re-open. `Math` is a namespace
|
|
199
|
+
* (`declare namespace Math`), the others are `*Constructor` interfaces declared by
|
|
200
|
+
* `sfmc-globals.d.ts` (e.g. `interface ArrayConstructor`).
|
|
201
|
+
*/
|
|
202
|
+
const STATIC_POLYFILL_TARGET_BY_CTOR = {
|
|
203
|
+
Array: { target: 'ArrayConstructor', kind: 'interface' },
|
|
204
|
+
Object: { target: 'ObjectConstructor', kind: 'interface' },
|
|
205
|
+
Number: { target: 'NumberConstructor', kind: 'interface' },
|
|
206
|
+
String: { target: 'StringConstructor', kind: 'interface' },
|
|
207
|
+
Date: { target: 'DateConstructor', kind: 'interface' },
|
|
208
|
+
Math: { target: 'Math', kind: 'namespace' },
|
|
209
|
+
JSON: { target: 'JSON', kind: 'namespace' },
|
|
210
|
+
};
|
|
211
|
+
/**
|
|
212
|
+
* Scans SSJS source for STATIC polyfills of the form `Ctor.method = function (…)`
|
|
213
|
+
* (e.g. `Array.isArray = …`, `Object.getPrototypeOf = …`, `Math.max = …`) and
|
|
214
|
+
* returns TypeScript declarations that add each member to the matching
|
|
215
|
+
* `*Constructor` interface (via declaration merging) or `Math`/`JSON` namespace.
|
|
216
|
+
*
|
|
217
|
+
* Like `parsePolyfillDeclarations` for prototype members, this is required because
|
|
218
|
+
* `sfmc-globals.d.ts` intentionally omits unsupported statics. Once the
|
|
219
|
+
* "Insert polyfill" quick-fix adds `Array.isArray = function () { … }`, the
|
|
220
|
+
* assignment target must exist or TypeScript raises ts2339
|
|
221
|
+
* ("Property 'isArray' does not exist on type 'ArrayConstructor'").
|
|
222
|
+
*
|
|
223
|
+
* Returns an empty string when no static polyfills are present.
|
|
224
|
+
* @param text - SSJS source text to scan
|
|
225
|
+
* @returns TypeScript merge statements, or an empty string
|
|
226
|
+
*/
|
|
227
|
+
function parseStaticPolyfillDeclarations(text) {
|
|
228
|
+
// Match `Ctor.method = function (params)` where Ctor is a known built-in and
|
|
229
|
+
// `method` is NOT `prototype` (those are handled by parsePolyfillDeclarations).
|
|
230
|
+
// The canonical polyfill form ssjs-data ships uses a self-guard —
|
|
231
|
+
// `Array.isArray = Array.isArray || function (…)` — so tolerate an optional
|
|
232
|
+
// `<expr> ||` prefix between `=` and `function` (e.g. `Array.isArray ||`).
|
|
233
|
+
const STATIC_POLYFILL = /\b(Array|Object|Number|String|Date|Math|JSON)\s*\.\s*([$A-Z_a-z][\w$]*)\s*=\s*(?:[$A-Z_a-z][\w$.]*\s*\|\|\s*)?function\s*\*?\s*[$A-Z_a-z]*\s*\(([^)]*)\)/g;
|
|
234
|
+
// target name → { kind, methods }
|
|
235
|
+
const byTarget = new Map();
|
|
236
|
+
let match;
|
|
237
|
+
while ((match = STATIC_POLYFILL.exec(text)) !== null) {
|
|
238
|
+
const ctor = match[1];
|
|
239
|
+
const method = match[2];
|
|
240
|
+
if (method === 'prototype')
|
|
241
|
+
continue;
|
|
242
|
+
const target = STATIC_POLYFILL_TARGET_BY_CTOR[ctor];
|
|
243
|
+
if (!target)
|
|
244
|
+
continue;
|
|
245
|
+
const rawParameters = match[3];
|
|
246
|
+
const parameters = rawParameters
|
|
247
|
+
.split(',')
|
|
248
|
+
.map((p) => p.trim())
|
|
249
|
+
.map((p) => p
|
|
250
|
+
.replace(/^\.\.\./, '')
|
|
251
|
+
.split('=', 1)[0]
|
|
252
|
+
.trim())
|
|
253
|
+
.filter((p) => /^[$A-Z_a-z][\w$]*$/.test(p));
|
|
254
|
+
const rawJsdoc = extractPrecedingJsdoc(text, match.index);
|
|
255
|
+
const { paramTypes, optionalParams, returnType } = parseJsdocTypes(rawJsdoc);
|
|
256
|
+
const jsdoc = stripJsdocTypeAnnotations(rawJsdoc);
|
|
257
|
+
let bucket = byTarget.get(target.target);
|
|
258
|
+
if (!bucket) {
|
|
259
|
+
bucket = { kind: target.kind, methods: new Map() };
|
|
260
|
+
byTarget.set(target.target, bucket);
|
|
261
|
+
}
|
|
262
|
+
if (!bucket.methods.has(method)) {
|
|
263
|
+
bucket.methods.set(method, {
|
|
264
|
+
params: parameters,
|
|
265
|
+
jsdoc,
|
|
266
|
+
paramTypes,
|
|
267
|
+
optionalParams,
|
|
268
|
+
returnType,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (byTarget.size === 0)
|
|
273
|
+
return '';
|
|
274
|
+
const blocks = [];
|
|
275
|
+
for (const [target, { kind, methods }] of byTarget) {
|
|
276
|
+
const memberLines = [];
|
|
277
|
+
for (const [name, { params, jsdoc, paramTypes, optionalParams, returnType }] of methods) {
|
|
278
|
+
if (jsdoc)
|
|
279
|
+
memberLines.push(indentLines(jsdoc, ' '.repeat(4)));
|
|
280
|
+
let isSawOptional = false;
|
|
281
|
+
const parameterString = params
|
|
282
|
+
.map((p) => {
|
|
283
|
+
const optional = isSawOptional || optionalParams.has(p);
|
|
284
|
+
if (optional)
|
|
285
|
+
isSawOptional = true;
|
|
286
|
+
return `${p}${optional ? '?' : ''}: ${paramTypes.get(p) ?? 'any'}`;
|
|
287
|
+
})
|
|
288
|
+
.join(', ');
|
|
289
|
+
// Namespace members use `function name(...)`; interface members `name(...)`.
|
|
290
|
+
memberLines.push(kind === 'namespace'
|
|
291
|
+
? ` function ${name}(${parameterString}): ${returnType};`
|
|
292
|
+
: ` ${name}(${parameterString}): ${returnType};`);
|
|
293
|
+
}
|
|
294
|
+
const header = kind === 'namespace' ? `declare namespace ${target}` : `interface ${target}`;
|
|
295
|
+
blocks.push(`${header} {\n${memberLines.join('\n')}\n}`);
|
|
296
|
+
}
|
|
297
|
+
return blocks.join('\n') + '\n';
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Map a single JSDoc type token to a TypeScript-safe type. Primitives and the
|
|
301
|
+
* known built-in interfaces pass through (with canonical casing); `Array`
|
|
302
|
+
* becomes `any[]`; anything not recognised (e.g. user types like `Client` that
|
|
303
|
+
* are not declared in the virtual program) falls back to `any` so the generated
|
|
304
|
+
* `.polyfills.d.ts` never references an undeclared name.
|
|
305
|
+
* @param raw - a single JSDoc type token (no `{}`)
|
|
306
|
+
* @returns a TypeScript-safe type string
|
|
307
|
+
*/
|
|
308
|
+
function jsdocTokenToTsType(raw) {
|
|
309
|
+
const t = raw.trim();
|
|
310
|
+
if (!t)
|
|
311
|
+
return 'any';
|
|
312
|
+
// String literal unions like 'a'|'b' — keep as-is (valid TS literal types).
|
|
313
|
+
if (/^(['"]).*\1$/.test(t))
|
|
314
|
+
return t;
|
|
315
|
+
const lower = t.toLowerCase();
|
|
316
|
+
switch (lower) {
|
|
317
|
+
case 'array': {
|
|
318
|
+
return 'any[]';
|
|
319
|
+
}
|
|
320
|
+
case 'void':
|
|
321
|
+
case 'undefined':
|
|
322
|
+
case 'null':
|
|
323
|
+
case 'any': {
|
|
324
|
+
return lower;
|
|
325
|
+
}
|
|
326
|
+
case 'string':
|
|
327
|
+
case 'number':
|
|
328
|
+
case 'boolean': {
|
|
329
|
+
return lower;
|
|
330
|
+
}
|
|
331
|
+
case 'object': {
|
|
332
|
+
return 'Object';
|
|
333
|
+
}
|
|
334
|
+
case 'date': {
|
|
335
|
+
return 'Date';
|
|
336
|
+
}
|
|
337
|
+
case 'function': {
|
|
338
|
+
return 'Function';
|
|
339
|
+
}
|
|
340
|
+
case 'regexp': {
|
|
341
|
+
return 'RegExp';
|
|
342
|
+
}
|
|
343
|
+
default: {
|
|
344
|
+
return 'any';
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Convert a JSDoc type expression (the text inside `{...}`) into a TypeScript
|
|
350
|
+
* type, supporting `|` unions and `Type[]` array suffixes. Unknown tokens
|
|
351
|
+
* degrade to `any`.
|
|
352
|
+
* @param expression - JSDoc type expression without surrounding braces
|
|
353
|
+
* @returns a TypeScript-safe type string
|
|
354
|
+
*/
|
|
355
|
+
function jsdocTypeToTs(expression) {
|
|
356
|
+
const trimmed = expression.trim();
|
|
357
|
+
if (!trimmed)
|
|
358
|
+
return 'any';
|
|
359
|
+
if (trimmed.includes('|')) {
|
|
360
|
+
return trimmed
|
|
361
|
+
.split('|')
|
|
362
|
+
.map((p) => jsdocTypeToTs(p))
|
|
363
|
+
.join(' | ');
|
|
364
|
+
}
|
|
365
|
+
// `Type[]` suffix.
|
|
366
|
+
const arrayMatch = trimmed.match(/^(.+?)\s*\[\s*\]$/);
|
|
367
|
+
if (arrayMatch) {
|
|
368
|
+
const inner = jsdocTokenToTsType(arrayMatch[1]);
|
|
369
|
+
return inner === 'any' ? 'any[]' : `${inner}[]`;
|
|
370
|
+
}
|
|
371
|
+
return jsdocTokenToTsType(trimmed);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Parse `@param {Type} name` and `@returns {Type}` annotations out of a JSDoc
|
|
375
|
+
* comment block, returning a map of parameter name to TS type, the set of
|
|
376
|
+
* parameters marked optional (JSDoc `[name]` / `[name=default]` syntax), and the
|
|
377
|
+
* return type (defaulting to `any` when no `@returns` type is documented).
|
|
378
|
+
* @param jsdoc - the raw JSDoc comment block
|
|
379
|
+
* @returns parsed parameter types, optional-parameter names, and the return type
|
|
380
|
+
*/
|
|
381
|
+
function parseJsdocTypes(jsdoc) {
|
|
382
|
+
const parameterTypes = new Map();
|
|
383
|
+
const optionalParameters = new Set();
|
|
384
|
+
let returnType = 'any';
|
|
385
|
+
if (!jsdoc)
|
|
386
|
+
return { paramTypes: parameterTypes, optionalParams: optionalParameters, returnType };
|
|
387
|
+
// Match `@param {Type} name` and the optional form `@param {Type} [name]`
|
|
388
|
+
// (or `[name=default]`). The bracket and default value only mark optionality
|
|
389
|
+
// — the bare identifier is captured as the parameter name.
|
|
390
|
+
const parameterRe = /@param\s*\{([^}]*)\}\s*(\[)?\s*([$A-Z_a-z][\w$]*)(?:\s*=\s*[^\]]*)?(\])?/g;
|
|
391
|
+
let m;
|
|
392
|
+
while ((m = parameterRe.exec(jsdoc)) !== null) {
|
|
393
|
+
const name = m[3];
|
|
394
|
+
parameterTypes.set(name, jsdocTypeToTs(m[1]));
|
|
395
|
+
if (m[2] === '[' && m[4] === ']')
|
|
396
|
+
optionalParameters.add(name);
|
|
397
|
+
}
|
|
398
|
+
const returnRe = /@returns?\s*\{([^}]*)\}/;
|
|
399
|
+
const rm = returnRe.exec(jsdoc);
|
|
400
|
+
if (rm)
|
|
401
|
+
returnType = jsdocTypeToTs(rm[1]);
|
|
402
|
+
return { paramTypes: parameterTypes, optionalParams: optionalParameters, returnType };
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Remove JSDoc *type* annotations from a comment block so it is safe to forward
|
|
406
|
+
* into a generated `.d.ts`. TypeScript type-checks type expressions inside JSDoc
|
|
407
|
+
* tags (`@param {Type}`, `@returns {Type}`, `@property {Type}`, `@typedef
|
|
408
|
+
* {Type}`, …); an undeclared or duplicate type name in a forwarded comment
|
|
409
|
+
* would raise spurious diagnostics and can break the surrounding interface merge.
|
|
410
|
+
* Stripping the `{...}` (and dropping whole `@typedef`/`@property` lines, which
|
|
411
|
+
* only exist to declare types) leaves human-readable descriptions intact while
|
|
412
|
+
* removing anything TypeScript would try to resolve.
|
|
413
|
+
* @param jsdoc - the raw JSDoc comment block
|
|
414
|
+
* @returns the JSDoc block with type annotations removed
|
|
415
|
+
*/
|
|
416
|
+
function stripJsdocTypeAnnotations(jsdoc) {
|
|
417
|
+
if (!jsdoc)
|
|
418
|
+
return '';
|
|
419
|
+
const cleaned = jsdoc
|
|
420
|
+
.split('\n')
|
|
421
|
+
.filter((line) => !/^\s*\*?\s*@(?:typedef|property|prop)\b/.test(line))
|
|
422
|
+
// Remove the `{Type}` token from any remaining tag (e.g. @param, @returns).
|
|
423
|
+
.map((line) => line.replaceAll(/(@\w+)\s*\{[^}]*\}/g, '$1'))
|
|
424
|
+
.join('\n');
|
|
425
|
+
return cleaned;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Extract the JSDoc block (`/** … *\/`) immediately preceding `index` in
|
|
429
|
+
* `text`, ignoring intervening whitespace. Returns the raw comment (without
|
|
430
|
+
* surrounding indentation) or an empty string when none is directly adjacent.
|
|
431
|
+
* @param text - full source text
|
|
432
|
+
* @param index - offset of the polyfill assignment
|
|
433
|
+
* @returns the adjacent JSDoc comment, or an empty string
|
|
434
|
+
*/
|
|
435
|
+
function extractPrecedingJsdoc(text, index) {
|
|
436
|
+
const before = text.slice(0, index);
|
|
437
|
+
// Only a JSDoc block separated from the assignment by whitespace counts.
|
|
438
|
+
// The body must not contain a `*/`, so the match is the *closest* comment to
|
|
439
|
+
// the assignment — otherwise a lazy `[\s\S]*?` would span from an earlier
|
|
440
|
+
// comment across intervening source code into this one.
|
|
441
|
+
const match = before.match(/\/\*\*(?:(?!\*\/)[\s\S])*\*\/\s*$/);
|
|
442
|
+
if (!match)
|
|
443
|
+
return '';
|
|
444
|
+
// Normalize leading indentation so re-indentation is predictable.
|
|
445
|
+
return match[0]
|
|
446
|
+
.split('\n')
|
|
447
|
+
.map((l) => l.replace(/^\s+/, () => (l.trimStart().startsWith('*') ? ' ' : '')))
|
|
448
|
+
.join('\n');
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Re-indent a multi-line block so every line is prefixed with `indent`.
|
|
452
|
+
* @param block - text block to indent
|
|
453
|
+
* @param indent - indentation string to prepend to each line
|
|
454
|
+
* @returns the indented block
|
|
455
|
+
*/
|
|
456
|
+
function indentLines(block, indent) {
|
|
457
|
+
return block
|
|
458
|
+
.split('\n')
|
|
459
|
+
.map((l) => indent + l)
|
|
460
|
+
.join('\n');
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Compute the `[start, end)` offset ranges of every JSDoc block comment
|
|
464
|
+
* (`/** … *\/`) in the given source text.
|
|
465
|
+
* @param text - full document text
|
|
466
|
+
* @returns an array of `[start, end)` offset tuples
|
|
467
|
+
*/
|
|
468
|
+
function jsdocCommentRanges(text) {
|
|
469
|
+
const ranges = [];
|
|
470
|
+
const re = /\/\*\*[\s\S]*?\*\//g;
|
|
471
|
+
let m;
|
|
472
|
+
while ((m = re.exec(text)) !== null) {
|
|
473
|
+
ranges.push([m.index, m.index + m[0].length]);
|
|
474
|
+
}
|
|
475
|
+
return ranges;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Determine whether `offset` falls within any of the supplied comment ranges.
|
|
479
|
+
* @param offset - character offset to test
|
|
480
|
+
* @param ranges - JSDoc comment ranges from {@link jsdocCommentRanges}
|
|
481
|
+
* @returns true when the offset is inside a JSDoc comment
|
|
482
|
+
*/
|
|
483
|
+
function isInsideJsdoc(offset, ranges) {
|
|
484
|
+
return ranges.some(([start, end]) => offset >= start && offset < end);
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Compute the `[start, end)` offset ranges of every prototype-polyfill
|
|
488
|
+
* assignment body — `Ctor.prototype.method = [Ctor.prototype.method ||] function (…) { … }`.
|
|
489
|
+
*
|
|
490
|
+
* The self-guarded form (`X = X || function () {}`) defeats TypeScript's
|
|
491
|
+
* contextual `this` typing under `noLib:true`: the declared `this: any[]`
|
|
492
|
+
* parameter on the merged interface member does not flow into the function
|
|
493
|
+
* operand of the `||`, so a body reading `this.length` or doing `return this`
|
|
494
|
+
* raises spurious ts2339 / ts2322. These are known-good SSJS polyfills, so the
|
|
495
|
+
* `this`-related diagnostics inside their bodies are suppressed.
|
|
496
|
+
* @param text - full document text
|
|
497
|
+
* @returns an array of `[start, end)` offset tuples spanning each assignment body
|
|
498
|
+
*/
|
|
499
|
+
function prototypePolyfillBodyRanges(text) {
|
|
500
|
+
const ranges = [];
|
|
501
|
+
// Match up to the opening `{` of the function body; then balance braces to
|
|
502
|
+
// find the matching close so the whole body is covered.
|
|
503
|
+
const re = /\b(?:Array|String|Number|Boolean|Object|Date|Function|RegExp)\s*\.\s*prototype\s*\.\s*[$A-Z_a-z][\w$]*\s*=\s*(?:[$A-Z_a-z][\w$.]*\s*\|\|\s*)?function\s*\*?\s*[$A-Z_a-z]*\s*\([^)]*\)\s*\{/g;
|
|
504
|
+
let m;
|
|
505
|
+
while ((m = re.exec(text)) !== null) {
|
|
506
|
+
const bodyOpen = m.index + m[0].length - 1;
|
|
507
|
+
let depth = 1;
|
|
508
|
+
let index = bodyOpen + 1;
|
|
509
|
+
for (; index < text.length && depth > 0; index++) {
|
|
510
|
+
const ch = text[index];
|
|
511
|
+
if (ch === '{')
|
|
512
|
+
depth += 1;
|
|
513
|
+
else if (ch === '}')
|
|
514
|
+
depth -= 1;
|
|
515
|
+
}
|
|
516
|
+
ranges.push([m.index, index]);
|
|
517
|
+
}
|
|
518
|
+
return ranges;
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Read the method identifier at `offset` inside a generated `.polyfills.d.ts`
|
|
522
|
+
* interface member so the reference remap can locate the matching prototype
|
|
523
|
+
* assignment in the source document.
|
|
524
|
+
* @param text - the polyfills declaration file content
|
|
525
|
+
* @param offset - the reference text-span start within that file
|
|
526
|
+
* @returns the method name at the offset, or an empty string
|
|
527
|
+
*/
|
|
528
|
+
function prototypeMethodNameFor(text, offset) {
|
|
529
|
+
const match = /^[$A-Z_a-z][\w$]*/.exec(text.slice(offset));
|
|
530
|
+
return match ? match[0] : '';
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Determine whether `offset` falls inside a line (`// …`) or block (`/* … *\/`)
|
|
534
|
+
* comment in the given source text. Used to detect when TypeScript resolved a
|
|
535
|
+
* prototype-polyfill definition into its leading JSDoc block instead of the
|
|
536
|
+
* assignment identifier, so the definition can be redirected to the code line.
|
|
537
|
+
* @param text - source text to scan
|
|
538
|
+
* @param offset - character offset to test
|
|
539
|
+
* @returns true when the offset lies within a comment
|
|
540
|
+
*/
|
|
541
|
+
function isOffsetInsideComment(text, offset) {
|
|
542
|
+
// Block comments: /* … */ (covers JSDoc /** … */).
|
|
543
|
+
const block = /\/\*[\s\S]*?\*\//g;
|
|
544
|
+
let m;
|
|
545
|
+
while ((m = block.exec(text)) !== null) {
|
|
546
|
+
if (offset >= m.index && offset < m.index + m[0].length)
|
|
547
|
+
return true;
|
|
548
|
+
}
|
|
549
|
+
// Line comments: // … to end of line.
|
|
550
|
+
const line = /\/\/[^\n]*/g;
|
|
551
|
+
while ((m = line.exec(text)) !== null) {
|
|
552
|
+
if (offset >= m.index && offset < m.index + m[0].length)
|
|
553
|
+
return true;
|
|
554
|
+
}
|
|
555
|
+
return false;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Locate the `…prototype.<method>` assignment for a polyfilled method in the
|
|
559
|
+
* document source and return the text span covering the method name, so
|
|
560
|
+
* go-to-definition lands on the polyfill itself.
|
|
561
|
+
* @param text - document source text
|
|
562
|
+
* @param method - the polyfilled method name
|
|
563
|
+
* @returns the method-name text span, or null if not found
|
|
564
|
+
*/
|
|
565
|
+
function findPrototypeAssignmentSpan(text, method) {
|
|
566
|
+
const escaped = method.replaceAll('$', String.raw `\$`);
|
|
567
|
+
const re = new RegExp(String.raw `\bprototype\s*\.\s*(` + escaped + String.raw `)\b`, 'g');
|
|
568
|
+
let match;
|
|
569
|
+
while ((match = re.exec(text)) !== null) {
|
|
570
|
+
// Offset of the captured method name (group 1) within the full match.
|
|
571
|
+
const start = match.index + match[0].indexOf(match[1]);
|
|
572
|
+
// The polyfill's own JSDoc references the method as
|
|
573
|
+
// `Ctor.prototype.method` in prose (e.g. "Polyfill for
|
|
574
|
+
// String.prototype.search"); skip any match inside a comment so the
|
|
575
|
+
// span lands on the real assignment identifier, not the doc text.
|
|
576
|
+
if (isOffsetInsideComment(text, start))
|
|
577
|
+
continue;
|
|
578
|
+
return { start, length: match[1].length };
|
|
579
|
+
}
|
|
580
|
+
return undefined;
|
|
581
|
+
}
|
|
582
|
+
//# sourceMappingURL=source-analysis.js.map
|