screw-up 1.29.0 → 1.31.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.
Files changed (46) hide show
  1. package/dist/index.cjs +561 -100
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +502 -74
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/main.cjs +64 -31
  6. package/dist/main.cjs.map +1 -1
  7. package/dist/main.mjs +5 -5
  8. package/dist/main.mjs.map +1 -1
  9. package/dist/{metadata-file-CyQ2yue9.js → metadata-file-BWd04LhD.js} +63 -34
  10. package/dist/metadata-file-BWd04LhD.js.map +1 -0
  11. package/dist/{packageMetadata-CpakAG0S.cjs → packageMetadata-BDGBM3Fx.cjs} +3 -3
  12. package/dist/{packageMetadata-DnXbVLQ5.js → packageMetadata-BsMXJpMH.js} +6 -6
  13. package/dist/{packageMetadata-DnXbVLQ5.js.map → packageMetadata-BsMXJpMH.js.map} +1 -1
  14. package/dist/{packageMetadata-K_w0Knb7.cjs → packageMetadata-ip0rBTwa.cjs} +5 -5
  15. package/dist/{packageMetadata-K_w0Knb7.cjs.map → packageMetadata-ip0rBTwa.cjs.map} +1 -1
  16. package/dist/src/analyzer.d.ts +2 -2
  17. package/dist/src/analyzer.d.ts.map +1 -1
  18. package/dist/src/cli-internal.d.ts +3 -3
  19. package/dist/src/cli-internal.d.ts.map +1 -1
  20. package/dist/src/cli.d.ts +3 -3
  21. package/dist/src/cli.d.ts.map +1 -1
  22. package/dist/src/declaration-import-fix.d.ts +21 -0
  23. package/dist/src/declaration-import-fix.d.ts.map +1 -0
  24. package/dist/src/default-import-fix.d.ts +2 -2
  25. package/dist/src/default-import-fix.d.ts.map +1 -1
  26. package/dist/src/fast-tags.d.ts +2 -2
  27. package/dist/src/fast-tags.d.ts.map +1 -1
  28. package/dist/src/generated/packageMetadata.d.ts +4 -4
  29. package/dist/src/git-operations.d.ts +3 -3
  30. package/dist/src/git-operations.d.ts.map +1 -1
  31. package/dist/src/git-ref-utils.d.ts +25 -0
  32. package/dist/src/git-ref-utils.d.ts.map +1 -0
  33. package/dist/src/index.d.ts +4 -4
  34. package/dist/src/index.d.ts.map +1 -1
  35. package/dist/src/internal.d.ts +3 -3
  36. package/dist/src/main.d.ts +2 -2
  37. package/dist/src/metadata-file.d.ts +4 -4
  38. package/dist/src/metadata-file.d.ts.map +1 -1
  39. package/dist/src/text-edits.d.ts +24 -0
  40. package/dist/src/text-edits.d.ts.map +1 -0
  41. package/dist/src/types.d.ts +7 -2
  42. package/dist/src/types.d.ts.map +1 -1
  43. package/dist/src/vite-plugin.d.ts +3 -3
  44. package/dist/src/vite-plugin.d.ts.map +1 -1
  45. package/package.json +14 -10
  46. package/dist/metadata-file-CyQ2yue9.js.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,27 +1,30 @@
1
1
  /*!
2
2
  * name: screw-up
3
- * version: 1.29.0
3
+ * version: 1.31.0
4
4
  * description: Simply package metadata inserter on Vite plugin
5
5
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
6
6
  * license: MIT
7
7
  * repository.url: https://github.com/kekyo/screw-up.git
8
- * git.commit.hash: 3833f6ef842d9e5a0b4f7277ca3b118f26fd4a6b
8
+ * git.commit.hash: ebb41ebf06ebe1bec39a3770c70a62cb95b4b7d6
9
9
  */
10
- import { i as getFetchGitMetadata, l as resolvePackageMetadata, n as generateMetadataFileContent, o as createConsoleLogger, r as writeFileIfChanged, t as ensureMetadataGitignore } from "./metadata-file-CyQ2yue9.js";
11
- import { i as version, n as name, t as git_commit_hash } from "./packageMetadata-DnXbVLQ5.js";
10
+ import { i as getFetchGitMetadata, l as resolvePackageMetadata, n as generateMetadataFileContent, o as createConsoleLogger, r as writeFileIfChanged, t as ensureMetadataGitignore } from "./metadata-file-BWd04LhD.js";
11
+ import { i as version, n as name, t as git_commit_hash } from "./packageMetadata-BsMXJpMH.js";
12
12
  import { readFile, readdir, writeFile } from "fs/promises";
