screw-up 1.29.0 → 1.30.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 (43) hide show
  1. package/dist/index.cjs +471 -67
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +472 -68
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/main.cjs +4 -4
  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-CpFkBJPS.js} +3 -3
  10. package/dist/{metadata-file-CyQ2yue9.js.map → metadata-file-CpFkBJPS.js.map} +1 -1
  11. package/dist/{packageMetadata-K_w0Knb7.cjs → packageMetadata-Lj9bVuVM.cjs} +5 -5
  12. package/dist/{packageMetadata-K_w0Knb7.cjs.map → packageMetadata-Lj9bVuVM.cjs.map} +1 -1
  13. package/dist/{packageMetadata-DnXbVLQ5.js → packageMetadata-YWwXZbaj.js} +6 -6
  14. package/dist/{packageMetadata-DnXbVLQ5.js.map → packageMetadata-YWwXZbaj.js.map} +1 -1
  15. package/dist/{packageMetadata-CpakAG0S.cjs → packageMetadata-zaiRRUve.cjs} +3 -3
  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/index.d.ts +4 -4
  32. package/dist/src/index.d.ts.map +1 -1
  33. package/dist/src/internal.d.ts +3 -3
  34. package/dist/src/main.d.ts +2 -2
  35. package/dist/src/metadata-file.d.ts +4 -4
  36. package/dist/src/metadata-file.d.ts.map +1 -1
  37. package/dist/src/text-edits.d.ts +24 -0
  38. package/dist/src/text-edits.d.ts.map +1 -0
  39. package/dist/src/types.d.ts +7 -2
  40. package/dist/src/types.d.ts.map +1 -1
  41. package/dist/src/vite-plugin.d.ts +3 -3
  42. package/dist/src/vite-plugin.d.ts.map +1 -1
  43. package/package.json +14 -10
