@pulsec/dts 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +49 -2
- package/bin/pulsec-dts.mjs +90 -0
- package/index.d.cts +166 -0
- package/index.d.ts +185 -0
- package/package.json +75 -4
- package/src/assemble.cjs +1483 -0
- package/src/bundler.cjs +834 -0
- package/src/index.cjs +14 -0
- package/src/index.mjs +20 -0
- package/src/resolver.cjs +536 -0
- package/src/tsconfig.cjs +241 -0
- package/src/vite-plugin.mjs +91 -0
- package/vite.d.ts +24 -0
package/src/bundler.cjs
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const fsp = require('node:fs/promises');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const { loadTsconfig } = require('./tsconfig.cjs');
|
|
7
|
+
const {
|
|
8
|
+
FastModuleResolver,
|
|
9
|
+
extractModuleSpecifiers,
|
|
10
|
+
normalizeVirtualPath,
|
|
11
|
+
toPosix,
|
|
12
|
+
} = require('./resolver.cjs');
|
|
13
|
+
|
|
14
|
+
const { assembleBundle } = require('./assemble.cjs');
|
|
15
|
+
|
|
16
|
+
function loadPulsecDts() {
|
|
17
|
+
if (!__dirname.includes(`${path.sep}node_modules${path.sep}`)) {
|
|
18
|
+
try {
|
|
19
|
+
return require('../../../src/dts.cjs');
|
|
20
|
+
} catch {
|
|
21
|
+
// fall through to package resolution
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return require('pulsec/dts');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const pulsecDts = loadPulsecDts();
|
|
28
|
+
const DTS_FILE_RE = /\.d\.(?:[cm]?ts)$/i;
|
|
29
|
+
|
|
30
|
+
function normalizeFileMap(rawFiles) {
|
|
31
|
+
if (!rawFiles) return null;
|
|
32
|
+
const out = Object.create(null);
|
|
33
|
+
for (const [k, v] of Object.entries(rawFiles)) {
|
|
34
|
+
out[normalizeVirtualPath(k)] = v;
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function sourcesEqual(a, b) {
|
|
40
|
+
if (a === b) return true;
|
|
41
|
+
if (typeof a === 'string' && typeof b === 'string') return a === b;
|
|
42
|
+
if (a instanceof Uint8Array && b instanceof Uint8Array) {
|
|
43
|
+
if (a.byteLength !== b.byteLength) return false;
|
|
44
|
+
return Buffer.compare(a, b) === 0;
|
|
45
|
+
}
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Creates an incremental in-memory cache for `.d.ts` emission results.
|
|
51
|
+
*/
|
|
52
|
+
function createDtsCache() {
|
|
53
|
+
const diskCache = new Map();
|
|
54
|
+
const memCache = new Map();
|
|
55
|
+
const stats = { hits: 0, misses: 0 };
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
stats,
|
|
59
|
+
getDisk(filePath, mtimeMs, size) {
|
|
60
|
+
const entry = diskCache.get(filePath);
|
|
61
|
+
if (entry && entry.mtimeMs === mtimeMs && entry.size === size) {
|
|
62
|
+
stats.hits++;
|
|
63
|
+
return entry;
|
|
64
|
+
}
|
|
65
|
+
stats.misses++;
|
|
66
|
+
return null;
|
|
67
|
+
},
|
|
68
|
+
setDisk(filePath, mtimeMs, size, result) {
|
|
69
|
+
diskCache.set(filePath, { mtimeMs, size, result });
|
|
70
|
+
},
|
|
71
|
+
getMem(filePath, source) {
|
|
72
|
+
const entry = memCache.get(filePath);
|
|
73
|
+
if (entry && sourcesEqual(entry.source, source)) {
|
|
74
|
+
stats.hits++;
|
|
75
|
+
return entry;
|
|
76
|
+
}
|
|
77
|
+
stats.misses++;
|
|
78
|
+
return null;
|
|
79
|
+
},
|
|
80
|
+
setMem(filePath, source, result) {
|
|
81
|
+
// Snapshot mutable Uint8Array inputs so subsequent in-place edits cannot cause stale cache hits.
|
|
82
|
+
const snapshot = source instanceof Uint8Array ? Buffer.from(source) : source;
|
|
83
|
+
memCache.set(filePath, { source: snapshot, result });
|
|
84
|
+
},
|
|
85
|
+
invalidate(filePath) {
|
|
86
|
+
diskCache.delete(filePath);
|
|
87
|
+
memCache.delete(filePath);
|
|
88
|
+
},
|
|
89
|
+
clear() {
|
|
90
|
+
diskCache.clear();
|
|
91
|
+
memCache.clear();
|
|
92
|
+
stats.hits = 0;
|
|
93
|
+
stats.misses = 0;
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function resolveTsconfigOption(tsconfig) {
|
|
99
|
+
if (!tsconfig) return null;
|
|
100
|
+
if (typeof tsconfig === 'string') return loadTsconfig(tsconfig);
|
|
101
|
+
if (typeof tsconfig === 'object') return tsconfig;
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function applyBannerFooter(code, banner, footer) {
|
|
106
|
+
if (code === null) return null;
|
|
107
|
+
let out = code;
|
|
108
|
+
if (banner) out = `${banner.endsWith('\n') ? banner : `${banner}\n`}${out}`;
|
|
109
|
+
if (footer) out = `${out.endsWith('\n') ? out : `${out}\n`}${footer.endsWith('\n') ? footer : `${footer}\n`}`;
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function discoverEntryGraph(entryPath, resolver, fileMap, sharedSources, sharedStats, sharedSpecs, diagnostics) {
|
|
114
|
+
const normalizedEntry = fileMap
|
|
115
|
+
? normalizeVirtualPath(entryPath)
|
|
116
|
+
: toPosix(path.resolve(entryPath));
|
|
117
|
+
|
|
118
|
+
const visited = new Set();
|
|
119
|
+
const order = [];
|
|
120
|
+
|
|
121
|
+
function visit(file) {
|
|
122
|
+
if (visited.has(file)) return;
|
|
123
|
+
visited.add(file);
|
|
124
|
+
|
|
125
|
+
let source = sharedSources.get(file);
|
|
126
|
+
if (source === undefined) {
|
|
127
|
+
try {
|
|
128
|
+
if (fileMap) {
|
|
129
|
+
source = fileMap[file];
|
|
130
|
+
if (source === undefined) throw new Error(`Virtual file not found: ${file}`);
|
|
131
|
+
} else {
|
|
132
|
+
const st = fs.statSync(file);
|
|
133
|
+
source = fs.readFileSync(file);
|
|
134
|
+
sharedStats.set(file, { mtimeMs: st.mtimeMs, size: st.size });
|
|
135
|
+
}
|
|
136
|
+
} catch (err) {
|
|
137
|
+
diagnostics.push({
|
|
138
|
+
file,
|
|
139
|
+
code: 'ENOENT',
|
|
140
|
+
severity: 'error',
|
|
141
|
+
message: err instanceof Error ? err.message : String(err),
|
|
142
|
+
start: 0,
|
|
143
|
+
end: 0,
|
|
144
|
+
});
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
sharedSources.set(file, source);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let specs = sharedSpecs.get(file);
|
|
151
|
+
if (specs === undefined) {
|
|
152
|
+
const text = typeof source === 'string' ? source : Buffer.from(source).toString('utf8');
|
|
153
|
+
specs = extractModuleSpecifiers(text);
|
|
154
|
+
sharedSpecs.set(file, specs);
|
|
155
|
+
}
|
|
156
|
+
for (let i = 0; i < specs.length; i++) {
|
|
157
|
+
const spec = specs[i];
|
|
158
|
+
const res = resolver.resolve(file, spec);
|
|
159
|
+
if (res.external) continue;
|
|
160
|
+
if (!res.path) {
|
|
161
|
+
diagnostics.push({
|
|
162
|
+
file,
|
|
163
|
+
code: 'UNRESOLVED_MODULE',
|
|
164
|
+
severity: 'error',
|
|
165
|
+
message: `Cannot resolve module "${spec}"`,
|
|
166
|
+
start: 0,
|
|
167
|
+
end: 0,
|
|
168
|
+
});
|
|
169
|
+
} else {
|
|
170
|
+
visit(res.path);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
order.push(file);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
visit(normalizedEntry);
|
|
177
|
+
return { entry: normalizedEntry, order };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function emitMissingSync(uniqueFiles, sharedSources, sharedStats, fileMap, cache, concurrency) {
|
|
181
|
+
const resultsByFile = new Map();
|
|
182
|
+
const toEmit = [];
|
|
183
|
+
let cacheHits = 0;
|
|
184
|
+
let cacheMisses = 0;
|
|
185
|
+
|
|
186
|
+
for (let i = 0; i < uniqueFiles.length; i++) {
|
|
187
|
+
const file = uniqueFiles[i];
|
|
188
|
+
const rawSource = sharedSources.get(file);
|
|
189
|
+
// Snapshot mutable Uint8Array before async dispatch so emit and cache observe identical bytes.
|
|
190
|
+
const source = rawSource instanceof Uint8Array ? Buffer.from(rawSource) : rawSource;
|
|
191
|
+
if (DTS_FILE_RE.test(file)) {
|
|
192
|
+
const text = typeof source === 'string' ? source : Buffer.from(source).toString('utf8');
|
|
193
|
+
resultsByFile.set(file, { backend: 'passthrough', code: text, diagnostics: [] });
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
if (cache) {
|
|
197
|
+
let cached = null;
|
|
198
|
+
if (fileMap) {
|
|
199
|
+
cached = cache.getMem(file, source);
|
|
200
|
+
} else {
|
|
201
|
+
const st = sharedStats.get(file);
|
|
202
|
+
if (st) cached = cache.getDisk(file, st.mtimeMs, st.size);
|
|
203
|
+
}
|
|
204
|
+
if (cached) {
|
|
205
|
+
resultsByFile.set(file, cached.result);
|
|
206
|
+
cacheHits++;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
cacheMisses++;
|
|
211
|
+
toEmit.push({ file, source });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (toEmit.length > 0) {
|
|
215
|
+
const emitted = pulsecDts.emitDeclarationsSync(toEmit, { concurrency });
|
|
216
|
+
for (let i = 0; i < toEmit.length; i++) {
|
|
217
|
+
const file = toEmit[i].file;
|
|
218
|
+
const res = emitted[i];
|
|
219
|
+
resultsByFile.set(file, res);
|
|
220
|
+
if (cache) {
|
|
221
|
+
if (fileMap) {
|
|
222
|
+
cache.setMem(file, toEmit[i].source, res);
|
|
223
|
+
} else {
|
|
224
|
+
const st = sharedStats.get(file);
|
|
225
|
+
if (st) cache.setDisk(file, st.mtimeMs, st.size, res);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return { resultsByFile, cacheHits, cacheMisses };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function emitMissingAsync(uniqueFiles, sharedSources, sharedStats, fileMap, cache, concurrency) {
|
|
235
|
+
const resultsByFile = new Map();
|
|
236
|
+
const toEmit = [];
|
|
237
|
+
let cacheHits = 0;
|
|
238
|
+
let cacheMisses = 0;
|
|
239
|
+
|
|
240
|
+
for (let i = 0; i < uniqueFiles.length; i++) {
|
|
241
|
+
const file = uniqueFiles[i];
|
|
242
|
+
const rawSource = sharedSources.get(file);
|
|
243
|
+
// Snapshot mutable Uint8Array before async dispatch so emit and cache observe identical bytes.
|
|
244
|
+
const source = rawSource instanceof Uint8Array ? Buffer.from(rawSource) : rawSource;
|
|
245
|
+
if (DTS_FILE_RE.test(file)) {
|
|
246
|
+
const text = typeof source === 'string' ? source : Buffer.from(source).toString('utf8');
|
|
247
|
+
resultsByFile.set(file, { backend: 'passthrough', code: text, diagnostics: [] });
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (cache) {
|
|
251
|
+
let cached = null;
|
|
252
|
+
if (fileMap) {
|
|
253
|
+
cached = cache.getMem(file, source);
|
|
254
|
+
} else {
|
|
255
|
+
const st = sharedStats.get(file);
|
|
256
|
+
if (st) cached = cache.getDisk(file, st.mtimeMs, st.size);
|
|
257
|
+
}
|
|
258
|
+
if (cached) {
|
|
259
|
+
resultsByFile.set(file, cached.result);
|
|
260
|
+
cacheHits++;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
cacheMisses++;
|
|
265
|
+
toEmit.push({ file, source });
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (toEmit.length > 0) {
|
|
269
|
+
const emitted = await pulsecDts.emitDeclarations(toEmit, { concurrency });
|
|
270
|
+
for (let i = 0; i < toEmit.length; i++) {
|
|
271
|
+
const file = toEmit[i].file;
|
|
272
|
+
const res = emitted[i];
|
|
273
|
+
resultsByFile.set(file, res);
|
|
274
|
+
if (cache) {
|
|
275
|
+
if (fileMap) {
|
|
276
|
+
cache.setMem(file, toEmit[i].source, res);
|
|
277
|
+
} else {
|
|
278
|
+
const st = sharedStats.get(file);
|
|
279
|
+
if (st) cache.setDisk(file, st.mtimeMs, st.size, res);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return { resultsByFile, cacheHits, cacheMisses };
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function finalizeEntryBundle(entry, order, resultsByFile, fileMap, resolveSpec, banner, footer) {
|
|
289
|
+
const diagnostics = [];
|
|
290
|
+
const dtsByFile = new Map();
|
|
291
|
+
for (let i = 0; i < order.length; i++) {
|
|
292
|
+
const file = order[i];
|
|
293
|
+
const r = resultsByFile.get(file);
|
|
294
|
+
if (!r || r.code === null || (r.diagnostics && r.diagnostics.length > 0)) {
|
|
295
|
+
if (r && r.diagnostics) diagnostics.push(...r.diagnostics);
|
|
296
|
+
} else {
|
|
297
|
+
dtsByFile.set(file, r.code);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (diagnostics.length > 0) {
|
|
301
|
+
return { code: null, files: order, diagnostics };
|
|
302
|
+
}
|
|
303
|
+
const assembled = assembleBundle(entry, order, dtsByFile, fileMap, resolveSpec);
|
|
304
|
+
return {
|
|
305
|
+
code: applyBannerFooter(assembled.code, banner, footer),
|
|
306
|
+
files: order,
|
|
307
|
+
diagnostics: assembled.diagnostics,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Bundles a single entry TypeScript module into a single `.d.ts` file (sync).
|
|
313
|
+
*/
|
|
314
|
+
function bundleDeclarationsSync(options) {
|
|
315
|
+
if (!options || typeof options !== 'object' || typeof options.entry !== 'string') {
|
|
316
|
+
throw new TypeError('bundleDeclarationsSync requires { entry: string }');
|
|
317
|
+
}
|
|
318
|
+
const fileMap = normalizeFileMap(options.files);
|
|
319
|
+
const tsconfig = resolveTsconfigOption(options.tsconfig);
|
|
320
|
+
const resolver = new FastModuleResolver({
|
|
321
|
+
fileMap,
|
|
322
|
+
tsconfig,
|
|
323
|
+
external: options.external,
|
|
324
|
+
});
|
|
325
|
+
const sharedSources = new Map();
|
|
326
|
+
const sharedStats = new Map();
|
|
327
|
+
const sharedSpecs = new Map();
|
|
328
|
+
const graphDiags = [];
|
|
329
|
+
const { entry, order } = discoverEntryGraph(
|
|
330
|
+
options.entry,
|
|
331
|
+
resolver,
|
|
332
|
+
fileMap,
|
|
333
|
+
sharedSources,
|
|
334
|
+
sharedStats,
|
|
335
|
+
sharedSpecs,
|
|
336
|
+
graphDiags,
|
|
337
|
+
);
|
|
338
|
+
if (graphDiags.length > 0) {
|
|
339
|
+
return { code: null, files: order, diagnostics: graphDiags };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const { resultsByFile } = emitMissingSync(
|
|
343
|
+
order,
|
|
344
|
+
sharedSources,
|
|
345
|
+
sharedStats,
|
|
346
|
+
fileMap,
|
|
347
|
+
options.cache || null,
|
|
348
|
+
options.concurrency,
|
|
349
|
+
);
|
|
350
|
+
return finalizeEntryBundle(
|
|
351
|
+
entry,
|
|
352
|
+
order,
|
|
353
|
+
resultsByFile,
|
|
354
|
+
fileMap,
|
|
355
|
+
(from, spec) => resolver.resolve(from, spec),
|
|
356
|
+
options.banner,
|
|
357
|
+
options.footer,
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Bundles a single entry TypeScript module into a single `.d.ts` file (async, multi-threaded).
|
|
363
|
+
*/
|
|
364
|
+
async function bundleDeclarations(options) {
|
|
365
|
+
if (!options || typeof options !== 'object' || typeof options.entry !== 'string') {
|
|
366
|
+
throw new TypeError('bundleDeclarations requires { entry: string }');
|
|
367
|
+
}
|
|
368
|
+
const fileMap = normalizeFileMap(options.files);
|
|
369
|
+
const tsconfig = resolveTsconfigOption(options.tsconfig);
|
|
370
|
+
const resolver = new FastModuleResolver({
|
|
371
|
+
fileMap,
|
|
372
|
+
tsconfig,
|
|
373
|
+
external: options.external,
|
|
374
|
+
});
|
|
375
|
+
const sharedSources = new Map();
|
|
376
|
+
const sharedStats = new Map();
|
|
377
|
+
const sharedSpecs = new Map();
|
|
378
|
+
const graphDiags = [];
|
|
379
|
+
const { entry, order } = discoverEntryGraph(
|
|
380
|
+
options.entry,
|
|
381
|
+
resolver,
|
|
382
|
+
fileMap,
|
|
383
|
+
sharedSources,
|
|
384
|
+
sharedStats,
|
|
385
|
+
sharedSpecs,
|
|
386
|
+
graphDiags,
|
|
387
|
+
);
|
|
388
|
+
if (graphDiags.length > 0) {
|
|
389
|
+
return { code: null, files: order, diagnostics: graphDiags };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const { resultsByFile } = await emitMissingAsync(
|
|
393
|
+
order,
|
|
394
|
+
sharedSources,
|
|
395
|
+
sharedStats,
|
|
396
|
+
fileMap,
|
|
397
|
+
options.cache || null,
|
|
398
|
+
options.concurrency,
|
|
399
|
+
);
|
|
400
|
+
return finalizeEntryBundle(
|
|
401
|
+
entry,
|
|
402
|
+
order,
|
|
403
|
+
resultsByFile,
|
|
404
|
+
fileMap,
|
|
405
|
+
(from, spec) => resolver.resolve(from, spec),
|
|
406
|
+
options.banner,
|
|
407
|
+
options.footer,
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function normalizeEntriesInput(entries) {
|
|
412
|
+
if (Array.isArray(entries)) {
|
|
413
|
+
const out = [];
|
|
414
|
+
const seen = new Map();
|
|
415
|
+
for (let i = 0; i < entries.length; i++) {
|
|
416
|
+
const e = entries[i];
|
|
417
|
+
const base = path.basename(e).replace(/\.(?:[cm]?ts|tsx)$/i, '');
|
|
418
|
+
if (seen.has(base)) {
|
|
419
|
+
throw new Error(`Duplicate entry output name "${base}" for "${seen.get(base)}" and "${e}"; pass an object map { name: entryPath } to disambiguate`);
|
|
420
|
+
}
|
|
421
|
+
seen.set(base, e);
|
|
422
|
+
out.push({ name: base, entry: e });
|
|
423
|
+
}
|
|
424
|
+
return out;
|
|
425
|
+
}
|
|
426
|
+
if (entries && typeof entries === 'object') {
|
|
427
|
+
return Object.entries(entries).map(([name, entry]) => ({ name, entry }));
|
|
428
|
+
}
|
|
429
|
+
throw new TypeError('bundleEntries requires `entries` as string[] or Record<string, string>');
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Bundles multiple entry points in a single shared native parallel batch.
|
|
434
|
+
* Shared dependencies are emitted only once across all entries.
|
|
435
|
+
*/
|
|
436
|
+
async function bundleEntries(options) {
|
|
437
|
+
if (!options || typeof options !== 'object') {
|
|
438
|
+
throw new TypeError('bundleEntries requires an options object');
|
|
439
|
+
}
|
|
440
|
+
const normalizedEntries = normalizeEntriesInput(options.entries);
|
|
441
|
+
const fileMap = normalizeFileMap(options.files);
|
|
442
|
+
const tsconfig = resolveTsconfigOption(options.tsconfig);
|
|
443
|
+
const resolver = new FastModuleResolver({
|
|
444
|
+
fileMap,
|
|
445
|
+
tsconfig,
|
|
446
|
+
external: options.external,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
const sharedSources = new Map();
|
|
450
|
+
const sharedStats = new Map();
|
|
451
|
+
const sharedSpecs = new Map();
|
|
452
|
+
const uniqueSet = new Set();
|
|
453
|
+
const uniqueFiles = [];
|
|
454
|
+
const entryGraphs = [];
|
|
455
|
+
const allDiagnostics = [];
|
|
456
|
+
|
|
457
|
+
for (let i = 0; i < normalizedEntries.length; i++) {
|
|
458
|
+
const { name, entry: rawEntry } = normalizedEntries[i];
|
|
459
|
+
const graphDiags = [];
|
|
460
|
+
const { entry, order } = discoverEntryGraph(
|
|
461
|
+
rawEntry,
|
|
462
|
+
resolver,
|
|
463
|
+
fileMap,
|
|
464
|
+
sharedSources,
|
|
465
|
+
sharedStats,
|
|
466
|
+
sharedSpecs,
|
|
467
|
+
graphDiags,
|
|
468
|
+
);
|
|
469
|
+
for (let j = 0; j < order.length; j++) {
|
|
470
|
+
if (!uniqueSet.has(order[j])) {
|
|
471
|
+
uniqueSet.add(order[j]);
|
|
472
|
+
uniqueFiles.push(order[j]);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
entryGraphs.push({ name, entry, order, graphDiags });
|
|
476
|
+
if (graphDiags.length > 0) allDiagnostics.push(...graphDiags);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const { resultsByFile, cacheHits, cacheMisses } = await emitMissingAsync(
|
|
480
|
+
uniqueFiles,
|
|
481
|
+
sharedSources,
|
|
482
|
+
sharedStats,
|
|
483
|
+
fileMap,
|
|
484
|
+
options.cache || null,
|
|
485
|
+
options.concurrency,
|
|
486
|
+
);
|
|
487
|
+
|
|
488
|
+
const resolveSpec = (from, spec) => resolver.resolve(from, spec);
|
|
489
|
+
const outputs = Object.create(null);
|
|
490
|
+
for (let i = 0; i < entryGraphs.length; i++) {
|
|
491
|
+
const { name, entry, order, graphDiags } = entryGraphs[i];
|
|
492
|
+
if (graphDiags.length > 0) {
|
|
493
|
+
outputs[name] = { code: null, files: order, diagnostics: graphDiags };
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
const res = finalizeEntryBundle(
|
|
497
|
+
entry,
|
|
498
|
+
order,
|
|
499
|
+
resultsByFile,
|
|
500
|
+
fileMap,
|
|
501
|
+
resolveSpec,
|
|
502
|
+
options.banner,
|
|
503
|
+
options.footer,
|
|
504
|
+
);
|
|
505
|
+
outputs[name] = res;
|
|
506
|
+
if (res.diagnostics.length > 0) allDiagnostics.push(...res.diagnostics);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
return {
|
|
510
|
+
entries: outputs,
|
|
511
|
+
files: uniqueFiles,
|
|
512
|
+
diagnostics: allDiagnostics,
|
|
513
|
+
cacheHits,
|
|
514
|
+
cacheMisses,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function isWithinDir(baseReal, targetPath) {
|
|
519
|
+
const rel = path.relative(baseReal, targetPath);
|
|
520
|
+
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function toDtsPath(filePath) {
|
|
524
|
+
return filePath
|
|
525
|
+
.replace(/\.mts$/i, '.d.mts')
|
|
526
|
+
.replace(/\.cts$/i, '.d.cts')
|
|
527
|
+
.replace(/\.tsx?$/i, '.d.ts');
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function resolveCanonicalDest(outDirReal, destPath) {
|
|
531
|
+
const parts = [];
|
|
532
|
+
let cur = destPath;
|
|
533
|
+
while (cur !== outDirReal && cur !== path.dirname(cur)) {
|
|
534
|
+
try {
|
|
535
|
+
const real = fs.realpathSync(cur);
|
|
536
|
+
return parts.length > 0 ? path.join(real, ...parts.reverse()) : real;
|
|
537
|
+
} catch {
|
|
538
|
+
parts.push(path.basename(cur));
|
|
539
|
+
cur = path.dirname(cur);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return parts.length > 0 ? path.join(outDirReal, ...parts.reverse()) : outDirReal;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function assertSafeOutputTarget(outDirReal, destPath) {
|
|
546
|
+
if (!isWithinDir(outDirReal, destPath)) {
|
|
547
|
+
throw new Error(`Refusing to write outside outDir: ${destPath}`);
|
|
548
|
+
}
|
|
549
|
+
let cur = destPath;
|
|
550
|
+
while (cur !== outDirReal && cur !== path.dirname(cur)) {
|
|
551
|
+
let lst = null;
|
|
552
|
+
try {
|
|
553
|
+
lst = fs.lstatSync(cur);
|
|
554
|
+
} catch (err) {
|
|
555
|
+
if (!err || err.code !== 'ENOENT') throw err;
|
|
556
|
+
}
|
|
557
|
+
if (lst && lst.isSymbolicLink()) {
|
|
558
|
+
let real;
|
|
559
|
+
try {
|
|
560
|
+
real = fs.realpathSync(cur);
|
|
561
|
+
} catch {
|
|
562
|
+
// Dangling symlink: reject because its target cannot be proven to stay inside outDirReal.
|
|
563
|
+
throw new Error(`Refusing to follow dangling symlink escaping outDir: ${cur}`);
|
|
564
|
+
}
|
|
565
|
+
if (real !== outDirReal && !isWithinDir(outDirReal, real)) {
|
|
566
|
+
throw new Error(`Refusing to follow symlink escaping outDir: ${cur}`);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
cur = path.dirname(cur);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function collectTsFiles(targets) {
|
|
574
|
+
const out = [];
|
|
575
|
+
const seenDirs = new Set();
|
|
576
|
+
const seenFiles = new Set();
|
|
577
|
+
|
|
578
|
+
const walk = p => {
|
|
579
|
+
const st = fs.statSync(p);
|
|
580
|
+
if (st.isDirectory()) {
|
|
581
|
+
const realDir = fs.realpathSync(p);
|
|
582
|
+
if (seenDirs.has(realDir)) return;
|
|
583
|
+
seenDirs.add(realDir);
|
|
584
|
+
for (const entry of fs.readdirSync(p, { withFileTypes: true })) {
|
|
585
|
+
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist') continue;
|
|
586
|
+
walk(path.join(p, entry.name));
|
|
587
|
+
}
|
|
588
|
+
} else if (st.isFile() && /\.(?:[cm]?ts|tsx)$/i.test(p) && !/\.d\.(?:[cm]?ts|tsx)$/i.test(p)) {
|
|
589
|
+
const realFile = fs.realpathSync(p);
|
|
590
|
+
if (!seenFiles.has(realFile)) {
|
|
591
|
+
seenFiles.add(realFile);
|
|
592
|
+
out.push(realFile);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
for (let i = 0; i < targets.length; i++) walk(path.resolve(targets[i]));
|
|
597
|
+
out.sort();
|
|
598
|
+
return out;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Emits `.d.ts` files for an entire directory/file list using parallel I/O and
|
|
603
|
+
* pulsec's native OS thread pool.
|
|
604
|
+
*/
|
|
605
|
+
async function emitProject(options) {
|
|
606
|
+
if (!options || typeof options !== 'object') {
|
|
607
|
+
throw new TypeError('emitProject requires an options object');
|
|
608
|
+
}
|
|
609
|
+
const tsconfig = resolveTsconfigOption(options.tsconfig);
|
|
610
|
+
const inputs = Array.isArray(options.inputs)
|
|
611
|
+
? options.inputs
|
|
612
|
+
: typeof options.inputs === 'string'
|
|
613
|
+
? [options.inputs]
|
|
614
|
+
: tsconfig && tsconfig.rootDir
|
|
615
|
+
? [tsconfig.rootDir]
|
|
616
|
+
: [];
|
|
617
|
+
if (inputs.length === 0) {
|
|
618
|
+
throw new Error('emitProject requires `inputs` (or a tsconfig with rootDir)');
|
|
619
|
+
}
|
|
620
|
+
const outDirRaw = options.outDir || (tsconfig && tsconfig.outDir);
|
|
621
|
+
if (!outDirRaw) {
|
|
622
|
+
throw new Error('emitProject requires `outDir` (or a tsconfig with outDir)');
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const files = collectTsFiles(inputs);
|
|
626
|
+
if (files.length === 0) {
|
|
627
|
+
return { written: [], skipped: [], diagnostics: [] };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const inferredRoot = options.rootDir
|
|
631
|
+
|| (tsconfig && tsconfig.rootDir)
|
|
632
|
+
|| (inputs.length === 1 && fs.statSync(path.resolve(inputs[0])).isDirectory()
|
|
633
|
+
? path.resolve(inputs[0])
|
|
634
|
+
: process.cwd());
|
|
635
|
+
const rootDirReal = fs.realpathSync(path.resolve(inferredRoot));
|
|
636
|
+
const outDirAbs = path.resolve(outDirRaw);
|
|
637
|
+
fs.mkdirSync(outDirAbs, { recursive: true });
|
|
638
|
+
const outDirReal = fs.realpathSync(outDirAbs);
|
|
639
|
+
|
|
640
|
+
const planned = [];
|
|
641
|
+
const seenDest = new Map();
|
|
642
|
+
const seenRealDest = new Map();
|
|
643
|
+
for (let i = 0; i < files.length; i++) {
|
|
644
|
+
const f = files[i];
|
|
645
|
+
if (!isWithinDir(rootDirReal, f)) {
|
|
646
|
+
throw new Error(`Input file is outside rootDir (${rootDirReal}): ${f}`);
|
|
647
|
+
}
|
|
648
|
+
const rel = path.relative(rootDirReal, f);
|
|
649
|
+
const dest = path.resolve(outDirReal, toDtsPath(rel));
|
|
650
|
+
assertSafeOutputTarget(outDirReal, dest);
|
|
651
|
+
if (seenDest.has(dest)) {
|
|
652
|
+
throw new Error(`Output path collision: ${seenDest.get(dest)} and ${f} both map to ${dest}`);
|
|
653
|
+
}
|
|
654
|
+
const canonicalDest = resolveCanonicalDest(outDirReal, dest);
|
|
655
|
+
if (seenRealDest.has(canonicalDest)) {
|
|
656
|
+
throw new Error(`Output path collision via symlink: ${seenRealDest.get(canonicalDest)} and ${f} both map to ${canonicalDest}`);
|
|
657
|
+
}
|
|
658
|
+
seenDest.set(dest, f);
|
|
659
|
+
seenRealDest.set(canonicalDest, f);
|
|
660
|
+
planned.push({ file: f, dest });
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Parallel file I/O; skip extra stat syscall when no cache is active.
|
|
664
|
+
const cache = options.cache || null;
|
|
665
|
+
const skipUnchanged = options.skipUnchanged !== false;
|
|
666
|
+
let cacheHits = 0;
|
|
667
|
+
let cacheMisses = 0;
|
|
668
|
+
const loaded = await Promise.all(
|
|
669
|
+
planned.map(async p => {
|
|
670
|
+
const key = toPosix(p.file);
|
|
671
|
+
if (cache) {
|
|
672
|
+
const st = await fsp.stat(p.file);
|
|
673
|
+
const hit = cache.getDisk(key, st.mtimeMs, st.size);
|
|
674
|
+
if (hit) {
|
|
675
|
+
cacheHits++;
|
|
676
|
+
return { ...p, key, mtimeMs: st.mtimeMs, size: st.size, source: null, cachedResult: hit.result };
|
|
677
|
+
}
|
|
678
|
+
cacheMisses++;
|
|
679
|
+
const buf = await fsp.readFile(p.file);
|
|
680
|
+
return { ...p, key, mtimeMs: st.mtimeMs, size: st.size, source: buf, cachedResult: null };
|
|
681
|
+
}
|
|
682
|
+
cacheMisses++;
|
|
683
|
+
const buf = await fsp.readFile(p.file);
|
|
684
|
+
return { ...p, key, mtimeMs: 0, size: buf.length, source: buf, cachedResult: null };
|
|
685
|
+
}),
|
|
686
|
+
);
|
|
687
|
+
|
|
688
|
+
const resultsByFile = new Map();
|
|
689
|
+
const toEmit = [];
|
|
690
|
+
const toEmitMeta = [];
|
|
691
|
+
for (let i = 0; i < loaded.length; i++) {
|
|
692
|
+
const item = loaded[i];
|
|
693
|
+
if (item.cachedResult) {
|
|
694
|
+
resultsByFile.set(item.key, item.cachedResult);
|
|
695
|
+
} else {
|
|
696
|
+
toEmit.push({ file: item.key, source: item.source });
|
|
697
|
+
toEmitMeta.push(item);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (toEmit.length > 0) {
|
|
702
|
+
const emitted = await pulsecDts.emitDeclarations(toEmit, { concurrency: options.concurrency });
|
|
703
|
+
for (let i = 0; i < toEmit.length; i++) {
|
|
704
|
+
const item = toEmitMeta[i];
|
|
705
|
+
const res = emitted[i];
|
|
706
|
+
resultsByFile.set(item.key, res);
|
|
707
|
+
if (cache) cache.setDisk(item.key, item.mtimeMs, item.size, res);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
const diagnostics = [];
|
|
712
|
+
for (let i = 0; i < loaded.length; i++) {
|
|
713
|
+
const r = resultsByFile.get(loaded[i].key);
|
|
714
|
+
if (!r || r.code === null || (r.diagnostics && r.diagnostics.length > 0)) {
|
|
715
|
+
if (r && r.diagnostics) diagnostics.push(...r.diagnostics);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
if (diagnostics.length > 0) {
|
|
719
|
+
return { written: [], skipped: [], diagnostics, cacheHits, cacheMisses };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// Ensure unique parent directories once, then write in parallel.
|
|
723
|
+
const dirs = new Set();
|
|
724
|
+
for (let i = 0; i < loaded.length; i++) dirs.add(path.dirname(loaded[i].dest));
|
|
725
|
+
for (const d of dirs) fs.mkdirSync(d, { recursive: true });
|
|
726
|
+
|
|
727
|
+
const written = [];
|
|
728
|
+
const skipped = [];
|
|
729
|
+
await Promise.all(
|
|
730
|
+
loaded.map(async item => {
|
|
731
|
+
assertSafeOutputTarget(outDirReal, item.dest);
|
|
732
|
+
const code = applyBannerFooter(resultsByFile.get(item.key).code, options.banner, options.footer);
|
|
733
|
+
if (skipUnchanged) {
|
|
734
|
+
try {
|
|
735
|
+
const prev = await fsp.readFile(item.dest, 'utf8');
|
|
736
|
+
if (prev === code) {
|
|
737
|
+
skipped.push(item.dest);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
} catch {
|
|
741
|
+
// proceed to write
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
await fsp.writeFile(item.dest, code, 'utf8');
|
|
745
|
+
written.push(item.dest);
|
|
746
|
+
}),
|
|
747
|
+
);
|
|
748
|
+
|
|
749
|
+
written.sort();
|
|
750
|
+
skipped.sort();
|
|
751
|
+
return { written, skipped, diagnostics: [], cacheHits, cacheMisses };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* High-level declaration build helper supporting both bundled and per-file modes.
|
|
756
|
+
*/
|
|
757
|
+
async function buildDeclarations(options) {
|
|
758
|
+
if (!options || typeof options !== 'object') {
|
|
759
|
+
throw new TypeError('buildDeclarations requires an options object');
|
|
760
|
+
}
|
|
761
|
+
if (options.bundle) {
|
|
762
|
+
const entries = options.entries || (options.entry ? [options.entry] : null);
|
|
763
|
+
if (!entries) throw new Error('buildDeclarations({ bundle: true }) requires `entry` or `entries`');
|
|
764
|
+
const res = await bundleEntries({
|
|
765
|
+
entries,
|
|
766
|
+
files: options.files,
|
|
767
|
+
tsconfig: options.tsconfig,
|
|
768
|
+
external: options.external,
|
|
769
|
+
concurrency: options.concurrency,
|
|
770
|
+
cache: options.cache,
|
|
771
|
+
banner: options.banner,
|
|
772
|
+
footer: options.footer,
|
|
773
|
+
});
|
|
774
|
+
const written = [];
|
|
775
|
+
if (res.diagnostics.length === 0 && (options.out || options.outDir)) {
|
|
776
|
+
const entryNames = Object.keys(res.entries);
|
|
777
|
+
if (options.out && entryNames.length === 1) {
|
|
778
|
+
const outPath = path.resolve(options.out);
|
|
779
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
780
|
+
await fsp.writeFile(outPath, res.entries[entryNames[0]].code, 'utf8');
|
|
781
|
+
written.push(outPath);
|
|
782
|
+
} else if (options.outDir) {
|
|
783
|
+
const outDirAbs = path.resolve(options.outDir);
|
|
784
|
+
fs.mkdirSync(outDirAbs, { recursive: true });
|
|
785
|
+
const outDirReal = fs.realpathSync(outDirAbs);
|
|
786
|
+
// Pre-validate all output targets and detect string/symlink collisions before writing any file.
|
|
787
|
+
const plannedWrites = [];
|
|
788
|
+
const seenDest = new Map();
|
|
789
|
+
const seenRealDest = new Map();
|
|
790
|
+
for (let i = 0; i < entryNames.length; i++) {
|
|
791
|
+
const name = entryNames[i];
|
|
792
|
+
const fileName = name.endsWith('.d.ts') || name.endsWith('.d.mts') || name.endsWith('.d.cts')
|
|
793
|
+
? name
|
|
794
|
+
: `${name}.d.ts`;
|
|
795
|
+
const dest = path.resolve(outDirReal, fileName);
|
|
796
|
+
assertSafeOutputTarget(outDirReal, dest);
|
|
797
|
+
if (seenDest.has(dest)) {
|
|
798
|
+
throw new Error(`Output path collision: "${seenDest.get(dest)}" and "${name}" both map to ${dest}`);
|
|
799
|
+
}
|
|
800
|
+
const canonicalDest = resolveCanonicalDest(outDirReal, dest);
|
|
801
|
+
if (seenRealDest.has(canonicalDest)) {
|
|
802
|
+
throw new Error(`Output path collision via symlink: "${seenRealDest.get(canonicalDest)}" and "${name}" both map to ${canonicalDest}`);
|
|
803
|
+
}
|
|
804
|
+
seenDest.set(dest, name);
|
|
805
|
+
seenRealDest.set(canonicalDest, name);
|
|
806
|
+
plannedWrites.push({ name, dest });
|
|
807
|
+
}
|
|
808
|
+
await Promise.all(
|
|
809
|
+
plannedWrites.map(async ({ name, dest }) => {
|
|
810
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
811
|
+
assertSafeOutputTarget(outDirReal, dest);
|
|
812
|
+
await fsp.writeFile(dest, res.entries[name].code, 'utf8');
|
|
813
|
+
written.push(dest);
|
|
814
|
+
}),
|
|
815
|
+
);
|
|
816
|
+
written.sort();
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return { ...res, written };
|
|
820
|
+
}
|
|
821
|
+
return emitProject(options);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
module.exports = {
|
|
825
|
+
emitDeclaration: pulsecDts.emitDeclaration,
|
|
826
|
+
emitDeclarations: pulsecDts.emitDeclarations,
|
|
827
|
+
emitDeclarationsSync: pulsecDts.emitDeclarationsSync,
|
|
828
|
+
bundleDeclarations,
|
|
829
|
+
bundleDeclarationsSync,
|
|
830
|
+
bundleEntries,
|
|
831
|
+
emitProject,
|
|
832
|
+
buildDeclarations,
|
|
833
|
+
createDtsCache,
|
|
834
|
+
};
|