13
13
  import { existsSync } from "fs";
14
- import { dirname, extname, join } from "path";
14
+ import { dirname, extname, join, posix, resolve } from "path";
15
15
  import { createHash } from "crypto";
16
16
  //#region node_modules/async-primitives/dist/index.mjs
17
17
  /*!
18
18
  * name: async-primitives
19
- * version: 1.5.0
19
+ * version: 1.7.0
20
20
  * description: A collection of primitive functions for asynchronous operations
21
21
  * author: Kouji Matsui (@kekyo@mi.kekyo.net)
22
22
  * license: MIT
23
23
  * repository.url: https://github.com/kekyo/async-primitives.git
24
- * git.commit.hash: cd35465b7e9b9945049186e7eaeecc0bfba65766
24
+ * git.commit.hash: 9472fbd5310b92690d84aaafb897429a04c013c5
25
+ */
26
+ /**
27
+ * A no-op Releasable object that does nothing when released or disposed
25
28
  */
26
29
  var __NOOP_HANDLER = () => {};
27
30
  var __NOOP_RELEASABLE = {
@@ -33,6 +36,12 @@ var toAbortError = (reason) => {
33
36
  if (typeof reason === "string") return new Error(reason);
34
37
  return /* @__PURE__ */ new Error("Operation aborted");
35
38
  };
39
+ /**
40
+ * Hooks up an abort handler to an AbortSignal and returns a handle for early cleanup
41
+ * @param signal - The AbortSignal to hook up to
42
+ * @param callback - The callback to call when the signal is aborted
43
+ * @returns A Releasable handle that can be used to remove the abort listener early
44
+ */
36
45
  var onAbort = (signal, callback) => {
37
46
  if (!signal) return __NOOP_RELEASABLE;
38
47
  if (signal.aborted) {
@@ -67,11 +76,21 @@ var onAbort = (signal, callback) => {
67
76
  [Symbol.dispose]: release
68
77
  };
69
78
  };
79
+ var runtimeGlobal$1 = globalThis;
70
80
  var defer = (fn) => {
71
- if (typeof setImmediate === "function") setImmediate(fn);
72
- else setTimeout(fn, 0);
81
+ const setImmediateHandler = runtimeGlobal$1.setImmediate;
82
+ if (typeof setImmediateHandler === "function") {
83
+ setImmediateHandler(fn);
84
+ return;
85
+ }
86
+ globalThis.setTimeout(fn, 0);
73
87
  };
74
88
  var ABORTED_ERROR$2 = () => /* @__PURE__ */ new Error("Lock acquisition was aborted");
89
+ /**
90
+ * Creates a new LockHandle instance
91
+ * @param releaseCallback Callback function to release the lock
92
+ * @returns A LockHandle object with release and dispose functionality
93
+ */
75
94
  var createLockHandle = (releaseCallback) => {
76
95
  let isActive = true;
77
96
  const release = () => {
@@ -87,15 +106,20 @@ var createLockHandle = (releaseCallback) => {
87
106
  [Symbol.dispose]: release
88
107
  };
89
108
  };
109
+ /**
110
+ * Creates a new Mutex instance
111
+ * @param maxConsecutiveCalls - The maximum number of consecutive calls to the lockAsync method before yielding control to the next item in the queue
112
+ * @returns A new Mutex for promise-based mutex operations
113
+ */
90
114
  var createMutex = (maxConsecutiveCalls = 20) => {
91
115
  let isLocked = false;
92
116
  const queue = [];
93
117
  let count = 0;
94
118
  const processQueue = () => {
95
- var _a;
119
+ var _item$signal;
96
120
  if (isLocked || queue.length === 0) return;
97
121
  const item = queue.shift();
98
- if ((_a = item.signal) == null ? void 0 : _a.aborted) {
122
+ if ((_item$signal = item.signal) === null || _item$signal === void 0 ? void 0 : _item$signal.aborted) {
99
123
  item.reject(ABORTED_ERROR$2());
100
124
  scheduleNextProcess();
101
125
  return;
@@ -171,6 +195,375 @@ var createLogicalContext = (id) => {
171
195
  };
172
196
  createLogicalContext(Symbol("[root]"));
173
197
  //#endregion
198
+ //#region node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
199
+ var comma = ",".charCodeAt(0);
200
+ var semicolon = ";".charCodeAt(0);
201
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
202
+ var intToChar = new Uint8Array(64);
203
+ var charToInt = new Uint8Array(128);
204
+ for (let i = 0; i < chars.length; i++) {
205
+ const c = chars.charCodeAt(i);
206
+ intToChar[i] = c;
207
+ charToInt[c] = i;
208
+ }
209
+ function decodeInteger(reader, relative) {
210
+ let value = 0;
211
+ let shift = 0;
212
+ let integer = 0;
213
+ do {
214
+ integer = charToInt[reader.next()];
215
+ value |= (integer & 31) << shift;
216
+ shift += 5;
217
+ } while (integer & 32);
218
+ const shouldNegate = value & 1;
219
+ value >>>= 1;
220
+ if (shouldNegate) value = -2147483648 | -value;
221
+ return relative + value;
222
+ }
223
+ function encodeInteger(builder, num, relative) {
224
+ let delta = num - relative;
225
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
226
+ do {
227
+ let clamped = delta & 31;
228
+ delta >>>= 5;
229
+ if (delta > 0) clamped |= 32;
230
+ builder.write(intToChar[clamped]);
231
+ } while (delta > 0);
232
+ return num;
233
+ }
234
+ function hasMoreVlq(reader, max) {
235
+ if (reader.pos >= max) return false;
236
+ return reader.peek() !== comma;
237
+ }
238
+ var bufLength = 1024 * 16;
239
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
240
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
241
+ } } : { decode(buf) {
242
+ let out = "";
243
+ for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
244
+ return out;
245
+ } };
246
+ var StringWriter = class {
247
+ constructor() {
248
+ this.pos = 0;
249
+ this.out = "";
250
+ this.buffer = new Uint8Array(bufLength);
251
+ }
252
+ write(v) {
253
+ const { buffer } = this;
254
+ buffer[this.pos++] = v;
255
+ if (this.pos === bufLength) {
256
+ this.out += td.decode(buffer);
257
+ this.pos = 0;
258
+ }
259
+ }
260
+ flush() {
261
+ const { buffer, out, pos } = this;
262
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
263
+ }
264
+ };
265
+ var StringReader = class {
266
+ constructor(buffer) {
267
+ this.pos = 0;
268
+ this.buffer = buffer;
269
+ }
270
+ next() {
271
+ return this.buffer.charCodeAt(this.pos++);
272
+ }
273
+ peek() {
274
+ return this.buffer.charCodeAt(this.pos);
275
+ }
276
+ indexOf(char) {
277
+ const { buffer, pos } = this;
278
+ const idx = buffer.indexOf(char, pos);
279
+ return idx === -1 ? buffer.length : idx;
280
+ }
281
+ };
282
+ function decode(mappings) {
283
+ const { length } = mappings;
284
+ const reader = new StringReader(mappings);
285
+ const decoded = [];
286
+ let genColumn = 0;
287
+ let sourcesIndex = 0;
288
+ let sourceLine = 0;
289
+ let sourceColumn = 0;
290
+ let namesIndex = 0;
291
+ do {
292
+ const semi = reader.indexOf(";");
293
+ const line = [];
294
+ let sorted = true;
295
+ let lastCol = 0;
296
+ genColumn = 0;
297
+ while (reader.pos < semi) {
298
+ let seg;
299
+ genColumn = decodeInteger(reader, genColumn);
300
+ if (genColumn < lastCol) sorted = false;
301
+ lastCol = genColumn;
302
+ if (hasMoreVlq(reader, semi)) {
303
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
304
+ sourceLine = decodeInteger(reader, sourceLine);
305
+ sourceColumn = decodeInteger(reader, sourceColumn);
306
+ if (hasMoreVlq(reader, semi)) {
307
+ namesIndex = decodeInteger(reader, namesIndex);
308
+ seg = [
309
+ genColumn,
310
+ sourcesIndex,
311
+ sourceLine,
312
+ sourceColumn,
313
+ namesIndex
314
+ ];
315
+ } else seg = [
316
+ genColumn,
317
+ sourcesIndex,
318
+ sourceLine,
319
+ sourceColumn
320
+ ];
321
+ } else seg = [genColumn];
322
+ line.push(seg);
323
+ reader.pos++;
324
+ }
325
+ if (!sorted) sort(line);
326
+ decoded.push(line);
327
+ reader.pos = semi + 1;
328
+ } while (reader.pos <= length);
329
+ return decoded;
330
+ }
331
+ function sort(line) {
332
+ line.sort(sortComparator);
333
+ }
334
+ function sortComparator(a, b) {
335
+ return a[0] - b[0];
336
+ }
337
+ function encode(decoded) {
338
+ const writer = new StringWriter();
339
+ let sourcesIndex = 0;
340
+ let sourceLine = 0;
341
+ let sourceColumn = 0;
342
+ let namesIndex = 0;
343
+ for (let i = 0; i < decoded.length; i++) {
344
+ const line = decoded[i];
345
+ if (i > 0) writer.write(semicolon);
346
+ if (line.length === 0) continue;
347
+ let genColumn = 0;
348
+ for (let j = 0; j < line.length; j++) {
349
+ const segment = line[j];
350
+ if (j > 0) writer.write(comma);
351
+ genColumn = encodeInteger(writer, segment[0], genColumn);
352
+ if (segment.length === 1) continue;
353
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
354
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
355
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
356
+ if (segment.length === 4) continue;
357
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
358
+ }
359
+ }
360
+ return writer.flush();
361
+ }
362
+ //#endregion
363
+ //#region src/text-edits.ts
364
+ var readNewlineAt = (value, index) => {
365
+ if (index < 0 || index >= value.length) return;
366
+ if (value.startsWith("\r\n", index)) return "\r\n";
367
+ const char = value[index];
368
+ if (char === "\n" || char === "\r") return char;
369
+ };
370
+ var findFirstNewline = (value) => {
371
+ for (let index = 0; index < value.length; index++) {
372
+ const newline = readNewlineAt(value, index);
373
+ if (newline) return newline;
374
+ }
375
+ };
376
+ var findPreviousNewline = (value, index) => {
377
+ for (let current = index - 1; current >= 0; current--) {
378
+ if (value[current] === "\n") return current > 0 && value[current - 1] === "\r" ? "\r\n" : "\n";
379
+ if (value[current] === "\r") return "\r";
380
+ }
381
+ };
382
+ var applyTextEdits = (value, edits) => {
383
+ if (edits.length === 0) return value;
384
+ const sorted = [...edits].sort((lhs, rhs) => rhs.start - lhs.start);
385
+ let result = value;
386
+ let previousStart = value.length;
387
+ for (const edit of sorted) {
388
+ if (edit.start > edit.end) throw new Error(`Invalid text edit range: ${edit.start} > ${edit.end}`);
389
+ if (edit.end > previousStart) throw new Error("Overlapping text edits are not supported");
390
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
391
+ previousStart = edit.start;
392
+ }
393
+ return result;
394
+ };
395
+ var detectPreferredNewline = (value, start, end) => {
396
+ var _findFirstNewline;
397
+ const within = findFirstNewline(value.slice(start, end));
398
+ if (within) return within;
399
+ const adjacent = readNewlineAt(value, end);
400
+ if (adjacent) return adjacent;
401
+ const after = findFirstNewline(value.slice(end));
402
+ if (after) return after;
403
+ const before = findPreviousNewline(value, start);
404
+ if (before) return before;
405
+ return (_findFirstNewline = findFirstNewline(value)) !== null && _findFirstNewline !== void 0 ? _findFirstNewline : "\n";
406
+ };
407
+ var collectLineStarts = (value) => {
408
+ const starts = [0];
409
+ for (let index = 0; index < value.length; index++) {
410
+ const char = value[index];
411
+ if (char === "\r") {
412
+ if (value[index + 1] === "\n") index += 1;
413
+ starts.push(index + 1);
414
+ continue;
415
+ }
416
+ if (char === "\n") starts.push(index + 1);
417
+ }
418
+ return starts;
419
+ };
420
+ var getLineColumnOffset = (lineStarts, offset) => {
421
+ let low = 0;
422
+ let high = lineStarts.length - 1;
423
+ while (low <= high) {
424
+ const middle = low + high >> 1;
425
+ const lineStart = lineStarts[middle];
426
+ const nextStart = middle + 1 < lineStarts.length ? lineStarts[middle + 1] : Number.MAX_SAFE_INTEGER;
427
+ if (offset < lineStart) {
428
+ high = middle - 1;
429
+ continue;
430
+ }
431
+ if (offset >= nextStart) {
432
+ low = middle + 1;
433
+ continue;
434
+ }
435
+ return {
436
+ line: middle,
437
+ column: offset - lineStart
438
+ };
439
+ }
440
+ const lastLine = Math.max(0, lineStarts.length - 1);
441
+ return {
442
+ line: lastLine,
443
+ column: offset - lineStarts[lastLine]
444
+ };
445
+ };
446
+ //#endregion
447
+ //#region src/declaration-import-fix.ts
448
+ var declarationFilePattern = /\.d\.(?:cts|mts|ts)$/;
449
+ var isRelativeSpecifier = (specifier) => specifier.startsWith("./") || specifier.startsWith("../");
450
+ var hasExplicitExtension = (specifier) => posix.extname(specifier) !== "";
451
+ var getDeclarationRuntimeSuffix = (declarationPath) => {
452
+ if (declarationPath.endsWith(".d.mts")) return ".mjs";
453
+ if (declarationPath.endsWith(".d.cts")) return ".cjs";
454
+ return ".js";
455
+ };
456
+ var createCandidateDeclarationPaths = (resolvedPath) => [
457
+ `${resolvedPath}.d.ts`,
458
+ `${resolvedPath}.d.mts`,
459
+ `${resolvedPath}.d.cts`,
460
+ join(resolvedPath, "index.d.ts"),
461
+ join(resolvedPath, "index.d.mts"),
462
+ join(resolvedPath, "index.d.cts")
463
+ ];
464
+ var resolveSpecifierSuffix = (specifier, importerPath, declarationFiles, logger) => {
465
+ if (!isRelativeSpecifier(specifier) || hasExplicitExtension(specifier)) return;
466
+ const resolvedPath = resolve(dirname(importerPath), specifier);
467
+ const matches = createCandidateDeclarationPaths(resolvedPath).filter((path) => declarationFiles.has(path));
468
+ if (matches.length === 0) return;
469
+ if (matches.length >= 2) {
470
+ logger === null || logger === void 0 || logger.warn(`[fixDeclarationImports] Skipped ambiguous declaration import: ${specifier} (${matches.map((path) => {
471
+ var _path$split$pop;
472
+ return (_path$split$pop = path.split(/[/\\]/).pop()) !== null && _path$split$pop !== void 0 ? _path$split$pop : path;
473
+ }).join(", ")})`);
474
+ return;
475
+ }
476
+ const match = matches[0];
477
+ const runtimeSuffix = getDeclarationRuntimeSuffix(match);
478
+ const indexPrefix = join(resolvedPath, "index.");
479
+ return match.startsWith(indexPrefix) ? `/index${runtimeSuffix}` : runtimeSuffix;
480
+ };
481
+ var collectModuleSpecifierEdits = (ts, sourceFile, importerPath, declarationFiles, logger) => {
482
+ const edits = [];
483
+ const seen = /* @__PURE__ */ new Set();
484
+ const pushSpecifierEdit = (literal) => {
485
+ const suffix = resolveSpecifierSuffix(literal.text, importerPath, declarationFiles, logger);
486
+ if (!suffix) return;
487
+ const insertionPoint = literal.getEnd() - 1;
488
+ if (seen.has(insertionPoint)) return;
489
+ seen.add(insertionPoint);
490
+ edits.push({
491
+ start: insertionPoint,
492
+ end: insertionPoint,
493
+ text: suffix
494
+ });
495
+ };
496
+ const visit = (node) => {
497
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
498
+ if (node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) pushSpecifierEdit(node.moduleSpecifier);
499
+ } else if (ts.isImportTypeNode(node)) {
500
+ const argument = node.argument;
501
+ if (ts.isLiteralTypeNode(argument) && ts.isStringLiteralLike(argument.literal)) pushSpecifierEdit(argument.literal);
502
+ }
503
+ node.forEachChild(visit);
504
+ };
505
+ sourceFile.forEachChild(visit);
506
+ return edits;
507
+ };
508
+ var isDeclarationFilePath = (filePath) => declarationFilePattern.test(filePath);
509
+ var fixDeclarationImportSpecifiers = (ts, code, filePath, declarationFiles, logger) => {
510
+ const edits = collectModuleSpecifierEdits(ts, ts.createSourceFile(filePath, code, ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS), filePath, declarationFiles, logger);
511
+ if (edits.length === 0) return {
512
+ changed: false,
513
+ code,
514
+ edits
515
+ };
516
+ return {
517
+ changed: true,
518
+ code: applyTextEdits(code, edits),
519
+ edits
520
+ };
521
+ };
522
+ var adjustSourceMapForDeclarationEdits = (source, originalCode, edits) => {
523
+ if (edits.length === 0) return;
524
+ const original = typeof source === "string" ? source : Buffer.from(source).toString("utf-8");
525
+ let map;
526
+ try {
527
+ map = JSON.parse(original);
528
+ } catch (_unused) {
529
+ return;
530
+ }
531
+ if (!map || typeof map.mappings !== "string") return;
532
+ const lineStarts = collectLineStarts(originalCode);
533
+ const lineDeltas = /* @__PURE__ */ new Map();
534
+ for (const edit of edits) {
535
+ var _lineDeltas$get;
536
+ if (edit.start !== edit.end) return;
537
+ if (edit.text.includes("\n") || edit.text.includes("\r")) return;
538
+ const position = getLineColumnOffset(lineStarts, edit.start);
539
+ const entries = (_lineDeltas$get = lineDeltas.get(position.line)) !== null && _lineDeltas$get !== void 0 ? _lineDeltas$get : [];
540
+ entries.push({
541
+ column: position.column,
542
+ delta: edit.text.length
543
+ });
544
+ lineDeltas.set(position.line, entries);
545
+ }
546
+ if (lineDeltas.size === 0) return;
547
+ const decodedMappings = decode(map.mappings);
548
+ for (const [line, entries] of lineDeltas.entries()) {
549
+ const segments = decodedMappings[line];
550
+ if (!segments || segments.length === 0) continue;
551
+ const sortedEntries = [...entries].sort((lhs, rhs) => lhs.column - rhs.column);
552
+ let entryIndex = 0;
553
+ let cumulativeDelta = 0;
554
+ for (const segment of segments) {
555
+ while (entryIndex < sortedEntries.length && sortedEntries[entryIndex].column <= segment[0]) {
556
+ cumulativeDelta += sortedEntries[entryIndex].delta;
557
+ entryIndex += 1;
558
+ }
559
+ segment[0] += cumulativeDelta;
560
+ }
561
+ }
562
+ map.mappings = encode(decodedMappings);
563
+ const serialized = JSON.stringify(map);
564
+ return original.endsWith("\n") ? `${serialized}\n` : serialized;
565
+ };
566
+ //#endregion
174
567
  //#region src/default-import-fix.ts
175
568
  var importConditions = [
176
569
  "import",
@@ -312,45 +705,46 @@ var cjsInteropGlobalFlagAssignmentPattern = new RegExp(`\\bglobalThis\\.${cjsInt
312
705
  var createCjsInteropHelperId = (seed) => {
313
706
  return createHash("sha256").update(seed).digest("hex").slice(0, cjsInteropIdLength);
314
707
  };
315
- var buildHelperFunctionSource = (helperId) => `
316
- globalThis.${cjsInteropGlobalFlagPrefix}${helperId} = false;
317
- function __resolveDefaultExport<T>(module: T | { default?: T }, isESM: boolean): T {
318
- const __isInCJS =
319
- typeof globalThis !== 'undefined' &&
320
- (globalThis as any).${cjsInteropGlobalFlagPrefix}${helperId} === true;
321
- const maybe = module as { default?: T };
322
- const hasDefault = !!(maybe && typeof maybe === 'object' && 'default' in maybe);
323
- const unwrapNamespaceDefault = (value: unknown): unknown => {
324
- if (!value || typeof value !== 'object') {
325
- return value;
326
- }
327
- const inner = value as any;
328
- const isModule =
329
- inner.__esModule === true ||
330
- (typeof Symbol !== 'undefined' &&
331
- (inner as any)[Symbol.toStringTag] === 'Module');
332
- if (isModule && 'default' in inner) {
333
- return inner.default;
334
- }
335
- return value;
336
- };
337
- const resolvedDefault = hasDefault
338
- ? unwrapNamespaceDefault((maybe as any).default)
339
- : undefined;
340
-
341
- if (__isInCJS) {
342
- return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);
343
- }
344
-
345
- if (isESM) {
346
- if (hasDefault) {
347
- return resolvedDefault as T;
348
- }
349
- throw new Error('Default export not found.');
350
- }
351
-
352
- return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);
353
- }`;
708
+ var buildHelperFunctionSource = (helperId, newline) => [
709
+ `globalThis.${cjsInteropGlobalFlagPrefix}${helperId} = false;`,
710
+ "function __resolveDefaultExport<T>(module: T | { default?: T }, isESM: boolean): T {",
711
+ " const __isInCJS =",
712
+ " typeof globalThis !== 'undefined' &&",
713
+ ` (globalThis as any).${cjsInteropGlobalFlagPrefix}${helperId} === true;`,
714
+ " const maybe = module as { default?: T };",
715
+ " const hasDefault = !!(maybe && typeof maybe === 'object' && 'default' in maybe);",
716
+ " const unwrapNamespaceDefault = (value: unknown): unknown => {",
717
+ " if (!value || typeof value !== 'object') {",
718
+ " return value;",
719
+ " }",
720
+ " const inner = value as any;",
721
+ " const isModule =",
722
+ " inner.__esModule === true ||",
723
+ " (typeof Symbol !== 'undefined' &&",
724
+ " (inner as any)[Symbol.toStringTag] === 'Module');",
725
+ " if (isModule && 'default' in inner) {",
726
+ " return inner.default;",
727
+ " }",
728
+ " return value;",
729
+ " };",
730
+ " const resolvedDefault = hasDefault",
731
+ " ? unwrapNamespaceDefault((maybe as any).default)",
732
+ " : undefined;",
733
+ "",
734
+ " if (__isInCJS) {",
735
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
736
+ " }",
737
+ "",
738
+ " if (isESM) {",
739
+ " if (hasDefault) {",
740
+ " return resolvedDefault as T;",
741
+ " }",
742
+ " throw new Error('Default export not found.');",
743
+ " }",
744
+ "",
745
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
746
+ "}"
747
+ ].join(newline);
354
748
  var injectCjsInteropFlag = (code) => {
355
749
  let changed = false;
356
750
  return {
@@ -461,7 +855,8 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
461
855
  if (importClause.namedBindings && ts.isNamedImports(importClause.namedBindings)) replacementImports.push(buildNamedImport(moduleName, importClause.namedBindings));
462
856
  }
463
857
  const interopSource = (_namespaceName = namespaceName) !== null && _namespaceName !== void 0 ? _namespaceName : defaultImportName;
464
- const replacement = `${replacementImports.join("\n")}\nconst ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
858
+ const newline = detectPreferredNewline(code, statement.getStart(sourceFile), statement.getEnd());
859
+ const replacement = `${replacementImports.join(newline)}${newline}const ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
465
860
  edits.push({
466
861
  start: statement.getStart(sourceFile),
467
862
  end: statement.getEnd(),
@@ -477,20 +872,17 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
477
872
  const importStatements = sourceFile.statements.filter(ts.isImportDeclaration);
478
873
  const lastImport = importStatements[importStatements.length - 1];
479
874
  if (lastImport) {
480
- const newline = code.includes("\r\n") ? "\r\n" : "\n";
875
+ const newline = detectPreferredNewline(code, lastImport.getStart(sourceFile), lastImport.getEnd());
481
876
  const helperId = createCjsInteropHelperId(normalizedId);
482
877
  edits.push({
483
878
  start: lastImport.getEnd(),
484
879
  end: lastImport.getEnd(),
485
- text: `${newline}${buildHelperFunctionSource(helperId)}${newline}`
880
+ text: `${newline}${buildHelperFunctionSource(helperId, newline)}${newline}`
486
881
  });
487
882
  }
488
883
  }
489
- edits.sort((a, b) => b.start - a.start);
490
- let nextCode = code;
491
- for (const edit of edits) nextCode = nextCode.slice(0, edit.start) + edit.text + nextCode.slice(edit.end);
492
884
  return {
493
- code: nextCode,
885
+ code: applyTextEdits(code, edits),
494
886
  changed: true
495
887
  };
496
888
  };
@@ -598,7 +990,7 @@ var screwUp = (options = {}) => {
598
990
  "license",
599
991
  "repository.url",
600
992
  "git.commit.hash"
601
- ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true } = options;
993
+ ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true, fixDeclarationImportExtensions = true } = options;
602
994
  const assetFiltersRegex = assetFilters.map((filter) => new RegExp(filter));
603
995
  const generateMetadataSourceLocker = createMutex();
604
996
  const resolveModuleKind = createNodeModuleKindResolver();
@@ -777,29 +1169,65 @@ var screwUp = (options = {}) => {
777
1169
  }
778
1170
  },
779
1171
  writeBundle: async (options) => {
780
- if (!insertMetadataBanner || !options.dir) return;
1172
+ if (!options.dir) return;
781
1173
  try {
782
1174
  const files = await readdir(options.dir, { recursive: true });
783
- let count = 0;
1175
+ const declarationFiles = new Set(files.filter((file) => isDeclarationFilePath(file)).map((file) => resolve(options.dir, file)));
1176
+ const ts = fixDeclarationImportExtensions ? await loadTypeScript() : void 0;
1177
+ let bannerCount = 0;
1178
+ let declarationCount = 0;
784
1179
  for (const file of files) {
785
1180
  const filePath = join(options.dir, file);
786
- if (assetFiltersRegex.some((filter) => filter.test(file))) try {
787
- const content = await readFile(filePath, "utf-8");
788
- if (!content.includes(banner)) {
789
- const bannerBlock = `${banner}\n`;
790
- await writeFile(filePath, insertBannerHeader(content, bannerBlock));
791
- const lineOffset = countInsertedLines(bannerBlock);
792
- const mapPath = `${filePath}.map`;
1181
+ const isAssetTarget = assetFiltersRegex.some((filter) => filter.test(file));
1182
+ const isDeclarationTarget = fixDeclarationImportExtensions && !!ts && isDeclarationFilePath(filePath);
1183
+ if (!isAssetTarget && !isDeclarationTarget) continue;
1184
+ try {
1185
+ let content = await readFile(filePath, "utf-8");
1186
+ let contentChanged = false;
1187
+ let mapLoaded = false;
1188
+ let mapContent;
1189
+ const mapPath = `${filePath}.map`;
1190
+ const loadMapContent = async () => {
1191
+ if (mapLoaded) return mapContent;
1192
+ mapLoaded = true;
793
1193
  try {
794
- const adjusted = applyLineOffsetToSourceMap(await readFile(mapPath, "utf-8"), lineOffset);
795
- if (adjusted !== void 0) await writeFile(mapPath, adjusted);
796
- } catch (_unused2) {}
797
- count++;
1194
+ mapContent = await readFile(mapPath, "utf-8");
1195
+ } catch (_unused2) {
1196
+ mapContent = void 0;
1197
+ }
1198
+ return mapContent;
1199
+ };
1200
+ if (insertMetadataBanner && isAssetTarget && !content.includes(banner)) {
1201
+ const bannerBlock = `${banner}\n`;
1202
+ content = insertBannerHeader(content, bannerBlock);
1203
+ contentChanged = true;
1204
+ const currentMapContent = await loadMapContent();
1205
+ if (currentMapContent !== void 0) {
1206
+ const adjusted = applyLineOffsetToSourceMap(currentMapContent, countInsertedLines(bannerBlock));
1207
+ if (adjusted !== void 0) mapContent = adjusted;
1208
+ }
1209
+ bannerCount++;
1210
+ }
1211
+ if (isDeclarationTarget) {
1212
+ const declarationResult = fixDeclarationImportSpecifiers(ts, content, filePath, declarationFiles, logger);
1213
+ if (declarationResult.changed) {
1214
+ const currentMapContent = await loadMapContent();
1215
+ if (currentMapContent !== void 0) {
1216
+ const adjusted = adjustSourceMapForDeclarationEdits(currentMapContent, content, declarationResult.edits);
1217
+ if (adjusted !== void 0) mapContent = adjusted;
1218
+ }
1219
+ content = declarationResult.code;
1220
+ contentChanged = true;
1221
+ declarationCount++;
1222
+ }
798
1223
  }
799
- } catch (error) {}
1224
+ if (contentChanged) await writeFile(filePath, content);
1225
+ if (mapLoaded && mapContent !== void 0) await writeFile(mapPath, mapContent);
1226
+ } catch (_unused3) {}
800
1227
  }
801
- if (count >= 1) logger.debug(`writeBundle: Banner header inserted: ${count} file(s)`);
802
- } catch (error) {}
1228
+ if (bannerCount >= 1) logger.debug(`writeBundle: Banner header inserted: ${bannerCount} file(s)`);
1229
+ if (declarationCount >= 1) logger.debug(`writeBundle: Declaration imports fixed: ${declarationCount} file(s)`);
1230
+ } catch (_unused4) {}
803
1231
  }
804
1232
  };
805
1233
  };