package/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
1
  /*!
2
2
  * name: screw-up
3
- * version: 1.29.0
3
+ * version: 1.30.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: ac6785ada0880218ecbaef699721d3a169362e76
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-CpFkBJPS.js";
11
+ import { i as version, n as name, t as git_commit_hash } from "./packageMetadata-YWwXZbaj.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
  /*!
@@ -171,6 +171,375 @@ var createLogicalContext = (id) => {
171
171
  };
172
172
  createLogicalContext(Symbol("[root]"));
173
173
  //#endregion
174
+ //#region node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
175
+ var comma = ",".charCodeAt(0);
176
+ var semicolon = ";".charCodeAt(0);
177
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
178
+ var intToChar = new Uint8Array(64);
179
+ var charToInt = new Uint8Array(128);
180
+ for (let i = 0; i < chars.length; i++) {
181
+ const c = chars.charCodeAt(i);
182
+ intToChar[i] = c;
183
+ charToInt[c] = i;
184
+ }
185
+ function decodeInteger(reader, relative) {
186
+ let value = 0;
187
+ let shift = 0;
188
+ let integer = 0;
189
+ do {
190
+ integer = charToInt[reader.next()];
191
+ value |= (integer & 31) << shift;
192
+ shift += 5;
193
+ } while (integer & 32);
194
+ const shouldNegate = value & 1;
195
+ value >>>= 1;
196
+ if (shouldNegate) value = -2147483648 | -value;
197
+ return relative + value;
198
+ }
199
+ function encodeInteger(builder, num, relative) {
200
+ let delta = num - relative;
201
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
202
+ do {
203
+ let clamped = delta & 31;
204
+ delta >>>= 5;
205
+ if (delta > 0) clamped |= 32;
206
+ builder.write(intToChar[clamped]);
207
+ } while (delta > 0);
208
+ return num;
209
+ }
210
+ function hasMoreVlq(reader, max) {
211
+ if (reader.pos >= max) return false;
212
+ return reader.peek() !== comma;
213
+ }
214
+ var bufLength = 1024 * 16;
215
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { decode(buf) {
216
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString();
217
+ } } : { decode(buf) {
218
+ let out = "";
219
+ for (let i = 0; i < buf.length; i++) out += String.fromCharCode(buf[i]);
220
+ return out;
221
+ } };
222
+ var StringWriter = class {
223
+ constructor() {
224
+ this.pos = 0;
225
+ this.out = "";
226
+ this.buffer = new Uint8Array(bufLength);
227
+ }
228
+ write(v) {
229
+ const { buffer } = this;
230
+ buffer[this.pos++] = v;
231
+ if (this.pos === bufLength) {
232
+ this.out += td.decode(buffer);
233
+ this.pos = 0;
234
+ }
235
+ }
236
+ flush() {
237
+ const { buffer, out, pos } = this;
238
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
239
+ }
240
+ };
241
+ var StringReader = class {
242
+ constructor(buffer) {
243
+ this.pos = 0;
244
+ this.buffer = buffer;
245
+ }
246
+ next() {
247
+ return this.buffer.charCodeAt(this.pos++);
248
+ }
249
+ peek() {
250
+ return this.buffer.charCodeAt(this.pos);
251
+ }
252
+ indexOf(char) {
253
+ const { buffer, pos } = this;
254
+ const idx = buffer.indexOf(char, pos);
255
+ return idx === -1 ? buffer.length : idx;
256
+ }
257
+ };
258
+ function decode(mappings) {
259
+ const { length } = mappings;
260
+ const reader = new StringReader(mappings);
261
+ const decoded = [];
262
+ let genColumn = 0;
263
+ let sourcesIndex = 0;
264
+ let sourceLine = 0;
265
+ let sourceColumn = 0;
266
+ let namesIndex = 0;
267
+ do {
268
+ const semi = reader.indexOf(";");
269
+ const line = [];
270
+ let sorted = true;
271
+ let lastCol = 0;
272
+ genColumn = 0;
273
+ while (reader.pos < semi) {
274
+ let seg;
275
+ genColumn = decodeInteger(reader, genColumn);
276
+ if (genColumn < lastCol) sorted = false;
277
+ lastCol = genColumn;
278
+ if (hasMoreVlq(reader, semi)) {
279
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
280
+ sourceLine = decodeInteger(reader, sourceLine);
281
+ sourceColumn = decodeInteger(reader, sourceColumn);
282
+ if (hasMoreVlq(reader, semi)) {
283
+ namesIndex = decodeInteger(reader, namesIndex);
284
+ seg = [
285
+ genColumn,
286
+ sourcesIndex,
287
+ sourceLine,
288
+ sourceColumn,
289
+ namesIndex
290
+ ];
291
+ } else seg = [
292
+ genColumn,
293
+ sourcesIndex,
294
+ sourceLine,
295
+ sourceColumn
296
+ ];
297
+ } else seg = [genColumn];
298
+ line.push(seg);
299
+ reader.pos++;
300
+ }
301
+ if (!sorted) sort(line);
302
+ decoded.push(line);
303
+ reader.pos = semi + 1;
304
+ } while (reader.pos <= length);
305
+ return decoded;
306
+ }
307
+ function sort(line) {
308
+ line.sort(sortComparator);
309
+ }
310
+ function sortComparator(a, b) {
311
+ return a[0] - b[0];
312
+ }
313
+ function encode(decoded) {
314
+ const writer = new StringWriter();
315
+ let sourcesIndex = 0;
316
+ let sourceLine = 0;
317
+ let sourceColumn = 0;
318
+ let namesIndex = 0;
319
+ for (let i = 0; i < decoded.length; i++) {
320
+ const line = decoded[i];
321
+ if (i > 0) writer.write(semicolon);
322
+ if (line.length === 0) continue;
323
+ let genColumn = 0;
324
+ for (let j = 0; j < line.length; j++) {
325
+ const segment = line[j];
326
+ if (j > 0) writer.write(comma);
327
+ genColumn = encodeInteger(writer, segment[0], genColumn);
328
+ if (segment.length === 1) continue;
329
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
330
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
331
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
332
+ if (segment.length === 4) continue;
333
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
334
+ }
335
+ }
336
+ return writer.flush();
337
+ }
338
+ //#endregion
339
+ //#region src/text-edits.ts
340
+ var readNewlineAt = (value, index) => {
341
+ if (index < 0 || index >= value.length) return;
342
+ if (value.startsWith("\r\n", index)) return "\r\n";
343
+ const char = value[index];
344
+ if (char === "\n" || char === "\r") return char;
345
+ };
346
+ var findFirstNewline = (value) => {
347
+ for (let index = 0; index < value.length; index++) {
348
+ const newline = readNewlineAt(value, index);
349
+ if (newline) return newline;
350
+ }
351
+ };
352
+ var findPreviousNewline = (value, index) => {
353
+ for (let current = index - 1; current >= 0; current--) {
354
+ if (value[current] === "\n") return current > 0 && value[current - 1] === "\r" ? "\r\n" : "\n";
355
+ if (value[current] === "\r") return "\r";
356
+ }
357
+ };
358
+ var applyTextEdits = (value, edits) => {
359
+ if (edits.length === 0) return value;
360
+ const sorted = [...edits].sort((lhs, rhs) => rhs.start - lhs.start);
361
+ let result = value;
362
+ let previousStart = value.length;
363
+ for (const edit of sorted) {
364
+ if (edit.start > edit.end) throw new Error(`Invalid text edit range: ${edit.start} > ${edit.end}`);
365
+ if (edit.end > previousStart) throw new Error("Overlapping text edits are not supported");
366
+ result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
367
+ previousStart = edit.start;
368
+ }
369
+ return result;
370
+ };
371
+ var detectPreferredNewline = (value, start, end) => {
372
+ var _findFirstNewline;
373
+ const within = findFirstNewline(value.slice(start, end));
374
+ if (within) return within;
375
+ const adjacent = readNewlineAt(value, end);
376
+ if (adjacent) return adjacent;
377
+ const after = findFirstNewline(value.slice(end));
378
+ if (after) return after;
379
+ const before = findPreviousNewline(value, start);
380
+ if (before) return before;
381
+ return (_findFirstNewline = findFirstNewline(value)) !== null && _findFirstNewline !== void 0 ? _findFirstNewline : "\n";
382
+ };
383
+ var collectLineStarts = (value) => {
384
+ const starts = [0];
385
+ for (let index = 0; index < value.length; index++) {
386
+ const char = value[index];
387
+ if (char === "\r") {
388
+ if (value[index + 1] === "\n") index += 1;
389
+ starts.push(index + 1);
390
+ continue;
391
+ }
392
+ if (char === "\n") starts.push(index + 1);
393
+ }
394
+ return starts;
395
+ };
396
+ var getLineColumnOffset = (lineStarts, offset) => {
397
+ let low = 0;
398
+ let high = lineStarts.length - 1;
399
+ while (low <= high) {
400
+ const middle = low + high >> 1;
401
+ const lineStart = lineStarts[middle];
402
+ const nextStart = middle + 1 < lineStarts.length ? lineStarts[middle + 1] : Number.MAX_SAFE_INTEGER;
403
+ if (offset < lineStart) {
404
+ high = middle - 1;
405
+ continue;
406
+ }
407
+ if (offset >= nextStart) {
408
+ low = middle + 1;
409
+ continue;
410
+ }
411
+ return {
412
+ line: middle,
413
+ column: offset - lineStart
414
+ };
415
+ }
416
+ const lastLine = Math.max(0, lineStarts.length - 1);
417
+ return {
418
+ line: lastLine,
419
+ column: offset - lineStarts[lastLine]
420
+ };
421
+ };
422
+ //#endregion
423
+ //#region src/declaration-import-fix.ts
424
+ var declarationFilePattern = /\.d\.(?:cts|mts|ts)$/;
425
+ var isRelativeSpecifier = (specifier) => specifier.startsWith("./") || specifier.startsWith("../");
426
+ var hasExplicitExtension = (specifier) => posix.extname(specifier) !== "";
427
+ var getDeclarationRuntimeSuffix = (declarationPath) => {
428
+ if (declarationPath.endsWith(".d.mts")) return ".mjs";
429
+ if (declarationPath.endsWith(".d.cts")) return ".cjs";
430
+ return ".js";
431
+ };
432
+ var createCandidateDeclarationPaths = (resolvedPath) => [
433
+ `${resolvedPath}.d.ts`,
434
+ `${resolvedPath}.d.mts`,
435
+ `${resolvedPath}.d.cts`,
436
+ join(resolvedPath, "index.d.ts"),
437
+ join(resolvedPath, "index.d.mts"),
438
+ join(resolvedPath, "index.d.cts")
439
+ ];
440
+ var resolveSpecifierSuffix = (specifier, importerPath, declarationFiles, logger) => {
441
+ if (!isRelativeSpecifier(specifier) || hasExplicitExtension(specifier)) return;
442
+ const resolvedPath = resolve(dirname(importerPath), specifier);
443
+ const matches = createCandidateDeclarationPaths(resolvedPath).filter((path) => declarationFiles.has(path));
444
+ if (matches.length === 0) return;
445
+ if (matches.length >= 2) {
446
+ logger === null || logger === void 0 || logger.warn(`[fixDeclarationImports] Skipped ambiguous declaration import: ${specifier} (${matches.map((path) => {
447
+ var _path$split$pop;
448
+ return (_path$split$pop = path.split(/[/\\]/).pop()) !== null && _path$split$pop !== void 0 ? _path$split$pop : path;
449
+ }).join(", ")})`);
450
+ return;
451
+ }
452
+ const match = matches[0];
453
+ const runtimeSuffix = getDeclarationRuntimeSuffix(match);
454
+ const indexPrefix = join(resolvedPath, "index.");
455
+ return match.startsWith(indexPrefix) ? `/index${runtimeSuffix}` : runtimeSuffix;
456
+ };
457
+ var collectModuleSpecifierEdits = (ts, sourceFile, importerPath, declarationFiles, logger) => {
458
+ const edits = [];
459
+ const seen = /* @__PURE__ */ new Set();
460
+ const pushSpecifierEdit = (literal) => {
461
+ const suffix = resolveSpecifierSuffix(literal.text, importerPath, declarationFiles, logger);
462
+ if (!suffix) return;
463
+ const insertionPoint = literal.getEnd() - 1;
464
+ if (seen.has(insertionPoint)) return;
465
+ seen.add(insertionPoint);
466
+ edits.push({
467
+ start: insertionPoint,
468
+ end: insertionPoint,
469
+ text: suffix
470
+ });
471
+ };
472
+ const visit = (node) => {
473
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
474
+ if (node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) pushSpecifierEdit(node.moduleSpecifier);
475
+ } else if (ts.isImportTypeNode(node)) {
476
+ const argument = node.argument;
477
+ if (ts.isLiteralTypeNode(argument) && ts.isStringLiteralLike(argument.literal)) pushSpecifierEdit(argument.literal);
478
+ }
479
+ node.forEachChild(visit);
480
+ };
481
+ sourceFile.forEachChild(visit);
482
+ return edits;
483
+ };
484
+ var isDeclarationFilePath = (filePath) => declarationFilePattern.test(filePath);
485
+ var fixDeclarationImportSpecifiers = (ts, code, filePath, declarationFiles, logger) => {
486
+ const edits = collectModuleSpecifierEdits(ts, ts.createSourceFile(filePath, code, ts.ScriptTarget.ESNext, false, ts.ScriptKind.TS), filePath, declarationFiles, logger);
487
+ if (edits.length === 0) return {
488
+ changed: false,
489
+ code,
490
+ edits
491
+ };
492
+ return {
493
+ changed: true,
494
+ code: applyTextEdits(code, edits),
495
+ edits
496
+ };
497
+ };
498
+ var adjustSourceMapForDeclarationEdits = (source, originalCode, edits) => {
499
+ if (edits.length === 0) return;
500
+ const original = typeof source === "string" ? source : Buffer.from(source).toString("utf-8");
501
+ let map;
502
+ try {
503
+ map = JSON.parse(original);
504
+ } catch (_unused) {
505
+ return;
506
+ }
507
+ if (!map || typeof map.mappings !== "string") return;
508
+ const lineStarts = collectLineStarts(originalCode);
509
+ const lineDeltas = /* @__PURE__ */ new Map();
510
+ for (const edit of edits) {
511
+ var _lineDeltas$get;
512
+ if (edit.start !== edit.end) return;
513
+ if (edit.text.includes("\n") || edit.text.includes("\r")) return;
514
+ const position = getLineColumnOffset(lineStarts, edit.start);
515
+ const entries = (_lineDeltas$get = lineDeltas.get(position.line)) !== null && _lineDeltas$get !== void 0 ? _lineDeltas$get : [];
516
+ entries.push({
517
+ column: position.column,
518
+ delta: edit.text.length
519
+ });
520
+ lineDeltas.set(position.line, entries);
521
+ }
522
+ if (lineDeltas.size === 0) return;
523
+ const decodedMappings = decode(map.mappings);
524
+ for (const [line, entries] of lineDeltas.entries()) {
525
+ const segments = decodedMappings[line];
526
+ if (!segments || segments.length === 0) continue;
527
+ const sortedEntries = [...entries].sort((lhs, rhs) => lhs.column - rhs.column);
528
+ let entryIndex = 0;
529
+ let cumulativeDelta = 0;
530
+ for (const segment of segments) {
531
+ while (entryIndex < sortedEntries.length && sortedEntries[entryIndex].column <= segment[0]) {
532
+ cumulativeDelta += sortedEntries[entryIndex].delta;
533
+ entryIndex += 1;
534
+ }
535
+ segment[0] += cumulativeDelta;
536
+ }
537
+ }
538
+ map.mappings = encode(decodedMappings);
539
+ const serialized = JSON.stringify(map);
540
+ return original.endsWith("\n") ? `${serialized}\n` : serialized;
541
+ };
542
+ //#endregion
174
543
  //#region src/default-import-fix.ts
