dtsroll 1.7.1 → 1.7.2
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/dist/cli.mjs +5 -5
- package/dist/index-DaiC_aHH.mjs +4729 -0
- package/dist/index.mjs +4 -4
- package/dist/vite.mjs +4 -4
- package/package.json +2 -3
- package/dist/index-D25w_e6R.mjs +0 -905
|
@@ -0,0 +1,4729 @@
|
|
|
1
|
+
import{createRequire as _pkgrollCR}from"node:module";const require=_pkgrollCR(import.meta.url);import * as path from 'node:path';
|
|
2
|
+
import path__default from 'node:path';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import { rollup } from 'rollup';
|
|
5
|
+
import ts from 'typescript';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import convert$1 from 'convert-source-map';
|
|
8
|
+
import nodeResolve from '@rollup/plugin-node-resolve';
|
|
9
|
+
import { up } from 'empathic/find';
|
|
10
|
+
import { resolveImports } from 'resolve-pkg-maps';
|
|
11
|
+
import byteSize from 'byte-size';
|
|
12
|
+
|
|
13
|
+
let enabled = true;
|
|
14
|
+
const globalVar = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {};
|
|
15
|
+
let supportLevel = 0;
|
|
16
|
+
if (globalVar.process && globalVar.process.env && globalVar.process.stdout) {
|
|
17
|
+
const { FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, COLORTERM } = globalVar.process.env;
|
|
18
|
+
if (NODE_DISABLE_COLORS || NO_COLOR || FORCE_COLOR === "0") {
|
|
19
|
+
enabled = false;
|
|
20
|
+
} else if (FORCE_COLOR === "1" || FORCE_COLOR === "2" || FORCE_COLOR === "3") {
|
|
21
|
+
enabled = true;
|
|
22
|
+
} else if (TERM === "dumb") {
|
|
23
|
+
enabled = false;
|
|
24
|
+
} else if ("CI" in globalVar.process.env && [
|
|
25
|
+
"TRAVIS",
|
|
26
|
+
"CIRCLECI",
|
|
27
|
+
"APPVEYOR",
|
|
28
|
+
"GITLAB_CI",
|
|
29
|
+
"GITHUB_ACTIONS",
|
|
30
|
+
"BUILDKITE",
|
|
31
|
+
"DRONE"
|
|
32
|
+
].some((vendor) => vendor in globalVar.process.env)) {
|
|
33
|
+
enabled = true;
|
|
34
|
+
} else {
|
|
35
|
+
enabled = process.stdout.isTTY;
|
|
36
|
+
}
|
|
37
|
+
if (enabled) {
|
|
38
|
+
if (process.platform === "win32") {
|
|
39
|
+
supportLevel = 3;
|
|
40
|
+
} else {
|
|
41
|
+
if (COLORTERM && (COLORTERM === "truecolor" || COLORTERM === "24bit")) {
|
|
42
|
+
supportLevel = 3;
|
|
43
|
+
} else if (TERM && (TERM.endsWith("-256color") || TERM.endsWith("256"))) {
|
|
44
|
+
supportLevel = 2;
|
|
45
|
+
} else {
|
|
46
|
+
supportLevel = 1;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let options = {
|
|
52
|
+
enabled,
|
|
53
|
+
supportLevel
|
|
54
|
+
};
|
|
55
|
+
function kolorist(start, end, level = 1) {
|
|
56
|
+
const open = `\x1B[${start}m`;
|
|
57
|
+
const close = `\x1B[${end}m`;
|
|
58
|
+
const regex = new RegExp(`\\x1b\\[${end}m`, "g");
|
|
59
|
+
return (str) => {
|
|
60
|
+
return options.enabled && options.supportLevel >= level ? open + ("" + str).replace(regex, open) + close : "" + str;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const bold = kolorist(1, 22);
|
|
64
|
+
const dim = kolorist(2, 22);
|
|
65
|
+
const underline = kolorist(4, 24);
|
|
66
|
+
const black = kolorist(30, 39);
|
|
67
|
+
const red = kolorist(31, 39);
|
|
68
|
+
const green = kolorist(32, 39);
|
|
69
|
+
const yellow = kolorist(33, 39);
|
|
70
|
+
const magenta = kolorist(35, 39);
|
|
71
|
+
const lightYellow = kolorist(93, 39);
|
|
72
|
+
const bgYellow = kolorist(43, 49);
|
|
73
|
+
|
|
74
|
+
const cwd = process.cwd();
|
|
75
|
+
|
|
76
|
+
const isPath = (filePath) => filePath[0] === "." || path__default.isAbsolute(filePath);
|
|
77
|
+
const normalizePath$1 = (filepath) => filepath.replaceAll("\\", "/");
|
|
78
|
+
const getDisplayPath = (fullPath) => {
|
|
79
|
+
const relativePath = path__default.relative(cwd, fullPath);
|
|
80
|
+
return normalizePath$1(
|
|
81
|
+
relativePath.length < fullPath.length ? relativePath : fullPath
|
|
82
|
+
);
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const warningSignUnicode = "\u26A0";
|
|
86
|
+
const warningPrefix = yellow("Warning:");
|
|
87
|
+
const logOutput = (dtsOutput) => {
|
|
88
|
+
console.log(underline("dtsroll"));
|
|
89
|
+
const { inputs } = dtsOutput;
|
|
90
|
+
const isCliInput = inputs[0]?.[1] === void 0;
|
|
91
|
+
console.log(bold(`
|
|
92
|
+
\u{1F4E5} Entry points${isCliInput ? "" : " in package.json"}`));
|
|
93
|
+
console.log(
|
|
94
|
+
inputs.map(([inputFile, inputSource, error]) => {
|
|
95
|
+
const logPath2 = getDisplayPath(inputFile);
|
|
96
|
+
if (error) {
|
|
97
|
+
return ` ${lightYellow(`${warningSignUnicode} ${logPath2} ${dim(error)}`)}`;
|
|
98
|
+
}
|
|
99
|
+
return ` \u2192 ${green(logPath2)}${inputSource ? ` ${dim(`from ${inputSource}`)}` : ""}`;
|
|
100
|
+
}).join("\n")
|
|
101
|
+
);
|
|
102
|
+
if ("error" in dtsOutput) {
|
|
103
|
+
console.error(`${red("Error:")} ${dtsOutput.error}`);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
const {
|
|
107
|
+
outputDirectory,
|
|
108
|
+
output: {
|
|
109
|
+
entries: outputEntries,
|
|
110
|
+
chunks: outputChunks
|
|
111
|
+
},
|
|
112
|
+
size,
|
|
113
|
+
externals
|
|
114
|
+
} = dtsOutput;
|
|
115
|
+
const logPath = `${getDisplayPath(outputDirectory)}/`;
|
|
116
|
+
const logChunk = ({
|
|
117
|
+
file,
|
|
118
|
+
indent,
|
|
119
|
+
bullet,
|
|
120
|
+
color
|
|
121
|
+
}) => {
|
|
122
|
+
const sizeFormatted = byteSize(file.size).toString();
|
|
123
|
+
let log = `${indent}${bullet} ${dim(color(logPath))}${color(file.fileName)} ${sizeFormatted}`;
|
|
124
|
+
const { moduleIds, moduleToPackage } = file;
|
|
125
|
+
log += `
|
|
126
|
+
${moduleIds.sort().map((moduleId, index) => {
|
|
127
|
+
const isLast = index === moduleIds.length - 1;
|
|
128
|
+
const prefix = `${indent} ${isLast ? "\u2514\u2500 " : "\u251C\u2500 "}`;
|
|
129
|
+
const logModuleId = getDisplayPath(moduleId);
|
|
130
|
+
const bareSpecifier = moduleToPackage[moduleId];
|
|
131
|
+
if (bareSpecifier) {
|
|
132
|
+
return `${prefix}${dim(`${magenta(bareSpecifier)} (${logModuleId})`)}`;
|
|
133
|
+
}
|
|
134
|
+
return `${prefix}${dim(logModuleId)}`;
|
|
135
|
+
}).join("\n")}`;
|
|
136
|
+
return log;
|
|
137
|
+
};
|
|
138
|
+
console.log(bold("\n\u{1F4A0} Bundled output"));
|
|
139
|
+
console.log(
|
|
140
|
+
outputEntries.map((file) => logChunk({
|
|
141
|
+
file,
|
|
142
|
+
indent: " ",
|
|
143
|
+
bullet: "\u25CF",
|
|
144
|
+
color: green
|
|
145
|
+
})).join("\n\n")
|
|
146
|
+
);
|
|
147
|
+
if (outputChunks.length > 0) {
|
|
148
|
+
console.log(bold("\n Chunks"));
|
|
149
|
+
console.log(
|
|
150
|
+
outputChunks.map((file) => logChunk({
|
|
151
|
+
file,
|
|
152
|
+
indent: " ",
|
|
153
|
+
bullet: "\u25A0",
|
|
154
|
+
color: yellow
|
|
155
|
+
})).join("\n\n")
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
console.log(bold("\n\u2696\uFE0F Size savings"));
|
|
159
|
+
const difference = size.input - size.output;
|
|
160
|
+
const direction = difference > 0 ? "decrease" : "increase";
|
|
161
|
+
const percentage = (Math.abs(difference / size.input) * 100).toFixed(0);
|
|
162
|
+
console.log(` Input source size: ${byteSize(size.input).toString()}`);
|
|
163
|
+
console.log(` Bundled output size: ${byteSize(size.output).toString()}${difference === 0 ? "" : ` (${percentage}% ${direction})`}`);
|
|
164
|
+
if (externals.length > 0) {
|
|
165
|
+
console.log(bold("\n\u{1F4E6} External packages"));
|
|
166
|
+
console.log(
|
|
167
|
+
externals.map(([packageName, reason, devTypePackage]) => {
|
|
168
|
+
let stdout = ` \u2500 ${magenta(packageName)} ${dim(`externalized ${reason}`)}`;
|
|
169
|
+
if (devTypePackage) {
|
|
170
|
+
stdout += `
|
|
171
|
+
${warningPrefix} ${magenta(devTypePackage)} should not be in devDependencies if ${magenta(packageName)} is externalized`;
|
|
172
|
+
}
|
|
173
|
+
return stdout;
|
|
174
|
+
}).sort().join("\n")
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
class DtsrollBuildError extends Error {
|
|
180
|
+
id;
|
|
181
|
+
importChain;
|
|
182
|
+
constructor(message, id, importChain) {
|
|
183
|
+
super(message);
|
|
184
|
+
this.name = "DtsrollBuildError";
|
|
185
|
+
this.id = id;
|
|
186
|
+
this.importChain = importChain;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const dtsExtensions = [".d.ts", ".d.cts", ".d.mts"];
|
|
191
|
+
const isDts = (fileName) => dtsExtensions.some((extension) => fileName.endsWith(extension));
|
|
192
|
+
|
|
193
|
+
const isValidIdentifier = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
|
|
194
|
+
const reservedWords = /* @__PURE__ */ new Set([
|
|
195
|
+
"do",
|
|
196
|
+
"if",
|
|
197
|
+
"in",
|
|
198
|
+
"for",
|
|
199
|
+
"int",
|
|
200
|
+
"new",
|
|
201
|
+
"try",
|
|
202
|
+
"var",
|
|
203
|
+
"byte",
|
|
204
|
+
"case",
|
|
205
|
+
"char",
|
|
206
|
+
"else",
|
|
207
|
+
"enum",
|
|
208
|
+
"goto",
|
|
209
|
+
"long",
|
|
210
|
+
"null",
|
|
211
|
+
"this",
|
|
212
|
+
"true",
|
|
213
|
+
"void",
|
|
214
|
+
"with",
|
|
215
|
+
"break",
|
|
216
|
+
"catch",
|
|
217
|
+
"class",
|
|
218
|
+
"const",
|
|
219
|
+
"false",
|
|
220
|
+
"final",
|
|
221
|
+
"float",
|
|
222
|
+
"short",
|
|
223
|
+
"super",
|
|
224
|
+
"throw",
|
|
225
|
+
"while",
|
|
226
|
+
"delete",
|
|
227
|
+
"double",
|
|
228
|
+
"export",
|
|
229
|
+
"import",
|
|
230
|
+
"native",
|
|
231
|
+
"public",
|
|
232
|
+
"return",
|
|
233
|
+
"static",
|
|
234
|
+
"switch",
|
|
235
|
+
"throws",
|
|
236
|
+
"typeof",
|
|
237
|
+
"boolean",
|
|
238
|
+
"default",
|
|
239
|
+
"extends",
|
|
240
|
+
"finally",
|
|
241
|
+
"package",
|
|
242
|
+
"private",
|
|
243
|
+
"abstract",
|
|
244
|
+
"continue",
|
|
245
|
+
"debugger",
|
|
246
|
+
"function",
|
|
247
|
+
"volatile",
|
|
248
|
+
"interface",
|
|
249
|
+
"protected",
|
|
250
|
+
"transient",
|
|
251
|
+
"implements",
|
|
252
|
+
"instanceof",
|
|
253
|
+
"synchronized"
|
|
254
|
+
]);
|
|
255
|
+
const propertyNeedsQuotes = (property) => !isValidIdentifier.test(property) || reservedWords.has(property);
|
|
256
|
+
|
|
257
|
+
const pathExists = async (filePath) => fs.access(filePath).then(() => true, () => false);
|
|
258
|
+
|
|
259
|
+
const typesPrefix = "@types/";
|
|
260
|
+
const getOriginalPackageName = (typePackageName) => {
|
|
261
|
+
let originalPackageName = typePackageName.slice(typesPrefix.length);
|
|
262
|
+
if (originalPackageName.includes("__")) {
|
|
263
|
+
originalPackageName = `@${originalPackageName.replace("__", "/")}`;
|
|
264
|
+
}
|
|
265
|
+
return originalPackageName;
|
|
266
|
+
};
|
|
267
|
+
const getPackageName = (id) => {
|
|
268
|
+
let indexOfSlash = id.indexOf("/");
|
|
269
|
+
if (indexOfSlash === -1) {
|
|
270
|
+
return id;
|
|
271
|
+
}
|
|
272
|
+
if (id[0] === "@") {
|
|
273
|
+
const secondSlash = id.indexOf("/", indexOfSlash + 1);
|
|
274
|
+
if (secondSlash === -1) {
|
|
275
|
+
return id;
|
|
276
|
+
}
|
|
277
|
+
indexOfSlash = secondSlash;
|
|
278
|
+
}
|
|
279
|
+
return id.slice(0, indexOfSlash);
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const getAllFiles = async (directoryPath, dontShortenPath) => {
|
|
283
|
+
const directoryFiles = await fs.readdir(directoryPath, { withFileTypes: true });
|
|
284
|
+
const fileTree = await Promise.all(
|
|
285
|
+
directoryFiles.map(async (entry) => {
|
|
286
|
+
const filePath = path__default.join(directoryPath, entry.name);
|
|
287
|
+
if (entry.isDirectory()) {
|
|
288
|
+
const files = await getAllFiles(filePath, true);
|
|
289
|
+
return dontShortenPath ? files : files.map((file) => `./${normalizePath$1(path__default.relative(directoryPath, file))}`);
|
|
290
|
+
}
|
|
291
|
+
return dontShortenPath ? filePath : `./${normalizePath$1(path__default.relative(directoryPath, filePath))}`;
|
|
292
|
+
})
|
|
293
|
+
);
|
|
294
|
+
return fileTree.flat();
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const readPackageJson = async (filePath) => {
|
|
298
|
+
const packageJsonString = await fs.readFile(filePath, "utf8");
|
|
299
|
+
return JSON.parse(packageJsonString);
|
|
300
|
+
};
|
|
301
|
+
const traverseExports = (exportValue, propertyPath) => {
|
|
302
|
+
if (typeof exportValue === "string") {
|
|
303
|
+
return [[exportValue, propertyPath]];
|
|
304
|
+
}
|
|
305
|
+
if (Array.isArray(exportValue)) {
|
|
306
|
+
return exportValue.flatMap((value, index) => traverseExports(value, `${propertyPath}[${index}]`));
|
|
307
|
+
}
|
|
308
|
+
if (typeof exportValue === "object" && exportValue !== null) {
|
|
309
|
+
return Object.entries(exportValue).flatMap(([property, value]) => {
|
|
310
|
+
const newProperty = propertyNeedsQuotes(property) ? `["${property}"]` : `.${property}`;
|
|
311
|
+
return traverseExports(value, propertyPath + newProperty);
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
return [];
|
|
315
|
+
};
|
|
316
|
+
const getDtsEntryPoints = async (packageJson, packageJsonDirectory) => {
|
|
317
|
+
const entryPoints = {};
|
|
318
|
+
const addEntry = (subpath, from) => {
|
|
319
|
+
if (!isDts(subpath)) {
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
const entryPath = path__default.join(packageJsonDirectory, subpath);
|
|
323
|
+
if (!entryPoints[entryPath]) {
|
|
324
|
+
entryPoints[entryPath] = from;
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
if (packageJson.types) {
|
|
328
|
+
addEntry(packageJson.types, "types");
|
|
329
|
+
}
|
|
330
|
+
if (packageJson.typings) {
|
|
331
|
+
addEntry(packageJson.typings, "typings");
|
|
332
|
+
}
|
|
333
|
+
if (packageJson.exports) {
|
|
334
|
+
const subpaths = traverseExports(packageJson.exports, "exports");
|
|
335
|
+
let packageFiles;
|
|
336
|
+
for (const [subpath, fromProperty] of subpaths) {
|
|
337
|
+
if (!subpath.includes("*")) {
|
|
338
|
+
addEntry(subpath, fromProperty);
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (!packageFiles) {
|
|
342
|
+
packageFiles = await getAllFiles(packageJsonDirectory);
|
|
343
|
+
}
|
|
344
|
+
const [prefix, suffix] = subpath.split("*", 2);
|
|
345
|
+
for (const file of packageFiles) {
|
|
346
|
+
if (file.startsWith(prefix) && file.endsWith(suffix)) {
|
|
347
|
+
addEntry(file, fromProperty);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return entryPoints;
|
|
353
|
+
};
|
|
354
|
+
const externalizedDependencies = [
|
|
355
|
+
"dependencies",
|
|
356
|
+
"peerDependencies",
|
|
357
|
+
"optionalDependencies"
|
|
358
|
+
];
|
|
359
|
+
const getExternals = (packageJson) => {
|
|
360
|
+
const external = /* @__PURE__ */ new Map();
|
|
361
|
+
for (const dependencyType of externalizedDependencies) {
|
|
362
|
+
const dependencyObject = packageJson[dependencyType];
|
|
363
|
+
if (dependencyObject) {
|
|
364
|
+
const dependencyNames = Object.keys(dependencyObject);
|
|
365
|
+
for (const dependencyName of dependencyNames) {
|
|
366
|
+
external.set(dependencyName, `by package.json ${dependencyType}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return external;
|
|
371
|
+
};
|
|
372
|
+
const getPackageJson = async (cwd) => {
|
|
373
|
+
const packageJsonPath = path__default.resolve(cwd, "package.json");
|
|
374
|
+
const exists = await pathExists(packageJsonPath);
|
|
375
|
+
if (!exists) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
let packageJson;
|
|
379
|
+
try {
|
|
380
|
+
packageJson = await readPackageJson(packageJsonPath);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
throw new Error(`Failed to parse package.json at ${packageJsonPath}: ${error.message}`);
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
getExternals: () => getExternals(packageJson),
|
|
386
|
+
getDtsEntryPoints: () => getDtsEntryPoints(packageJson, path__default.dirname(packageJsonPath)),
|
|
387
|
+
devTypePackages: !packageJson.private && packageJson.devDependencies ? Object.fromEntries(
|
|
388
|
+
Object.keys(packageJson.devDependencies).filter((dep) => dep.startsWith(typesPrefix)).map((dep) => [getOriginalPackageName(dep), dep])
|
|
389
|
+
) : {}
|
|
390
|
+
};
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
const getCommonDirectory = (filePaths) => {
|
|
394
|
+
const splitPaths = filePaths.map((filePath) => filePath.split(path__default.sep).slice(0, -1));
|
|
395
|
+
const commonPath = [];
|
|
396
|
+
const [firstPath] = splitPaths;
|
|
397
|
+
for (let i = 0; i < firstPath.length; i += 1) {
|
|
398
|
+
const segment = firstPath[i];
|
|
399
|
+
const segmentIsCommon = splitPaths.every((pathParts) => pathParts[i] === segment);
|
|
400
|
+
if (!segmentIsCommon) {
|
|
401
|
+
break;
|
|
402
|
+
}
|
|
403
|
+
commonPath.push(segment);
|
|
404
|
+
}
|
|
405
|
+
return commonPath.join(path__default.sep);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const validateInput = async (inputFiles) => {
|
|
409
|
+
if (!inputFiles) {
|
|
410
|
+
throw new Error("No input files");
|
|
411
|
+
}
|
|
412
|
+
const isCliInput = Array.isArray(inputFiles);
|
|
413
|
+
const inputNormalized = isCliInput ? inputFiles.map((i) => [i]) : Object.entries(inputFiles);
|
|
414
|
+
return await Promise.all(inputNormalized.map(
|
|
415
|
+
async ([inputFile, inputSource]) => {
|
|
416
|
+
if (!isDts(inputFile)) {
|
|
417
|
+
return [inputFile, inputSource, "Ignoring non-d.ts input"];
|
|
418
|
+
}
|
|
419
|
+
const exists = await pathExists(inputFile);
|
|
420
|
+
if (!exists) {
|
|
421
|
+
return [inputFile, inputSource, "File not found"];
|
|
422
|
+
}
|
|
423
|
+
return [inputFile, inputSource];
|
|
424
|
+
}
|
|
425
|
+
));
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
var comma = ",".charCodeAt(0);
|
|
429
|
+
var semicolon = ";".charCodeAt(0);
|
|
430
|
+
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
431
|
+
var intToChar = new Uint8Array(64);
|
|
432
|
+
var charToInt = new Uint8Array(128);
|
|
433
|
+
for (let i = 0; i < chars.length; i++) {
|
|
434
|
+
const c = chars.charCodeAt(i);
|
|
435
|
+
intToChar[i] = c;
|
|
436
|
+
charToInt[c] = i;
|
|
437
|
+
}
|
|
438
|
+
function decodeInteger(reader, relative) {
|
|
439
|
+
let value = 0;
|
|
440
|
+
let shift = 0;
|
|
441
|
+
let integer = 0;
|
|
442
|
+
do {
|
|
443
|
+
const c = reader.next();
|
|
444
|
+
integer = charToInt[c];
|
|
445
|
+
value |= (integer & 31) << shift;
|
|
446
|
+
shift += 5;
|
|
447
|
+
} while (integer & 32);
|
|
448
|
+
const shouldNegate = value & 1;
|
|
449
|
+
value >>>= 1;
|
|
450
|
+
if (shouldNegate) {
|
|
451
|
+
value = -2147483648 | -value;
|
|
452
|
+
}
|
|
453
|
+
return relative + value;
|
|
454
|
+
}
|
|
455
|
+
function encodeInteger(builder, num, relative) {
|
|
456
|
+
let delta = num - relative;
|
|
457
|
+
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
|
458
|
+
do {
|
|
459
|
+
let clamped = delta & 31;
|
|
460
|
+
delta >>>= 5;
|
|
461
|
+
if (delta > 0) clamped |= 32;
|
|
462
|
+
builder.write(intToChar[clamped]);
|
|
463
|
+
} while (delta > 0);
|
|
464
|
+
return num;
|
|
465
|
+
}
|
|
466
|
+
function hasMoreVlq(reader, max) {
|
|
467
|
+
if (reader.pos >= max) return false;
|
|
468
|
+
return reader.peek() !== comma;
|
|
469
|
+
}
|
|
470
|
+
var bufLength = 1024 * 16;
|
|
471
|
+
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
|
472
|
+
decode(buf) {
|
|
473
|
+
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
474
|
+
return out.toString();
|
|
475
|
+
}
|
|
476
|
+
} : {
|
|
477
|
+
decode(buf) {
|
|
478
|
+
let out = "";
|
|
479
|
+
for (let i = 0; i < buf.length; i++) {
|
|
480
|
+
out += String.fromCharCode(buf[i]);
|
|
481
|
+
}
|
|
482
|
+
return out;
|
|
483
|
+
}
|
|
484
|
+
};
|
|
485
|
+
var StringWriter = class {
|
|
486
|
+
constructor() {
|
|
487
|
+
this.pos = 0;
|
|
488
|
+
this.out = "";
|
|
489
|
+
this.buffer = new Uint8Array(bufLength);
|
|
490
|
+
}
|
|
491
|
+
write(v) {
|
|
492
|
+
const { buffer } = this;
|
|
493
|
+
buffer[this.pos++] = v;
|
|
494
|
+
if (this.pos === bufLength) {
|
|
495
|
+
this.out += td.decode(buffer);
|
|
496
|
+
this.pos = 0;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
flush() {
|
|
500
|
+
const { buffer, out, pos } = this;
|
|
501
|
+
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
var StringReader = class {
|
|
505
|
+
constructor(buffer) {
|
|
506
|
+
this.pos = 0;
|
|
507
|
+
this.buffer = buffer;
|
|
508
|
+
}
|
|
509
|
+
next() {
|
|
510
|
+
return this.buffer.charCodeAt(this.pos++);
|
|
511
|
+
}
|
|
512
|
+
peek() {
|
|
513
|
+
return this.buffer.charCodeAt(this.pos);
|
|
514
|
+
}
|
|
515
|
+
indexOf(char) {
|
|
516
|
+
const { buffer, pos } = this;
|
|
517
|
+
const idx = buffer.indexOf(char, pos);
|
|
518
|
+
return idx === -1 ? buffer.length : idx;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
function decode(mappings) {
|
|
522
|
+
const { length } = mappings;
|
|
523
|
+
const reader = new StringReader(mappings);
|
|
524
|
+
const decoded = [];
|
|
525
|
+
let genColumn = 0;
|
|
526
|
+
let sourcesIndex = 0;
|
|
527
|
+
let sourceLine = 0;
|
|
528
|
+
let sourceColumn = 0;
|
|
529
|
+
let namesIndex = 0;
|
|
530
|
+
do {
|
|
531
|
+
const semi = reader.indexOf(";");
|
|
532
|
+
const line = [];
|
|
533
|
+
let sorted = true;
|
|
534
|
+
let lastCol = 0;
|
|
535
|
+
genColumn = 0;
|
|
536
|
+
while (reader.pos < semi) {
|
|
537
|
+
let seg;
|
|
538
|
+
genColumn = decodeInteger(reader, genColumn);
|
|
539
|
+
if (genColumn < lastCol) sorted = false;
|
|
540
|
+
lastCol = genColumn;
|
|
541
|
+
if (hasMoreVlq(reader, semi)) {
|
|
542
|
+
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
|
543
|
+
sourceLine = decodeInteger(reader, sourceLine);
|
|
544
|
+
sourceColumn = decodeInteger(reader, sourceColumn);
|
|
545
|
+
if (hasMoreVlq(reader, semi)) {
|
|
546
|
+
namesIndex = decodeInteger(reader, namesIndex);
|
|
547
|
+
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
|
548
|
+
} else {
|
|
549
|
+
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
|
550
|
+
}
|
|
551
|
+
} else {
|
|
552
|
+
seg = [genColumn];
|
|
553
|
+
}
|
|
554
|
+
line.push(seg);
|
|
555
|
+
reader.pos++;
|
|
556
|
+
}
|
|
557
|
+
if (!sorted) sort(line);
|
|
558
|
+
decoded.push(line);
|
|
559
|
+
reader.pos = semi + 1;
|
|
560
|
+
} while (reader.pos <= length);
|
|
561
|
+
return decoded;
|
|
562
|
+
}
|
|
563
|
+
function sort(line) {
|
|
564
|
+
line.sort(sortComparator$1);
|
|
565
|
+
}
|
|
566
|
+
function sortComparator$1(a, b) {
|
|
567
|
+
return a[0] - b[0];
|
|
568
|
+
}
|
|
569
|
+
function encode(decoded) {
|
|
570
|
+
const writer = new StringWriter();
|
|
571
|
+
let sourcesIndex = 0;
|
|
572
|
+
let sourceLine = 0;
|
|
573
|
+
let sourceColumn = 0;
|
|
574
|
+
let namesIndex = 0;
|
|
575
|
+
for (let i = 0; i < decoded.length; i++) {
|
|
576
|
+
const line = decoded[i];
|
|
577
|
+
if (i > 0) writer.write(semicolon);
|
|
578
|
+
if (line.length === 0) continue;
|
|
579
|
+
let genColumn = 0;
|
|
580
|
+
for (let j = 0; j < line.length; j++) {
|
|
581
|
+
const segment = line[j];
|
|
582
|
+
if (j > 0) writer.write(comma);
|
|
583
|
+
genColumn = encodeInteger(writer, segment[0], genColumn);
|
|
584
|
+
if (segment.length === 1) continue;
|
|
585
|
+
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
|
586
|
+
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
|
587
|
+
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
|
588
|
+
if (segment.length === 4) continue;
|
|
589
|
+
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return writer.flush();
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const schemeRegex = /^[\w+.-]+:\/\//;
|
|
596
|
+
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
|
|
597
|
+
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
|
|
598
|
+
function isAbsoluteUrl(input) {
|
|
599
|
+
return schemeRegex.test(input);
|
|
600
|
+
}
|
|
601
|
+
function isSchemeRelativeUrl(input) {
|
|
602
|
+
return input.startsWith("//");
|
|
603
|
+
}
|
|
604
|
+
function isAbsolutePath(input) {
|
|
605
|
+
return input.startsWith("/");
|
|
606
|
+
}
|
|
607
|
+
function isFileUrl(input) {
|
|
608
|
+
return input.startsWith("file:");
|
|
609
|
+
}
|
|
610
|
+
function isRelative(input) {
|
|
611
|
+
return /^[.?#]/.test(input);
|
|
612
|
+
}
|
|
613
|
+
function parseAbsoluteUrl(input) {
|
|
614
|
+
const match = urlRegex.exec(input);
|
|
615
|
+
return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
|
|
616
|
+
}
|
|
617
|
+
function parseFileUrl(input) {
|
|
618
|
+
const match = fileRegex.exec(input);
|
|
619
|
+
const path = match[2];
|
|
620
|
+
return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
|
|
621
|
+
}
|
|
622
|
+
function makeUrl(scheme, user, host, port, path, query, hash) {
|
|
623
|
+
return {
|
|
624
|
+
scheme,
|
|
625
|
+
user,
|
|
626
|
+
host,
|
|
627
|
+
port,
|
|
628
|
+
path,
|
|
629
|
+
query,
|
|
630
|
+
hash,
|
|
631
|
+
type: 7
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
function parseUrl(input) {
|
|
635
|
+
if (isSchemeRelativeUrl(input)) {
|
|
636
|
+
const url2 = parseAbsoluteUrl("http:" + input);
|
|
637
|
+
url2.scheme = "";
|
|
638
|
+
url2.type = 6;
|
|
639
|
+
return url2;
|
|
640
|
+
}
|
|
641
|
+
if (isAbsolutePath(input)) {
|
|
642
|
+
const url2 = parseAbsoluteUrl("http://foo.com" + input);
|
|
643
|
+
url2.scheme = "";
|
|
644
|
+
url2.host = "";
|
|
645
|
+
url2.type = 5;
|
|
646
|
+
return url2;
|
|
647
|
+
}
|
|
648
|
+
if (isFileUrl(input))
|
|
649
|
+
return parseFileUrl(input);
|
|
650
|
+
if (isAbsoluteUrl(input))
|
|
651
|
+
return parseAbsoluteUrl(input);
|
|
652
|
+
const url = parseAbsoluteUrl("http://foo.com/" + input);
|
|
653
|
+
url.scheme = "";
|
|
654
|
+
url.host = "";
|
|
655
|
+
url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
|
|
656
|
+
return url;
|
|
657
|
+
}
|
|
658
|
+
function stripPathFilename(path) {
|
|
659
|
+
if (path.endsWith("/.."))
|
|
660
|
+
return path;
|
|
661
|
+
const index = path.lastIndexOf("/");
|
|
662
|
+
return path.slice(0, index + 1);
|
|
663
|
+
}
|
|
664
|
+
function mergePaths(url, base) {
|
|
665
|
+
normalizePath(base, base.type);
|
|
666
|
+
if (url.path === "/") {
|
|
667
|
+
url.path = base.path;
|
|
668
|
+
} else {
|
|
669
|
+
url.path = stripPathFilename(base.path) + url.path;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
function normalizePath(url, type) {
|
|
673
|
+
const rel = type <= 4;
|
|
674
|
+
const pieces = url.path.split("/");
|
|
675
|
+
let pointer = 1;
|
|
676
|
+
let positive = 0;
|
|
677
|
+
let addTrailingSlash = false;
|
|
678
|
+
for (let i = 1; i < pieces.length; i++) {
|
|
679
|
+
const piece = pieces[i];
|
|
680
|
+
if (!piece) {
|
|
681
|
+
addTrailingSlash = true;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
addTrailingSlash = false;
|
|
685
|
+
if (piece === ".")
|
|
686
|
+
continue;
|
|
687
|
+
if (piece === "..") {
|
|
688
|
+
if (positive) {
|
|
689
|
+
addTrailingSlash = true;
|
|
690
|
+
positive--;
|
|
691
|
+
pointer--;
|
|
692
|
+
} else if (rel) {
|
|
693
|
+
pieces[pointer++] = piece;
|
|
694
|
+
}
|
|
695
|
+
continue;
|
|
696
|
+
}
|
|
697
|
+
pieces[pointer++] = piece;
|
|
698
|
+
positive++;
|
|
699
|
+
}
|
|
700
|
+
let path = "";
|
|
701
|
+
for (let i = 1; i < pointer; i++) {
|
|
702
|
+
path += "/" + pieces[i];
|
|
703
|
+
}
|
|
704
|
+
if (!path || addTrailingSlash && !path.endsWith("/..")) {
|
|
705
|
+
path += "/";
|
|
706
|
+
}
|
|
707
|
+
url.path = path;
|
|
708
|
+
}
|
|
709
|
+
function resolve(input, base) {
|
|
710
|
+
if (!input && !base)
|
|
711
|
+
return "";
|
|
712
|
+
const url = parseUrl(input);
|
|
713
|
+
let inputType = url.type;
|
|
714
|
+
if (base && inputType !== 7) {
|
|
715
|
+
const baseUrl = parseUrl(base);
|
|
716
|
+
const baseType = baseUrl.type;
|
|
717
|
+
switch (inputType) {
|
|
718
|
+
case 1:
|
|
719
|
+
url.hash = baseUrl.hash;
|
|
720
|
+
// fall through
|
|
721
|
+
case 2:
|
|
722
|
+
url.query = baseUrl.query;
|
|
723
|
+
// fall through
|
|
724
|
+
case 3:
|
|
725
|
+
case 4:
|
|
726
|
+
mergePaths(url, baseUrl);
|
|
727
|
+
// fall through
|
|
728
|
+
case 5:
|
|
729
|
+
url.user = baseUrl.user;
|
|
730
|
+
url.host = baseUrl.host;
|
|
731
|
+
url.port = baseUrl.port;
|
|
732
|
+
// fall through
|
|
733
|
+
case 6:
|
|
734
|
+
url.scheme = baseUrl.scheme;
|
|
735
|
+
}
|
|
736
|
+
if (baseType > inputType)
|
|
737
|
+
inputType = baseType;
|
|
738
|
+
}
|
|
739
|
+
normalizePath(url, inputType);
|
|
740
|
+
const queryHash = url.query + url.hash;
|
|
741
|
+
switch (inputType) {
|
|
742
|
+
// This is impossible, because of the empty checks at the start of the function.
|
|
743
|
+
// case UrlType.Empty:
|
|
744
|
+
case 2:
|
|
745
|
+
case 3:
|
|
746
|
+
return queryHash;
|
|
747
|
+
case 4: {
|
|
748
|
+
const path = url.path.slice(1);
|
|
749
|
+
if (!path)
|
|
750
|
+
return queryHash || ".";
|
|
751
|
+
if (isRelative(base || input) && !isRelative(path)) {
|
|
752
|
+
return "./" + path + queryHash;
|
|
753
|
+
}
|
|
754
|
+
return path + queryHash;
|
|
755
|
+
}
|
|
756
|
+
case 5:
|
|
757
|
+
return url.path + queryHash;
|
|
758
|
+
default:
|
|
759
|
+
return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function stripFilename(path) {
|
|
764
|
+
if (!path) return "";
|
|
765
|
+
const index = path.lastIndexOf("/");
|
|
766
|
+
return path.slice(0, index + 1);
|
|
767
|
+
}
|
|
768
|
+
function resolver(mapUrl, sourceRoot) {
|
|
769
|
+
const from = stripFilename(mapUrl);
|
|
770
|
+
const prefix = sourceRoot ? sourceRoot + "/" : "";
|
|
771
|
+
return (source) => resolve(prefix + (source || ""), from);
|
|
772
|
+
}
|
|
773
|
+
var COLUMN$1 = 0;
|
|
774
|
+
function maybeSort(mappings, owned) {
|
|
775
|
+
const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
|
|
776
|
+
if (unsortedIndex === mappings.length) return mappings;
|
|
777
|
+
if (!owned) mappings = mappings.slice();
|
|
778
|
+
for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
|
|
779
|
+
mappings[i] = sortSegments(mappings[i], owned);
|
|
780
|
+
}
|
|
781
|
+
return mappings;
|
|
782
|
+
}
|
|
783
|
+
function nextUnsortedSegmentLine(mappings, start) {
|
|
784
|
+
for (let i = start; i < mappings.length; i++) {
|
|
785
|
+
if (!isSorted(mappings[i])) return i;
|
|
786
|
+
}
|
|
787
|
+
return mappings.length;
|
|
788
|
+
}
|
|
789
|
+
function isSorted(line) {
|
|
790
|
+
for (let j = 1; j < line.length; j++) {
|
|
791
|
+
if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return true;
|
|
796
|
+
}
|
|
797
|
+
function sortSegments(line, owned) {
|
|
798
|
+
if (!owned) line = line.slice();
|
|
799
|
+
return line.sort(sortComparator);
|
|
800
|
+
}
|
|
801
|
+
function sortComparator(a, b) {
|
|
802
|
+
return a[COLUMN$1] - b[COLUMN$1];
|
|
803
|
+
}
|
|
804
|
+
var found = false;
|
|
805
|
+
function binarySearch(haystack, needle, low, high) {
|
|
806
|
+
while (low <= high) {
|
|
807
|
+
const mid = low + (high - low >> 1);
|
|
808
|
+
const cmp = haystack[mid][COLUMN$1] - needle;
|
|
809
|
+
if (cmp === 0) {
|
|
810
|
+
found = true;
|
|
811
|
+
return mid;
|
|
812
|
+
}
|
|
813
|
+
if (cmp < 0) {
|
|
814
|
+
low = mid + 1;
|
|
815
|
+
} else {
|
|
816
|
+
high = mid - 1;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
found = false;
|
|
820
|
+
return low - 1;
|
|
821
|
+
}
|
|
822
|
+
function lowerBound(haystack, needle, index) {
|
|
823
|
+
for (let i = index - 1; i >= 0; index = i--) {
|
|
824
|
+
if (haystack[i][COLUMN$1] !== needle) break;
|
|
825
|
+
}
|
|
826
|
+
return index;
|
|
827
|
+
}
|
|
828
|
+
function memoizedState() {
|
|
829
|
+
return {
|
|
830
|
+
lastKey: -1,
|
|
831
|
+
lastNeedle: -1,
|
|
832
|
+
lastIndex: -1
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
function memoizedBinarySearch(haystack, needle, state, key) {
|
|
836
|
+
const { lastKey, lastNeedle, lastIndex } = state;
|
|
837
|
+
let low = 0;
|
|
838
|
+
let high = haystack.length - 1;
|
|
839
|
+
if (key === lastKey) {
|
|
840
|
+
if (needle === lastNeedle) {
|
|
841
|
+
found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
|
|
842
|
+
return lastIndex;
|
|
843
|
+
}
|
|
844
|
+
if (needle >= lastNeedle) {
|
|
845
|
+
low = lastIndex === -1 ? 0 : lastIndex;
|
|
846
|
+
} else {
|
|
847
|
+
high = lastIndex;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
state.lastKey = key;
|
|
851
|
+
state.lastNeedle = needle;
|
|
852
|
+
return state.lastIndex = binarySearch(haystack, needle, low, high);
|
|
853
|
+
}
|
|
854
|
+
function parse$1(map) {
|
|
855
|
+
return typeof map === "string" ? JSON.parse(map) : map;
|
|
856
|
+
}
|
|
857
|
+
var TraceMap = class {
|
|
858
|
+
constructor(map, mapUrl) {
|
|
859
|
+
const isString = typeof map === "string";
|
|
860
|
+
if (!isString && map._decodedMemo) return map;
|
|
861
|
+
const parsed = parse$1(map);
|
|
862
|
+
const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
|
|
863
|
+
this.version = version;
|
|
864
|
+
this.file = file;
|
|
865
|
+
this.names = names || [];
|
|
866
|
+
this.sourceRoot = sourceRoot;
|
|
867
|
+
this.sources = sources;
|
|
868
|
+
this.sourcesContent = sourcesContent;
|
|
869
|
+
this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
|
|
870
|
+
const resolve = resolver(mapUrl, sourceRoot);
|
|
871
|
+
this.resolvedSources = sources.map(resolve);
|
|
872
|
+
const { mappings } = parsed;
|
|
873
|
+
if (typeof mappings === "string") {
|
|
874
|
+
this._encoded = mappings;
|
|
875
|
+
this._decoded = void 0;
|
|
876
|
+
} else if (Array.isArray(mappings)) {
|
|
877
|
+
this._encoded = void 0;
|
|
878
|
+
this._decoded = maybeSort(mappings, isString);
|
|
879
|
+
} else if (parsed.sections) {
|
|
880
|
+
throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
|
|
881
|
+
} else {
|
|
882
|
+
throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
|
|
883
|
+
}
|
|
884
|
+
this._decodedMemo = memoizedState();
|
|
885
|
+
this._bySources = void 0;
|
|
886
|
+
this._bySourceMemos = void 0;
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
function cast$1(map) {
|
|
890
|
+
return map;
|
|
891
|
+
}
|
|
892
|
+
function decodedMappings(map) {
|
|
893
|
+
var _a;
|
|
894
|
+
return (_a = cast$1(map))._decoded || (_a._decoded = decode(cast$1(map)._encoded));
|
|
895
|
+
}
|
|
896
|
+
function traceSegment(map, line, column) {
|
|
897
|
+
const decoded = decodedMappings(map);
|
|
898
|
+
if (line >= decoded.length) return null;
|
|
899
|
+
const segments = decoded[line];
|
|
900
|
+
const index = traceSegmentInternal(
|
|
901
|
+
segments,
|
|
902
|
+
cast$1(map)._decodedMemo,
|
|
903
|
+
line,
|
|
904
|
+
column);
|
|
905
|
+
return index === -1 ? null : segments[index];
|
|
906
|
+
}
|
|
907
|
+
function traceSegmentInternal(segments, memo, line, column, bias) {
|
|
908
|
+
let index = memoizedBinarySearch(segments, column, memo, line);
|
|
909
|
+
if (found) {
|
|
910
|
+
index = (lowerBound)(segments, column, index);
|
|
911
|
+
}
|
|
912
|
+
if (index === -1 || index === segments.length) return -1;
|
|
913
|
+
return index;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
var SetArray = class {
|
|
917
|
+
constructor() {
|
|
918
|
+
this._indexes = { __proto__: null };
|
|
919
|
+
this.array = [];
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
function cast(set) {
|
|
923
|
+
return set;
|
|
924
|
+
}
|
|
925
|
+
function get(setarr, key) {
|
|
926
|
+
return cast(setarr)._indexes[key];
|
|
927
|
+
}
|
|
928
|
+
function put(setarr, key) {
|
|
929
|
+
const index = get(setarr, key);
|
|
930
|
+
if (index !== void 0) return index;
|
|
931
|
+
const { array, _indexes: indexes } = cast(setarr);
|
|
932
|
+
const length = array.push(key);
|
|
933
|
+
return indexes[key] = length - 1;
|
|
934
|
+
}
|
|
935
|
+
function remove(setarr, key) {
|
|
936
|
+
const index = get(setarr, key);
|
|
937
|
+
if (index === void 0) return;
|
|
938
|
+
const { array, _indexes: indexes } = cast(setarr);
|
|
939
|
+
for (let i = index + 1; i < array.length; i++) {
|
|
940
|
+
const k = array[i];
|
|
941
|
+
array[i - 1] = k;
|
|
942
|
+
indexes[k]--;
|
|
943
|
+
}
|
|
944
|
+
indexes[key] = void 0;
|
|
945
|
+
array.pop();
|
|
946
|
+
}
|
|
947
|
+
var COLUMN = 0;
|
|
948
|
+
var SOURCES_INDEX = 1;
|
|
949
|
+
var SOURCE_LINE = 2;
|
|
950
|
+
var SOURCE_COLUMN = 3;
|
|
951
|
+
var NAMES_INDEX = 4;
|
|
952
|
+
var NO_NAME = -1;
|
|
953
|
+
var GenMapping = class {
|
|
954
|
+
constructor({ file, sourceRoot } = {}) {
|
|
955
|
+
this._names = new SetArray();
|
|
956
|
+
this._sources = new SetArray();
|
|
957
|
+
this._sourcesContent = [];
|
|
958
|
+
this._mappings = [];
|
|
959
|
+
this.file = file;
|
|
960
|
+
this.sourceRoot = sourceRoot;
|
|
961
|
+
this._ignoreList = new SetArray();
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
function cast2(map) {
|
|
965
|
+
return map;
|
|
966
|
+
}
|
|
967
|
+
var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
|
|
968
|
+
return addSegmentInternal(
|
|
969
|
+
true,
|
|
970
|
+
map,
|
|
971
|
+
genLine,
|
|
972
|
+
genColumn,
|
|
973
|
+
source,
|
|
974
|
+
sourceLine,
|
|
975
|
+
sourceColumn,
|
|
976
|
+
name);
|
|
977
|
+
};
|
|
978
|
+
function setSourceContent(map, source, content) {
|
|
979
|
+
const {
|
|
980
|
+
_sources: sources,
|
|
981
|
+
_sourcesContent: sourcesContent
|
|
982
|
+
// _originalScopes: originalScopes,
|
|
983
|
+
} = cast2(map);
|
|
984
|
+
const index = put(sources, source);
|
|
985
|
+
sourcesContent[index] = content;
|
|
986
|
+
}
|
|
987
|
+
function setIgnore(map, source, ignore = true) {
|
|
988
|
+
const {
|
|
989
|
+
_sources: sources,
|
|
990
|
+
_sourcesContent: sourcesContent,
|
|
991
|
+
_ignoreList: ignoreList
|
|
992
|
+
// _originalScopes: originalScopes,
|
|
993
|
+
} = cast2(map);
|
|
994
|
+
const index = put(sources, source);
|
|
995
|
+
if (index === sourcesContent.length) sourcesContent[index] = null;
|
|
996
|
+
if (ignore) put(ignoreList, index);
|
|
997
|
+
else remove(ignoreList, index);
|
|
998
|
+
}
|
|
999
|
+
function toDecodedMap(map) {
|
|
1000
|
+
const {
|
|
1001
|
+
_mappings: mappings,
|
|
1002
|
+
_sources: sources,
|
|
1003
|
+
_sourcesContent: sourcesContent,
|
|
1004
|
+
_names: names,
|
|
1005
|
+
_ignoreList: ignoreList
|
|
1006
|
+
// _originalScopes: originalScopes,
|
|
1007
|
+
// _generatedRanges: generatedRanges,
|
|
1008
|
+
} = cast2(map);
|
|
1009
|
+
removeEmptyFinalLines(mappings);
|
|
1010
|
+
return {
|
|
1011
|
+
version: 3,
|
|
1012
|
+
file: map.file || void 0,
|
|
1013
|
+
names: names.array,
|
|
1014
|
+
sourceRoot: map.sourceRoot || void 0,
|
|
1015
|
+
sources: sources.array,
|
|
1016
|
+
sourcesContent,
|
|
1017
|
+
mappings,
|
|
1018
|
+
// originalScopes,
|
|
1019
|
+
// generatedRanges,
|
|
1020
|
+
ignoreList: ignoreList.array
|
|
1021
|
+
};
|
|
1022
|
+
}
|
|
1023
|
+
function toEncodedMap(map) {
|
|
1024
|
+
const decoded = toDecodedMap(map);
|
|
1025
|
+
return Object.assign({}, decoded, {
|
|
1026
|
+
// originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)),
|
|
1027
|
+
// generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]),
|
|
1028
|
+
mappings: encode(decoded.mappings)
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) {
|
|
1032
|
+
const {
|
|
1033
|
+
_mappings: mappings,
|
|
1034
|
+
_sources: sources,
|
|
1035
|
+
_sourcesContent: sourcesContent,
|
|
1036
|
+
_names: names
|
|
1037
|
+
// _originalScopes: originalScopes,
|
|
1038
|
+
} = cast2(map);
|
|
1039
|
+
const line = getIndex(mappings, genLine);
|
|
1040
|
+
const index = getColumnIndex(line, genColumn);
|
|
1041
|
+
if (!source) {
|
|
1042
|
+
if (skipSourceless(line, index)) return;
|
|
1043
|
+
return insert(line, index, [genColumn]);
|
|
1044
|
+
}
|
|
1045
|
+
const sourcesIndex = put(sources, source);
|
|
1046
|
+
const namesIndex = name ? put(names, name) : NO_NAME;
|
|
1047
|
+
if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null;
|
|
1048
|
+
if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
return insert(
|
|
1052
|
+
line,
|
|
1053
|
+
index,
|
|
1054
|
+
name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
function getIndex(arr, index) {
|
|
1058
|
+
for (let i = arr.length; i <= index; i++) {
|
|
1059
|
+
arr[i] = [];
|
|
1060
|
+
}
|
|
1061
|
+
return arr[index];
|
|
1062
|
+
}
|
|
1063
|
+
function getColumnIndex(line, genColumn) {
|
|
1064
|
+
let index = line.length;
|
|
1065
|
+
for (let i = index - 1; i >= 0; index = i--) {
|
|
1066
|
+
const current = line[i];
|
|
1067
|
+
if (genColumn >= current[COLUMN]) break;
|
|
1068
|
+
}
|
|
1069
|
+
return index;
|
|
1070
|
+
}
|
|
1071
|
+
function insert(array, index, value) {
|
|
1072
|
+
for (let i = array.length; i > index; i--) {
|
|
1073
|
+
array[i] = array[i - 1];
|
|
1074
|
+
}
|
|
1075
|
+
array[index] = value;
|
|
1076
|
+
}
|
|
1077
|
+
function removeEmptyFinalLines(mappings) {
|
|
1078
|
+
const { length } = mappings;
|
|
1079
|
+
let len = length;
|
|
1080
|
+
for (let i = len - 1; i >= 0; len = i, i--) {
|
|
1081
|
+
if (mappings[i].length > 0) break;
|
|
1082
|
+
}
|
|
1083
|
+
if (len < length) mappings.length = len;
|
|
1084
|
+
}
|
|
1085
|
+
function skipSourceless(line, index) {
|
|
1086
|
+
if (index === 0) return true;
|
|
1087
|
+
const prev = line[index - 1];
|
|
1088
|
+
return prev.length === 1;
|
|
1089
|
+
}
|
|
1090
|
+
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
|
|
1091
|
+
if (index === 0) return false;
|
|
1092
|
+
const prev = line[index - 1];
|
|
1093
|
+
if (prev.length === 1) return false;
|
|
1094
|
+
return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false);
|
|
1098
|
+
var EMPTY_SOURCES = [];
|
|
1099
|
+
function SegmentObject(source, line, column, name, content, ignore) {
|
|
1100
|
+
return { source, line, column, name, content, ignore };
|
|
1101
|
+
}
|
|
1102
|
+
function Source(map, sources, source, content, ignore) {
|
|
1103
|
+
return {
|
|
1104
|
+
map,
|
|
1105
|
+
sources,
|
|
1106
|
+
source,
|
|
1107
|
+
content,
|
|
1108
|
+
ignore
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
function MapSource(map, sources) {
|
|
1112
|
+
return Source(map, sources, "", null, false);
|
|
1113
|
+
}
|
|
1114
|
+
function OriginalSource(source, content, ignore) {
|
|
1115
|
+
return Source(null, EMPTY_SOURCES, source, content, ignore);
|
|
1116
|
+
}
|
|
1117
|
+
function traceMappings(tree) {
|
|
1118
|
+
const gen = new GenMapping({ file: tree.map.file });
|
|
1119
|
+
const { sources: rootSources, map } = tree;
|
|
1120
|
+
const rootNames = map.names;
|
|
1121
|
+
const rootMappings = decodedMappings(map);
|
|
1122
|
+
for (let i = 0; i < rootMappings.length; i++) {
|
|
1123
|
+
const segments = rootMappings[i];
|
|
1124
|
+
for (let j = 0; j < segments.length; j++) {
|
|
1125
|
+
const segment = segments[j];
|
|
1126
|
+
const genCol = segment[0];
|
|
1127
|
+
let traced = SOURCELESS_MAPPING;
|
|
1128
|
+
if (segment.length !== 1) {
|
|
1129
|
+
const source2 = rootSources[segment[1]];
|
|
1130
|
+
traced = originalPositionFor(
|
|
1131
|
+
source2,
|
|
1132
|
+
segment[2],
|
|
1133
|
+
segment[3],
|
|
1134
|
+
segment.length === 5 ? rootNames[segment[4]] : ""
|
|
1135
|
+
);
|
|
1136
|
+
if (traced == null) continue;
|
|
1137
|
+
}
|
|
1138
|
+
const { column, line, name, content, source, ignore } = traced;
|
|
1139
|
+
maybeAddSegment(gen, i, genCol, source, line, column, name);
|
|
1140
|
+
if (source && content != null) setSourceContent(gen, source, content);
|
|
1141
|
+
if (ignore) setIgnore(gen, source, true);
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return gen;
|
|
1145
|
+
}
|
|
1146
|
+
function originalPositionFor(source, line, column, name) {
|
|
1147
|
+
if (!source.map) {
|
|
1148
|
+
return SegmentObject(source.source, line, column, name, source.content, source.ignore);
|
|
1149
|
+
}
|
|
1150
|
+
const segment = traceSegment(source.map, line, column);
|
|
1151
|
+
if (segment == null) return null;
|
|
1152
|
+
if (segment.length === 1) return SOURCELESS_MAPPING;
|
|
1153
|
+
return originalPositionFor(
|
|
1154
|
+
source.sources[segment[1]],
|
|
1155
|
+
segment[2],
|
|
1156
|
+
segment[3],
|
|
1157
|
+
segment.length === 5 ? source.map.names[segment[4]] : name
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
function asArray(value) {
|
|
1161
|
+
if (Array.isArray(value)) return value;
|
|
1162
|
+
return [value];
|
|
1163
|
+
}
|
|
1164
|
+
function buildSourceMapTree(input, loader) {
|
|
1165
|
+
const maps = asArray(input).map((m) => new TraceMap(m, ""));
|
|
1166
|
+
const map = maps.pop();
|
|
1167
|
+
for (let i = 0; i < maps.length; i++) {
|
|
1168
|
+
if (maps[i].sources.length > 1) {
|
|
1169
|
+
throw new Error(
|
|
1170
|
+
`Transformation map ${i} must have exactly one source file.
|
|
1171
|
+
Did you specify these with the most recent transformation maps first?`
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
let tree = build$1(map, loader, "", 0);
|
|
1176
|
+
for (let i = maps.length - 1; i >= 0; i--) {
|
|
1177
|
+
tree = MapSource(maps[i], [tree]);
|
|
1178
|
+
}
|
|
1179
|
+
return tree;
|
|
1180
|
+
}
|
|
1181
|
+
function build$1(map, loader, importer, importerDepth) {
|
|
1182
|
+
const { resolvedSources, sourcesContent, ignoreList } = map;
|
|
1183
|
+
const depth = importerDepth + 1;
|
|
1184
|
+
const children = resolvedSources.map((sourceFile, i) => {
|
|
1185
|
+
const ctx = {
|
|
1186
|
+
importer,
|
|
1187
|
+
depth,
|
|
1188
|
+
source: sourceFile || "",
|
|
1189
|
+
content: void 0,
|
|
1190
|
+
ignore: void 0
|
|
1191
|
+
};
|
|
1192
|
+
const sourceMap = loader(ctx.source, ctx);
|
|
1193
|
+
const { source} = ctx;
|
|
1194
|
+
if (sourceMap) return build$1(new TraceMap(sourceMap, source), loader, source, depth);
|
|
1195
|
+
const sourceContent = sourcesContent ? sourcesContent[i] : null;
|
|
1196
|
+
const ignored = ignoreList ? ignoreList.includes(i) : false;
|
|
1197
|
+
return OriginalSource(source, sourceContent, ignored);
|
|
1198
|
+
});
|
|
1199
|
+
return MapSource(map, children);
|
|
1200
|
+
}
|
|
1201
|
+
var SourceMap$1 = class SourceMap {
|
|
1202
|
+
constructor(map, options) {
|
|
1203
|
+
const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
|
|
1204
|
+
this.version = out.version;
|
|
1205
|
+
this.file = out.file;
|
|
1206
|
+
this.mappings = out.mappings;
|
|
1207
|
+
this.names = out.names;
|
|
1208
|
+
this.ignoreList = out.ignoreList;
|
|
1209
|
+
this.sourceRoot = out.sourceRoot;
|
|
1210
|
+
this.sources = out.sources;
|
|
1211
|
+
if (!options.excludeContent) {
|
|
1212
|
+
this.sourcesContent = out.sourcesContent;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
toString() {
|
|
1216
|
+
return JSON.stringify(this);
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
function remapping(input, loader, options) {
|
|
1220
|
+
const opts = { excludeContent: false, decodedMappings: false };
|
|
1221
|
+
const tree = buildSourceMapTree(input, loader);
|
|
1222
|
+
return new SourceMap$1(traceMappings(tree), opts);
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
class BitSet {
|
|
1226
|
+
constructor(arg) {
|
|
1227
|
+
this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
|
|
1228
|
+
}
|
|
1229
|
+
add(n2) {
|
|
1230
|
+
this.bits[n2 >> 5] |= 1 << (n2 & 31);
|
|
1231
|
+
}
|
|
1232
|
+
has(n2) {
|
|
1233
|
+
return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
class Chunk {
|
|
1237
|
+
constructor(start, end, content) {
|
|
1238
|
+
this.start = start;
|
|
1239
|
+
this.end = end;
|
|
1240
|
+
this.original = content;
|
|
1241
|
+
this.intro = "";
|
|
1242
|
+
this.outro = "";
|
|
1243
|
+
this.content = content;
|
|
1244
|
+
this.storeName = false;
|
|
1245
|
+
this.edited = false;
|
|
1246
|
+
{
|
|
1247
|
+
this.previous = null;
|
|
1248
|
+
this.next = null;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
appendLeft(content) {
|
|
1252
|
+
this.outro += content;
|
|
1253
|
+
}
|
|
1254
|
+
appendRight(content) {
|
|
1255
|
+
this.intro = this.intro + content;
|
|
1256
|
+
}
|
|
1257
|
+
clone() {
|
|
1258
|
+
const chunk = new Chunk(this.start, this.end, this.original);
|
|
1259
|
+
chunk.intro = this.intro;
|
|
1260
|
+
chunk.outro = this.outro;
|
|
1261
|
+
chunk.content = this.content;
|
|
1262
|
+
chunk.storeName = this.storeName;
|
|
1263
|
+
chunk.edited = this.edited;
|
|
1264
|
+
return chunk;
|
|
1265
|
+
}
|
|
1266
|
+
contains(index) {
|
|
1267
|
+
return this.start < index && index < this.end;
|
|
1268
|
+
}
|
|
1269
|
+
eachNext(fn) {
|
|
1270
|
+
let chunk = this;
|
|
1271
|
+
while (chunk) {
|
|
1272
|
+
fn(chunk);
|
|
1273
|
+
chunk = chunk.next;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
eachPrevious(fn) {
|
|
1277
|
+
let chunk = this;
|
|
1278
|
+
while (chunk) {
|
|
1279
|
+
fn(chunk);
|
|
1280
|
+
chunk = chunk.previous;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
edit(content, storeName, contentOnly) {
|
|
1284
|
+
this.content = content;
|
|
1285
|
+
if (!contentOnly) {
|
|
1286
|
+
this.intro = "";
|
|
1287
|
+
this.outro = "";
|
|
1288
|
+
}
|
|
1289
|
+
this.storeName = storeName;
|
|
1290
|
+
this.edited = true;
|
|
1291
|
+
return this;
|
|
1292
|
+
}
|
|
1293
|
+
prependLeft(content) {
|
|
1294
|
+
this.outro = content + this.outro;
|
|
1295
|
+
}
|
|
1296
|
+
prependRight(content) {
|
|
1297
|
+
this.intro = content + this.intro;
|
|
1298
|
+
}
|
|
1299
|
+
reset() {
|
|
1300
|
+
this.intro = "";
|
|
1301
|
+
this.outro = "";
|
|
1302
|
+
if (this.edited) {
|
|
1303
|
+
this.content = this.original;
|
|
1304
|
+
this.storeName = false;
|
|
1305
|
+
this.edited = false;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
split(index) {
|
|
1309
|
+
const sliceIndex = index - this.start;
|
|
1310
|
+
const originalBefore = this.original.slice(0, sliceIndex);
|
|
1311
|
+
const originalAfter = this.original.slice(sliceIndex);
|
|
1312
|
+
this.original = originalBefore;
|
|
1313
|
+
const newChunk = new Chunk(index, this.end, originalAfter);
|
|
1314
|
+
newChunk.outro = this.outro;
|
|
1315
|
+
this.outro = "";
|
|
1316
|
+
this.end = index;
|
|
1317
|
+
if (this.edited) {
|
|
1318
|
+
newChunk.edit("", false);
|
|
1319
|
+
this.content = "";
|
|
1320
|
+
} else {
|
|
1321
|
+
this.content = originalBefore;
|
|
1322
|
+
}
|
|
1323
|
+
newChunk.next = this.next;
|
|
1324
|
+
if (newChunk.next) newChunk.next.previous = newChunk;
|
|
1325
|
+
newChunk.previous = this;
|
|
1326
|
+
this.next = newChunk;
|
|
1327
|
+
return newChunk;
|
|
1328
|
+
}
|
|
1329
|
+
toString() {
|
|
1330
|
+
return this.intro + this.content + this.outro;
|
|
1331
|
+
}
|
|
1332
|
+
trimEnd(rx) {
|
|
1333
|
+
this.outro = this.outro.replace(rx, "");
|
|
1334
|
+
if (this.outro.length) return true;
|
|
1335
|
+
const trimmed = this.content.replace(rx, "");
|
|
1336
|
+
if (trimmed.length) {
|
|
1337
|
+
if (trimmed !== this.content) {
|
|
1338
|
+
this.split(this.start + trimmed.length).edit("", void 0, true);
|
|
1339
|
+
if (this.edited) {
|
|
1340
|
+
this.edit(trimmed, this.storeName, true);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
return true;
|
|
1344
|
+
} else {
|
|
1345
|
+
this.edit("", void 0, true);
|
|
1346
|
+
this.intro = this.intro.replace(rx, "");
|
|
1347
|
+
if (this.intro.length) return true;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
trimStart(rx) {
|
|
1351
|
+
this.intro = this.intro.replace(rx, "");
|
|
1352
|
+
if (this.intro.length) return true;
|
|
1353
|
+
const trimmed = this.content.replace(rx, "");
|
|
1354
|
+
if (trimmed.length) {
|
|
1355
|
+
if (trimmed !== this.content) {
|
|
1356
|
+
const newChunk = this.split(this.end - trimmed.length);
|
|
1357
|
+
if (this.edited) {
|
|
1358
|
+
newChunk.edit(trimmed, this.storeName, true);
|
|
1359
|
+
}
|
|
1360
|
+
this.edit("", void 0, true);
|
|
1361
|
+
}
|
|
1362
|
+
return true;
|
|
1363
|
+
} else {
|
|
1364
|
+
this.edit("", void 0, true);
|
|
1365
|
+
this.outro = this.outro.replace(rx, "");
|
|
1366
|
+
if (this.outro.length) return true;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
function getBtoa() {
|
|
1371
|
+
if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
|
|
1372
|
+
return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
|
|
1373
|
+
} else if (typeof Buffer === "function") {
|
|
1374
|
+
return (str) => Buffer.from(str, "utf-8").toString("base64");
|
|
1375
|
+
} else {
|
|
1376
|
+
return () => {
|
|
1377
|
+
throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
const btoa = /* @__PURE__ */ getBtoa();
|
|
1382
|
+
class SourceMap {
|
|
1383
|
+
constructor(properties) {
|
|
1384
|
+
this.version = 3;
|
|
1385
|
+
this.file = properties.file;
|
|
1386
|
+
this.sources = properties.sources;
|
|
1387
|
+
this.sourcesContent = properties.sourcesContent;
|
|
1388
|
+
this.names = properties.names;
|
|
1389
|
+
this.mappings = encode(properties.mappings);
|
|
1390
|
+
if (typeof properties.x_google_ignoreList !== "undefined") {
|
|
1391
|
+
this.x_google_ignoreList = properties.x_google_ignoreList;
|
|
1392
|
+
}
|
|
1393
|
+
if (typeof properties.debugId !== "undefined") {
|
|
1394
|
+
this.debugId = properties.debugId;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
toString() {
|
|
1398
|
+
return JSON.stringify(this);
|
|
1399
|
+
}
|
|
1400
|
+
toUrl() {
|
|
1401
|
+
return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
function guessIndent(code) {
|
|
1405
|
+
const lines = code.split("\n");
|
|
1406
|
+
const tabbed = lines.filter((line) => /^\t+/.test(line));
|
|
1407
|
+
const spaced = lines.filter((line) => /^ {2,}/.test(line));
|
|
1408
|
+
if (tabbed.length === 0 && spaced.length === 0) {
|
|
1409
|
+
return null;
|
|
1410
|
+
}
|
|
1411
|
+
if (tabbed.length >= spaced.length) {
|
|
1412
|
+
return " ";
|
|
1413
|
+
}
|
|
1414
|
+
const min = spaced.reduce((previous, current) => {
|
|
1415
|
+
const numSpaces = /^ +/.exec(current)[0].length;
|
|
1416
|
+
return Math.min(numSpaces, previous);
|
|
1417
|
+
}, Infinity);
|
|
1418
|
+
return new Array(min + 1).join(" ");
|
|
1419
|
+
}
|
|
1420
|
+
function getRelativePath(from, to) {
|
|
1421
|
+
const fromParts = from.split(/[/\\]/);
|
|
1422
|
+
const toParts = to.split(/[/\\]/);
|
|
1423
|
+
fromParts.pop();
|
|
1424
|
+
while (fromParts[0] === toParts[0]) {
|
|
1425
|
+
fromParts.shift();
|
|
1426
|
+
toParts.shift();
|
|
1427
|
+
}
|
|
1428
|
+
if (fromParts.length) {
|
|
1429
|
+
let i = fromParts.length;
|
|
1430
|
+
while (i--) fromParts[i] = "..";
|
|
1431
|
+
}
|
|
1432
|
+
return fromParts.concat(toParts).join("/");
|
|
1433
|
+
}
|
|
1434
|
+
const toString = Object.prototype.toString;
|
|
1435
|
+
function isObject(thing) {
|
|
1436
|
+
return toString.call(thing) === "[object Object]";
|
|
1437
|
+
}
|
|
1438
|
+
function getLocator(source) {
|
|
1439
|
+
const originalLines = source.split("\n");
|
|
1440
|
+
const lineOffsets = [];
|
|
1441
|
+
for (let i = 0, pos = 0; i < originalLines.length; i++) {
|
|
1442
|
+
lineOffsets.push(pos);
|
|
1443
|
+
pos += originalLines[i].length + 1;
|
|
1444
|
+
}
|
|
1445
|
+
return function locate(index) {
|
|
1446
|
+
let i = 0;
|
|
1447
|
+
let j = lineOffsets.length;
|
|
1448
|
+
while (i < j) {
|
|
1449
|
+
const m = i + j >> 1;
|
|
1450
|
+
if (index < lineOffsets[m]) {
|
|
1451
|
+
j = m;
|
|
1452
|
+
} else {
|
|
1453
|
+
i = m + 1;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
const line = i - 1;
|
|
1457
|
+
const column = index - lineOffsets[line];
|
|
1458
|
+
return { line, column };
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
const wordRegex = /\w/;
|
|
1462
|
+
class Mappings {
|
|
1463
|
+
constructor(hires) {
|
|
1464
|
+
this.hires = hires;
|
|
1465
|
+
this.generatedCodeLine = 0;
|
|
1466
|
+
this.generatedCodeColumn = 0;
|
|
1467
|
+
this.raw = [];
|
|
1468
|
+
this.rawSegments = this.raw[this.generatedCodeLine] = [];
|
|
1469
|
+
this.pending = null;
|
|
1470
|
+
}
|
|
1471
|
+
addEdit(sourceIndex, content, loc, nameIndex) {
|
|
1472
|
+
if (content.length) {
|
|
1473
|
+
const contentLengthMinusOne = content.length - 1;
|
|
1474
|
+
let contentLineEnd = content.indexOf("\n", 0);
|
|
1475
|
+
let previousContentLineEnd = -1;
|
|
1476
|
+
while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
|
|
1477
|
+
const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
1478
|
+
if (nameIndex >= 0) {
|
|
1479
|
+
segment2.push(nameIndex);
|
|
1480
|
+
}
|
|
1481
|
+
this.rawSegments.push(segment2);
|
|
1482
|
+
this.generatedCodeLine += 1;
|
|
1483
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
1484
|
+
this.generatedCodeColumn = 0;
|
|
1485
|
+
previousContentLineEnd = contentLineEnd;
|
|
1486
|
+
contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
|
|
1487
|
+
}
|
|
1488
|
+
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
1489
|
+
if (nameIndex >= 0) {
|
|
1490
|
+
segment.push(nameIndex);
|
|
1491
|
+
}
|
|
1492
|
+
this.rawSegments.push(segment);
|
|
1493
|
+
this.advance(content.slice(previousContentLineEnd + 1));
|
|
1494
|
+
} else if (this.pending) {
|
|
1495
|
+
this.rawSegments.push(this.pending);
|
|
1496
|
+
this.advance(content);
|
|
1497
|
+
}
|
|
1498
|
+
this.pending = null;
|
|
1499
|
+
}
|
|
1500
|
+
addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
|
|
1501
|
+
let originalCharIndex = chunk.start;
|
|
1502
|
+
let first = true;
|
|
1503
|
+
let charInHiresBoundary = false;
|
|
1504
|
+
while (originalCharIndex < chunk.end) {
|
|
1505
|
+
if (original[originalCharIndex] === "\n") {
|
|
1506
|
+
loc.line += 1;
|
|
1507
|
+
loc.column = 0;
|
|
1508
|
+
this.generatedCodeLine += 1;
|
|
1509
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
1510
|
+
this.generatedCodeColumn = 0;
|
|
1511
|
+
first = true;
|
|
1512
|
+
charInHiresBoundary = false;
|
|
1513
|
+
} else {
|
|
1514
|
+
if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
|
|
1515
|
+
const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
|
|
1516
|
+
if (this.hires === "boundary") {
|
|
1517
|
+
if (wordRegex.test(original[originalCharIndex])) {
|
|
1518
|
+
if (!charInHiresBoundary) {
|
|
1519
|
+
this.rawSegments.push(segment);
|
|
1520
|
+
charInHiresBoundary = true;
|
|
1521
|
+
}
|
|
1522
|
+
} else {
|
|
1523
|
+
this.rawSegments.push(segment);
|
|
1524
|
+
charInHiresBoundary = false;
|
|
1525
|
+
}
|
|
1526
|
+
} else {
|
|
1527
|
+
this.rawSegments.push(segment);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
loc.column += 1;
|
|
1531
|
+
this.generatedCodeColumn += 1;
|
|
1532
|
+
first = false;
|
|
1533
|
+
}
|
|
1534
|
+
originalCharIndex += 1;
|
|
1535
|
+
}
|
|
1536
|
+
this.pending = null;
|
|
1537
|
+
}
|
|
1538
|
+
advance(str) {
|
|
1539
|
+
if (!str) return;
|
|
1540
|
+
const lines = str.split("\n");
|
|
1541
|
+
if (lines.length > 1) {
|
|
1542
|
+
for (let i = 0; i < lines.length - 1; i++) {
|
|
1543
|
+
this.generatedCodeLine++;
|
|
1544
|
+
this.raw[this.generatedCodeLine] = this.rawSegments = [];
|
|
1545
|
+
}
|
|
1546
|
+
this.generatedCodeColumn = 0;
|
|
1547
|
+
}
|
|
1548
|
+
this.generatedCodeColumn += lines[lines.length - 1].length;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
const n = "\n";
|
|
1552
|
+
const warned = {
|
|
1553
|
+
insertLeft: false,
|
|
1554
|
+
insertRight: false,
|
|
1555
|
+
storeName: false
|
|
1556
|
+
};
|
|
1557
|
+
class MagicString {
|
|
1558
|
+
constructor(string, options = {}) {
|
|
1559
|
+
const chunk = new Chunk(0, string.length, string);
|
|
1560
|
+
Object.defineProperties(this, {
|
|
1561
|
+
original: { writable: true, value: string },
|
|
1562
|
+
outro: { writable: true, value: "" },
|
|
1563
|
+
intro: { writable: true, value: "" },
|
|
1564
|
+
firstChunk: { writable: true, value: chunk },
|
|
1565
|
+
lastChunk: { writable: true, value: chunk },
|
|
1566
|
+
lastSearchedChunk: { writable: true, value: chunk },
|
|
1567
|
+
byStart: { writable: true, value: {} },
|
|
1568
|
+
byEnd: { writable: true, value: {} },
|
|
1569
|
+
filename: { writable: true, value: options.filename },
|
|
1570
|
+
indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
|
|
1571
|
+
sourcemapLocations: { writable: true, value: new BitSet() },
|
|
1572
|
+
storedNames: { writable: true, value: {} },
|
|
1573
|
+
indentStr: { writable: true, value: void 0 },
|
|
1574
|
+
ignoreList: { writable: true, value: options.ignoreList },
|
|
1575
|
+
offset: { writable: true, value: options.offset || 0 }
|
|
1576
|
+
});
|
|
1577
|
+
this.byStart[0] = chunk;
|
|
1578
|
+
this.byEnd[string.length] = chunk;
|
|
1579
|
+
}
|
|
1580
|
+
addSourcemapLocation(char) {
|
|
1581
|
+
this.sourcemapLocations.add(char);
|
|
1582
|
+
}
|
|
1583
|
+
append(content) {
|
|
1584
|
+
if (typeof content !== "string") throw new TypeError("outro content must be a string");
|
|
1585
|
+
this.outro += content;
|
|
1586
|
+
return this;
|
|
1587
|
+
}
|
|
1588
|
+
appendLeft(index, content) {
|
|
1589
|
+
index = index + this.offset;
|
|
1590
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
1591
|
+
this._split(index);
|
|
1592
|
+
const chunk = this.byEnd[index];
|
|
1593
|
+
if (chunk) {
|
|
1594
|
+
chunk.appendLeft(content);
|
|
1595
|
+
} else {
|
|
1596
|
+
this.intro += content;
|
|
1597
|
+
}
|
|
1598
|
+
return this;
|
|
1599
|
+
}
|
|
1600
|
+
appendRight(index, content) {
|
|
1601
|
+
index = index + this.offset;
|
|
1602
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
1603
|
+
this._split(index);
|
|
1604
|
+
const chunk = this.byStart[index];
|
|
1605
|
+
if (chunk) {
|
|
1606
|
+
chunk.appendRight(content);
|
|
1607
|
+
} else {
|
|
1608
|
+
this.outro += content;
|
|
1609
|
+
}
|
|
1610
|
+
return this;
|
|
1611
|
+
}
|
|
1612
|
+
clone() {
|
|
1613
|
+
const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
|
|
1614
|
+
let originalChunk = this.firstChunk;
|
|
1615
|
+
let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
|
|
1616
|
+
while (originalChunk) {
|
|
1617
|
+
cloned.byStart[clonedChunk.start] = clonedChunk;
|
|
1618
|
+
cloned.byEnd[clonedChunk.end] = clonedChunk;
|
|
1619
|
+
const nextOriginalChunk = originalChunk.next;
|
|
1620
|
+
const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
|
|
1621
|
+
if (nextClonedChunk) {
|
|
1622
|
+
clonedChunk.next = nextClonedChunk;
|
|
1623
|
+
nextClonedChunk.previous = clonedChunk;
|
|
1624
|
+
clonedChunk = nextClonedChunk;
|
|
1625
|
+
}
|
|
1626
|
+
originalChunk = nextOriginalChunk;
|
|
1627
|
+
}
|
|
1628
|
+
cloned.lastChunk = clonedChunk;
|
|
1629
|
+
if (this.indentExclusionRanges) {
|
|
1630
|
+
cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
|
|
1631
|
+
}
|
|
1632
|
+
cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
|
|
1633
|
+
cloned.intro = this.intro;
|
|
1634
|
+
cloned.outro = this.outro;
|
|
1635
|
+
return cloned;
|
|
1636
|
+
}
|
|
1637
|
+
generateDecodedMap(options) {
|
|
1638
|
+
options = options || {};
|
|
1639
|
+
const sourceIndex = 0;
|
|
1640
|
+
const names = Object.keys(this.storedNames);
|
|
1641
|
+
const mappings = new Mappings(options.hires);
|
|
1642
|
+
const locate = getLocator(this.original);
|
|
1643
|
+
if (this.intro) {
|
|
1644
|
+
mappings.advance(this.intro);
|
|
1645
|
+
}
|
|
1646
|
+
this.firstChunk.eachNext((chunk) => {
|
|
1647
|
+
const loc = locate(chunk.start);
|
|
1648
|
+
if (chunk.intro.length) mappings.advance(chunk.intro);
|
|
1649
|
+
if (chunk.edited) {
|
|
1650
|
+
mappings.addEdit(
|
|
1651
|
+
sourceIndex,
|
|
1652
|
+
chunk.content,
|
|
1653
|
+
loc,
|
|
1654
|
+
chunk.storeName ? names.indexOf(chunk.original) : -1
|
|
1655
|
+
);
|
|
1656
|
+
} else {
|
|
1657
|
+
mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
|
|
1658
|
+
}
|
|
1659
|
+
if (chunk.outro.length) mappings.advance(chunk.outro);
|
|
1660
|
+
});
|
|
1661
|
+
if (this.outro) {
|
|
1662
|
+
mappings.advance(this.outro);
|
|
1663
|
+
}
|
|
1664
|
+
return {
|
|
1665
|
+
file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
|
|
1666
|
+
sources: [
|
|
1667
|
+
options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
|
|
1668
|
+
],
|
|
1669
|
+
sourcesContent: options.includeContent ? [this.original] : void 0,
|
|
1670
|
+
names,
|
|
1671
|
+
mappings: mappings.raw,
|
|
1672
|
+
x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
generateMap(options) {
|
|
1676
|
+
return new SourceMap(this.generateDecodedMap(options));
|
|
1677
|
+
}
|
|
1678
|
+
_ensureindentStr() {
|
|
1679
|
+
if (this.indentStr === void 0) {
|
|
1680
|
+
this.indentStr = guessIndent(this.original);
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
_getRawIndentString() {
|
|
1684
|
+
this._ensureindentStr();
|
|
1685
|
+
return this.indentStr;
|
|
1686
|
+
}
|
|
1687
|
+
getIndentString() {
|
|
1688
|
+
this._ensureindentStr();
|
|
1689
|
+
return this.indentStr === null ? " " : this.indentStr;
|
|
1690
|
+
}
|
|
1691
|
+
indent(indentStr, options) {
|
|
1692
|
+
const pattern = /^[^\r\n]/gm;
|
|
1693
|
+
if (isObject(indentStr)) {
|
|
1694
|
+
options = indentStr;
|
|
1695
|
+
indentStr = void 0;
|
|
1696
|
+
}
|
|
1697
|
+
if (indentStr === void 0) {
|
|
1698
|
+
this._ensureindentStr();
|
|
1699
|
+
indentStr = this.indentStr || " ";
|
|
1700
|
+
}
|
|
1701
|
+
if (indentStr === "") return this;
|
|
1702
|
+
options = options || {};
|
|
1703
|
+
const isExcluded = {};
|
|
1704
|
+
if (options.exclude) {
|
|
1705
|
+
const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
|
|
1706
|
+
exclusions.forEach((exclusion) => {
|
|
1707
|
+
for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
|
|
1708
|
+
isExcluded[i] = true;
|
|
1709
|
+
}
|
|
1710
|
+
});
|
|
1711
|
+
}
|
|
1712
|
+
let shouldIndentNextCharacter = options.indentStart !== false;
|
|
1713
|
+
const replacer = (match) => {
|
|
1714
|
+
if (shouldIndentNextCharacter) return `${indentStr}${match}`;
|
|
1715
|
+
shouldIndentNextCharacter = true;
|
|
1716
|
+
return match;
|
|
1717
|
+
};
|
|
1718
|
+
this.intro = this.intro.replace(pattern, replacer);
|
|
1719
|
+
let charIndex = 0;
|
|
1720
|
+
let chunk = this.firstChunk;
|
|
1721
|
+
while (chunk) {
|
|
1722
|
+
const end = chunk.end;
|
|
1723
|
+
if (chunk.edited) {
|
|
1724
|
+
if (!isExcluded[charIndex]) {
|
|
1725
|
+
chunk.content = chunk.content.replace(pattern, replacer);
|
|
1726
|
+
if (chunk.content.length) {
|
|
1727
|
+
shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
} else {
|
|
1731
|
+
charIndex = chunk.start;
|
|
1732
|
+
while (charIndex < end) {
|
|
1733
|
+
if (!isExcluded[charIndex]) {
|
|
1734
|
+
const char = this.original[charIndex];
|
|
1735
|
+
if (char === "\n") {
|
|
1736
|
+
shouldIndentNextCharacter = true;
|
|
1737
|
+
} else if (char !== "\r" && shouldIndentNextCharacter) {
|
|
1738
|
+
shouldIndentNextCharacter = false;
|
|
1739
|
+
if (charIndex === chunk.start) {
|
|
1740
|
+
chunk.prependRight(indentStr);
|
|
1741
|
+
} else {
|
|
1742
|
+
this._splitChunk(chunk, charIndex);
|
|
1743
|
+
chunk = chunk.next;
|
|
1744
|
+
chunk.prependRight(indentStr);
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
charIndex += 1;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
charIndex = chunk.end;
|
|
1752
|
+
chunk = chunk.next;
|
|
1753
|
+
}
|
|
1754
|
+
this.outro = this.outro.replace(pattern, replacer);
|
|
1755
|
+
return this;
|
|
1756
|
+
}
|
|
1757
|
+
insert() {
|
|
1758
|
+
throw new Error(
|
|
1759
|
+
"magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
|
|
1760
|
+
);
|
|
1761
|
+
}
|
|
1762
|
+
insertLeft(index, content) {
|
|
1763
|
+
if (!warned.insertLeft) {
|
|
1764
|
+
console.warn(
|
|
1765
|
+
"magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
|
|
1766
|
+
);
|
|
1767
|
+
warned.insertLeft = true;
|
|
1768
|
+
}
|
|
1769
|
+
return this.appendLeft(index, content);
|
|
1770
|
+
}
|
|
1771
|
+
insertRight(index, content) {
|
|
1772
|
+
if (!warned.insertRight) {
|
|
1773
|
+
console.warn(
|
|
1774
|
+
"magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
|
|
1775
|
+
);
|
|
1776
|
+
warned.insertRight = true;
|
|
1777
|
+
}
|
|
1778
|
+
return this.prependRight(index, content);
|
|
1779
|
+
}
|
|
1780
|
+
move(start, end, index) {
|
|
1781
|
+
start = start + this.offset;
|
|
1782
|
+
end = end + this.offset;
|
|
1783
|
+
index = index + this.offset;
|
|
1784
|
+
if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
|
|
1785
|
+
this._split(start);
|
|
1786
|
+
this._split(end);
|
|
1787
|
+
this._split(index);
|
|
1788
|
+
const first = this.byStart[start];
|
|
1789
|
+
const last = this.byEnd[end];
|
|
1790
|
+
const oldLeft = first.previous;
|
|
1791
|
+
const oldRight = last.next;
|
|
1792
|
+
const newRight = this.byStart[index];
|
|
1793
|
+
if (!newRight && last === this.lastChunk) return this;
|
|
1794
|
+
const newLeft = newRight ? newRight.previous : this.lastChunk;
|
|
1795
|
+
if (oldLeft) oldLeft.next = oldRight;
|
|
1796
|
+
if (oldRight) oldRight.previous = oldLeft;
|
|
1797
|
+
if (newLeft) newLeft.next = first;
|
|
1798
|
+
if (newRight) newRight.previous = last;
|
|
1799
|
+
if (!first.previous) this.firstChunk = last.next;
|
|
1800
|
+
if (!last.next) {
|
|
1801
|
+
this.lastChunk = first.previous;
|
|
1802
|
+
this.lastChunk.next = null;
|
|
1803
|
+
}
|
|
1804
|
+
first.previous = newLeft;
|
|
1805
|
+
last.next = newRight || null;
|
|
1806
|
+
if (!newLeft) this.firstChunk = first;
|
|
1807
|
+
if (!newRight) this.lastChunk = last;
|
|
1808
|
+
return this;
|
|
1809
|
+
}
|
|
1810
|
+
overwrite(start, end, content, options) {
|
|
1811
|
+
options = options || {};
|
|
1812
|
+
return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
|
|
1813
|
+
}
|
|
1814
|
+
update(start, end, content, options) {
|
|
1815
|
+
start = start + this.offset;
|
|
1816
|
+
end = end + this.offset;
|
|
1817
|
+
if (typeof content !== "string") throw new TypeError("replacement content must be a string");
|
|
1818
|
+
if (this.original.length !== 0) {
|
|
1819
|
+
while (start < 0) start += this.original.length;
|
|
1820
|
+
while (end < 0) end += this.original.length;
|
|
1821
|
+
}
|
|
1822
|
+
if (end > this.original.length) throw new Error("end is out of bounds");
|
|
1823
|
+
if (start === end)
|
|
1824
|
+
throw new Error(
|
|
1825
|
+
"Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead"
|
|
1826
|
+
);
|
|
1827
|
+
this._split(start);
|
|
1828
|
+
this._split(end);
|
|
1829
|
+
if (options === true) {
|
|
1830
|
+
if (!warned.storeName) {
|
|
1831
|
+
console.warn(
|
|
1832
|
+
"The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
|
|
1833
|
+
);
|
|
1834
|
+
warned.storeName = true;
|
|
1835
|
+
}
|
|
1836
|
+
options = { storeName: true };
|
|
1837
|
+
}
|
|
1838
|
+
const storeName = options !== void 0 ? options.storeName : false;
|
|
1839
|
+
const overwrite = options !== void 0 ? options.overwrite : false;
|
|
1840
|
+
if (storeName) {
|
|
1841
|
+
const original = this.original.slice(start, end);
|
|
1842
|
+
Object.defineProperty(this.storedNames, original, {
|
|
1843
|
+
writable: true,
|
|
1844
|
+
value: true,
|
|
1845
|
+
enumerable: true
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
const first = this.byStart[start];
|
|
1849
|
+
const last = this.byEnd[end];
|
|
1850
|
+
if (first) {
|
|
1851
|
+
let chunk = first;
|
|
1852
|
+
while (chunk !== last) {
|
|
1853
|
+
if (chunk.next !== this.byStart[chunk.end]) {
|
|
1854
|
+
throw new Error("Cannot overwrite across a split point");
|
|
1855
|
+
}
|
|
1856
|
+
chunk = chunk.next;
|
|
1857
|
+
chunk.edit("", false);
|
|
1858
|
+
}
|
|
1859
|
+
first.edit(content, storeName, !overwrite);
|
|
1860
|
+
} else {
|
|
1861
|
+
const newChunk = new Chunk(start, end, "").edit(content, storeName);
|
|
1862
|
+
last.next = newChunk;
|
|
1863
|
+
newChunk.previous = last;
|
|
1864
|
+
}
|
|
1865
|
+
return this;
|
|
1866
|
+
}
|
|
1867
|
+
prepend(content) {
|
|
1868
|
+
if (typeof content !== "string") throw new TypeError("outro content must be a string");
|
|
1869
|
+
this.intro = content + this.intro;
|
|
1870
|
+
return this;
|
|
1871
|
+
}
|
|
1872
|
+
prependLeft(index, content) {
|
|
1873
|
+
index = index + this.offset;
|
|
1874
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
1875
|
+
this._split(index);
|
|
1876
|
+
const chunk = this.byEnd[index];
|
|
1877
|
+
if (chunk) {
|
|
1878
|
+
chunk.prependLeft(content);
|
|
1879
|
+
} else {
|
|
1880
|
+
this.intro = content + this.intro;
|
|
1881
|
+
}
|
|
1882
|
+
return this;
|
|
1883
|
+
}
|
|
1884
|
+
prependRight(index, content) {
|
|
1885
|
+
index = index + this.offset;
|
|
1886
|
+
if (typeof content !== "string") throw new TypeError("inserted content must be a string");
|
|
1887
|
+
this._split(index);
|
|
1888
|
+
const chunk = this.byStart[index];
|
|
1889
|
+
if (chunk) {
|
|
1890
|
+
chunk.prependRight(content);
|
|
1891
|
+
} else {
|
|
1892
|
+
this.outro = content + this.outro;
|
|
1893
|
+
}
|
|
1894
|
+
return this;
|
|
1895
|
+
}
|
|
1896
|
+
remove(start, end) {
|
|
1897
|
+
start = start + this.offset;
|
|
1898
|
+
end = end + this.offset;
|
|
1899
|
+
if (this.original.length !== 0) {
|
|
1900
|
+
while (start < 0) start += this.original.length;
|
|
1901
|
+
while (end < 0) end += this.original.length;
|
|
1902
|
+
}
|
|
1903
|
+
if (start === end) return this;
|
|
1904
|
+
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
|
|
1905
|
+
if (start > end) throw new Error("end must be greater than start");
|
|
1906
|
+
this._split(start);
|
|
1907
|
+
this._split(end);
|
|
1908
|
+
let chunk = this.byStart[start];
|
|
1909
|
+
while (chunk) {
|
|
1910
|
+
chunk.intro = "";
|
|
1911
|
+
chunk.outro = "";
|
|
1912
|
+
chunk.edit("");
|
|
1913
|
+
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
|
1914
|
+
}
|
|
1915
|
+
return this;
|
|
1916
|
+
}
|
|
1917
|
+
reset(start, end) {
|
|
1918
|
+
start = start + this.offset;
|
|
1919
|
+
end = end + this.offset;
|
|
1920
|
+
if (this.original.length !== 0) {
|
|
1921
|
+
while (start < 0) start += this.original.length;
|
|
1922
|
+
while (end < 0) end += this.original.length;
|
|
1923
|
+
}
|
|
1924
|
+
if (start === end) return this;
|
|
1925
|
+
if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
|
|
1926
|
+
if (start > end) throw new Error("end must be greater than start");
|
|
1927
|
+
this._split(start);
|
|
1928
|
+
this._split(end);
|
|
1929
|
+
let chunk = this.byStart[start];
|
|
1930
|
+
while (chunk) {
|
|
1931
|
+
chunk.reset();
|
|
1932
|
+
chunk = end > chunk.end ? this.byStart[chunk.end] : null;
|
|
1933
|
+
}
|
|
1934
|
+
return this;
|
|
1935
|
+
}
|
|
1936
|
+
lastChar() {
|
|
1937
|
+
if (this.outro.length) return this.outro[this.outro.length - 1];
|
|
1938
|
+
let chunk = this.lastChunk;
|
|
1939
|
+
do {
|
|
1940
|
+
if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
|
|
1941
|
+
if (chunk.content.length) return chunk.content[chunk.content.length - 1];
|
|
1942
|
+
if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
|
|
1943
|
+
} while (chunk = chunk.previous);
|
|
1944
|
+
if (this.intro.length) return this.intro[this.intro.length - 1];
|
|
1945
|
+
return "";
|
|
1946
|
+
}
|
|
1947
|
+
lastLine() {
|
|
1948
|
+
let lineIndex = this.outro.lastIndexOf(n);
|
|
1949
|
+
if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
|
|
1950
|
+
let lineStr = this.outro;
|
|
1951
|
+
let chunk = this.lastChunk;
|
|
1952
|
+
do {
|
|
1953
|
+
if (chunk.outro.length > 0) {
|
|
1954
|
+
lineIndex = chunk.outro.lastIndexOf(n);
|
|
1955
|
+
if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
|
|
1956
|
+
lineStr = chunk.outro + lineStr;
|
|
1957
|
+
}
|
|
1958
|
+
if (chunk.content.length > 0) {
|
|
1959
|
+
lineIndex = chunk.content.lastIndexOf(n);
|
|
1960
|
+
if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
|
|
1961
|
+
lineStr = chunk.content + lineStr;
|
|
1962
|
+
}
|
|
1963
|
+
if (chunk.intro.length > 0) {
|
|
1964
|
+
lineIndex = chunk.intro.lastIndexOf(n);
|
|
1965
|
+
if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
|
|
1966
|
+
lineStr = chunk.intro + lineStr;
|
|
1967
|
+
}
|
|
1968
|
+
} while (chunk = chunk.previous);
|
|
1969
|
+
lineIndex = this.intro.lastIndexOf(n);
|
|
1970
|
+
if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
|
|
1971
|
+
return this.intro + lineStr;
|
|
1972
|
+
}
|
|
1973
|
+
slice(start = 0, end = this.original.length - this.offset) {
|
|
1974
|
+
start = start + this.offset;
|
|
1975
|
+
end = end + this.offset;
|
|
1976
|
+
if (this.original.length !== 0) {
|
|
1977
|
+
while (start < 0) start += this.original.length;
|
|
1978
|
+
while (end < 0) end += this.original.length;
|
|
1979
|
+
}
|
|
1980
|
+
let result = "";
|
|
1981
|
+
let chunk = this.firstChunk;
|
|
1982
|
+
while (chunk && (chunk.start > start || chunk.end <= start)) {
|
|
1983
|
+
if (chunk.start < end && chunk.end >= end) {
|
|
1984
|
+
return result;
|
|
1985
|
+
}
|
|
1986
|
+
chunk = chunk.next;
|
|
1987
|
+
}
|
|
1988
|
+
if (chunk && chunk.edited && chunk.start !== start)
|
|
1989
|
+
throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
|
|
1990
|
+
const startChunk = chunk;
|
|
1991
|
+
while (chunk) {
|
|
1992
|
+
if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
|
|
1993
|
+
result += chunk.intro;
|
|
1994
|
+
}
|
|
1995
|
+
const containsEnd = chunk.start < end && chunk.end >= end;
|
|
1996
|
+
if (containsEnd && chunk.edited && chunk.end !== end)
|
|
1997
|
+
throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
|
|
1998
|
+
const sliceStart = startChunk === chunk ? start - chunk.start : 0;
|
|
1999
|
+
const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
|
|
2000
|
+
result += chunk.content.slice(sliceStart, sliceEnd);
|
|
2001
|
+
if (chunk.outro && (!containsEnd || chunk.end === end)) {
|
|
2002
|
+
result += chunk.outro;
|
|
2003
|
+
}
|
|
2004
|
+
if (containsEnd) {
|
|
2005
|
+
break;
|
|
2006
|
+
}
|
|
2007
|
+
chunk = chunk.next;
|
|
2008
|
+
}
|
|
2009
|
+
return result;
|
|
2010
|
+
}
|
|
2011
|
+
// TODO deprecate this? not really very useful
|
|
2012
|
+
snip(start, end) {
|
|
2013
|
+
const clone = this.clone();
|
|
2014
|
+
clone.remove(0, start);
|
|
2015
|
+
clone.remove(end, clone.original.length);
|
|
2016
|
+
return clone;
|
|
2017
|
+
}
|
|
2018
|
+
_split(index) {
|
|
2019
|
+
if (this.byStart[index] || this.byEnd[index]) return;
|
|
2020
|
+
let chunk = this.lastSearchedChunk;
|
|
2021
|
+
let previousChunk = chunk;
|
|
2022
|
+
const searchForward = index > chunk.end;
|
|
2023
|
+
while (chunk) {
|
|
2024
|
+
if (chunk.contains(index)) return this._splitChunk(chunk, index);
|
|
2025
|
+
chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
|
|
2026
|
+
if (chunk === previousChunk) return;
|
|
2027
|
+
previousChunk = chunk;
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
_splitChunk(chunk, index) {
|
|
2031
|
+
if (chunk.edited && chunk.content.length) {
|
|
2032
|
+
const loc = getLocator(this.original)(index);
|
|
2033
|
+
throw new Error(
|
|
2034
|
+
`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`
|
|
2035
|
+
);
|
|
2036
|
+
}
|
|
2037
|
+
const newChunk = chunk.split(index);
|
|
2038
|
+
this.byEnd[index] = chunk;
|
|
2039
|
+
this.byStart[index] = newChunk;
|
|
2040
|
+
this.byEnd[newChunk.end] = newChunk;
|
|
2041
|
+
if (chunk === this.lastChunk) this.lastChunk = newChunk;
|
|
2042
|
+
this.lastSearchedChunk = chunk;
|
|
2043
|
+
return true;
|
|
2044
|
+
}
|
|
2045
|
+
toString() {
|
|
2046
|
+
let str = this.intro;
|
|
2047
|
+
let chunk = this.firstChunk;
|
|
2048
|
+
while (chunk) {
|
|
2049
|
+
str += chunk.toString();
|
|
2050
|
+
chunk = chunk.next;
|
|
2051
|
+
}
|
|
2052
|
+
return str + this.outro;
|
|
2053
|
+
}
|
|
2054
|
+
isEmpty() {
|
|
2055
|
+
let chunk = this.firstChunk;
|
|
2056
|
+
do {
|
|
2057
|
+
if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
|
|
2058
|
+
return false;
|
|
2059
|
+
} while (chunk = chunk.next);
|
|
2060
|
+
return true;
|
|
2061
|
+
}
|
|
2062
|
+
length() {
|
|
2063
|
+
let chunk = this.firstChunk;
|
|
2064
|
+
let length = 0;
|
|
2065
|
+
do {
|
|
2066
|
+
length += chunk.intro.length + chunk.content.length + chunk.outro.length;
|
|
2067
|
+
} while (chunk = chunk.next);
|
|
2068
|
+
return length;
|
|
2069
|
+
}
|
|
2070
|
+
trimLines() {
|
|
2071
|
+
return this.trim("[\\r\\n]");
|
|
2072
|
+
}
|
|
2073
|
+
trim(charType) {
|
|
2074
|
+
return this.trimStart(charType).trimEnd(charType);
|
|
2075
|
+
}
|
|
2076
|
+
trimEndAborted(charType) {
|
|
2077
|
+
const rx = new RegExp((charType || "\\s") + "+$");
|
|
2078
|
+
this.outro = this.outro.replace(rx, "");
|
|
2079
|
+
if (this.outro.length) return true;
|
|
2080
|
+
let chunk = this.lastChunk;
|
|
2081
|
+
do {
|
|
2082
|
+
const end = chunk.end;
|
|
2083
|
+
const aborted = chunk.trimEnd(rx);
|
|
2084
|
+
if (chunk.end !== end) {
|
|
2085
|
+
if (this.lastChunk === chunk) {
|
|
2086
|
+
this.lastChunk = chunk.next;
|
|
2087
|
+
}
|
|
2088
|
+
this.byEnd[chunk.end] = chunk;
|
|
2089
|
+
this.byStart[chunk.next.start] = chunk.next;
|
|
2090
|
+
this.byEnd[chunk.next.end] = chunk.next;
|
|
2091
|
+
}
|
|
2092
|
+
if (aborted) return true;
|
|
2093
|
+
chunk = chunk.previous;
|
|
2094
|
+
} while (chunk);
|
|
2095
|
+
return false;
|
|
2096
|
+
}
|
|
2097
|
+
trimEnd(charType) {
|
|
2098
|
+
this.trimEndAborted(charType);
|
|
2099
|
+
return this;
|
|
2100
|
+
}
|
|
2101
|
+
trimStartAborted(charType) {
|
|
2102
|
+
const rx = new RegExp("^" + (charType || "\\s") + "+");
|
|
2103
|
+
this.intro = this.intro.replace(rx, "");
|
|
2104
|
+
if (this.intro.length) return true;
|
|
2105
|
+
let chunk = this.firstChunk;
|
|
2106
|
+
do {
|
|
2107
|
+
const end = chunk.end;
|
|
2108
|
+
const aborted = chunk.trimStart(rx);
|
|
2109
|
+
if (chunk.end !== end) {
|
|
2110
|
+
if (chunk === this.lastChunk) this.lastChunk = chunk.next;
|
|
2111
|
+
this.byEnd[chunk.end] = chunk;
|
|
2112
|
+
this.byStart[chunk.next.start] = chunk.next;
|
|
2113
|
+
this.byEnd[chunk.next.end] = chunk.next;
|
|
2114
|
+
}
|
|
2115
|
+
if (aborted) return true;
|
|
2116
|
+
chunk = chunk.next;
|
|
2117
|
+
} while (chunk);
|
|
2118
|
+
return false;
|
|
2119
|
+
}
|
|
2120
|
+
trimStart(charType) {
|
|
2121
|
+
this.trimStartAborted(charType);
|
|
2122
|
+
return this;
|
|
2123
|
+
}
|
|
2124
|
+
hasChanged() {
|
|
2125
|
+
return this.original !== this.toString();
|
|
2126
|
+
}
|
|
2127
|
+
_replaceRegexp(searchValue, replacement) {
|
|
2128
|
+
function getReplacement(match, str) {
|
|
2129
|
+
if (typeof replacement === "string") {
|
|
2130
|
+
return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
|
|
2131
|
+
if (i === "$") return "$";
|
|
2132
|
+
if (i === "&") return match[0];
|
|
2133
|
+
const num = +i;
|
|
2134
|
+
if (num < match.length) return match[+i];
|
|
2135
|
+
return `$${i}`;
|
|
2136
|
+
});
|
|
2137
|
+
} else {
|
|
2138
|
+
return replacement(...match, match.index, str, match.groups);
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
function matchAll(re, str) {
|
|
2142
|
+
let match;
|
|
2143
|
+
const matches = [];
|
|
2144
|
+
while (match = re.exec(str)) {
|
|
2145
|
+
matches.push(match);
|
|
2146
|
+
}
|
|
2147
|
+
return matches;
|
|
2148
|
+
}
|
|
2149
|
+
if (searchValue.global) {
|
|
2150
|
+
const matches = matchAll(searchValue, this.original);
|
|
2151
|
+
matches.forEach((match) => {
|
|
2152
|
+
if (match.index != null) {
|
|
2153
|
+
const replacement2 = getReplacement(match, this.original);
|
|
2154
|
+
if (replacement2 !== match[0]) {
|
|
2155
|
+
this.overwrite(match.index, match.index + match[0].length, replacement2);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
});
|
|
2159
|
+
} else {
|
|
2160
|
+
const match = this.original.match(searchValue);
|
|
2161
|
+
if (match && match.index != null) {
|
|
2162
|
+
const replacement2 = getReplacement(match, this.original);
|
|
2163
|
+
if (replacement2 !== match[0]) {
|
|
2164
|
+
this.overwrite(match.index, match.index + match[0].length, replacement2);
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
return this;
|
|
2169
|
+
}
|
|
2170
|
+
_replaceString(string, replacement) {
|
|
2171
|
+
const { original } = this;
|
|
2172
|
+
const index = original.indexOf(string);
|
|
2173
|
+
if (index !== -1) {
|
|
2174
|
+
if (typeof replacement === "function") {
|
|
2175
|
+
replacement = replacement(string, index, original);
|
|
2176
|
+
}
|
|
2177
|
+
if (string !== replacement) {
|
|
2178
|
+
this.overwrite(index, index + string.length, replacement);
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
return this;
|
|
2182
|
+
}
|
|
2183
|
+
replace(searchValue, replacement) {
|
|
2184
|
+
if (typeof searchValue === "string") {
|
|
2185
|
+
return this._replaceString(searchValue, replacement);
|
|
2186
|
+
}
|
|
2187
|
+
return this._replaceRegexp(searchValue, replacement);
|
|
2188
|
+
}
|
|
2189
|
+
_replaceAllString(string, replacement) {
|
|
2190
|
+
const { original } = this;
|
|
2191
|
+
const stringLength = string.length;
|
|
2192
|
+
for (let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)) {
|
|
2193
|
+
const previous = original.slice(index, index + stringLength);
|
|
2194
|
+
let _replacement = replacement;
|
|
2195
|
+
if (typeof replacement === "function") {
|
|
2196
|
+
_replacement = replacement(previous, index, original);
|
|
2197
|
+
}
|
|
2198
|
+
if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
|
|
2199
|
+
}
|
|
2200
|
+
return this;
|
|
2201
|
+
}
|
|
2202
|
+
replaceAll(searchValue, replacement) {
|
|
2203
|
+
if (typeof searchValue === "string") {
|
|
2204
|
+
return this._replaceAllString(searchValue, replacement);
|
|
2205
|
+
}
|
|
2206
|
+
if (!searchValue.global) {
|
|
2207
|
+
throw new TypeError(
|
|
2208
|
+
"MagicString.prototype.replaceAll called with a non-global RegExp argument"
|
|
2209
|
+
);
|
|
2210
|
+
}
|
|
2211
|
+
return this._replaceRegexp(searchValue, replacement);
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
function resolveDefaultOptions(options) {
|
|
2216
|
+
return {
|
|
2217
|
+
...options,
|
|
2218
|
+
compilerOptions: options.compilerOptions ?? {},
|
|
2219
|
+
respectExternal: options.respectExternal ?? false,
|
|
2220
|
+
includeExternal: options.includeExternal ?? []
|
|
2221
|
+
};
|
|
2222
|
+
}
|
|
2223
|
+
const DTS_EXTENSIONS = /\.d\.(c|m)?tsx?$/;
|
|
2224
|
+
const JSON_EXTENSIONS = /\.json$/;
|
|
2225
|
+
const SUPPORTED_EXTENSIONS = /((\.d)?\.(c|m)?(t|j)sx?|\.json)$/;
|
|
2226
|
+
function trimExtension(path2) {
|
|
2227
|
+
return path2.replace(SUPPORTED_EXTENSIONS, "");
|
|
2228
|
+
}
|
|
2229
|
+
function getDeclarationId(path2) {
|
|
2230
|
+
return path2.replace(SUPPORTED_EXTENSIONS, ".d.ts");
|
|
2231
|
+
}
|
|
2232
|
+
function parse(fileName, code) {
|
|
2233
|
+
return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true);
|
|
2234
|
+
}
|
|
2235
|
+
const formatHost = {
|
|
2236
|
+
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
|
|
2237
|
+
getNewLine: () => ts.sys.newLine,
|
|
2238
|
+
getCanonicalFileName: ts.sys.useCaseSensitiveFileNames ? (f) => f : (f) => f.toLowerCase()
|
|
2239
|
+
};
|
|
2240
|
+
const DEFAULT_OPTIONS = {
|
|
2241
|
+
// Ensure ".d.ts" modules are generated
|
|
2242
|
+
declaration: true,
|
|
2243
|
+
// Skip ".js" generation
|
|
2244
|
+
noEmit: false,
|
|
2245
|
+
emitDeclarationOnly: true,
|
|
2246
|
+
// Skip code generation when error occurs
|
|
2247
|
+
noEmitOnError: true,
|
|
2248
|
+
// Avoid extra work
|
|
2249
|
+
checkJs: false,
|
|
2250
|
+
declarationMap: false,
|
|
2251
|
+
skipLibCheck: true,
|
|
2252
|
+
// Ensure TS2742 errors are visible
|
|
2253
|
+
preserveSymlinks: true,
|
|
2254
|
+
// Ensure we can parse the latest code
|
|
2255
|
+
target: ts.ScriptTarget.ESNext,
|
|
2256
|
+
// Allows importing `*.json`
|
|
2257
|
+
resolveJsonModule: true
|
|
2258
|
+
};
|
|
2259
|
+
const configByPath = /* @__PURE__ */ new Map();
|
|
2260
|
+
const logCache = (...args) => process.env.DTS_LOG_CACHE ? console.log("[cache]", ...args) : null;
|
|
2261
|
+
function cacheConfig([fromPath, toPath], config) {
|
|
2262
|
+
logCache(fromPath);
|
|
2263
|
+
configByPath.set(fromPath, config);
|
|
2264
|
+
while (fromPath !== toPath && // make sure we're not stuck in an infinite loop
|
|
2265
|
+
fromPath !== path.dirname(fromPath)) {
|
|
2266
|
+
fromPath = path.dirname(fromPath);
|
|
2267
|
+
logCache("up", fromPath);
|
|
2268
|
+
if (configByPath.has(fromPath))
|
|
2269
|
+
return logCache("has", fromPath);
|
|
2270
|
+
configByPath.set(fromPath, config);
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
function getCompilerOptions(input, overrideOptions, overrideConfigPath) {
|
|
2274
|
+
const compilerOptions = { ...DEFAULT_OPTIONS, ...overrideOptions };
|
|
2275
|
+
let dirName = path.dirname(input);
|
|
2276
|
+
let dtsFiles = [];
|
|
2277
|
+
const cacheKey = overrideConfigPath || dirName;
|
|
2278
|
+
if (!configByPath.has(cacheKey)) {
|
|
2279
|
+
logCache("miss", cacheKey);
|
|
2280
|
+
const configPath = overrideConfigPath ? path.resolve(process.cwd(), overrideConfigPath) : ts.findConfigFile(dirName, ts.sys.fileExists);
|
|
2281
|
+
if (!configPath) {
|
|
2282
|
+
return { dtsFiles, dirName, compilerOptions };
|
|
2283
|
+
}
|
|
2284
|
+
const inputDirName = dirName;
|
|
2285
|
+
dirName = path.dirname(configPath);
|
|
2286
|
+
const { config, error } = ts.readConfigFile(configPath, ts.sys.readFile);
|
|
2287
|
+
if (error) {
|
|
2288
|
+
console.error(ts.formatDiagnostic(error, formatHost));
|
|
2289
|
+
return { dtsFiles, dirName, compilerOptions };
|
|
2290
|
+
}
|
|
2291
|
+
logCache("tsconfig", config);
|
|
2292
|
+
const configContents = ts.parseJsonConfigFileContent(config, ts.sys, dirName);
|
|
2293
|
+
if (overrideConfigPath) {
|
|
2294
|
+
cacheConfig([overrideConfigPath, overrideConfigPath], configContents);
|
|
2295
|
+
} else {
|
|
2296
|
+
cacheConfig([inputDirName, dirName], configContents);
|
|
2297
|
+
}
|
|
2298
|
+
} else {
|
|
2299
|
+
logCache("HIT", cacheKey);
|
|
2300
|
+
}
|
|
2301
|
+
const { fileNames, options, errors } = configByPath.get(cacheKey);
|
|
2302
|
+
dtsFiles = fileNames.filter((name) => DTS_EXTENSIONS.test(name));
|
|
2303
|
+
if (errors.length) {
|
|
2304
|
+
console.error(ts.formatDiagnostics(errors, formatHost));
|
|
2305
|
+
return { dtsFiles, dirName, compilerOptions };
|
|
2306
|
+
}
|
|
2307
|
+
return {
|
|
2308
|
+
dtsFiles,
|
|
2309
|
+
dirName,
|
|
2310
|
+
compilerOptions: {
|
|
2311
|
+
...options,
|
|
2312
|
+
...compilerOptions
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
function createProgram$1(fileName, overrideOptions, tsconfig) {
|
|
2317
|
+
const { dtsFiles, compilerOptions } = getCompilerOptions(fileName, overrideOptions, tsconfig);
|
|
2318
|
+
return ts.createProgram([fileName].concat(Array.from(dtsFiles)), compilerOptions, ts.createCompilerHost(compilerOptions, true));
|
|
2319
|
+
}
|
|
2320
|
+
function createPrograms(input, overrideOptions, tsconfig) {
|
|
2321
|
+
const programs = [];
|
|
2322
|
+
const dtsFiles = /* @__PURE__ */ new Set();
|
|
2323
|
+
let inputs = [];
|
|
2324
|
+
let dirName = "";
|
|
2325
|
+
let compilerOptions = {};
|
|
2326
|
+
for (let main of input) {
|
|
2327
|
+
if (DTS_EXTENSIONS.test(main)) {
|
|
2328
|
+
continue;
|
|
2329
|
+
}
|
|
2330
|
+
main = path.resolve(main);
|
|
2331
|
+
const options = getCompilerOptions(main, overrideOptions, tsconfig);
|
|
2332
|
+
options.dtsFiles.forEach(dtsFiles.add, dtsFiles);
|
|
2333
|
+
if (!inputs.length) {
|
|
2334
|
+
inputs.push(main);
|
|
2335
|
+
({ dirName, compilerOptions } = options);
|
|
2336
|
+
continue;
|
|
2337
|
+
}
|
|
2338
|
+
if (options.dirName === dirName) {
|
|
2339
|
+
inputs.push(main);
|
|
2340
|
+
} else {
|
|
2341
|
+
const host = ts.createCompilerHost(compilerOptions, true);
|
|
2342
|
+
const program = ts.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
|
|
2343
|
+
programs.push(program);
|
|
2344
|
+
inputs = [main];
|
|
2345
|
+
({ dirName, compilerOptions } = options);
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
if (inputs.length) {
|
|
2349
|
+
const host = ts.createCompilerHost(compilerOptions, true);
|
|
2350
|
+
const program = ts.createProgram(inputs.concat(Array.from(dtsFiles)), compilerOptions, host);
|
|
2351
|
+
programs.push(program);
|
|
2352
|
+
}
|
|
2353
|
+
return programs;
|
|
2354
|
+
}
|
|
2355
|
+
function getCodeFrame() {
|
|
2356
|
+
let codeFrameColumns = void 0;
|
|
2357
|
+
try {
|
|
2358
|
+
({ codeFrameColumns } = require("@babel/code-frame"));
|
|
2359
|
+
return codeFrameColumns;
|
|
2360
|
+
} catch {
|
|
2361
|
+
try {
|
|
2362
|
+
const esmRequire = createRequire(import.meta.url);
|
|
2363
|
+
({ codeFrameColumns } = esmRequire("@babel/code-frame"));
|
|
2364
|
+
return codeFrameColumns;
|
|
2365
|
+
} catch {
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
return void 0;
|
|
2369
|
+
}
|
|
2370
|
+
function getLocation(node) {
|
|
2371
|
+
const sourceFile = node.getSourceFile();
|
|
2372
|
+
const start = sourceFile.getLineAndCharacterOfPosition(node.getStart());
|
|
2373
|
+
const end = sourceFile.getLineAndCharacterOfPosition(node.getEnd());
|
|
2374
|
+
return {
|
|
2375
|
+
start: { line: start.line + 1, column: start.character + 1 },
|
|
2376
|
+
end: { line: end.line + 1, column: end.character + 1 }
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
function frameNode(node) {
|
|
2380
|
+
const codeFrame = getCodeFrame();
|
|
2381
|
+
const sourceFile = node.getSourceFile();
|
|
2382
|
+
const code = sourceFile.getFullText();
|
|
2383
|
+
const location = getLocation(node);
|
|
2384
|
+
if (codeFrame) {
|
|
2385
|
+
return "\n" + codeFrame(code, location, {
|
|
2386
|
+
highlightCode: true
|
|
2387
|
+
});
|
|
2388
|
+
} else {
|
|
2389
|
+
return `
|
|
2390
|
+
${location.start.line}:${location.start.column}: \`${node.getFullText().trim()}\``;
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
class UnsupportedSyntaxError extends Error {
|
|
2394
|
+
constructor(node, message = "Syntax not yet supported") {
|
|
2395
|
+
super(`${message}
|
|
2396
|
+
${frameNode(node)}`);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
class NamespaceFixer {
|
|
2400
|
+
constructor(sourceFile) {
|
|
2401
|
+
this.sourceFile = sourceFile;
|
|
2402
|
+
}
|
|
2403
|
+
findNamespaces() {
|
|
2404
|
+
const namespaces = [];
|
|
2405
|
+
const items = {};
|
|
2406
|
+
for (const node of this.sourceFile.statements) {
|
|
2407
|
+
const location = {
|
|
2408
|
+
start: node.getStart(),
|
|
2409
|
+
end: node.getEnd()
|
|
2410
|
+
};
|
|
2411
|
+
if (ts.isEmptyStatement(node)) {
|
|
2412
|
+
namespaces.unshift({
|
|
2413
|
+
name: "",
|
|
2414
|
+
exports: [],
|
|
2415
|
+
location
|
|
2416
|
+
});
|
|
2417
|
+
continue;
|
|
2418
|
+
}
|
|
2419
|
+
if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
|
|
2420
|
+
const { text } = node.moduleSpecifier;
|
|
2421
|
+
if (text.startsWith(".") && (text.endsWith(".d.ts") || text.endsWith(".d.cts") || text.endsWith(".d.mts"))) {
|
|
2422
|
+
const start = node.moduleSpecifier.getStart() + 1;
|
|
2423
|
+
const end = node.moduleSpecifier.getEnd() - 1;
|
|
2424
|
+
namespaces.unshift({
|
|
2425
|
+
name: "",
|
|
2426
|
+
exports: [],
|
|
2427
|
+
location: {
|
|
2428
|
+
start,
|
|
2429
|
+
end
|
|
2430
|
+
},
|
|
2431
|
+
textBeforeCodeAfter: text.replace(/\.d\.ts$/, ".js").replace(/\.d\.cts$/, ".cjs").replace(/\.d\.mts$/, ".mjs")
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
}
|
|
2435
|
+
if (ts.isModuleDeclaration(node) && node.body && ts.isModuleBlock(node.body)) {
|
|
2436
|
+
for (const stmt of node.body.statements) {
|
|
2437
|
+
if (ts.isExportDeclaration(stmt) && stmt.exportClause) {
|
|
2438
|
+
if (ts.isNamespaceExport(stmt.exportClause)) {
|
|
2439
|
+
continue;
|
|
2440
|
+
}
|
|
2441
|
+
for (const decl2 of stmt.exportClause.elements) {
|
|
2442
|
+
if (decl2.propertyName && decl2.propertyName.getText() == decl2.name.getText()) {
|
|
2443
|
+
namespaces.unshift({
|
|
2444
|
+
name: "",
|
|
2445
|
+
exports: [],
|
|
2446
|
+
location: {
|
|
2447
|
+
start: decl2.propertyName.getEnd(),
|
|
2448
|
+
end: decl2.name.getEnd()
|
|
2449
|
+
}
|
|
2450
|
+
});
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
if (ts.isClassDeclaration(node)) {
|
|
2457
|
+
items[node.name.getText()] = { type: "class", generics: node.typeParameters };
|
|
2458
|
+
} else if (ts.isFunctionDeclaration(node)) {
|
|
2459
|
+
items[node.name.getText()] = { type: "function" };
|
|
2460
|
+
} else if (ts.isInterfaceDeclaration(node)) {
|
|
2461
|
+
items[node.name.getText()] = { type: "interface", generics: node.typeParameters };
|
|
2462
|
+
} else if (ts.isTypeAliasDeclaration(node)) {
|
|
2463
|
+
items[node.name.getText()] = { type: "type", generics: node.typeParameters };
|
|
2464
|
+
} else if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)) {
|
|
2465
|
+
items[node.name.getText()] = { type: "namespace" };
|
|
2466
|
+
} else if (ts.isEnumDeclaration(node)) {
|
|
2467
|
+
items[node.name.getText()] = { type: "enum" };
|
|
2468
|
+
}
|
|
2469
|
+
if (!ts.isVariableStatement(node)) {
|
|
2470
|
+
continue;
|
|
2471
|
+
}
|
|
2472
|
+
const { declarations } = node.declarationList;
|
|
2473
|
+
if (declarations.length !== 1) {
|
|
2474
|
+
continue;
|
|
2475
|
+
}
|
|
2476
|
+
const decl = declarations[0];
|
|
2477
|
+
const name = decl.name.getText();
|
|
2478
|
+
if (!decl.initializer || !ts.isCallExpression(decl.initializer)) {
|
|
2479
|
+
items[name] = { type: "var" };
|
|
2480
|
+
continue;
|
|
2481
|
+
}
|
|
2482
|
+
const obj = decl.initializer.arguments[0];
|
|
2483
|
+
if (!decl.initializer.expression.getFullText().includes("/*#__PURE__*/Object.freeze") || !ts.isObjectLiteralExpression(obj)) {
|
|
2484
|
+
continue;
|
|
2485
|
+
}
|
|
2486
|
+
const exports$1 = [];
|
|
2487
|
+
for (const prop of obj.properties) {
|
|
2488
|
+
if (!ts.isPropertyAssignment(prop) || !(ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) || prop.name.text !== "__proto__" && !ts.isIdentifier(prop.initializer)) {
|
|
2489
|
+
throw new UnsupportedSyntaxError(prop, "Expected a property assignment");
|
|
2490
|
+
}
|
|
2491
|
+
if (prop.name.text === "__proto__") {
|
|
2492
|
+
continue;
|
|
2493
|
+
}
|
|
2494
|
+
exports$1.push({
|
|
2495
|
+
exportedName: prop.name.text,
|
|
2496
|
+
localName: prop.initializer.getText()
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
namespaces.unshift({
|
|
2500
|
+
name,
|
|
2501
|
+
exports: exports$1,
|
|
2502
|
+
location
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
return { namespaces, itemTypes: items };
|
|
2506
|
+
}
|
|
2507
|
+
fix() {
|
|
2508
|
+
let code = this.sourceFile.getFullText();
|
|
2509
|
+
const { namespaces, itemTypes } = this.findNamespaces();
|
|
2510
|
+
for (const ns of namespaces) {
|
|
2511
|
+
const codeAfter = code.slice(ns.location.end);
|
|
2512
|
+
code = code.slice(0, ns.location.start);
|
|
2513
|
+
for (const { exportedName, localName } of ns.exports) {
|
|
2514
|
+
if (exportedName === localName) {
|
|
2515
|
+
const { type, generics } = itemTypes[localName] || {};
|
|
2516
|
+
if (type === "interface" || type === "type") {
|
|
2517
|
+
const typeParams = renderTypeParams(generics);
|
|
2518
|
+
code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};
|
|
2519
|
+
`;
|
|
2520
|
+
} else if (type === "enum" || type === "class") {
|
|
2521
|
+
const typeParams = renderTypeParams(generics);
|
|
2522
|
+
code += `type ${ns.name}_${exportedName}${typeParams.in} = ${localName}${typeParams.out};
|
|
2523
|
+
`;
|
|
2524
|
+
code += `declare const ${ns.name}_${exportedName}: typeof ${localName};
|
|
2525
|
+
`;
|
|
2526
|
+
} else if (type === "namespace") {
|
|
2527
|
+
code += `import ${ns.name}_${exportedName} = ${localName};
|
|
2528
|
+
`;
|
|
2529
|
+
} else {
|
|
2530
|
+
code += `declare const ${ns.name}_${exportedName}: typeof ${localName};
|
|
2531
|
+
`;
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
if (ns.name) {
|
|
2536
|
+
code += `declare namespace ${ns.name} {
|
|
2537
|
+
`;
|
|
2538
|
+
code += ` export {
|
|
2539
|
+
`;
|
|
2540
|
+
for (const { exportedName, localName } of ns.exports) {
|
|
2541
|
+
if (exportedName === localName) {
|
|
2542
|
+
code += ` ${ns.name}_${exportedName} as ${exportedName},
|
|
2543
|
+
`;
|
|
2544
|
+
} else {
|
|
2545
|
+
code += ` ${localName} as ${exportedName},
|
|
2546
|
+
`;
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
code += ` };
|
|
2550
|
+
`;
|
|
2551
|
+
code += `}`;
|
|
2552
|
+
}
|
|
2553
|
+
code += ns.textBeforeCodeAfter ?? "";
|
|
2554
|
+
code += codeAfter;
|
|
2555
|
+
}
|
|
2556
|
+
return code;
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
function renderTypeParams(typeParameters) {
|
|
2560
|
+
if (!typeParameters || !typeParameters.length) {
|
|
2561
|
+
return { in: "", out: "" };
|
|
2562
|
+
}
|
|
2563
|
+
return {
|
|
2564
|
+
in: `<${typeParameters.map((param) => param.getText()).join(", ")}>`,
|
|
2565
|
+
out: `<${typeParameters.map((param) => param.name.getText()).join(", ")}>`
|
|
2566
|
+
};
|
|
2567
|
+
}
|
|
2568
|
+
let IDs = 1;
|
|
2569
|
+
function createProgram(node) {
|
|
2570
|
+
return withStartEnd({
|
|
2571
|
+
type: "Program",
|
|
2572
|
+
sourceType: "module",
|
|
2573
|
+
body: []
|
|
2574
|
+
}, { start: node.getFullStart(), end: node.getEnd() });
|
|
2575
|
+
}
|
|
2576
|
+
function createReference(id) {
|
|
2577
|
+
const ident = {
|
|
2578
|
+
type: "Identifier",
|
|
2579
|
+
name: String(IDs++)
|
|
2580
|
+
};
|
|
2581
|
+
return {
|
|
2582
|
+
ident,
|
|
2583
|
+
expr: {
|
|
2584
|
+
type: "AssignmentPattern",
|
|
2585
|
+
left: ident,
|
|
2586
|
+
right: id
|
|
2587
|
+
}
|
|
2588
|
+
};
|
|
2589
|
+
}
|
|
2590
|
+
function createIdentifier(node) {
|
|
2591
|
+
return withStartEnd({
|
|
2592
|
+
type: "Identifier",
|
|
2593
|
+
name: node.getText()
|
|
2594
|
+
}, node);
|
|
2595
|
+
}
|
|
2596
|
+
function createIIFE(range) {
|
|
2597
|
+
const fn = withStartEnd({
|
|
2598
|
+
type: "FunctionExpression",
|
|
2599
|
+
id: null,
|
|
2600
|
+
params: [],
|
|
2601
|
+
body: { type: "BlockStatement", body: [] }
|
|
2602
|
+
}, range);
|
|
2603
|
+
const iife = withStartEnd({
|
|
2604
|
+
type: "ExpressionStatement",
|
|
2605
|
+
expression: {
|
|
2606
|
+
type: "CallExpression",
|
|
2607
|
+
callee: { type: "Identifier", name: String(IDs++) },
|
|
2608
|
+
arguments: [fn],
|
|
2609
|
+
optional: false
|
|
2610
|
+
}
|
|
2611
|
+
}, range);
|
|
2612
|
+
return { fn, iife };
|
|
2613
|
+
}
|
|
2614
|
+
function createReturn() {
|
|
2615
|
+
const expr = {
|
|
2616
|
+
type: "ArrayExpression",
|
|
2617
|
+
elements: []
|
|
2618
|
+
};
|
|
2619
|
+
return {
|
|
2620
|
+
expr,
|
|
2621
|
+
stmt: {
|
|
2622
|
+
type: "ReturnStatement",
|
|
2623
|
+
argument: expr
|
|
2624
|
+
}
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
function createDeclaration(id, range) {
|
|
2628
|
+
return withStartEnd({
|
|
2629
|
+
type: "FunctionDeclaration",
|
|
2630
|
+
id: withStartEnd({
|
|
2631
|
+
type: "Identifier",
|
|
2632
|
+
name: ts.idText(id)
|
|
2633
|
+
}, id),
|
|
2634
|
+
params: [],
|
|
2635
|
+
body: { type: "BlockStatement", body: [] }
|
|
2636
|
+
}, range);
|
|
2637
|
+
}
|
|
2638
|
+
function convertExpression(node) {
|
|
2639
|
+
if (ts.isLiteralExpression(node)) {
|
|
2640
|
+
return { type: "Literal", value: node.text };
|
|
2641
|
+
}
|
|
2642
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
2643
|
+
if (ts.isPrivateIdentifier(node.name)) {
|
|
2644
|
+
throw new UnsupportedSyntaxError(node.name);
|
|
2645
|
+
}
|
|
2646
|
+
return withStartEnd({
|
|
2647
|
+
type: "MemberExpression",
|
|
2648
|
+
computed: false,
|
|
2649
|
+
optional: false,
|
|
2650
|
+
object: convertExpression(node.expression),
|
|
2651
|
+
property: convertExpression(node.name)
|
|
2652
|
+
}, {
|
|
2653
|
+
start: node.expression.getStart(),
|
|
2654
|
+
end: node.name.getEnd()
|
|
2655
|
+
});
|
|
2656
|
+
}
|
|
2657
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
2658
|
+
return withStartEnd({
|
|
2659
|
+
type: "ObjectExpression",
|
|
2660
|
+
properties: node.properties.map((prop) => {
|
|
2661
|
+
if (ts.isPropertyAssignment(prop)) {
|
|
2662
|
+
return withStartEnd({
|
|
2663
|
+
type: "Property",
|
|
2664
|
+
key: ts.isIdentifier(prop.name) ? createIdentifier(prop.name) : convertExpression(prop.name),
|
|
2665
|
+
value: convertExpression(prop.initializer),
|
|
2666
|
+
kind: "init",
|
|
2667
|
+
method: false,
|
|
2668
|
+
shorthand: false,
|
|
2669
|
+
computed: ts.isComputedPropertyName(prop.name)
|
|
2670
|
+
}, prop);
|
|
2671
|
+
} else if (ts.isShorthandPropertyAssignment(prop)) {
|
|
2672
|
+
return withStartEnd({
|
|
2673
|
+
type: "Property",
|
|
2674
|
+
key: createIdentifier(prop.name),
|
|
2675
|
+
value: createIdentifier(prop.name),
|
|
2676
|
+
kind: "init",
|
|
2677
|
+
method: false,
|
|
2678
|
+
shorthand: true,
|
|
2679
|
+
computed: false
|
|
2680
|
+
}, prop);
|
|
2681
|
+
} else {
|
|
2682
|
+
throw new UnsupportedSyntaxError(prop, "Unsupported property type in object literal");
|
|
2683
|
+
}
|
|
2684
|
+
})
|
|
2685
|
+
}, node);
|
|
2686
|
+
}
|
|
2687
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
2688
|
+
return withStartEnd({
|
|
2689
|
+
type: "ArrayExpression",
|
|
2690
|
+
elements: node.elements.map((elem) => {
|
|
2691
|
+
if (ts.isExpression(elem)) {
|
|
2692
|
+
return convertExpression(elem);
|
|
2693
|
+
} else {
|
|
2694
|
+
throw new UnsupportedSyntaxError(elem, "Unsupported element type in array literal");
|
|
2695
|
+
}
|
|
2696
|
+
})
|
|
2697
|
+
}, node);
|
|
2698
|
+
}
|
|
2699
|
+
if (ts.isIdentifier(node)) {
|
|
2700
|
+
return createIdentifier(node);
|
|
2701
|
+
} else if (node.kind == ts.SyntaxKind.NullKeyword) {
|
|
2702
|
+
return { type: "Literal", value: null };
|
|
2703
|
+
} else {
|
|
2704
|
+
throw new UnsupportedSyntaxError(node);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
function withStartEnd(esNode, nodeOrRange) {
|
|
2708
|
+
const range = "start" in nodeOrRange ? nodeOrRange : { start: nodeOrRange.getStart(), end: nodeOrRange.getEnd() };
|
|
2709
|
+
return Object.assign(esNode, range);
|
|
2710
|
+
}
|
|
2711
|
+
function matchesModifier(node, flags) {
|
|
2712
|
+
const nodeFlags = ts.getCombinedModifierFlags(node);
|
|
2713
|
+
return (nodeFlags & flags) === flags;
|
|
2714
|
+
}
|
|
2715
|
+
class LanguageService {
|
|
2716
|
+
constructor(code) {
|
|
2717
|
+
this.fileName = "index.d.ts";
|
|
2718
|
+
const serviceHost = {
|
|
2719
|
+
getCompilationSettings: () => ({
|
|
2720
|
+
noEmit: true,
|
|
2721
|
+
noResolve: true,
|
|
2722
|
+
skipLibCheck: true,
|
|
2723
|
+
declaration: false,
|
|
2724
|
+
checkJs: false,
|
|
2725
|
+
declarationMap: false,
|
|
2726
|
+
target: ts.ScriptTarget.ESNext
|
|
2727
|
+
}),
|
|
2728
|
+
getScriptFileNames: () => [this.fileName],
|
|
2729
|
+
getScriptVersion: () => "1",
|
|
2730
|
+
getScriptSnapshot: (fileName) => fileName === this.fileName ? ts.ScriptSnapshot.fromString(code) : void 0,
|
|
2731
|
+
getCurrentDirectory: () => "",
|
|
2732
|
+
getDefaultLibFileName: () => "",
|
|
2733
|
+
fileExists: (fileName) => fileName === this.fileName,
|
|
2734
|
+
readFile: (fileName) => fileName === this.fileName ? code : void 0
|
|
2735
|
+
};
|
|
2736
|
+
this.service = ts.createLanguageService(serviceHost, ts.createDocumentRegistry(void 0, ""), ts.LanguageServiceMode.PartialSemantic);
|
|
2737
|
+
}
|
|
2738
|
+
findReferenceCount(node) {
|
|
2739
|
+
const referencedSymbols = this.service.findReferences(this.fileName, node.getStart());
|
|
2740
|
+
if (!referencedSymbols?.length) {
|
|
2741
|
+
return 0;
|
|
2742
|
+
}
|
|
2743
|
+
return referencedSymbols.reduce((total, symbol) => total + symbol.references.length, 0);
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
class TypeOnlyFixer {
|
|
2747
|
+
constructor(fileName, rawCode) {
|
|
2748
|
+
this.DEBUG = !!process.env.DTS_EXPORTS_FIXER_DEBUG;
|
|
2749
|
+
this.types = /* @__PURE__ */ new Set();
|
|
2750
|
+
this.values = /* @__PURE__ */ new Set();
|
|
2751
|
+
this.typeHints = /* @__PURE__ */ new Map();
|
|
2752
|
+
this.reExportTypeHints = /* @__PURE__ */ new Map();
|
|
2753
|
+
this.importNodes = [];
|
|
2754
|
+
this.exportNodes = [];
|
|
2755
|
+
this.rawCode = rawCode;
|
|
2756
|
+
this.source = parse(fileName, rawCode);
|
|
2757
|
+
this.code = new MagicString(rawCode);
|
|
2758
|
+
}
|
|
2759
|
+
fix() {
|
|
2760
|
+
this.analyze(this.source.statements);
|
|
2761
|
+
if (this.typeHints.size || this.reExportTypeHints.size) {
|
|
2762
|
+
this.service = new LanguageService(this.rawCode);
|
|
2763
|
+
this.importNodes.forEach((node) => this.fixTypeOnlyImport(node));
|
|
2764
|
+
}
|
|
2765
|
+
if (this.types.size) {
|
|
2766
|
+
this.exportNodes.forEach((node) => this.fixTypeOnlyExport(node));
|
|
2767
|
+
}
|
|
2768
|
+
return this.types.size ? {
|
|
2769
|
+
magicCode: this.code
|
|
2770
|
+
} : {
|
|
2771
|
+
code: this.rawCode,
|
|
2772
|
+
map: null
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
fixTypeOnlyImport(node) {
|
|
2776
|
+
let hasRemoved = false;
|
|
2777
|
+
const typeImports = [];
|
|
2778
|
+
const valueImports = [];
|
|
2779
|
+
const specifier = node.moduleSpecifier.getText();
|
|
2780
|
+
const nameNode = node.importClause.name;
|
|
2781
|
+
const namedBindings = node.importClause.namedBindings;
|
|
2782
|
+
if (nameNode) {
|
|
2783
|
+
const name = nameNode.text;
|
|
2784
|
+
if (this.isTypeOnly(name)) {
|
|
2785
|
+
if (this.isUselessImport(nameNode)) {
|
|
2786
|
+
hasRemoved = true;
|
|
2787
|
+
} else {
|
|
2788
|
+
typeImports.push(`import type ${name} from ${specifier};`);
|
|
2789
|
+
}
|
|
2790
|
+
} else {
|
|
2791
|
+
valueImports.push(`import ${name} from ${specifier};`);
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
if (namedBindings && ts.isNamespaceImport(namedBindings)) {
|
|
2795
|
+
const name = namedBindings.name.text;
|
|
2796
|
+
if (this.isTypeOnly(name)) {
|
|
2797
|
+
if (this.isUselessImport(namedBindings.name)) {
|
|
2798
|
+
hasRemoved = true;
|
|
2799
|
+
} else {
|
|
2800
|
+
typeImports.push(`import type * as ${name} from ${specifier};`);
|
|
2801
|
+
}
|
|
2802
|
+
} else {
|
|
2803
|
+
valueImports.push(`import * as ${name} from ${specifier};`);
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
if (namedBindings && ts.isNamedImports(namedBindings)) {
|
|
2807
|
+
const typeNames = [];
|
|
2808
|
+
const valueNames = [];
|
|
2809
|
+
for (const element of namedBindings.elements) {
|
|
2810
|
+
if (this.isTypeOnly(element.name.text)) {
|
|
2811
|
+
if (this.isUselessImport(element.name)) {
|
|
2812
|
+
hasRemoved = true;
|
|
2813
|
+
} else {
|
|
2814
|
+
typeNames.push(element.getText());
|
|
2815
|
+
}
|
|
2816
|
+
} else {
|
|
2817
|
+
valueNames.push(element.getText());
|
|
2818
|
+
}
|
|
2819
|
+
}
|
|
2820
|
+
if (typeNames.length) {
|
|
2821
|
+
typeImports.push(`import type { ${typeNames.join(", ")} } from ${specifier};`);
|
|
2822
|
+
}
|
|
2823
|
+
if (valueNames.length) {
|
|
2824
|
+
valueImports.push(`import { ${valueNames.join(", ")} } from ${specifier};`);
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
if (typeImports.length || hasRemoved) {
|
|
2828
|
+
this.code.overwrite(node.getStart(), node.getEnd(), [...valueImports, ...typeImports].join(`
|
|
2829
|
+
${getNodeIndent(node)}`));
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
fixTypeOnlyExport(node) {
|
|
2833
|
+
const typeExports = [];
|
|
2834
|
+
const valueExports = [];
|
|
2835
|
+
const specifier = node.moduleSpecifier?.getText();
|
|
2836
|
+
if (ts.isNamespaceExport(node.exportClause)) {
|
|
2837
|
+
const name = node.exportClause.name.text;
|
|
2838
|
+
if (this.isReExportTypeOnly(name)) {
|
|
2839
|
+
typeExports.push(`export type * as ${name} from ${specifier};`);
|
|
2840
|
+
} else {
|
|
2841
|
+
valueExports.push(`export * as ${name} from ${specifier};`);
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
if (ts.isNamedExports(node.exportClause)) {
|
|
2845
|
+
const typeNames = [];
|
|
2846
|
+
const valueNames = [];
|
|
2847
|
+
for (const element of node.exportClause.elements) {
|
|
2848
|
+
const name = element.propertyName?.text || element.name.text;
|
|
2849
|
+
const isType = node.moduleSpecifier ? this.isReExportTypeOnly(element.name.text) : this.isTypeOnly(name);
|
|
2850
|
+
if (isType) {
|
|
2851
|
+
typeNames.push(element.getText());
|
|
2852
|
+
} else {
|
|
2853
|
+
valueNames.push(element.getText());
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
if (typeNames.length) {
|
|
2857
|
+
typeExports.push(`export type { ${typeNames.join(", ")} }${specifier ? ` from ${specifier}` : ""};`);
|
|
2858
|
+
}
|
|
2859
|
+
if (valueNames.length) {
|
|
2860
|
+
valueExports.push(`export { ${valueNames.join(", ")} }${specifier ? ` from ${specifier}` : ""};`);
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
if (typeExports.length) {
|
|
2864
|
+
this.code.overwrite(node.getStart(), node.getEnd(), [...valueExports, ...typeExports].join(`
|
|
2865
|
+
${getNodeIndent(node)}`));
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2868
|
+
analyze(nodes) {
|
|
2869
|
+
for (const node of nodes) {
|
|
2870
|
+
this.DEBUG && console.log(node.getText(), node.kind);
|
|
2871
|
+
if (ts.isImportDeclaration(node) && node.importClause) {
|
|
2872
|
+
this.importNodes.push(node);
|
|
2873
|
+
continue;
|
|
2874
|
+
}
|
|
2875
|
+
if (ts.isExportDeclaration(node) && node.exportClause) {
|
|
2876
|
+
this.exportNodes.push(node);
|
|
2877
|
+
continue;
|
|
2878
|
+
}
|
|
2879
|
+
if (ts.isInterfaceDeclaration(node)) {
|
|
2880
|
+
this.DEBUG && console.log(`${node.name.getFullText()} is a type`);
|
|
2881
|
+
this.types.add(node.name.text);
|
|
2882
|
+
continue;
|
|
2883
|
+
}
|
|
2884
|
+
if (ts.isTypeAliasDeclaration(node)) {
|
|
2885
|
+
const alias = node.name.text;
|
|
2886
|
+
this.DEBUG && console.log(`${node.name.getFullText()} is a type`);
|
|
2887
|
+
this.types.add(alias);
|
|
2888
|
+
continue;
|
|
2889
|
+
}
|
|
2890
|
+
if (ts.isEnumDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isVariableStatement(node)) {
|
|
2891
|
+
if (ts.isVariableStatement(node)) {
|
|
2892
|
+
for (const declaration of node.declarationList.declarations) {
|
|
2893
|
+
if (ts.isIdentifier(declaration.name)) {
|
|
2894
|
+
this.DEBUG && console.log(`${declaration.name.getFullText()} is a value (from var statement)`);
|
|
2895
|
+
this.values.add(declaration.name.text);
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
} else {
|
|
2899
|
+
if (node.name) {
|
|
2900
|
+
this.DEBUG && console.log(`${node.name.getFullText()} is a value (from declaration)`);
|
|
2901
|
+
this.values.add(node.name.text);
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
continue;
|
|
2905
|
+
}
|
|
2906
|
+
if (ts.isModuleBlock(node)) {
|
|
2907
|
+
this.analyze(node.statements);
|
|
2908
|
+
continue;
|
|
2909
|
+
}
|
|
2910
|
+
if (ts.isModuleDeclaration(node)) {
|
|
2911
|
+
if (node.name && ts.isIdentifier(node.name)) {
|
|
2912
|
+
this.DEBUG && console.log(`${node.name.getFullText()} is a value (from module declaration)`);
|
|
2913
|
+
this.values.add(node.name.text);
|
|
2914
|
+
}
|
|
2915
|
+
this.analyze(node.getChildren());
|
|
2916
|
+
continue;
|
|
2917
|
+
}
|
|
2918
|
+
this.DEBUG && console.log("unhandled statement", node.getFullText(), node.kind);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
// The type-hint statements may lead to redundant import statements.
|
|
2922
|
+
// After type-hint statements been removed,
|
|
2923
|
+
// it is better to also remove these redundant import statements as well.
|
|
2924
|
+
// Of course, this is not necessary since it won't cause issues,
|
|
2925
|
+
// but it can make the output bundles cleaner :)
|
|
2926
|
+
isUselessImport(node) {
|
|
2927
|
+
const referenceCount = this.service.findReferenceCount(node);
|
|
2928
|
+
const typeHintCount = this.typeHints.get(node.text);
|
|
2929
|
+
return typeHintCount && typeHintCount + 1 >= referenceCount;
|
|
2930
|
+
}
|
|
2931
|
+
isTypeOnly(name) {
|
|
2932
|
+
return this.typeHints.has(name) || this.types.has(name) && !this.values.has(name);
|
|
2933
|
+
}
|
|
2934
|
+
isReExportTypeOnly(name) {
|
|
2935
|
+
return this.reExportTypeHints.has(name);
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
function getNodeIndent(node) {
|
|
2939
|
+
const match = node.getFullText().match(/^(?:\n*)([ ]*)/);
|
|
2940
|
+
return " ".repeat(match?.[1]?.length || 0);
|
|
2941
|
+
}
|
|
2942
|
+
function preProcessNamespaceBody(body, code, sourceFile) {
|
|
2943
|
+
for (const stmt of body.statements) {
|
|
2944
|
+
fixModifiers(code, stmt);
|
|
2945
|
+
if (ts.isModuleDeclaration(stmt) && stmt.body && ts.isModuleBlock(stmt.body)) {
|
|
2946
|
+
preProcessNamespaceBody(stmt.body, code);
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
}
|
|
2950
|
+
function preProcess({ sourceFile, isEntry, isJSON }) {
|
|
2951
|
+
const code = new MagicString(sourceFile.getFullText());
|
|
2952
|
+
const treatAsGlobalModule = !isEntry && isGlobalModule(sourceFile);
|
|
2953
|
+
const declaredNames = /* @__PURE__ */ new Set();
|
|
2954
|
+
const exportedNames = /* @__PURE__ */ new Set();
|
|
2955
|
+
let defaultExport = "";
|
|
2956
|
+
const inlineImports = /* @__PURE__ */ new Map();
|
|
2957
|
+
const nameRanges = /* @__PURE__ */ new Map();
|
|
2958
|
+
for (const node of sourceFile.statements) {
|
|
2959
|
+
if (ts.isEmptyStatement(node)) {
|
|
2960
|
+
code.remove(node.getStart(), node.getEnd());
|
|
2961
|
+
continue;
|
|
2962
|
+
}
|
|
2963
|
+
if (ts.isImportDeclaration(node)) {
|
|
2964
|
+
if (!node.importClause) {
|
|
2965
|
+
continue;
|
|
2966
|
+
}
|
|
2967
|
+
if (node.importClause.name) {
|
|
2968
|
+
declaredNames.add(node.importClause.name.text);
|
|
2969
|
+
}
|
|
2970
|
+
if (node.importClause.namedBindings) {
|
|
2971
|
+
if (ts.isNamespaceImport(node.importClause.namedBindings)) {
|
|
2972
|
+
declaredNames.add(node.importClause.namedBindings.name.text);
|
|
2973
|
+
} else {
|
|
2974
|
+
node.importClause.namedBindings.elements.forEach((element) => declaredNames.add(element.name.text));
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
} else if (ts.isEnumDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node) || ts.isTypeAliasDeclaration(node) || ts.isModuleDeclaration(node)) {
|
|
2978
|
+
if (node.name) {
|
|
2979
|
+
const name = node.name.getText();
|
|
2980
|
+
declaredNames.add(name);
|
|
2981
|
+
if (matchesModifier(node, ts.ModifierFlags.ExportDefault)) {
|
|
2982
|
+
defaultExport = name;
|
|
2983
|
+
} else if (treatAsGlobalModule && ts.isIdentifier(node.name) || matchesModifier(node, ts.ModifierFlags.Export)) {
|
|
2984
|
+
exportedNames.add(name);
|
|
2985
|
+
}
|
|
2986
|
+
if (!(node.flags & ts.NodeFlags.GlobalAugmentation)) {
|
|
2987
|
+
pushNamedNode(name, [getStart(node), getEnd(node)]);
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
if (ts.isModuleDeclaration(node)) {
|
|
2991
|
+
if (node.body && ts.isModuleBlock(node.body)) {
|
|
2992
|
+
preProcessNamespaceBody(node.body, code);
|
|
2993
|
+
}
|
|
2994
|
+
duplicateExports(code, node);
|
|
2995
|
+
}
|
|
2996
|
+
fixModifiers(code, node);
|
|
2997
|
+
} else if (ts.isVariableStatement(node)) {
|
|
2998
|
+
const { declarations } = node.declarationList;
|
|
2999
|
+
const isExport = matchesModifier(node, ts.ModifierFlags.Export);
|
|
3000
|
+
for (const decl of node.declarationList.declarations) {
|
|
3001
|
+
if (ts.isIdentifier(decl.name)) {
|
|
3002
|
+
const name = decl.name.getText();
|
|
3003
|
+
declaredNames.add(name);
|
|
3004
|
+
if (treatAsGlobalModule || isExport) {
|
|
3005
|
+
exportedNames.add(name);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
fixModifiers(code, node);
|
|
3010
|
+
if (declarations.length === 1) {
|
|
3011
|
+
const decl = declarations[0];
|
|
3012
|
+
if (ts.isIdentifier(decl.name)) {
|
|
3013
|
+
pushNamedNode(decl.name.getText(), [getStart(node), getEnd(node)]);
|
|
3014
|
+
}
|
|
3015
|
+
} else {
|
|
3016
|
+
const decls = declarations.slice();
|
|
3017
|
+
const first = decls.shift();
|
|
3018
|
+
pushNamedNode(first.name.getText(), [getStart(node), first.getEnd()]);
|
|
3019
|
+
for (const decl of decls) {
|
|
3020
|
+
if (ts.isIdentifier(decl.name)) {
|
|
3021
|
+
pushNamedNode(decl.name.getText(), [decl.getFullStart(), decl.getEnd()]);
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
const { flags } = node.declarationList;
|
|
3026
|
+
const type = flags & ts.NodeFlags.Let ? "let" : flags & ts.NodeFlags.Const ? "const" : "var";
|
|
3027
|
+
const prefix = `declare ${type} `;
|
|
3028
|
+
const list = node.declarationList.getChildren().find((c) => c.kind === ts.SyntaxKind.SyntaxList).getChildren();
|
|
3029
|
+
let commaPos = 0;
|
|
3030
|
+
for (const node2 of list) {
|
|
3031
|
+
if (node2.kind === ts.SyntaxKind.CommaToken) {
|
|
3032
|
+
commaPos = node2.getStart();
|
|
3033
|
+
code.remove(commaPos, node2.getEnd());
|
|
3034
|
+
} else if (commaPos) {
|
|
3035
|
+
code.appendLeft(commaPos, ";\n");
|
|
3036
|
+
const start = node2.getFullStart();
|
|
3037
|
+
const slice = code.slice(start, node2.getStart());
|
|
3038
|
+
const whitespace = slice.length - slice.trimStart().length;
|
|
3039
|
+
if (whitespace) {
|
|
3040
|
+
code.overwrite(start, start + whitespace, prefix);
|
|
3041
|
+
} else {
|
|
3042
|
+
code.appendLeft(start, prefix);
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
for (const node of sourceFile.statements) {
|
|
3049
|
+
checkInlineImport(node);
|
|
3050
|
+
if (ts.isExportAssignment(node) && !node.isExportEquals) {
|
|
3051
|
+
if (ts.isObjectLiteralExpression(node.expression) || ts.isArrayLiteralExpression(node.expression)) {
|
|
3052
|
+
if (!defaultExport) {
|
|
3053
|
+
defaultExport = uniqName("export_default");
|
|
3054
|
+
}
|
|
3055
|
+
code.overwrite(node.getStart(), node.expression.getStart(), `declare var ${defaultExport} = `);
|
|
3056
|
+
continue;
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
if (!matchesModifier(node, ts.ModifierFlags.ExportDefault)) {
|
|
3060
|
+
continue;
|
|
3061
|
+
}
|
|
3062
|
+
if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) {
|
|
3063
|
+
if (node.name) {
|
|
3064
|
+
continue;
|
|
3065
|
+
}
|
|
3066
|
+
if (!defaultExport) {
|
|
3067
|
+
defaultExport = uniqName("export_default");
|
|
3068
|
+
}
|
|
3069
|
+
const children = node.getChildren();
|
|
3070
|
+
const idx = children.findIndex((node2) => node2.kind === ts.SyntaxKind.ClassKeyword || node2.kind === ts.SyntaxKind.FunctionKeyword);
|
|
3071
|
+
const token = children[idx];
|
|
3072
|
+
const nextToken = children[idx + 1];
|
|
3073
|
+
const isPunctuation = nextToken.kind >= ts.SyntaxKind.FirstPunctuation && nextToken.kind <= ts.SyntaxKind.LastPunctuation;
|
|
3074
|
+
if (isPunctuation) {
|
|
3075
|
+
const addSpace = code.slice(token.getEnd(), nextToken.getStart()) != " ";
|
|
3076
|
+
code.appendLeft(nextToken.getStart(), `${addSpace ? " " : ""}${defaultExport}`);
|
|
3077
|
+
} else {
|
|
3078
|
+
code.appendRight(token.getEnd(), ` ${defaultExport}`);
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
for (const ranges of nameRanges.values()) {
|
|
3083
|
+
const last = ranges.pop();
|
|
3084
|
+
const start = last[0];
|
|
3085
|
+
for (const node of ranges) {
|
|
3086
|
+
code.move(node[0], node[1], start);
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
if (defaultExport) {
|
|
3090
|
+
code.append(`
|
|
3091
|
+
export default ${defaultExport};
|
|
3092
|
+
`);
|
|
3093
|
+
}
|
|
3094
|
+
if (exportedNames.size) {
|
|
3095
|
+
code.append(`
|
|
3096
|
+
export { ${[...exportedNames].join(", ")} };
|
|
3097
|
+
`);
|
|
3098
|
+
}
|
|
3099
|
+
if (isJSON && exportedNames.size) {
|
|
3100
|
+
defaultExport = uniqName("export_default");
|
|
3101
|
+
code.append([
|
|
3102
|
+
`
|
|
3103
|
+
declare const ${defaultExport}: {`,
|
|
3104
|
+
[...exportedNames].map((name) => ` ${name}: typeof ${name};`).join("\n"),
|
|
3105
|
+
`};`,
|
|
3106
|
+
`export default ${defaultExport};
|
|
3107
|
+
`
|
|
3108
|
+
].join("\n"));
|
|
3109
|
+
}
|
|
3110
|
+
for (const [fileId, importName] of inlineImports.entries()) {
|
|
3111
|
+
code.prepend(`import * as ${importName} from "${fileId}";
|
|
3112
|
+
`);
|
|
3113
|
+
}
|
|
3114
|
+
const lineStarts = sourceFile.getLineStarts();
|
|
3115
|
+
const typeReferences = /* @__PURE__ */ new Set();
|
|
3116
|
+
for (const ref of sourceFile.typeReferenceDirectives) {
|
|
3117
|
+
typeReferences.add(ref.fileName);
|
|
3118
|
+
const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
|
|
3119
|
+
const start = lineStarts[line];
|
|
3120
|
+
let end = sourceFile.getLineEndOfPosition(ref.pos);
|
|
3121
|
+
if (code.slice(end, end + 1) === "\n") {
|
|
3122
|
+
end += 1;
|
|
3123
|
+
}
|
|
3124
|
+
code.remove(start, end);
|
|
3125
|
+
}
|
|
3126
|
+
const fileReferences = /* @__PURE__ */ new Set();
|
|
3127
|
+
for (const ref of sourceFile.referencedFiles) {
|
|
3128
|
+
fileReferences.add(ref.fileName);
|
|
3129
|
+
const { line } = sourceFile.getLineAndCharacterOfPosition(ref.pos);
|
|
3130
|
+
const start = lineStarts[line];
|
|
3131
|
+
let end = sourceFile.getLineEndOfPosition(ref.pos);
|
|
3132
|
+
if (code.slice(end, end + 1) === "\n") {
|
|
3133
|
+
end += 1;
|
|
3134
|
+
}
|
|
3135
|
+
code.remove(start, end);
|
|
3136
|
+
}
|
|
3137
|
+
return {
|
|
3138
|
+
code,
|
|
3139
|
+
typeReferences,
|
|
3140
|
+
fileReferences
|
|
3141
|
+
};
|
|
3142
|
+
function checkInlineImport(node) {
|
|
3143
|
+
ts.forEachChild(node, checkInlineImport);
|
|
3144
|
+
if (ts.isImportTypeNode(node)) {
|
|
3145
|
+
if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) {
|
|
3146
|
+
throw new UnsupportedSyntaxError(node, "inline imports should have a literal argument");
|
|
3147
|
+
}
|
|
3148
|
+
const fileId = node.argument.literal.text;
|
|
3149
|
+
const children = node.getChildren();
|
|
3150
|
+
const start = children.find((t) => t.kind === ts.SyntaxKind.ImportKeyword).getStart();
|
|
3151
|
+
let end = node.getEnd();
|
|
3152
|
+
const token = children.find((t) => t.kind === ts.SyntaxKind.DotToken || t.kind === ts.SyntaxKind.LessThanToken);
|
|
3153
|
+
if (token) {
|
|
3154
|
+
end = token.getStart();
|
|
3155
|
+
}
|
|
3156
|
+
const importName = createNamespaceImport(fileId);
|
|
3157
|
+
code.overwrite(start, end, importName);
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
function createNamespaceImport(fileId) {
|
|
3161
|
+
let importName = inlineImports.get(fileId);
|
|
3162
|
+
if (!importName) {
|
|
3163
|
+
importName = uniqName(getSafeName(fileId));
|
|
3164
|
+
inlineImports.set(fileId, importName);
|
|
3165
|
+
}
|
|
3166
|
+
return importName;
|
|
3167
|
+
}
|
|
3168
|
+
function uniqName(hint) {
|
|
3169
|
+
let name = hint;
|
|
3170
|
+
while (declaredNames.has(name)) {
|
|
3171
|
+
name = `_${name}`;
|
|
3172
|
+
}
|
|
3173
|
+
declaredNames.add(name);
|
|
3174
|
+
return name;
|
|
3175
|
+
}
|
|
3176
|
+
function pushNamedNode(name, range) {
|
|
3177
|
+
let nodes = nameRanges.get(name);
|
|
3178
|
+
if (!nodes) {
|
|
3179
|
+
nodes = [range];
|
|
3180
|
+
nameRanges.set(name, nodes);
|
|
3181
|
+
} else {
|
|
3182
|
+
const last = nodes[nodes.length - 1];
|
|
3183
|
+
if (last[1] === range[0]) {
|
|
3184
|
+
last[1] = range[1];
|
|
3185
|
+
} else {
|
|
3186
|
+
nodes.push(range);
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
}
|
|
3191
|
+
function isGlobalModule(sourceFile) {
|
|
3192
|
+
let isModule = false;
|
|
3193
|
+
for (const node of sourceFile.statements) {
|
|
3194
|
+
if (ts.isExportDeclaration(node) || ts.isExportAssignment(node)) {
|
|
3195
|
+
return false;
|
|
3196
|
+
}
|
|
3197
|
+
if (isModule || ts.isImportDeclaration(node) || matchesModifier(node, ts.ModifierFlags.Export)) {
|
|
3198
|
+
isModule = true;
|
|
3199
|
+
}
|
|
3200
|
+
}
|
|
3201
|
+
return isModule;
|
|
3202
|
+
}
|
|
3203
|
+
function fixModifiers(code, node) {
|
|
3204
|
+
if (!ts.canHaveModifiers(node)) {
|
|
3205
|
+
return;
|
|
3206
|
+
}
|
|
3207
|
+
const isTopLevel = node.parent.kind === ts.SyntaxKind.SourceFile;
|
|
3208
|
+
if (isTopLevel) {
|
|
3209
|
+
let hasDeclare = false;
|
|
3210
|
+
const needsDeclare = ts.isEnumDeclaration(node) || ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isModuleDeclaration(node) || ts.isVariableStatement(node);
|
|
3211
|
+
for (const mod of node.modifiers ?? []) {
|
|
3212
|
+
switch (mod.kind) {
|
|
3213
|
+
case ts.SyntaxKind.ExportKeyword:
|
|
3214
|
+
// fall through
|
|
3215
|
+
case ts.SyntaxKind.DefaultKeyword:
|
|
3216
|
+
code.remove(mod.getStart(), mod.getEnd() + 1);
|
|
3217
|
+
break;
|
|
3218
|
+
case ts.SyntaxKind.DeclareKeyword:
|
|
3219
|
+
hasDeclare = true;
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
if (needsDeclare && !hasDeclare) {
|
|
3223
|
+
code.appendRight(node.getStart(), "declare ");
|
|
3224
|
+
}
|
|
3225
|
+
}
|
|
3226
|
+
}
|
|
3227
|
+
function duplicateExports(code, module) {
|
|
3228
|
+
if (!module.body || !ts.isModuleBlock(module.body)) {
|
|
3229
|
+
return;
|
|
3230
|
+
}
|
|
3231
|
+
for (const node of module.body.statements) {
|
|
3232
|
+
if (ts.isExportDeclaration(node) && node.exportClause) {
|
|
3233
|
+
if (ts.isNamespaceExport(node.exportClause)) {
|
|
3234
|
+
continue;
|
|
3235
|
+
}
|
|
3236
|
+
for (const decl of node.exportClause.elements) {
|
|
3237
|
+
if (!decl.propertyName) {
|
|
3238
|
+
code.appendLeft(decl.name.getEnd(), ` as ${decl.name.getText()}`);
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
function getSafeName(fileId) {
|
|
3245
|
+
return fileId.replace(/[^a-zA-Z0-9_$]/g, () => "_");
|
|
3246
|
+
}
|
|
3247
|
+
function getStart(node) {
|
|
3248
|
+
const start = node.getFullStart();
|
|
3249
|
+
return start + (newlineAt(node, start) ? 1 : 0);
|
|
3250
|
+
}
|
|
3251
|
+
function getEnd(node) {
|
|
3252
|
+
const end = node.getEnd();
|
|
3253
|
+
return end + (newlineAt(node, end) ? 1 : 0);
|
|
3254
|
+
}
|
|
3255
|
+
function newlineAt(node, idx) {
|
|
3256
|
+
return node.getSourceFile().getFullText()[idx] === "\n";
|
|
3257
|
+
}
|
|
3258
|
+
const IGNORE_TYPENODES = /* @__PURE__ */ new Set([
|
|
3259
|
+
ts.SyntaxKind.LiteralType,
|
|
3260
|
+
ts.SyntaxKind.VoidKeyword,
|
|
3261
|
+
ts.SyntaxKind.UnknownKeyword,
|
|
3262
|
+
ts.SyntaxKind.AnyKeyword,
|
|
3263
|
+
ts.SyntaxKind.BooleanKeyword,
|
|
3264
|
+
ts.SyntaxKind.NumberKeyword,
|
|
3265
|
+
ts.SyntaxKind.StringKeyword,
|
|
3266
|
+
ts.SyntaxKind.ObjectKeyword,
|
|
3267
|
+
ts.SyntaxKind.NullKeyword,
|
|
3268
|
+
ts.SyntaxKind.UndefinedKeyword,
|
|
3269
|
+
ts.SyntaxKind.SymbolKeyword,
|
|
3270
|
+
ts.SyntaxKind.NeverKeyword,
|
|
3271
|
+
ts.SyntaxKind.ThisKeyword,
|
|
3272
|
+
ts.SyntaxKind.ThisType,
|
|
3273
|
+
ts.SyntaxKind.BigIntKeyword
|
|
3274
|
+
]);
|
|
3275
|
+
class DeclarationScope {
|
|
3276
|
+
constructor({ id, range }) {
|
|
3277
|
+
this.scopes = [];
|
|
3278
|
+
if (id) {
|
|
3279
|
+
this.declaration = createDeclaration(id, range);
|
|
3280
|
+
} else {
|
|
3281
|
+
const { iife, fn } = createIIFE(range);
|
|
3282
|
+
this.iife = iife;
|
|
3283
|
+
this.declaration = fn;
|
|
3284
|
+
}
|
|
3285
|
+
const ret = createReturn();
|
|
3286
|
+
this.declaration.body.body.push(ret.stmt);
|
|
3287
|
+
this.returnExpr = ret.expr;
|
|
3288
|
+
}
|
|
3289
|
+
pushScope() {
|
|
3290
|
+
this.scopes.push(/* @__PURE__ */ new Set());
|
|
3291
|
+
}
|
|
3292
|
+
popScope(n = 1) {
|
|
3293
|
+
for (let i = 0; i < n; i++) {
|
|
3294
|
+
this.scopes.pop();
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
3297
|
+
pushTypeVariable(id) {
|
|
3298
|
+
const name = id.getText();
|
|
3299
|
+
this.scopes[this.scopes.length - 1]?.add(name);
|
|
3300
|
+
}
|
|
3301
|
+
pushReference(id) {
|
|
3302
|
+
let name;
|
|
3303
|
+
if (id.type === "Identifier") {
|
|
3304
|
+
name = id.name;
|
|
3305
|
+
} else if (id.type === "MemberExpression") {
|
|
3306
|
+
if (id.object.type === "Identifier") {
|
|
3307
|
+
name = id.object.name;
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
if (name) {
|
|
3311
|
+
for (const scope of this.scopes) {
|
|
3312
|
+
if (scope.has(name)) {
|
|
3313
|
+
return;
|
|
3314
|
+
}
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
if (name === "this")
|
|
3318
|
+
return;
|
|
3319
|
+
const { ident, expr } = createReference(id);
|
|
3320
|
+
this.declaration.params.push(expr);
|
|
3321
|
+
this.returnExpr.elements.push(ident);
|
|
3322
|
+
}
|
|
3323
|
+
pushIdentifierReference(id) {
|
|
3324
|
+
this.pushReference(createIdentifier(id));
|
|
3325
|
+
}
|
|
3326
|
+
convertEntityName(node) {
|
|
3327
|
+
if (ts.isIdentifier(node)) {
|
|
3328
|
+
return createIdentifier(node);
|
|
3329
|
+
}
|
|
3330
|
+
return withStartEnd({
|
|
3331
|
+
type: "MemberExpression",
|
|
3332
|
+
computed: false,
|
|
3333
|
+
optional: false,
|
|
3334
|
+
object: this.convertEntityName(node.left),
|
|
3335
|
+
property: createIdentifier(node.right)
|
|
3336
|
+
}, node);
|
|
3337
|
+
}
|
|
3338
|
+
convertPropertyAccess(node) {
|
|
3339
|
+
if (!ts.isIdentifier(node.expression) && !ts.isPropertyAccessExpression(node.expression)) {
|
|
3340
|
+
throw new UnsupportedSyntaxError(node.expression);
|
|
3341
|
+
}
|
|
3342
|
+
if (ts.isPrivateIdentifier(node.name)) {
|
|
3343
|
+
throw new UnsupportedSyntaxError(node.name);
|
|
3344
|
+
}
|
|
3345
|
+
const object = ts.isIdentifier(node.expression) ? createIdentifier(node.expression) : this.convertPropertyAccess(node.expression);
|
|
3346
|
+
return withStartEnd({
|
|
3347
|
+
type: "MemberExpression",
|
|
3348
|
+
computed: false,
|
|
3349
|
+
optional: false,
|
|
3350
|
+
object,
|
|
3351
|
+
property: createIdentifier(node.name)
|
|
3352
|
+
}, node);
|
|
3353
|
+
}
|
|
3354
|
+
convertComputedPropertyName(node) {
|
|
3355
|
+
if (!node.name || !ts.isComputedPropertyName(node.name)) {
|
|
3356
|
+
return;
|
|
3357
|
+
}
|
|
3358
|
+
const { expression } = node.name;
|
|
3359
|
+
if (ts.isLiteralExpression(expression) || ts.isPrefixUnaryExpression(expression)) {
|
|
3360
|
+
return;
|
|
3361
|
+
}
|
|
3362
|
+
if (ts.isIdentifier(expression)) {
|
|
3363
|
+
return this.pushReference(createIdentifier(expression));
|
|
3364
|
+
}
|
|
3365
|
+
if (ts.isPropertyAccessExpression(expression)) {
|
|
3366
|
+
return this.pushReference(this.convertPropertyAccess(expression));
|
|
3367
|
+
}
|
|
3368
|
+
throw new UnsupportedSyntaxError(expression);
|
|
3369
|
+
}
|
|
3370
|
+
convertParametersAndType(node) {
|
|
3371
|
+
this.convertComputedPropertyName(node);
|
|
3372
|
+
const typeVariables = this.convertTypeParameters(node.typeParameters);
|
|
3373
|
+
for (const param of node.parameters) {
|
|
3374
|
+
this.convertTypeNode(param.type);
|
|
3375
|
+
}
|
|
3376
|
+
this.convertTypeNode(node.type);
|
|
3377
|
+
this.popScope(typeVariables);
|
|
3378
|
+
}
|
|
3379
|
+
convertHeritageClauses(node) {
|
|
3380
|
+
for (const heritage of node.heritageClauses || []) {
|
|
3381
|
+
for (const type of heritage.types) {
|
|
3382
|
+
this.pushReference(convertExpression(type.expression));
|
|
3383
|
+
this.convertTypeArguments(type);
|
|
3384
|
+
}
|
|
3385
|
+
}
|
|
3386
|
+
}
|
|
3387
|
+
convertTypeArguments(node) {
|
|
3388
|
+
if (!node.typeArguments) {
|
|
3389
|
+
return;
|
|
3390
|
+
}
|
|
3391
|
+
for (const arg of node.typeArguments) {
|
|
3392
|
+
this.convertTypeNode(arg);
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
convertMembers(members) {
|
|
3396
|
+
for (const node of members) {
|
|
3397
|
+
if (ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isIndexSignatureDeclaration(node)) {
|
|
3398
|
+
if (ts.isPropertyDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) {
|
|
3399
|
+
this.pushReference(this.convertPropertyAccess(node.initializer));
|
|
3400
|
+
}
|
|
3401
|
+
this.convertComputedPropertyName(node);
|
|
3402
|
+
this.convertTypeNode(node.type);
|
|
3403
|
+
continue;
|
|
3404
|
+
}
|
|
3405
|
+
if (ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isConstructorDeclaration(node) || ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node)) {
|
|
3406
|
+
this.convertParametersAndType(node);
|
|
3407
|
+
} else {
|
|
3408
|
+
throw new UnsupportedSyntaxError(node);
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
convertTypeParameters(params) {
|
|
3413
|
+
if (!params) {
|
|
3414
|
+
return 0;
|
|
3415
|
+
}
|
|
3416
|
+
for (const node of params) {
|
|
3417
|
+
this.convertTypeNode(node.constraint);
|
|
3418
|
+
this.convertTypeNode(node.default);
|
|
3419
|
+
this.pushScope();
|
|
3420
|
+
this.pushTypeVariable(node.name);
|
|
3421
|
+
}
|
|
3422
|
+
return params.length;
|
|
3423
|
+
}
|
|
3424
|
+
convertTypeNode(node) {
|
|
3425
|
+
if (!node) {
|
|
3426
|
+
return;
|
|
3427
|
+
}
|
|
3428
|
+
if (IGNORE_TYPENODES.has(node.kind)) {
|
|
3429
|
+
return;
|
|
3430
|
+
}
|
|
3431
|
+
if (ts.isTypeReferenceNode(node)) {
|
|
3432
|
+
this.pushReference(this.convertEntityName(node.typeName));
|
|
3433
|
+
this.convertTypeArguments(node);
|
|
3434
|
+
return;
|
|
3435
|
+
}
|
|
3436
|
+
if (ts.isTypeLiteralNode(node)) {
|
|
3437
|
+
this.convertMembers(node.members);
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
if (ts.isArrayTypeNode(node)) {
|
|
3441
|
+
this.convertTypeNode(node.elementType);
|
|
3442
|
+
return;
|
|
3443
|
+
}
|
|
3444
|
+
if (ts.isTupleTypeNode(node)) {
|
|
3445
|
+
for (const type of node.elements) {
|
|
3446
|
+
this.convertTypeNode(type);
|
|
3447
|
+
}
|
|
3448
|
+
return;
|
|
3449
|
+
}
|
|
3450
|
+
if (ts.isNamedTupleMember(node) || ts.isParenthesizedTypeNode(node) || ts.isTypeOperatorNode(node) || ts.isTypePredicateNode(node)) {
|
|
3451
|
+
this.convertTypeNode(node.type);
|
|
3452
|
+
return;
|
|
3453
|
+
}
|
|
3454
|
+
if (ts.isUnionTypeNode(node) || ts.isIntersectionTypeNode(node)) {
|
|
3455
|
+
for (const type of node.types) {
|
|
3456
|
+
this.convertTypeNode(type);
|
|
3457
|
+
}
|
|
3458
|
+
return;
|
|
3459
|
+
}
|
|
3460
|
+
if (ts.isMappedTypeNode(node)) {
|
|
3461
|
+
const { typeParameter, type, nameType } = node;
|
|
3462
|
+
this.convertTypeNode(typeParameter.constraint);
|
|
3463
|
+
this.pushScope();
|
|
3464
|
+
this.pushTypeVariable(typeParameter.name);
|
|
3465
|
+
this.convertTypeNode(type);
|
|
3466
|
+
if (nameType) {
|
|
3467
|
+
this.convertTypeNode(nameType);
|
|
3468
|
+
}
|
|
3469
|
+
this.popScope();
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
if (ts.isConditionalTypeNode(node)) {
|
|
3473
|
+
this.convertTypeNode(node.checkType);
|
|
3474
|
+
this.pushScope();
|
|
3475
|
+
this.convertTypeNode(node.extendsType);
|
|
3476
|
+
this.convertTypeNode(node.trueType);
|
|
3477
|
+
this.convertTypeNode(node.falseType);
|
|
3478
|
+
this.popScope();
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
3481
|
+
if (ts.isIndexedAccessTypeNode(node)) {
|
|
3482
|
+
this.convertTypeNode(node.objectType);
|
|
3483
|
+
this.convertTypeNode(node.indexType);
|
|
3484
|
+
return;
|
|
3485
|
+
}
|
|
3486
|
+
if (ts.isFunctionOrConstructorTypeNode(node)) {
|
|
3487
|
+
this.convertParametersAndType(node);
|
|
3488
|
+
return;
|
|
3489
|
+
}
|
|
3490
|
+
if (ts.isTypeQueryNode(node)) {
|
|
3491
|
+
const reference = this.convertEntityName(node.exprName);
|
|
3492
|
+
this.pushReference(reference);
|
|
3493
|
+
this.convertTypeArguments(node);
|
|
3494
|
+
return;
|
|
3495
|
+
}
|
|
3496
|
+
if (ts.isRestTypeNode(node)) {
|
|
3497
|
+
this.convertTypeNode(node.type);
|
|
3498
|
+
return;
|
|
3499
|
+
}
|
|
3500
|
+
if (ts.isOptionalTypeNode(node)) {
|
|
3501
|
+
this.convertTypeNode(node.type);
|
|
3502
|
+
return;
|
|
3503
|
+
}
|
|
3504
|
+
if (ts.isTemplateLiteralTypeNode(node)) {
|
|
3505
|
+
for (const span of node.templateSpans) {
|
|
3506
|
+
this.convertTypeNode(span.type);
|
|
3507
|
+
}
|
|
3508
|
+
return;
|
|
3509
|
+
}
|
|
3510
|
+
if (ts.isInferTypeNode(node)) {
|
|
3511
|
+
const { typeParameter } = node;
|
|
3512
|
+
this.convertTypeNode(typeParameter.constraint);
|
|
3513
|
+
this.pushTypeVariable(typeParameter.name);
|
|
3514
|
+
return;
|
|
3515
|
+
} else {
|
|
3516
|
+
throw new UnsupportedSyntaxError(node);
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
convertNamespace(node, relaxedModuleBlock = false) {
|
|
3520
|
+
this.pushScope();
|
|
3521
|
+
if (relaxedModuleBlock && node.body && ts.isModuleDeclaration(node.body)) {
|
|
3522
|
+
this.convertNamespace(node.body, true);
|
|
3523
|
+
return;
|
|
3524
|
+
}
|
|
3525
|
+
if (!node.body || !ts.isModuleBlock(node.body)) {
|
|
3526
|
+
throw new UnsupportedSyntaxError(node, `namespace must have a "ModuleBlock" body.`);
|
|
3527
|
+
}
|
|
3528
|
+
const { statements } = node.body;
|
|
3529
|
+
for (const stmt of statements) {
|
|
3530
|
+
if (ts.isEnumDeclaration(stmt) || ts.isFunctionDeclaration(stmt) || ts.isClassDeclaration(stmt) || ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt) || ts.isModuleDeclaration(stmt)) {
|
|
3531
|
+
if (stmt.name && ts.isIdentifier(stmt.name)) {
|
|
3532
|
+
this.pushTypeVariable(stmt.name);
|
|
3533
|
+
} else {
|
|
3534
|
+
throw new UnsupportedSyntaxError(stmt, "non-Identifier name not supported");
|
|
3535
|
+
}
|
|
3536
|
+
continue;
|
|
3537
|
+
}
|
|
3538
|
+
if (ts.isVariableStatement(stmt)) {
|
|
3539
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
3540
|
+
if (ts.isIdentifier(decl.name)) {
|
|
3541
|
+
this.pushTypeVariable(decl.name);
|
|
3542
|
+
} else {
|
|
3543
|
+
throw new UnsupportedSyntaxError(decl, "non-Identifier name not supported");
|
|
3544
|
+
}
|
|
3545
|
+
}
|
|
3546
|
+
continue;
|
|
3547
|
+
}
|
|
3548
|
+
if (ts.isImportDeclaration(stmt)) {
|
|
3549
|
+
if (stmt.importClause) {
|
|
3550
|
+
if (stmt.importClause.name) {
|
|
3551
|
+
this.pushTypeVariable(stmt.importClause.name);
|
|
3552
|
+
}
|
|
3553
|
+
if (stmt.importClause.namedBindings) {
|
|
3554
|
+
if (ts.isNamespaceImport(stmt.importClause.namedBindings)) {
|
|
3555
|
+
this.pushTypeVariable(stmt.importClause.namedBindings.name);
|
|
3556
|
+
} else {
|
|
3557
|
+
for (const el of stmt.importClause.namedBindings.elements) {
|
|
3558
|
+
this.pushTypeVariable(el.name);
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
continue;
|
|
3564
|
+
}
|
|
3565
|
+
if (ts.isImportEqualsDeclaration(stmt)) {
|
|
3566
|
+
this.pushTypeVariable(stmt.name);
|
|
3567
|
+
continue;
|
|
3568
|
+
}
|
|
3569
|
+
if (ts.isExportDeclaration(stmt)) ;
|
|
3570
|
+
else {
|
|
3571
|
+
throw new UnsupportedSyntaxError(stmt, "namespace child (hoisting) not supported yet");
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
for (const stmt of statements) {
|
|
3575
|
+
if (ts.isVariableStatement(stmt)) {
|
|
3576
|
+
for (const decl of stmt.declarationList.declarations) {
|
|
3577
|
+
if (decl.type) {
|
|
3578
|
+
this.convertTypeNode(decl.type);
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
continue;
|
|
3582
|
+
}
|
|
3583
|
+
if (ts.isFunctionDeclaration(stmt)) {
|
|
3584
|
+
this.convertParametersAndType(stmt);
|
|
3585
|
+
continue;
|
|
3586
|
+
}
|
|
3587
|
+
if (ts.isInterfaceDeclaration(stmt) || ts.isClassDeclaration(stmt)) {
|
|
3588
|
+
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
|
|
3589
|
+
this.convertHeritageClauses(stmt);
|
|
3590
|
+
this.convertMembers(stmt.members);
|
|
3591
|
+
this.popScope(typeVariables);
|
|
3592
|
+
continue;
|
|
3593
|
+
}
|
|
3594
|
+
if (ts.isTypeAliasDeclaration(stmt)) {
|
|
3595
|
+
const typeVariables = this.convertTypeParameters(stmt.typeParameters);
|
|
3596
|
+
this.convertTypeNode(stmt.type);
|
|
3597
|
+
this.popScope(typeVariables);
|
|
3598
|
+
continue;
|
|
3599
|
+
}
|
|
3600
|
+
if (ts.isModuleDeclaration(stmt)) {
|
|
3601
|
+
this.convertNamespace(stmt, relaxedModuleBlock);
|
|
3602
|
+
continue;
|
|
3603
|
+
}
|
|
3604
|
+
if (ts.isEnumDeclaration(stmt)) {
|
|
3605
|
+
continue;
|
|
3606
|
+
}
|
|
3607
|
+
if (ts.isImportDeclaration(stmt)) {
|
|
3608
|
+
continue;
|
|
3609
|
+
}
|
|
3610
|
+
if (ts.isImportEqualsDeclaration(stmt)) {
|
|
3611
|
+
if (ts.isEntityName(stmt.moduleReference)) {
|
|
3612
|
+
this.pushReference(this.convertEntityName(stmt.moduleReference));
|
|
3613
|
+
}
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
if (ts.isExportDeclaration(stmt)) {
|
|
3617
|
+
if (stmt.exportClause) {
|
|
3618
|
+
if (ts.isNamespaceExport(stmt.exportClause)) {
|
|
3619
|
+
throw new UnsupportedSyntaxError(stmt.exportClause);
|
|
3620
|
+
}
|
|
3621
|
+
for (const decl of stmt.exportClause.elements) {
|
|
3622
|
+
const id = decl.propertyName || decl.name;
|
|
3623
|
+
this.pushIdentifierReference(id);
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
} else {
|
|
3627
|
+
throw new UnsupportedSyntaxError(stmt, "namespace child (walking) not supported yet");
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
this.popScope();
|
|
3631
|
+
}
|
|
3632
|
+
}
|
|
3633
|
+
function convert({ sourceFile }) {
|
|
3634
|
+
const transformer = new Transformer(sourceFile);
|
|
3635
|
+
return transformer.transform();
|
|
3636
|
+
}
|
|
3637
|
+
class Transformer {
|
|
3638
|
+
constructor(sourceFile) {
|
|
3639
|
+
this.sourceFile = sourceFile;
|
|
3640
|
+
this.declarations = /* @__PURE__ */ new Map();
|
|
3641
|
+
this.ast = createProgram(sourceFile);
|
|
3642
|
+
for (const stmt of sourceFile.statements) {
|
|
3643
|
+
this.convertStatement(stmt);
|
|
3644
|
+
}
|
|
3645
|
+
}
|
|
3646
|
+
transform() {
|
|
3647
|
+
return {
|
|
3648
|
+
ast: this.ast
|
|
3649
|
+
};
|
|
3650
|
+
}
|
|
3651
|
+
pushStatement(node) {
|
|
3652
|
+
this.ast.body.push(node);
|
|
3653
|
+
}
|
|
3654
|
+
createDeclaration(node, id) {
|
|
3655
|
+
const range = { start: node.getFullStart(), end: node.getEnd() };
|
|
3656
|
+
if (!id) {
|
|
3657
|
+
const scope2 = new DeclarationScope({ range });
|
|
3658
|
+
this.pushStatement(scope2.iife);
|
|
3659
|
+
return scope2;
|
|
3660
|
+
}
|
|
3661
|
+
const name = id.getText();
|
|
3662
|
+
const scope = new DeclarationScope({ id, range });
|
|
3663
|
+
const existingScope = this.declarations.get(name);
|
|
3664
|
+
if (existingScope) {
|
|
3665
|
+
existingScope.pushIdentifierReference(id);
|
|
3666
|
+
existingScope.declaration.end = range.end;
|
|
3667
|
+
const selfIdx = this.ast.body.findIndex((node2) => node2 == existingScope.declaration);
|
|
3668
|
+
for (let i = selfIdx + 1; i < this.ast.body.length; i++) {
|
|
3669
|
+
const decl = this.ast.body[i];
|
|
3670
|
+
decl.start = decl.end = range.end;
|
|
3671
|
+
}
|
|
3672
|
+
} else {
|
|
3673
|
+
this.pushStatement(scope.declaration);
|
|
3674
|
+
this.declarations.set(name, scope);
|
|
3675
|
+
}
|
|
3676
|
+
return existingScope || scope;
|
|
3677
|
+
}
|
|
3678
|
+
convertStatement(node) {
|
|
3679
|
+
if (ts.isEnumDeclaration(node)) {
|
|
3680
|
+
return this.convertEnumDeclaration(node);
|
|
3681
|
+
}
|
|
3682
|
+
if (ts.isFunctionDeclaration(node)) {
|
|
3683
|
+
return this.convertFunctionDeclaration(node);
|
|
3684
|
+
}
|
|
3685
|
+
if (ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) {
|
|
3686
|
+
return this.convertClassOrInterfaceDeclaration(node);
|
|
3687
|
+
}
|
|
3688
|
+
if (ts.isTypeAliasDeclaration(node)) {
|
|
3689
|
+
return this.convertTypeAliasDeclaration(node);
|
|
3690
|
+
}
|
|
3691
|
+
if (ts.isVariableStatement(node)) {
|
|
3692
|
+
return this.convertVariableStatement(node);
|
|
3693
|
+
}
|
|
3694
|
+
if (ts.isExportDeclaration(node) || ts.isExportAssignment(node)) {
|
|
3695
|
+
return this.convertExportDeclaration(node);
|
|
3696
|
+
}
|
|
3697
|
+
if (ts.isModuleDeclaration(node)) {
|
|
3698
|
+
return this.convertNamespaceDeclaration(node);
|
|
3699
|
+
}
|
|
3700
|
+
if (node.kind === ts.SyntaxKind.NamespaceExportDeclaration) {
|
|
3701
|
+
return this.removeStatement(node);
|
|
3702
|
+
}
|
|
3703
|
+
if (ts.isImportDeclaration(node) || ts.isImportEqualsDeclaration(node)) {
|
|
3704
|
+
return this.convertImportDeclaration(node);
|
|
3705
|
+
} else {
|
|
3706
|
+
throw new UnsupportedSyntaxError(node);
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
removeStatement(node) {
|
|
3710
|
+
this.pushStatement(withStartEnd({
|
|
3711
|
+
type: "ExpressionStatement",
|
|
3712
|
+
expression: { type: "Literal", value: "pls remove me" }
|
|
3713
|
+
}, node));
|
|
3714
|
+
}
|
|
3715
|
+
convertNamespaceDeclaration(node) {
|
|
3716
|
+
const isGlobalAugmentation = node.flags & ts.NodeFlags.GlobalAugmentation;
|
|
3717
|
+
if (isGlobalAugmentation || !ts.isIdentifier(node.name)) {
|
|
3718
|
+
const scope2 = this.createDeclaration(node);
|
|
3719
|
+
scope2.convertNamespace(node, true);
|
|
3720
|
+
return;
|
|
3721
|
+
}
|
|
3722
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3723
|
+
scope.pushIdentifierReference(node.name);
|
|
3724
|
+
scope.convertNamespace(node);
|
|
3725
|
+
}
|
|
3726
|
+
convertEnumDeclaration(node) {
|
|
3727
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3728
|
+
scope.pushIdentifierReference(node.name);
|
|
3729
|
+
}
|
|
3730
|
+
convertFunctionDeclaration(node) {
|
|
3731
|
+
if (!node.name) {
|
|
3732
|
+
throw new UnsupportedSyntaxError(node, "FunctionDeclaration should have a name");
|
|
3733
|
+
}
|
|
3734
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3735
|
+
scope.pushIdentifierReference(node.name);
|
|
3736
|
+
scope.convertParametersAndType(node);
|
|
3737
|
+
}
|
|
3738
|
+
convertClassOrInterfaceDeclaration(node) {
|
|
3739
|
+
if (!node.name) {
|
|
3740
|
+
throw new UnsupportedSyntaxError(node, "ClassDeclaration / InterfaceDeclaration should have a name");
|
|
3741
|
+
}
|
|
3742
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3743
|
+
const typeVariables = scope.convertTypeParameters(node.typeParameters);
|
|
3744
|
+
scope.convertHeritageClauses(node);
|
|
3745
|
+
scope.convertMembers(node.members);
|
|
3746
|
+
scope.popScope(typeVariables);
|
|
3747
|
+
}
|
|
3748
|
+
convertTypeAliasDeclaration(node) {
|
|
3749
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3750
|
+
const typeVariables = scope.convertTypeParameters(node.typeParameters);
|
|
3751
|
+
scope.convertTypeNode(node.type);
|
|
3752
|
+
scope.popScope(typeVariables);
|
|
3753
|
+
}
|
|
3754
|
+
convertVariableStatement(node) {
|
|
3755
|
+
const { declarations } = node.declarationList;
|
|
3756
|
+
if (declarations.length !== 1) {
|
|
3757
|
+
throw new UnsupportedSyntaxError(node, "VariableStatement with more than one declaration not yet supported");
|
|
3758
|
+
}
|
|
3759
|
+
for (const decl of declarations) {
|
|
3760
|
+
if (!ts.isIdentifier(decl.name)) {
|
|
3761
|
+
throw new UnsupportedSyntaxError(node, "VariableDeclaration must have a name");
|
|
3762
|
+
}
|
|
3763
|
+
const scope = this.createDeclaration(node, decl.name);
|
|
3764
|
+
scope.convertTypeNode(decl.type);
|
|
3765
|
+
if (decl.initializer) {
|
|
3766
|
+
this.trackExpressionReferences(decl.initializer, scope);
|
|
3767
|
+
}
|
|
3768
|
+
}
|
|
3769
|
+
}
|
|
3770
|
+
// Helper to track identifier references in expressions
|
|
3771
|
+
trackExpressionReferences(expr, scope) {
|
|
3772
|
+
if (ts.isIdentifier(expr)) {
|
|
3773
|
+
scope.pushIdentifierReference(expr);
|
|
3774
|
+
} else if (ts.isObjectLiteralExpression(expr)) {
|
|
3775
|
+
for (const prop of expr.properties) {
|
|
3776
|
+
if (ts.isShorthandPropertyAssignment(prop)) {
|
|
3777
|
+
scope.pushIdentifierReference(prop.name);
|
|
3778
|
+
} else if (ts.isPropertyAssignment(prop)) {
|
|
3779
|
+
this.trackExpressionReferences(prop.initializer, scope);
|
|
3780
|
+
}
|
|
3781
|
+
}
|
|
3782
|
+
} else if (ts.isArrayLiteralExpression(expr)) {
|
|
3783
|
+
for (const elem of expr.elements) {
|
|
3784
|
+
if (ts.isExpression(elem)) {
|
|
3785
|
+
this.trackExpressionReferences(elem, scope);
|
|
3786
|
+
}
|
|
3787
|
+
}
|
|
3788
|
+
} else if (ts.isPropertyAccessExpression(expr)) {
|
|
3789
|
+
this.trackExpressionReferences(expr.expression, scope);
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
convertExportDeclaration(node) {
|
|
3793
|
+
if (ts.isExportAssignment(node)) {
|
|
3794
|
+
this.pushStatement(withStartEnd({
|
|
3795
|
+
type: "ExportDefaultDeclaration",
|
|
3796
|
+
declaration: convertExpression(node.expression)
|
|
3797
|
+
}, node));
|
|
3798
|
+
return;
|
|
3799
|
+
}
|
|
3800
|
+
const source = node.moduleSpecifier ? convertExpression(node.moduleSpecifier) : void 0;
|
|
3801
|
+
if (!node.exportClause) {
|
|
3802
|
+
this.pushStatement(withStartEnd({
|
|
3803
|
+
type: "ExportAllDeclaration",
|
|
3804
|
+
source,
|
|
3805
|
+
exported: null,
|
|
3806
|
+
attributes: []
|
|
3807
|
+
}, node));
|
|
3808
|
+
} else if (ts.isNamespaceExport(node.exportClause)) {
|
|
3809
|
+
this.pushStatement(withStartEnd({
|
|
3810
|
+
type: "ExportAllDeclaration",
|
|
3811
|
+
source,
|
|
3812
|
+
exported: createIdentifier(node.exportClause.name),
|
|
3813
|
+
attributes: []
|
|
3814
|
+
}, node));
|
|
3815
|
+
} else {
|
|
3816
|
+
const specifiers = [];
|
|
3817
|
+
for (const elem of node.exportClause.elements) {
|
|
3818
|
+
specifiers.push(this.convertExportSpecifier(elem));
|
|
3819
|
+
}
|
|
3820
|
+
this.pushStatement(withStartEnd({
|
|
3821
|
+
type: "ExportNamedDeclaration",
|
|
3822
|
+
declaration: null,
|
|
3823
|
+
specifiers,
|
|
3824
|
+
source,
|
|
3825
|
+
attributes: []
|
|
3826
|
+
}, node));
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
convertImportDeclaration(node) {
|
|
3830
|
+
if (ts.isImportEqualsDeclaration(node)) {
|
|
3831
|
+
if (ts.isEntityName(node.moduleReference)) {
|
|
3832
|
+
const scope = this.createDeclaration(node, node.name);
|
|
3833
|
+
scope.pushReference(scope.convertEntityName(node.moduleReference));
|
|
3834
|
+
return;
|
|
3835
|
+
}
|
|
3836
|
+
if (!ts.isExternalModuleReference(node.moduleReference)) {
|
|
3837
|
+
throw new UnsupportedSyntaxError(node, "ImportEquals should have a literal source.");
|
|
3838
|
+
}
|
|
3839
|
+
this.pushStatement(withStartEnd({
|
|
3840
|
+
type: "ImportDeclaration",
|
|
3841
|
+
specifiers: [
|
|
3842
|
+
{
|
|
3843
|
+
type: "ImportDefaultSpecifier",
|
|
3844
|
+
local: createIdentifier(node.name)
|
|
3845
|
+
}
|
|
3846
|
+
],
|
|
3847
|
+
source: convertExpression(node.moduleReference.expression),
|
|
3848
|
+
attributes: []
|
|
3849
|
+
}, node));
|
|
3850
|
+
return;
|
|
3851
|
+
}
|
|
3852
|
+
const source = convertExpression(node.moduleSpecifier);
|
|
3853
|
+
const specifiers = node.importClause && node.importClause.namedBindings ? this.convertNamedImportBindings(node.importClause.namedBindings) : [];
|
|
3854
|
+
if (node.importClause && node.importClause.name) {
|
|
3855
|
+
specifiers.push({
|
|
3856
|
+
type: "ImportDefaultSpecifier",
|
|
3857
|
+
local: createIdentifier(node.importClause.name)
|
|
3858
|
+
});
|
|
3859
|
+
}
|
|
3860
|
+
this.pushStatement(withStartEnd({
|
|
3861
|
+
type: "ImportDeclaration",
|
|
3862
|
+
specifiers,
|
|
3863
|
+
source,
|
|
3864
|
+
attributes: []
|
|
3865
|
+
}, node));
|
|
3866
|
+
}
|
|
3867
|
+
convertNamedImportBindings(node) {
|
|
3868
|
+
if (ts.isNamedImports(node)) {
|
|
3869
|
+
return node.elements.map((el) => {
|
|
3870
|
+
const local = createIdentifier(el.name);
|
|
3871
|
+
const imported = el.propertyName ? createIdentifier(el.propertyName) : local;
|
|
3872
|
+
return {
|
|
3873
|
+
type: "ImportSpecifier",
|
|
3874
|
+
local,
|
|
3875
|
+
imported
|
|
3876
|
+
};
|
|
3877
|
+
});
|
|
3878
|
+
}
|
|
3879
|
+
return [
|
|
3880
|
+
{
|
|
3881
|
+
type: "ImportNamespaceSpecifier",
|
|
3882
|
+
local: createIdentifier(node.name)
|
|
3883
|
+
}
|
|
3884
|
+
];
|
|
3885
|
+
}
|
|
3886
|
+
convertExportSpecifier(node) {
|
|
3887
|
+
const exported = createIdentifier(node.name);
|
|
3888
|
+
return {
|
|
3889
|
+
type: "ExportSpecifier",
|
|
3890
|
+
exported,
|
|
3891
|
+
local: node.propertyName ? createIdentifier(node.propertyName) : exported
|
|
3892
|
+
};
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
class RelativeModuleDeclarationFixer {
|
|
3896
|
+
constructor(fileName, code, sourcemap, name) {
|
|
3897
|
+
this.sourcemap = sourcemap;
|
|
3898
|
+
this.DEBUG = !!process.env.DTS_EXPORTS_FIXER_DEBUG;
|
|
3899
|
+
this.relativeModuleDeclarations = [];
|
|
3900
|
+
this.source = parse(fileName, code.toString());
|
|
3901
|
+
this.code = code;
|
|
3902
|
+
this.name = name || "./index";
|
|
3903
|
+
}
|
|
3904
|
+
fix() {
|
|
3905
|
+
this.analyze(this.source.statements);
|
|
3906
|
+
for (const node of this.relativeModuleDeclarations) {
|
|
3907
|
+
const start = node.getStart();
|
|
3908
|
+
const end = node.getEnd();
|
|
3909
|
+
const quote = node.name.kind === ts.SyntaxKind.StringLiteral && "singleQuote" in node.name && node.name.singleQuote ? "'" : '"';
|
|
3910
|
+
const code = `declare module ${quote}${this.name}${quote} ${node.body.getText()}`;
|
|
3911
|
+
this.code.overwrite(start, end, code);
|
|
3912
|
+
}
|
|
3913
|
+
return {
|
|
3914
|
+
code: this.code.toString(),
|
|
3915
|
+
map: this.relativeModuleDeclarations.length && this.sourcemap ? this.code.generateMap() : null
|
|
3916
|
+
};
|
|
3917
|
+
}
|
|
3918
|
+
analyze(nodes) {
|
|
3919
|
+
for (const node of nodes) {
|
|
3920
|
+
if (ts.isModuleDeclaration(node) && node.body && ts.isModuleBlock(node.body) && /^\.\.?\//.test(node.name.text)) {
|
|
3921
|
+
if (this.DEBUG) {
|
|
3922
|
+
console.log(`Found relative module declaration: ${node.name.text} in ${this.source.fileName}`);
|
|
3923
|
+
}
|
|
3924
|
+
this.relativeModuleDeclarations.push(node);
|
|
3925
|
+
}
|
|
3926
|
+
}
|
|
3927
|
+
}
|
|
3928
|
+
}
|
|
3929
|
+
function hydrateSourcemap(sparseMappings, inputMap, outputCode) {
|
|
3930
|
+
const sparseDecoded = decode(sparseMappings);
|
|
3931
|
+
const inputDecoded = decode(inputMap.mappings);
|
|
3932
|
+
const outputLines = outputCode.split("\n");
|
|
3933
|
+
const hydratedMappings = [];
|
|
3934
|
+
for (let outLine = 0; outLine < sparseDecoded.length; outLine += 1) {
|
|
3935
|
+
const sparseSegments = sparseDecoded[outLine];
|
|
3936
|
+
if (!sparseSegments || sparseSegments.length === 0) {
|
|
3937
|
+
hydratedMappings.push([]);
|
|
3938
|
+
continue;
|
|
3939
|
+
}
|
|
3940
|
+
const anchor = sparseSegments[0];
|
|
3941
|
+
if (!anchor || anchor.length < 4) {
|
|
3942
|
+
hydratedMappings.push(sparseSegments);
|
|
3943
|
+
continue;
|
|
3944
|
+
}
|
|
3945
|
+
const [, srcIdx, srcLine] = anchor;
|
|
3946
|
+
if (srcIdx !== 0 || srcLine === void 0 || srcLine < 0 || srcLine >= inputDecoded.length) {
|
|
3947
|
+
hydratedMappings.push(sparseSegments);
|
|
3948
|
+
continue;
|
|
3949
|
+
}
|
|
3950
|
+
const inputSegments = inputDecoded[srcLine];
|
|
3951
|
+
if (!inputSegments || inputSegments.length === 0) {
|
|
3952
|
+
hydratedMappings.push(sparseSegments);
|
|
3953
|
+
continue;
|
|
3954
|
+
}
|
|
3955
|
+
const anchorOutCol = anchor[0];
|
|
3956
|
+
const anchorSrcCol = anchor.length >= 4 ? anchor[3] : 0;
|
|
3957
|
+
const delta = anchorOutCol - (anchorSrcCol ?? 0);
|
|
3958
|
+
const outputLine = outputLines[outLine] || "";
|
|
3959
|
+
const hydratedSegments = [];
|
|
3960
|
+
for (const seg of inputSegments) {
|
|
3961
|
+
const adjustedCol = seg[0] + delta;
|
|
3962
|
+
if (adjustedCol < 0 || adjustedCol > outputLine.length)
|
|
3963
|
+
continue;
|
|
3964
|
+
if (seg.length === 5) {
|
|
3965
|
+
hydratedSegments.push([adjustedCol, seg[1], seg[2], seg[3], seg[4]]);
|
|
3966
|
+
} else if (seg.length === 4) {
|
|
3967
|
+
hydratedSegments.push([adjustedCol, seg[1], seg[2], seg[3]]);
|
|
3968
|
+
} else {
|
|
3969
|
+
hydratedSegments.push([adjustedCol]);
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
hydratedSegments.sort((a, b) => a[0] - b[0]);
|
|
3973
|
+
hydratedMappings.push(hydratedSegments);
|
|
3974
|
+
}
|
|
3975
|
+
return encode(hydratedMappings);
|
|
3976
|
+
}
|
|
3977
|
+
async function loadInputSourcemap(info) {
|
|
3978
|
+
const { fileName, originalCode } = info;
|
|
3979
|
+
const inlineConverter = convert$1.fromSource(originalCode);
|
|
3980
|
+
if (inlineConverter) {
|
|
3981
|
+
return inlineConverter.toObject();
|
|
3982
|
+
}
|
|
3983
|
+
const readMap = async (mapFile) => {
|
|
3984
|
+
const urlWithoutQuery = mapFile.split(/[?#]/)[0];
|
|
3985
|
+
const mapFilePath = path.resolve(path.dirname(fileName), urlWithoutQuery);
|
|
3986
|
+
return fs.readFile(mapFilePath, "utf8");
|
|
3987
|
+
};
|
|
3988
|
+
try {
|
|
3989
|
+
const fileConverter = await convert$1.fromMapFileSource(originalCode, readMap);
|
|
3990
|
+
if (fileConverter) {
|
|
3991
|
+
return fileConverter.toObject();
|
|
3992
|
+
}
|
|
3993
|
+
} catch {
|
|
3994
|
+
}
|
|
3995
|
+
try {
|
|
3996
|
+
const mapContent = await fs.readFile(fileName + ".map", "utf8");
|
|
3997
|
+
return JSON.parse(mapContent);
|
|
3998
|
+
} catch {
|
|
3999
|
+
return null;
|
|
4000
|
+
}
|
|
4001
|
+
}
|
|
4002
|
+
const transform = () => {
|
|
4003
|
+
const allTypeReferences = /* @__PURE__ */ new Map();
|
|
4004
|
+
const allFileReferences = /* @__PURE__ */ new Map();
|
|
4005
|
+
const pendingSourcemaps = /* @__PURE__ */ new Map();
|
|
4006
|
+
return {
|
|
4007
|
+
name: "dts-transform",
|
|
4008
|
+
buildStart() {
|
|
4009
|
+
allTypeReferences.clear();
|
|
4010
|
+
allFileReferences.clear();
|
|
4011
|
+
pendingSourcemaps.clear();
|
|
4012
|
+
},
|
|
4013
|
+
options({ onLog, ...options }) {
|
|
4014
|
+
return {
|
|
4015
|
+
...options,
|
|
4016
|
+
onLog(level, log, defaultHandler) {
|
|
4017
|
+
if (level === "warn" && log.code === "CIRCULAR_DEPENDENCY") {
|
|
4018
|
+
return;
|
|
4019
|
+
}
|
|
4020
|
+
if (onLog) {
|
|
4021
|
+
onLog(level, log, defaultHandler);
|
|
4022
|
+
} else {
|
|
4023
|
+
defaultHandler(level, log);
|
|
4024
|
+
}
|
|
4025
|
+
},
|
|
4026
|
+
treeshake: {
|
|
4027
|
+
moduleSideEffects: "no-external",
|
|
4028
|
+
propertyReadSideEffects: true,
|
|
4029
|
+
unknownGlobalSideEffects: false
|
|
4030
|
+
}
|
|
4031
|
+
};
|
|
4032
|
+
},
|
|
4033
|
+
outputOptions(options) {
|
|
4034
|
+
return {
|
|
4035
|
+
...options,
|
|
4036
|
+
chunkFileNames: options.chunkFileNames || "[name]-[hash].d.ts",
|
|
4037
|
+
entryFileNames: options.entryFileNames || "[name].d.ts",
|
|
4038
|
+
format: "es",
|
|
4039
|
+
exports: "named",
|
|
4040
|
+
compact: false,
|
|
4041
|
+
freeze: true,
|
|
4042
|
+
interop: "esModule",
|
|
4043
|
+
generatedCode: Object.assign({ symbols: false }, options.generatedCode),
|
|
4044
|
+
strict: false
|
|
4045
|
+
};
|
|
4046
|
+
},
|
|
4047
|
+
transform(code, fileName) {
|
|
4048
|
+
const name = trimExtension(fileName);
|
|
4049
|
+
const moduleIds = this.getModuleIds();
|
|
4050
|
+
const moduleId = Array.from(moduleIds).find((id) => trimExtension(id) === name);
|
|
4051
|
+
const isEntry = Boolean(moduleId && this.getModuleInfo(moduleId)?.isEntry);
|
|
4052
|
+
const isJSON = Boolean(moduleId && JSON_EXTENSIONS.test(moduleId));
|
|
4053
|
+
let sourceFile = parse(fileName, code);
|
|
4054
|
+
const preprocessed = preProcess({ sourceFile, isEntry, isJSON });
|
|
4055
|
+
allTypeReferences.set(sourceFile.fileName, preprocessed.typeReferences);
|
|
4056
|
+
allFileReferences.set(sourceFile.fileName, preprocessed.fileReferences);
|
|
4057
|
+
code = preprocessed.code.toString();
|
|
4058
|
+
sourceFile = parse(fileName, code);
|
|
4059
|
+
const converted = convert({ sourceFile });
|
|
4060
|
+
if (process.env.DTS_DUMP_AST) {
|
|
4061
|
+
console.log(fileName);
|
|
4062
|
+
console.log(code);
|
|
4063
|
+
console.log(JSON.stringify(converted.ast.body, void 0, 2));
|
|
4064
|
+
}
|
|
4065
|
+
const map = preprocessed.code.generateMap({ hires: true, source: fileName });
|
|
4066
|
+
if (DTS_EXTENSIONS.test(fileName)) {
|
|
4067
|
+
pendingSourcemaps.set(fileName, {
|
|
4068
|
+
fileName,
|
|
4069
|
+
originalCode: code
|
|
4070
|
+
});
|
|
4071
|
+
}
|
|
4072
|
+
return { code, ast: converted.ast, map };
|
|
4073
|
+
},
|
|
4074
|
+
renderChunk(inputCode, chunk, options) {
|
|
4075
|
+
const source = parse(chunk.fileName, inputCode);
|
|
4076
|
+
const fixer = new NamespaceFixer(source);
|
|
4077
|
+
const typeReferences = /* @__PURE__ */ new Set();
|
|
4078
|
+
const fileReferences = /* @__PURE__ */ new Set();
|
|
4079
|
+
for (const fileName of Object.keys(chunk.modules)) {
|
|
4080
|
+
for (const ref of allTypeReferences.get(fileName.split("\\").join("/")) || []) {
|
|
4081
|
+
typeReferences.add(ref);
|
|
4082
|
+
}
|
|
4083
|
+
for (const ref of allFileReferences.get(fileName.split("\\").join("/")) || []) {
|
|
4084
|
+
if (ref.startsWith(".")) {
|
|
4085
|
+
const absolutePathToOriginal = path.join(path.dirname(fileName), ref);
|
|
4086
|
+
const chunkFolder = options.file && path.dirname(options.file) || chunk.facadeModuleId && path.dirname(chunk.facadeModuleId) || ".";
|
|
4087
|
+
let targetRelPath = path.relative(chunkFolder, absolutePathToOriginal).split("\\").join("/");
|
|
4088
|
+
if (targetRelPath[0] !== ".") {
|
|
4089
|
+
targetRelPath = "./" + targetRelPath;
|
|
4090
|
+
}
|
|
4091
|
+
fileReferences.add(targetRelPath);
|
|
4092
|
+
} else {
|
|
4093
|
+
fileReferences.add(ref);
|
|
4094
|
+
}
|
|
4095
|
+
}
|
|
4096
|
+
}
|
|
4097
|
+
let code = writeBlock(Array.from(fileReferences, (ref) => `/// <reference path="${ref}" />`));
|
|
4098
|
+
code += writeBlock(Array.from(typeReferences, (ref) => `/// <reference types="${ref}" />`));
|
|
4099
|
+
code += fixer.fix();
|
|
4100
|
+
if (!code) {
|
|
4101
|
+
code += "\nexport { };";
|
|
4102
|
+
}
|
|
4103
|
+
const typeOnlyFixer = new TypeOnlyFixer(chunk.fileName, code);
|
|
4104
|
+
const typesFixed = typeOnlyFixer.fix();
|
|
4105
|
+
const relativeModuleDeclarationFixed = new RelativeModuleDeclarationFixer(chunk.fileName, "magicCode" in typesFixed && typesFixed.magicCode ? typesFixed.magicCode : new MagicString(code), !!options.sourcemap, "./" + path.basename(chunk.fileName, ".d.ts"));
|
|
4106
|
+
return relativeModuleDeclarationFixed.fix();
|
|
4107
|
+
},
|
|
4108
|
+
async generateBundle(options, bundle) {
|
|
4109
|
+
if (!options.sourcemap)
|
|
4110
|
+
return;
|
|
4111
|
+
const inputSourcemaps = /* @__PURE__ */ new Map();
|
|
4112
|
+
const entries = Array.from(pendingSourcemaps.entries());
|
|
4113
|
+
const loadedMaps = await Promise.all(entries.map(async ([fileName, info]) => ({
|
|
4114
|
+
fileName,
|
|
4115
|
+
inputMap: await loadInputSourcemap(info)
|
|
4116
|
+
})));
|
|
4117
|
+
for (const { fileName, inputMap } of loadedMaps) {
|
|
4118
|
+
if (inputMap && inputMap.sources) {
|
|
4119
|
+
const inputMapDir = path.dirname(fileName);
|
|
4120
|
+
inputSourcemaps.set(fileName, {
|
|
4121
|
+
version: inputMap.version ?? 3,
|
|
4122
|
+
sources: inputMap.sources.map((source) => path.isAbsolute(source) ? source : path.resolve(inputMapDir, source)),
|
|
4123
|
+
sourcesContent: inputMap.sourcesContent,
|
|
4124
|
+
mappings: inputMap.mappings,
|
|
4125
|
+
names: inputMap.names
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
4128
|
+
}
|
|
4129
|
+
const outputDir = options.dir || (options.file ? path.dirname(options.file) : process.cwd());
|
|
4130
|
+
for (const chunk of Object.values(bundle)) {
|
|
4131
|
+
if (chunk.type !== "chunk" || !chunk.map)
|
|
4132
|
+
continue;
|
|
4133
|
+
const chunkDir = path.join(outputDir, path.dirname(chunk.fileName));
|
|
4134
|
+
const toRelativeSourcePath = (source) => {
|
|
4135
|
+
const relative = path.isAbsolute(source) ? path.relative(chunkDir, source) : source;
|
|
4136
|
+
return relative.replaceAll("\\", "/");
|
|
4137
|
+
};
|
|
4138
|
+
const sourcesToRemap = /* @__PURE__ */ new Map();
|
|
4139
|
+
for (const source of chunk.map.sources) {
|
|
4140
|
+
if (!source)
|
|
4141
|
+
continue;
|
|
4142
|
+
const absoluteSource = path.resolve(chunkDir, source);
|
|
4143
|
+
const inputMap = inputSourcemaps.get(absoluteSource);
|
|
4144
|
+
if (inputMap) {
|
|
4145
|
+
sourcesToRemap.set(absoluteSource, inputMap);
|
|
4146
|
+
}
|
|
4147
|
+
}
|
|
4148
|
+
if (sourcesToRemap.size === 0) {
|
|
4149
|
+
if (chunk.map.sources.length === 0 && chunk.facadeModuleId) {
|
|
4150
|
+
const inputMap = inputSourcemaps.get(chunk.facadeModuleId);
|
|
4151
|
+
if (inputMap && inputMap.sources.length > 0) {
|
|
4152
|
+
const newSources2 = inputMap.sources.map(toRelativeSourcePath);
|
|
4153
|
+
const newSourcesContent2 = inputMap.sourcesContent || [];
|
|
4154
|
+
chunk.map.sources = newSources2;
|
|
4155
|
+
chunk.map.sourcesContent = newSourcesContent2;
|
|
4156
|
+
updateSourcemapAsset(bundle, chunk.fileName, {
|
|
4157
|
+
sources: newSources2,
|
|
4158
|
+
sourcesContent: newSourcesContent2,
|
|
4159
|
+
mappings: chunk.map.mappings,
|
|
4160
|
+
names: chunk.map.names || []
|
|
4161
|
+
});
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4164
|
+
continue;
|
|
4165
|
+
}
|
|
4166
|
+
const isSingleSource = chunk.map.sources.length === 1 && sourcesToRemap.size === 1;
|
|
4167
|
+
const singleInputMap = isSingleSource ? Array.from(sourcesToRemap.values())[0] : null;
|
|
4168
|
+
const canSimplyReplace = singleInputMap && singleInputMap.sources.length === 1;
|
|
4169
|
+
let newSources;
|
|
4170
|
+
let newSourcesContent;
|
|
4171
|
+
let newMappings;
|
|
4172
|
+
let newNames;
|
|
4173
|
+
if (canSimplyReplace && singleInputMap) {
|
|
4174
|
+
newSources = singleInputMap.sources.map(toRelativeSourcePath);
|
|
4175
|
+
newSourcesContent = singleInputMap.sourcesContent || [null];
|
|
4176
|
+
newMappings = hydrateSourcemap(chunk.map.mappings, singleInputMap, chunk.code);
|
|
4177
|
+
newNames = singleInputMap.names || [];
|
|
4178
|
+
} else {
|
|
4179
|
+
const remapped = remapping(chunk.map, (file) => {
|
|
4180
|
+
const absolutePath = path.resolve(chunkDir, file);
|
|
4181
|
+
const inputMap = sourcesToRemap.get(absolutePath);
|
|
4182
|
+
if (inputMap) {
|
|
4183
|
+
return inputMap;
|
|
4184
|
+
}
|
|
4185
|
+
return null;
|
|
4186
|
+
});
|
|
4187
|
+
newSources = remapped.sources.filter((s) => s !== null).map(toRelativeSourcePath);
|
|
4188
|
+
newSourcesContent = remapped.sourcesContent || [];
|
|
4189
|
+
newMappings = typeof remapped.mappings === "string" ? remapped.mappings : "";
|
|
4190
|
+
newNames = remapped.names || [];
|
|
4191
|
+
}
|
|
4192
|
+
chunk.map.sources = newSources;
|
|
4193
|
+
chunk.map.sourcesContent = newSourcesContent;
|
|
4194
|
+
chunk.map.mappings = newMappings;
|
|
4195
|
+
chunk.map.names = newNames;
|
|
4196
|
+
updateSourcemapAsset(bundle, chunk.fileName, {
|
|
4197
|
+
sources: newSources,
|
|
4198
|
+
sourcesContent: newSourcesContent,
|
|
4199
|
+
mappings: newMappings,
|
|
4200
|
+
names: newNames
|
|
4201
|
+
});
|
|
4202
|
+
}
|
|
4203
|
+
}
|
|
4204
|
+
};
|
|
4205
|
+
};
|
|
4206
|
+
function writeBlock(codes) {
|
|
4207
|
+
if (codes.length) {
|
|
4208
|
+
return codes.join("\n") + "\n";
|
|
4209
|
+
}
|
|
4210
|
+
return "";
|
|
4211
|
+
}
|
|
4212
|
+
function updateSourcemapAsset(bundle, chunkFileName, data) {
|
|
4213
|
+
const mapFileName = `${chunkFileName}.map`;
|
|
4214
|
+
const mapAsset = bundle[mapFileName];
|
|
4215
|
+
if (mapAsset && mapAsset.type === "asset") {
|
|
4216
|
+
mapAsset.source = JSON.stringify({
|
|
4217
|
+
version: 3,
|
|
4218
|
+
// file should be just the basename since the .map is in the same directory
|
|
4219
|
+
file: path.basename(chunkFileName),
|
|
4220
|
+
...data
|
|
4221
|
+
});
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
const TS_EXTENSIONS = /\.([cm]ts|[tj]sx?)$/;
|
|
4225
|
+
function getModule({ entries, programs, resolvedOptions }, fileName, code) {
|
|
4226
|
+
const { compilerOptions, tsconfig } = resolvedOptions;
|
|
4227
|
+
if (!programs.length && DTS_EXTENSIONS.test(fileName)) {
|
|
4228
|
+
return { code };
|
|
4229
|
+
}
|
|
4230
|
+
const isEntry = entries.includes(fileName);
|
|
4231
|
+
const existingProgram = programs.find((p) => {
|
|
4232
|
+
if (isEntry) {
|
|
4233
|
+
return p.getRootFileNames().includes(fileName);
|
|
4234
|
+
} else {
|
|
4235
|
+
const sourceFile = p.getSourceFile(fileName);
|
|
4236
|
+
if (sourceFile && p.isSourceFileFromExternalLibrary(sourceFile)) {
|
|
4237
|
+
return false;
|
|
4238
|
+
}
|
|
4239
|
+
return !!sourceFile;
|
|
4240
|
+
}
|
|
4241
|
+
});
|
|
4242
|
+
if (existingProgram) {
|
|
4243
|
+
const source = existingProgram.getSourceFile(fileName);
|
|
4244
|
+
return {
|
|
4245
|
+
code: source?.getFullText(),
|
|
4246
|
+
source,
|
|
4247
|
+
program: existingProgram
|
|
4248
|
+
};
|
|
4249
|
+
} else if (ts.sys.fileExists(fileName)) {
|
|
4250
|
+
if (programs.length > 0 && DTS_EXTENSIONS.test(fileName)) {
|
|
4251
|
+
const shouldBundleExternal = resolvedOptions.includeExternal.length > 0 || resolvedOptions.respectExternal;
|
|
4252
|
+
if (shouldBundleExternal) {
|
|
4253
|
+
return { code };
|
|
4254
|
+
}
|
|
4255
|
+
}
|
|
4256
|
+
const newProgram = createProgram$1(fileName, compilerOptions, tsconfig);
|
|
4257
|
+
programs.push(newProgram);
|
|
4258
|
+
const source = newProgram.getSourceFile(fileName);
|
|
4259
|
+
return {
|
|
4260
|
+
code: source?.getFullText(),
|
|
4261
|
+
source,
|
|
4262
|
+
program: newProgram
|
|
4263
|
+
};
|
|
4264
|
+
} else {
|
|
4265
|
+
return null;
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
4268
|
+
const plugin = (options = {}) => {
|
|
4269
|
+
const transformPlugin = transform();
|
|
4270
|
+
const ctx = { entries: [], programs: [], resolvedOptions: resolveDefaultOptions(options) };
|
|
4271
|
+
return {
|
|
4272
|
+
name: "dts",
|
|
4273
|
+
// pass outputOptions, renderChunk, and generateBundle hooks to the inner transform plugin
|
|
4274
|
+
outputOptions: transformPlugin.outputOptions,
|
|
4275
|
+
renderChunk: transformPlugin.renderChunk,
|
|
4276
|
+
generateBundle: transformPlugin.generateBundle,
|
|
4277
|
+
options(options2) {
|
|
4278
|
+
let { input = [] } = options2;
|
|
4279
|
+
if (!Array.isArray(input)) {
|
|
4280
|
+
input = typeof input === "string" ? [input] : Object.values(input);
|
|
4281
|
+
} else if (input.length > 1) {
|
|
4282
|
+
options2.input = {};
|
|
4283
|
+
for (const filename of input) {
|
|
4284
|
+
let name = trimExtension(filename);
|
|
4285
|
+
if (path.isAbsolute(filename)) {
|
|
4286
|
+
name = path.basename(name);
|
|
4287
|
+
} else {
|
|
4288
|
+
name = path.normalize(name);
|
|
4289
|
+
}
|
|
4290
|
+
options2.input[name] = filename;
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
ctx.programs = createPrograms(Object.values(input), ctx.resolvedOptions.compilerOptions, ctx.resolvedOptions.tsconfig);
|
|
4294
|
+
return transformPlugin.options.call(this, options2);
|
|
4295
|
+
},
|
|
4296
|
+
transform(code, id) {
|
|
4297
|
+
if (!TS_EXTENSIONS.test(id) && !JSON_EXTENSIONS.test(id)) {
|
|
4298
|
+
return null;
|
|
4299
|
+
}
|
|
4300
|
+
const watchFiles = (module) => {
|
|
4301
|
+
if (module.program) {
|
|
4302
|
+
const sourceDirectory = path.dirname(id);
|
|
4303
|
+
const sourceFilesInProgram = module.program.getSourceFiles().map((sourceFile) => sourceFile.fileName).filter((fileName) => fileName.startsWith(sourceDirectory));
|
|
4304
|
+
sourceFilesInProgram.forEach(this.addWatchFile);
|
|
4305
|
+
}
|
|
4306
|
+
};
|
|
4307
|
+
const handleDtsFile = () => {
|
|
4308
|
+
const module = getModule(ctx, id, code);
|
|
4309
|
+
if (module) {
|
|
4310
|
+
watchFiles(module);
|
|
4311
|
+
return transformPlugin.transform.call(this, module.code, id);
|
|
4312
|
+
}
|
|
4313
|
+
return null;
|
|
4314
|
+
};
|
|
4315
|
+
const treatTsAsDts = () => {
|
|
4316
|
+
const declarationId = getDeclarationId(id);
|
|
4317
|
+
const module = getModule(ctx, declarationId, code);
|
|
4318
|
+
if (module) {
|
|
4319
|
+
watchFiles(module);
|
|
4320
|
+
return transformPlugin.transform.call(this, module.code, declarationId);
|
|
4321
|
+
}
|
|
4322
|
+
return null;
|
|
4323
|
+
};
|
|
4324
|
+
const generateDts = () => {
|
|
4325
|
+
const module = getModule(ctx, id, code);
|
|
4326
|
+
if (!module || !module.source || !module.program)
|
|
4327
|
+
return null;
|
|
4328
|
+
watchFiles(module);
|
|
4329
|
+
const declarationId = getDeclarationId(id);
|
|
4330
|
+
let generated;
|
|
4331
|
+
const { emitSkipped, diagnostics } = module.program.emit(
|
|
4332
|
+
module.source,
|
|
4333
|
+
(_, declarationText) => {
|
|
4334
|
+
generated = transformPlugin.transform.call(this, declarationText, declarationId);
|
|
4335
|
+
},
|
|
4336
|
+
void 0,
|
|
4337
|
+
// cancellationToken
|
|
4338
|
+
true,
|
|
4339
|
+
// emitOnlyDtsFiles
|
|
4340
|
+
void 0,
|
|
4341
|
+
// customTransformers
|
|
4342
|
+
// @ts-ignore This is a private API for workers, should be safe to use as TypeScript Playground has used it for a long time.
|
|
4343
|
+
true
|
|
4344
|
+
);
|
|
4345
|
+
if (emitSkipped) {
|
|
4346
|
+
const errors = diagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error);
|
|
4347
|
+
if (errors.length) {
|
|
4348
|
+
console.error(ts.formatDiagnostics(errors, formatHost));
|
|
4349
|
+
this.error("Failed to compile. Check the logs above.");
|
|
4350
|
+
}
|
|
4351
|
+
}
|
|
4352
|
+
return generated;
|
|
4353
|
+
};
|
|
4354
|
+
if (DTS_EXTENSIONS.test(id))
|
|
4355
|
+
return handleDtsFile();
|
|
4356
|
+
if (JSON_EXTENSIONS.test(id))
|
|
4357
|
+
return generateDts();
|
|
4358
|
+
return treatTsAsDts() ?? generateDts();
|
|
4359
|
+
},
|
|
4360
|
+
resolveId(source, importer) {
|
|
4361
|
+
if (!importer) {
|
|
4362
|
+
ctx.entries.push(path.resolve(source));
|
|
4363
|
+
return;
|
|
4364
|
+
}
|
|
4365
|
+
importer = importer.split("\\").join("/");
|
|
4366
|
+
let resolvedCompilerOptions = ctx.resolvedOptions.compilerOptions;
|
|
4367
|
+
if (ctx.resolvedOptions.tsconfig) {
|
|
4368
|
+
const resolvedSource = source.startsWith(".") ? path.resolve(path.dirname(importer), source) : source;
|
|
4369
|
+
resolvedCompilerOptions = getCompilerOptions(resolvedSource, ctx.resolvedOptions.compilerOptions, ctx.resolvedOptions.tsconfig).compilerOptions;
|
|
4370
|
+
}
|
|
4371
|
+
const { resolvedModule } = ts.resolveModuleName(source, importer, resolvedCompilerOptions, ts.sys);
|
|
4372
|
+
if (!resolvedModule) {
|
|
4373
|
+
return;
|
|
4374
|
+
}
|
|
4375
|
+
if (resolvedModule.isExternalLibraryImport && resolvedModule.packageId && ctx.resolvedOptions.includeExternal.includes(resolvedModule.packageId.name)) {
|
|
4376
|
+
return { id: path.resolve(resolvedModule.resolvedFileName) };
|
|
4377
|
+
} else if (!ctx.resolvedOptions.respectExternal && resolvedModule.isExternalLibraryImport) {
|
|
4378
|
+
return { id: source, external: true };
|
|
4379
|
+
} else {
|
|
4380
|
+
return { id: path.resolve(resolvedModule.resolvedFileName) };
|
|
4381
|
+
}
|
|
4382
|
+
}
|
|
4383
|
+
};
|
|
4384
|
+
};
|
|
4385
|
+
|
|
4386
|
+
const createExternalizePlugin = (configuredExternals) => {
|
|
4387
|
+
const resolvedBareSpecifiers = /* @__PURE__ */ new Map();
|
|
4388
|
+
const importPath = /* @__PURE__ */ new Map();
|
|
4389
|
+
const externalized = /* @__PURE__ */ new Map();
|
|
4390
|
+
const externalizePlugin = {
|
|
4391
|
+
name: "externalize",
|
|
4392
|
+
async resolveId(id, importer, options) {
|
|
4393
|
+
const packageName = !isPath(id) && getPackageName(id);
|
|
4394
|
+
if (packageName) {
|
|
4395
|
+
const externalReason = configuredExternals.get(packageName);
|
|
4396
|
+
if (externalReason) {
|
|
4397
|
+
externalized.set(packageName, externalReason);
|
|
4398
|
+
return {
|
|
4399
|
+
id,
|
|
4400
|
+
external: true
|
|
4401
|
+
};
|
|
4402
|
+
}
|
|
4403
|
+
}
|
|
4404
|
+
const resolved = await this.resolve(id, importer, options);
|
|
4405
|
+
if (resolved) {
|
|
4406
|
+
if (packageName) {
|
|
4407
|
+
resolvedBareSpecifiers.set(resolved.id, id);
|
|
4408
|
+
}
|
|
4409
|
+
if (
|
|
4410
|
+
// Self imports happen
|
|
4411
|
+
importer && resolved.id !== importer && importPath.get(importer) !== resolved.id
|
|
4412
|
+
) {
|
|
4413
|
+
importPath.set(resolved.id, importer);
|
|
4414
|
+
}
|
|
4415
|
+
return resolved;
|
|
4416
|
+
}
|
|
4417
|
+
if (packageName) {
|
|
4418
|
+
externalized.set(packageName, "because unresolvable");
|
|
4419
|
+
return {
|
|
4420
|
+
id,
|
|
4421
|
+
external: true
|
|
4422
|
+
};
|
|
4423
|
+
}
|
|
4424
|
+
}
|
|
4425
|
+
};
|
|
4426
|
+
const getPackageEntryPoint = (subpackagePath) => {
|
|
4427
|
+
let i = 0;
|
|
4428
|
+
let lastEntry = subpackagePath;
|
|
4429
|
+
do {
|
|
4430
|
+
if (resolvedBareSpecifiers.has(lastEntry)) {
|
|
4431
|
+
return resolvedBareSpecifiers.get(lastEntry);
|
|
4432
|
+
}
|
|
4433
|
+
lastEntry = importPath.get(lastEntry);
|
|
4434
|
+
i += 1;
|
|
4435
|
+
} while (lastEntry && i < 100);
|
|
4436
|
+
};
|
|
4437
|
+
return {
|
|
4438
|
+
externalizePlugin,
|
|
4439
|
+
externalized,
|
|
4440
|
+
getPackageEntryPoint
|
|
4441
|
+
};
|
|
4442
|
+
};
|
|
4443
|
+
|
|
4444
|
+
const createImportChainPlugin = () => {
|
|
4445
|
+
const importerMap = /* @__PURE__ */ new Map();
|
|
4446
|
+
const plugin = {
|
|
4447
|
+
name: "import-chain-tracker",
|
|
4448
|
+
buildStart: () => {
|
|
4449
|
+
importerMap.clear();
|
|
4450
|
+
},
|
|
4451
|
+
async resolveId(source, importer) {
|
|
4452
|
+
if (!importer) {
|
|
4453
|
+
return null;
|
|
4454
|
+
}
|
|
4455
|
+
const resolved = await this.resolve(source, importer, { skipSelf: true });
|
|
4456
|
+
if (resolved && !resolved.external && !importerMap.has(resolved.id)) {
|
|
4457
|
+
importerMap.set(resolved.id, importer);
|
|
4458
|
+
}
|
|
4459
|
+
return null;
|
|
4460
|
+
}
|
|
4461
|
+
};
|
|
4462
|
+
const getImportChain = (errorFileId) => {
|
|
4463
|
+
const chain = [];
|
|
4464
|
+
let current = errorFileId;
|
|
4465
|
+
while (current) {
|
|
4466
|
+
chain.unshift(current);
|
|
4467
|
+
current = importerMap.get(current);
|
|
4468
|
+
}
|
|
4469
|
+
return chain;
|
|
4470
|
+
};
|
|
4471
|
+
return {
|
|
4472
|
+
plugin,
|
|
4473
|
+
getImportChain
|
|
4474
|
+
};
|
|
4475
|
+
};
|
|
4476
|
+
|
|
4477
|
+
const nodeModules = `${path__default.sep}node_modules${path__default.sep}`;
|
|
4478
|
+
const removeBundledModulesPlugin = (outputDirectory, sizeRef) => {
|
|
4479
|
+
let deleteFiles = [];
|
|
4480
|
+
return {
|
|
4481
|
+
name: "remove-bundled-modules",
|
|
4482
|
+
transform: {
|
|
4483
|
+
// Get size of raw code before other transformations
|
|
4484
|
+
order: "pre",
|
|
4485
|
+
handler: (code) => ({
|
|
4486
|
+
meta: {
|
|
4487
|
+
size: Buffer.byteLength(code)
|
|
4488
|
+
}
|
|
4489
|
+
})
|
|
4490
|
+
},
|
|
4491
|
+
async generateBundle(options, bundle) {
|
|
4492
|
+
const modules = Object.values(bundle);
|
|
4493
|
+
const bundledFiles = Array.from(new Set(modules.flatMap(({ moduleIds }) => moduleIds)));
|
|
4494
|
+
let totalSize = 0;
|
|
4495
|
+
for (const moduleId of bundledFiles) {
|
|
4496
|
+
const moduleInfo = this.getModuleInfo(moduleId);
|
|
4497
|
+
const size = moduleInfo?.meta?.size;
|
|
4498
|
+
if (typeof size === "number") {
|
|
4499
|
+
totalSize += size;
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
sizeRef.value = totalSize;
|
|
4503
|
+
const outputFiles = new Set(modules.map(({ fileName }) => path__default.join(options.dir, fileName)));
|
|
4504
|
+
deleteFiles = bundledFiles.filter((moduleId) => moduleId && moduleId.startsWith(outputDirectory) && !moduleId.includes(nodeModules) && !outputFiles.has(moduleId));
|
|
4505
|
+
},
|
|
4506
|
+
writeBundle: async () => {
|
|
4507
|
+
await Promise.all(
|
|
4508
|
+
deleteFiles.flatMap((moduleId) => [
|
|
4509
|
+
fs.rm(moduleId),
|
|
4510
|
+
// Also delete orphaned sourcemap files
|
|
4511
|
+
fs.rm(`${moduleId}.map`, { force: true })
|
|
4512
|
+
])
|
|
4513
|
+
);
|
|
4514
|
+
}
|
|
4515
|
+
};
|
|
4516
|
+
};
|
|
4517
|
+
|
|
4518
|
+
const packageJsonCache = /* @__PURE__ */ new Map();
|
|
4519
|
+
const findPackageJsonUp = async (cwd) => {
|
|
4520
|
+
const packageJsonPath = up("package.json", { cwd });
|
|
4521
|
+
if (!packageJsonPath) {
|
|
4522
|
+
return void 0;
|
|
4523
|
+
}
|
|
4524
|
+
const packageRoot = path__default.dirname(packageJsonPath);
|
|
4525
|
+
let packageJson = packageJsonCache.get(packageRoot);
|
|
4526
|
+
if (!packageJson) {
|
|
4527
|
+
try {
|
|
4528
|
+
const content = await fs.readFile(packageJsonPath, "utf8");
|
|
4529
|
+
packageJson = JSON.parse(content);
|
|
4530
|
+
packageJsonCache.set(packageRoot, packageJson);
|
|
4531
|
+
} catch {
|
|
4532
|
+
return void 0;
|
|
4533
|
+
}
|
|
4534
|
+
}
|
|
4535
|
+
if (packageJson.imports) {
|
|
4536
|
+
return {
|
|
4537
|
+
imports: packageJson.imports,
|
|
4538
|
+
packageRoot
|
|
4539
|
+
};
|
|
4540
|
+
}
|
|
4541
|
+
};
|
|
4542
|
+
const resolveSubpathImportsPlugin = () => ({
|
|
4543
|
+
name: "resolve-subpath-imports",
|
|
4544
|
+
async resolveId(id, importer) {
|
|
4545
|
+
if (id[0] !== "#" || !importer) {
|
|
4546
|
+
return null;
|
|
4547
|
+
}
|
|
4548
|
+
const result = await findPackageJsonUp(path__default.dirname(importer));
|
|
4549
|
+
if (!result) {
|
|
4550
|
+
return null;
|
|
4551
|
+
}
|
|
4552
|
+
const { imports, packageRoot } = result;
|
|
4553
|
+
let resolvedPaths;
|
|
4554
|
+
try {
|
|
4555
|
+
resolvedPaths = resolveImports(imports, id, ["types", "import"]);
|
|
4556
|
+
} catch {
|
|
4557
|
+
return null;
|
|
4558
|
+
}
|
|
4559
|
+
if (resolvedPaths.length === 0) {
|
|
4560
|
+
return null;
|
|
4561
|
+
}
|
|
4562
|
+
return this.resolve(
|
|
4563
|
+
path__default.join(packageRoot, resolvedPaths[0]),
|
|
4564
|
+
importer,
|
|
4565
|
+
{ skipSelf: true }
|
|
4566
|
+
);
|
|
4567
|
+
}
|
|
4568
|
+
});
|
|
4569
|
+
|
|
4570
|
+
const createInputMap = (input, outputDirectory) => Object.fromEntries(
|
|
4571
|
+
input.map((inputFile) => [
|
|
4572
|
+
inputFile.slice(outputDirectory.length + 1),
|
|
4573
|
+
inputFile
|
|
4574
|
+
])
|
|
4575
|
+
);
|
|
4576
|
+
const build = async (input, outputDirectory, externals, mode, conditions, sourcemap) => {
|
|
4577
|
+
const {
|
|
4578
|
+
externalizePlugin,
|
|
4579
|
+
externalized,
|
|
4580
|
+
getPackageEntryPoint
|
|
4581
|
+
} = createExternalizePlugin(externals);
|
|
4582
|
+
const { plugin: importChainPlugin, getImportChain } = createImportChainPlugin();
|
|
4583
|
+
const sizeRef = {};
|
|
4584
|
+
const rollupConfig = {
|
|
4585
|
+
input: createInputMap(input, outputDirectory),
|
|
4586
|
+
output: {
|
|
4587
|
+
sourcemap,
|
|
4588
|
+
dir: outputDirectory,
|
|
4589
|
+
entryFileNames: "[name]",
|
|
4590
|
+
chunkFileNames: "_dtsroll-chunks/[hash]-[name].ts"
|
|
4591
|
+
},
|
|
4592
|
+
plugins: [
|
|
4593
|
+
importChainPlugin,
|
|
4594
|
+
externalizePlugin,
|
|
4595
|
+
removeBundledModulesPlugin(outputDirectory, sizeRef),
|
|
4596
|
+
resolveSubpathImportsPlugin(),
|
|
4597
|
+
nodeResolve({
|
|
4598
|
+
extensions: [".ts", ...dtsExtensions],
|
|
4599
|
+
exportConditions: conditions
|
|
4600
|
+
}),
|
|
4601
|
+
plugin({
|
|
4602
|
+
respectExternal: true
|
|
4603
|
+
/**
|
|
4604
|
+
* Setting a tsconfig or compilerOptions shouldn't be necessary since
|
|
4605
|
+
* we're dealing with pre-compiled d.ts files
|
|
4606
|
+
*
|
|
4607
|
+
* But may be something we need to support if we want to support
|
|
4608
|
+
* aliases in the future
|
|
4609
|
+
*/
|
|
4610
|
+
})
|
|
4611
|
+
]
|
|
4612
|
+
};
|
|
4613
|
+
try {
|
|
4614
|
+
const rollupBuild = await rollup(rollupConfig);
|
|
4615
|
+
const built = await rollupBuild[mode](rollupConfig.output);
|
|
4616
|
+
await rollupBuild.close();
|
|
4617
|
+
return {
|
|
4618
|
+
built,
|
|
4619
|
+
externalized,
|
|
4620
|
+
getPackageEntryPoint,
|
|
4621
|
+
sourceSize: sizeRef.value ?? 0
|
|
4622
|
+
};
|
|
4623
|
+
} catch (error) {
|
|
4624
|
+
if (error instanceof Error && "id" in error && typeof error.id === "string") {
|
|
4625
|
+
throw new DtsrollBuildError(
|
|
4626
|
+
error.message,
|
|
4627
|
+
error.id,
|
|
4628
|
+
getImportChain(error.id)
|
|
4629
|
+
);
|
|
4630
|
+
}
|
|
4631
|
+
throw error;
|
|
4632
|
+
}
|
|
4633
|
+
};
|
|
4634
|
+
|
|
4635
|
+
const dtsroll = async ({
|
|
4636
|
+
cwd = process.cwd(),
|
|
4637
|
+
inputs,
|
|
4638
|
+
external,
|
|
4639
|
+
conditions,
|
|
4640
|
+
dryRun,
|
|
4641
|
+
sourcemap
|
|
4642
|
+
} = {}) => {
|
|
4643
|
+
const pkgJson = await getPackageJson(cwd);
|
|
4644
|
+
const externals = pkgJson ? pkgJson.getExternals() : /* @__PURE__ */ new Map();
|
|
4645
|
+
if (external && external.length > 0) {
|
|
4646
|
+
if (pkgJson) {
|
|
4647
|
+
console.warn(`${warningPrefix} The --external flag is only supported when there is no package.json`);
|
|
4648
|
+
} else {
|
|
4649
|
+
for (const externalDependency of external) {
|
|
4650
|
+
externals.set(externalDependency, "by --external flag");
|
|
4651
|
+
}
|
|
4652
|
+
}
|
|
4653
|
+
}
|
|
4654
|
+
const manualInput = inputs && inputs.length > 0;
|
|
4655
|
+
const validatedInputs = await validateInput(
|
|
4656
|
+
manualInput ? inputs.map((file) => path__default.resolve(file)) : await pkgJson?.getDtsEntryPoints()
|
|
4657
|
+
);
|
|
4658
|
+
const inputFiles = validatedInputs.filter((input) => !input[2]).map(([file]) => file);
|
|
4659
|
+
if (inputFiles.length === 0) {
|
|
4660
|
+
return {
|
|
4661
|
+
inputs: validatedInputs,
|
|
4662
|
+
error: "No input files"
|
|
4663
|
+
};
|
|
4664
|
+
}
|
|
4665
|
+
const outputDirectory = getCommonDirectory(inputFiles);
|
|
4666
|
+
const {
|
|
4667
|
+
built,
|
|
4668
|
+
externalized,
|
|
4669
|
+
getPackageEntryPoint,
|
|
4670
|
+
sourceSize
|
|
4671
|
+
} = await build(
|
|
4672
|
+
inputFiles,
|
|
4673
|
+
outputDirectory,
|
|
4674
|
+
externals,
|
|
4675
|
+
dryRun ? "generate" : "write",
|
|
4676
|
+
conditions,
|
|
4677
|
+
sourcemap
|
|
4678
|
+
);
|
|
4679
|
+
let outputSize = 0;
|
|
4680
|
+
const outputEntries = [];
|
|
4681
|
+
const outputChunks = [];
|
|
4682
|
+
const moduleImports = /* @__PURE__ */ new Set();
|
|
4683
|
+
const chunks = built.output.filter((file) => file.type === "chunk");
|
|
4684
|
+
for (const file of chunks) {
|
|
4685
|
+
const size = Buffer.byteLength(file.code);
|
|
4686
|
+
outputSize += size;
|
|
4687
|
+
const moduleToPackage = Object.fromEntries(
|
|
4688
|
+
file.moduleIds.map((moduleId) => [moduleId, getPackageEntryPoint(moduleId)])
|
|
4689
|
+
);
|
|
4690
|
+
const chunkWithSize = Object.assign(file, {
|
|
4691
|
+
size,
|
|
4692
|
+
moduleToPackage
|
|
4693
|
+
});
|
|
4694
|
+
if (chunkWithSize.isEntry) {
|
|
4695
|
+
outputEntries.push(chunkWithSize);
|
|
4696
|
+
} else {
|
|
4697
|
+
outputChunks.push(chunkWithSize);
|
|
4698
|
+
}
|
|
4699
|
+
for (const id of file.imports) {
|
|
4700
|
+
moduleImports.add(getPackageName(id));
|
|
4701
|
+
}
|
|
4702
|
+
}
|
|
4703
|
+
const externalPackages = [];
|
|
4704
|
+
moduleImports.forEach((importedSpecifier) => {
|
|
4705
|
+
const reason = externalized.get(importedSpecifier);
|
|
4706
|
+
if (reason) {
|
|
4707
|
+
externalPackages.push([
|
|
4708
|
+
importedSpecifier,
|
|
4709
|
+
reason,
|
|
4710
|
+
pkgJson?.devTypePackages?.[importedSpecifier]
|
|
4711
|
+
]);
|
|
4712
|
+
}
|
|
4713
|
+
});
|
|
4714
|
+
return {
|
|
4715
|
+
inputs: validatedInputs,
|
|
4716
|
+
outputDirectory,
|
|
4717
|
+
output: {
|
|
4718
|
+
entries: outputEntries,
|
|
4719
|
+
chunks: outputChunks
|
|
4720
|
+
},
|
|
4721
|
+
size: {
|
|
4722
|
+
input: sourceSize,
|
|
4723
|
+
output: outputSize
|
|
4724
|
+
},
|
|
4725
|
+
externals: externalPackages
|
|
4726
|
+
};
|
|
4727
|
+
};
|
|
4728
|
+
|
|
4729
|
+
export { DtsrollBuildError as D, black as a, bgYellow as b, dtsroll as d, logOutput as l };
|