@nhtio/vite-plugins 1.20251212.2 → 1.20261021.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,3 +3,46 @@
3
3
  Preconfigured Commonly Used Vite Plugins
4
4
 
5
5
  For more information, see the [official documentation](https://vite-plugins.nht.io)
6
+
7
+ ## Package-private declaration imports (`dtsComplex`)
8
+
9
+ `dtsComplex` defaults to `internalImports: 'relative'`, preserving its existing
10
+ extensionless relative declaration output. For ESM packages consumed with
11
+ NodeNext, Node16 or bundler resolution, opt in to package-private imports:
12
+
13
+ ```typescript
14
+ import { dtsComplex } from "@nhtio/vite-plugins/dts_complex";
15
+
16
+ dtsComplex({
17
+ internalImports: "subpath",
18
+ subpathPrefix: "#types", // default; must start with #, not end with / or contain *
19
+ });
20
+ ```
21
+
22
+ Internal declaration references (including aliases, directory indexes, ambient
23
+ files and bundled dependencies) then use paths such as `#types/private/mixin` or
24
+ `#types/utils/index`, without extensions. External and published package-name
25
+ self-references remain unchanged. The build fails if any relative import/export
26
+ or import-type specifier remains in an emitted declaration.
27
+
28
+ Subpath mode also emits `dts-imports.json` at the output root:
29
+
30
+ ```json
31
+ { "#types/*": { "types": "./*.d.ts" } }
32
+ ```
33
+
34
+ Merge this manifest into the `imports` field of the **published** package.json,
35
+ next to the output declarations (the plugin does not write package.json):
36
+
37
+ ```typescript
38
+ const imports = JSON.parse(await readFile("dist/dts-imports.json", "utf8"));
39
+ const publishedPackage = {
40
+ ...packageJson,
41
+ imports: { ...packageJson.imports, ...imports },
42
+ };
43
+ await writeFile("dist/package.json", JSON.stringify(publishedPackage, null, 2));
44
+ ```
45
+
46
+ Publish the declaration tree unchanged alongside that package.json. A custom
47
+ `subpathPrefix`, for example `#internal`, changes both the references and manifest
48
+ key. This mapping is for declaration types only, not runtime JavaScript imports.
package/dts.d.ts CHANGED
@@ -47,3 +47,10 @@ export declare interface PackageJson {
47
47
  }
48
48
 
49
49
  export { }
50
+
51
+
52
+ declare module 'fixture-external' {
53
+ interface External {
54
+ augmented: string;
55
+ }
56
+ }
package/dts_complex.d.ts CHANGED
@@ -19,8 +19,10 @@ import { Plugin } from 'vite';
19
19
  * (e.g., `bundled_vendor_name.d.ts`) and referenced from your main declarations, rather than
20
20
  * being inlined.
21
21
  *
22
- * 4. **Path Alias Resolution**: All import/export paths are resolved to relative paths, eliminating
23
- * the need for consumers to configure `paths` in their `tsconfig.json`.
22
+ * 4. **Path Alias Resolution**: All import/export paths are resolved to relative paths by default,
23
+ * eliminating the need for consumers to configure `paths` in their `tsconfig.json`. Set
24
+ * `internalImports: 'subpath'` to emit package-private `#types/...` references and a
25
+ * `dts-imports.json` manifest for the published package's `imports` field.
24
26
  *
25
27
  * ## Pre-Rolled vs Bundled Dependencies
26
28
  *
@@ -75,7 +77,10 @@ import { Plugin } from 'vite';
75
77
  * preRolledDependencies: ['@nhtio/encoder'],
76
78
  * // Custom paths
77
79
  * tsConfigJsonPath: './tsconfig.build.json',
78
- * packageJsonPath: './package.json'
80
+ * packageJsonPath: './package.json',
81
+ * // Emits #types/... references plus dts-imports.json for package.json imports.
82
+ * internalImports: 'subpath',
83
+ * subpathPrefix: '#types'
79
84
  * })
80
85
  * ]