175
544
  var importConditions = [
176
545
  "import",
@@ -312,45 +681,46 @@ var cjsInteropGlobalFlagAssignmentPattern = new RegExp(`\\bglobalThis\\.${cjsInt
312
681
  var createCjsInteropHelperId = (seed) => {
313
682
  return createHash("sha256").update(seed).digest("hex").slice(0, cjsInteropIdLength);
314
683
  };
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
- }`;
684
+ var buildHelperFunctionSource = (helperId, newline) => [
685
+ `globalThis.${cjsInteropGlobalFlagPrefix}${helperId} = false;`,
686
+ "function __resolveDefaultExport<T>(module: T | { default?: T }, isESM: boolean): T {",
687
+ " const __isInCJS =",
688
+ " typeof globalThis !== 'undefined' &&",
689
+ ` (globalThis as any).${cjsInteropGlobalFlagPrefix}${helperId} === true;`,
690
+ " const maybe = module as { default?: T };",
691
+ " const hasDefault = !!(maybe && typeof maybe === 'object' && 'default' in maybe);",
692
+ " const unwrapNamespaceDefault = (value: unknown): unknown => {",
693
+ " if (!value || typeof value !== 'object') {",
694
+ " return value;",
695
+ " }",
696
+ " const inner = value as any;",
697
+ " const isModule =",
698
+ " inner.__esModule === true ||",
699
+ " (typeof Symbol !== 'undefined' &&",
700
+ " (inner as any)[Symbol.toStringTag] === 'Module');",
701
+ " if (isModule && 'default' in inner) {",
702
+ " return inner.default;",
703
+ " }",
704
+ " return value;",
705
+ " };",
706
+ " const resolvedDefault = hasDefault",
707
+ " ? unwrapNamespaceDefault((maybe as any).default)",
708
+ " : undefined;",
709
+ "",
710
+ " if (__isInCJS) {",
711
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
712
+ " }",
713
+ "",
714
+ " if (isESM) {",
715
+ " if (hasDefault) {",
716
+ " return resolvedDefault as T;",
717
+ " }",
718
+ " throw new Error('Default export not found.');",
719
+ " }",
720
+ "",
721
+ " return hasDefault ? ((resolvedDefault as T) ?? (module as T)) : (module as T);",
722
+ "}"
723
+ ].join(newline);
354
724
  var injectCjsInteropFlag = (code) => {
355
725
  let changed = false;
356
726
  return {
@@ -461,7 +831,8 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
461
831
  if (importClause.namedBindings && ts.isNamedImports(importClause.namedBindings)) replacementImports.push(buildNamedImport(moduleName, importClause.namedBindings));
462
832
  }
463
833
  const interopSource = (_namespaceName = namespaceName) !== null && _namespaceName !== void 0 ? _namespaceName : defaultImportName;
464
- const replacement = `${replacementImports.join("\n")}\nconst ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
834
+ const newline = detectPreferredNewline(code, statement.getStart(sourceFile), statement.getEnd());
835
+ const replacement = `${replacementImports.join(newline)}${newline}const ${defaultName} = __resolveDefaultExport(${interopSource}, ${isESM});`;
465
836
  edits.push({
466
837
  start: statement.getStart(sourceFile),
467
838
  end: statement.getEnd(),
@@ -477,20 +848,17 @@ var transformDefaultImports = async (ts, code, id, resolveModuleKind) => {
477
848
  const importStatements = sourceFile.statements.filter(ts.isImportDeclaration);
478
849
  const lastImport = importStatements[importStatements.length - 1];
479
850
  if (lastImport) {
480
- const newline = code.includes("\r\n") ? "\r\n" : "\n";
851
+ const newline = detectPreferredNewline(code, lastImport.getStart(sourceFile), lastImport.getEnd());
481
852
  const helperId = createCjsInteropHelperId(normalizedId);
482
853
  edits.push({
483
854
  start: lastImport.getEnd(),
484
855
  end: lastImport.getEnd(),
485
- text: `${newline}${buildHelperFunctionSource(helperId)}${newline}`
856
+ text: `${newline}${buildHelperFunctionSource(helperId, newline)}${newline}`
486
857
  });
487
858
  }
488
859
  }
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
860
  return {
493
- code: nextCode,
861
+ code: applyTextEdits(code, edits),
494
862
  changed: true
495
863
  };
496
864
  };
@@ -598,7 +966,7 @@ var screwUp = (options = {}) => {
598
966
  "license",
599
967
  "repository.url",
600
968
  "git.commit.hash"
601
- ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true } = options;
969
+ ], checkWorkingDirectoryStatus = true, alwaysOverrideVersionFromGit = true, insertMetadataBanner = true, fixDeclarationImportExtensions = true } = options;
602
970
  const assetFiltersRegex = assetFilters.map((filter) => new RegExp(filter));
603
971
  const generateMetadataSourceLocker = createMutex();
604
972
  const resolveModuleKind = createNodeModuleKindResolver();
@@ -777,29 +1145,65 @@ var screwUp = (options = {}) => {
777
1145
  }
778
1146
  },
779
1147
  writeBundle: async (options) => {
780
- if (!insertMetadataBanner || !options.dir) return;
1148
+ if (!options.dir) return;
781
1149
  try {
782
1150
  const files = await readdir(options.dir, { recursive: true });
783
- let count = 0;
1151
+ const declarationFiles = new Set(files.filter((file) => isDeclarationFilePath(file)).map((file) => resolve(options.dir, file)));
1152
+ const ts = fixDeclarationImportExtensions ? await loadTypeScript() : void 0;
1153
+ let bannerCount = 0;
1154
+ let declarationCount = 0;
784
1155
  for (const file of files) {
785
1156
  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`;
1157
+ const isAssetTarget = assetFiltersRegex.some((filter) => filter.test(file));
1158
+ const isDeclarationTarget = fixDeclarationImportExtensions && !!ts && isDeclarationFilePath(filePath);
1159
+ if (!isAssetTarget && !isDeclarationTarget) continue;
1160
+ try {
1161
+ let content = await readFile(filePath, "utf-8");
1162
+ let contentChanged = false;
1163
+ let mapLoaded = false;
1164
+ let mapContent;
1165
+ const mapPath = `${filePath}.map`;
1166
+ const loadMapContent = async () => {
1167
+ if (mapLoaded) return mapContent;
1168
+ mapLoaded = true;
793
1169
  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++;
1170
+ mapContent = await readFile(mapPath, "utf-8");
1171
+ } catch (_unused2) {
1172
+ mapContent = void 0;
1173
+ }
1174
+ return mapContent;
1175
+ };
1176
+ if (insertMetadataBanner && isAssetTarget && !content.includes(banner)) {
1177
+ const bannerBlock = `${banner}\n`;
1178
+ content = insertBannerHeader(content, bannerBlock);
1179
+ contentChanged = true;
1180
+ const currentMapContent = await loadMapContent();
1181
+ if (currentMapContent !== void 0) {
1182
+ const adjusted = applyLineOffsetToSourceMap(currentMapContent, countInsertedLines(bannerBlock));
1183
+ if (adjusted !== void 0) mapContent = adjusted;
1184
+ }
1185
+ bannerCount++;
1186
+ }
1187
+ if (isDeclarationTarget) {
1188
+ const declarationResult = fixDeclarationImportSpecifiers(ts, content, filePath, declarationFiles, logger);
1189
+ if (declarationResult.changed) {
1190
+ const currentMapContent = await loadMapContent();
1191
+ if (currentMapContent !== void 0) {
1192
+ const adjusted = adjustSourceMapForDeclarationEdits(currentMapContent, content, declarationResult.edits);
1193
+ if (adjusted !== void 0) mapContent = adjusted;
1194
+ }
1195
+ content = declarationResult.code;
1196
+ contentChanged = true;
1197
+ declarationCount++;
1198
+ }
798
1199
  }
799
- } catch (error) {}
1200
+ if (contentChanged) await writeFile(filePath, content);
1201
+ if (mapLoaded && mapContent !== void 0) await writeFile(mapPath, mapContent);
1202
+ } catch (_unused3) {}
800
1203
  }
801
- if (count >= 1) logger.debug(`writeBundle: Banner header inserted: ${count} file(s)`);
802
- } catch (error) {}
1204
+ if (bannerCount >= 1) logger.debug(`writeBundle: Banner header inserted: ${bannerCount} file(s)`);
1205
+ if (declarationCount >= 1) logger.debug(`writeBundle: Declaration imports fixed: ${declarationCount} file(s)`);
1206
+ } catch (_unused4) {}
803
1207
  }
804
1208
  };
805
1209
  };