81
86
  * })
@@ -125,6 +130,16 @@ export declare interface Options {
125
130
  * If the dependency is not already included in `bundledDependencies`, it will be treated as if it were.
126
131
  */
127
132
  preRolledDependencies?: Array<string | RegExp>;
133
+ /**
134
+ * Controls how references to declarations emitted by this package are written. `relative` preserves the legacy extensionless relative paths; `subpath` uses package-private imports.
135
+ * @default 'relative'
136
+ */
137
+ internalImports?: 'relative' | 'subpath';
138
+ /**
139
+ * Package-private import prefix used when `internalImports` is `subpath`. It must start with `#`, not end in `/`, and not contain `*`.
140
+ * @default '#types'
141
+ */
142
+ subpathPrefix?: string;
128
143
  /**
129
144
  * Activate additional debug output information
130
145
  */
@@ -136,3 +151,10 @@ export declare interface Options {
136
151
  }
137
152
 
138
153
  export { }
154
+
155
+
156
+ declare module 'fixture-external' {
157
+ interface External {
158
+ augmented: string;
159
+ }
160
+ }
package/dts_complex.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { d } from "./index-Cbnpkv0N.mjs";
1
+ import { d } from "./index-Crhrknhq.mjs";
2
2
  export {
3
3
  d as dtsComplex
4
4
  };
@@ -10,7 +10,7 @@ import { fileURLToPath } from "node:url";
10
10
  import require$$0$1 from "path";
11
11
  import require$$0 from "constants";
12
12
  import { ExtractorConfig, Extractor } from "@microsoft/api-extractor";
13
- import { readFile, writeFile, readdir, mkdtemp, symlink, unlink, rm } from "node:fs/promises";
13
+ import { readFile, readdir, mkdtemp, symlink, unlink, rm, mkdir, writeFile as writeFile$1 } from "node:fs/promises";
14
14
  const ANSI_BACKGROUND_OFFSET = 10;
15
15
  const wrapAnsi16 = (offset3 = 0) => (code2) => `\x1B[${code2 + offset3}m`;
16
16
  const wrapAnsi256 = (offset3 = 0) => (code2) => `\x1B[${38 + offset3};5;${code2}m`;
@@ -335474,12 +335474,18 @@ init_esm$1();
335474
335474
  __toESM$1(require_lib$8());
335475
335475
  var import_lib$1 = __toESM$1(require_lib$7());
335476
335476
  import_lib$1.location;
335477
+ const writeFile = async (filePath, data2, encoding) => {
335478
+ await mkdir(dirname(filePath), { recursive: true });
335479
+ await writeFile$1(filePath, data2, encoding);
335480
+ };
335477
335481
  const defaultOptions = {
335478
335482
  packageJsonPath: "./package.json",
335479
335483
  tsConfigJsonPath: "./tsconfig.json",
335480
335484
  nodeModulesPath: "./node_modules",
335481
335485
  bundledDependencies: [],
335482
335486
  preRolledDependencies: [],
335487
+ internalImports: "relative",
335488
+ subpathPrefix: "#types",
335483
335489
  debug: false,
335484
335490
  traceResolution: false
335485
335491
  };
@@ -335539,6 +335545,14 @@ const unpluginFactory = (options2) => {
335539
335545
  defaultOptions,
335540
335546
  options2 || {}
335541
335547
  );
335548
+ const { error: optionsError } = validator.object({
335549
+ internalImports: validator.string().valid("relative", "subpath").required(),
335550
+ subpathPrefix: validator.string().regex(/^#(?!.*\*)(?!.*\/$).*/).required()
335551
+ }).validate({
335552
+ internalImports: mergedOptions.internalImports,
335553
+ subpathPrefix: mergedOptions.subpathPrefix
335554
+ });
335555
+ if (optionsError) throw new Error(optionsError.message);
335542
335556
  const runtimeConfiguration = {
335543
335557
  entries: /* @__PURE__ */ new Map(),
335544
335558
  entryFileNameToEntryName: /* @__PURE__ */ new Map(),
@@ -335880,7 +335894,7 @@ const unpluginFactory = (options2) => {
335880
335894
  outDir: runtimeConfiguration.tempDirPath
335881
335895
  }
335882
335896
  };
335883
- const tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335897
+ let tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335884
335898
  const seenVendorLibPaths = /* @__PURE__ */ new Map();
335885
335899
  const seenPreBundledVendorLibSourceFiles = /* @__PURE__ */ new Map();
335886
335900
  const seeVendorLibPath = (node, sourceFilePath) => {
@@ -336048,14 +336062,45 @@ const unpluginFactory = (options2) => {
336048
336062
  console.log("[dts_complex] tmpDirRootNames sample (first 5):");
336049
336063
  Array.from(tmpDirRootNames).slice(0, 5).forEach((p) => console.log(" ", p));
336050
336064
  }
336065
+ if (mergedOptions.internalImports === "subpath") {
336066
+ for (const path2 of Object.values(rollupResults)) {
336067
+ if (path2) tmpDirRootNames.add(path2);
336068
+ }
336069
+ tmpDirProgram = ts.createProgram({
336070
+ ...tmpDirProgramConfig,
336071
+ rootNames: Array.from(tmpDirRootNames)
336072
+ });
336073
+ }
336051
336074
  const tmpDirTypeChecker = tmpDirProgram.getTypeChecker();
336052
336075
  const tmpDirTransformer = (context) => (sourceFile) => {
336053
336076
  const computeRelativePath = (targetPath) => {
336077
+ const withoutExtension = targetPath.replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336078
+ if (mergedOptions.internalImports === "subpath") {
336079
+ return `${mergedOptions.subpathPrefix}/${relative(
336080
+ runtimeConfiguration.tempDirPath,
336081
+ withoutExtension
336082
+ ).replace(/\\/g, "/")}`;
336083
+ }
336054
336084
  let relativeSpec = relative(dirname(sourceFile.fileName), targetPath).replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336055
336085
  if (!relativeSpec.startsWith(".")) relativeSpec = `./${relativeSpec}`;
336056
336086
  return relativeSpec;
336057
336087
  };
336088
+ const resolveRelativeSpecifier = (moduleName) => {
336089
+ if (!moduleName.startsWith("./") && !moduleName.startsWith("../")) return void 0;
336090
+ const candidate = resolve(dirname(sourceFile.fileName), moduleName);
336091
+ const targets = [candidate, `${candidate}.d.ts`, join(candidate, "index.d.ts")];
336092
+ const target = targets.find((path2) => tmpDirRootNames.has(path2));
336093
+ return target ? computeRelativePath(target) : void 0;
336094
+ };
336058
336095
  const resolveModuleSpecifier = (moduleName, moduleSpecifierNode) => {
336096
+ if (mergedOptions.internalImports === "subpath") {
336097
+ const packageName = runtimeConfiguration.packageJson.name;
336098
+ if (packageName && (moduleName === packageName || moduleName.startsWith(`${packageName}/`))) {
336099
+ return void 0;
336100
+ }
336101
+ const relativePath = resolveRelativeSpecifier(moduleName);
336102
+ if (relativePath) return relativePath;
336103
+ }
336059
336104
  if (isBundledVendorLib(moduleName)) {
336060
336105
  const defPath = rollupResults[moduleName];
336061
336106
  return defPath ? computeRelativePath(defPath) : void 0;
@@ -336071,7 +336116,7 @@ const unpluginFactory = (options2) => {
336071
336116
  console.log("[dts_complex] From file:", sourceFile.fileName);
336072
336117
  console.log("[dts_complex] Symbol target:", targetFile);
336073
336118
  }
336074
- if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts")) {
336119
+ if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts") && (mergedOptions.internalImports !== "subpath" || tmpDirRootNames.has(targetFile))) {
336075
336120
  const result = computeRelativePath(targetFile);
336076
336121
  if (runtimeConfiguration.debug) {
336077
336122
  console.log("[dts_complex] -> Using temp .d.ts:", result);
@@ -336164,7 +336209,7 @@ const unpluginFactory = (options2) => {
336164
336209
  if (newPath) {
336165
336210
  const newLiteral = ts.factory.createStringLiteral(newPath);
336166
336211
  const newLiteralType = ts.factory.createLiteralTypeNode(newLiteral);
336167
- return ts.factory.updateImportTypeNode(
336212
+ const updated = ts.factory.updateImportTypeNode(
336168
336213
  node,
336169
336214
  newLiteralType,
336170
336215
  node.attributes,
@@ -336172,6 +336217,7 @@ const unpluginFactory = (options2) => {
336172
336217
  node.typeArguments,
336173
336218
  node.isTypeOf
336174
336219
  );
336220
+ return mergedOptions.internalImports === "subpath" ? ts.visitEachChild(updated, visitor, context) : updated;
336175
336221
  }
336176
336222
  }
336177
336223
  }
@@ -336207,6 +336253,33 @@ const unpluginFactory = (options2) => {
336207
336253
  }
336208
336254
  }
336209
336255
  logger.succeed(`Fixed import and export references in generated declaration files`);
336256
+ if (mergedOptions.internalImports === "subpath") {
336257
+ const relativeSpecifiers = [];
336258
+ for (const absolutePath of tmpDirRootNames) {
336259
+ const source = ts.createSourceFile(
336260
+ absolutePath,
336261
+ await readFile(absolutePath, "utf-8"),
336262
+ ts.ScriptTarget.Latest
336263
+ );
336264
+ const visit = (node) => {
336265
+ const specifier = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) ? node.argument.literal : void 0;
336266
+ if (specifier && ts.isStringLiteral(specifier) && /^(\.\/|\.\.\/)/.test(specifier.text)) {
336267
+ relativeSpecifiers.push(
336268
+ `${relative(runtimeConfiguration.tempDirPath, absolutePath)}: ${specifier.text}`
336269
+ );
336270
+ }
336271
+ ts.forEachChild(node, visit);
336272
+ };
336273
+ visit(source);
336274
+ }
336275
+ if (relativeSpecifiers.length) {
336276
+ await cleanup();
336277
+ return this.error(
336278
+ `subpath imports left relative declaration specifiers:
336279
+ ${relativeSpecifiers.join("\n")}`
336280
+ );
336281
+ }
336282
+ }
336210
336283
  logger.info("Adding type definitions to the build output");
336211
336284
  logger.start("Generating Typescript Definition Files");
336212
336285
  const finalDirents = await readdir(runtimeConfiguration.tempDirPath, {
@@ -336242,6 +336315,18 @@ const unpluginFactory = (options2) => {
336242
336315
  return this.error(`Failed to add type definitions to the build output: ${String(e2)}`);
336243
336316
  }
336244
336317
  }
336318
+ if (mergedOptions.internalImports === "subpath") {
336319
+ const manifest = `${JSON.stringify({ [`${mergedOptions.subpathPrefix}/*`]: { types: "./*.d.ts" } }, null, 2)}
336320
+ `;
336321
+ this.emitFile({
336322
+ type: "asset",
336323
+ name: "dts-imports.json",
336324
+ needsCodeReference: false,
336325
+ originalFileName: "dts-imports.json",
336326
+ fileName: "dts-imports.json",
336327
+ source: manifest
336328
+ });
336329
+ }
336245
336330
  await cleanup();
336246
336331
  logger.succeed(`Generated Typescript Definition Files`);
336247
336332
  },
@@ -336255,4 +336340,4 @@ const dtsComplex = /* @__PURE__ */ createVitePlugin(unpluginFactory);
336255
336340
  export {
336256
336341
  dtsComplex as d
336257
336342
  };
336258
- //# sourceMappingURL=index-Cbnpkv0N.mjs.map
336343
+ //# sourceMappingURL=index-Crhrknhq.mjs.map