@nhtio/vite-plugins 0.1.0-master-830ce62d → 0.1.0-master-58153a44

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,51 @@
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, or a subpath specifier
27
+ resolves to its own declaration file.
28
+
29
+ A bundled dependency whose types API Extractor cannot inline keeps a bare import
30
+ or re-export of that package. As in relative mode, consumers must have its types
31
+ available (for example, by installing the corresponding `@types` package).
32
+
33
+ Subpath mode also emits `dts-imports.json` at the output root:
34
+
35
+ ```json
36
+ { "#types/*": { "types": "./*.d.ts" } }
37
+ ```
38
+
39
+ Merge this manifest into the `imports` field of the **published** package.json,
40
+ next to the output declarations (the plugin does not write package.json):
41
+
42
+ ```typescript
43
+ const imports = JSON.parse(await readFile("dist/dts-imports.json", "utf8"));
44
+ const publishedPackage = {
45
+ ...packageJson,
46
+ imports: { ...packageJson.imports, ...imports },
47
+ };
48
+ await writeFile("dist/package.json", JSON.stringify(publishedPackage, null, 2));
49
+ ```
50
+
51
+ Publish the declaration tree unchanged alongside that package.json. A custom
52
+ `subpathPrefix`, for example `#internal`, changes both the references and manifest
53
+ 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-C3j0_U_i.mjs";
1
+ import { d } from "./index-D70JB0pM.mjs";
2
2
  export {
3
3
  d as dtsComplex
4
4
  };
@@ -335484,6 +335484,8 @@ const defaultOptions = {
335484
335484
  nodeModulesPath: "./node_modules",
335485
335485
  bundledDependencies: [],
335486
335486
  preRolledDependencies: [],
335487
+ internalImports: "relative",
335488
+ subpathPrefix: "#types",
335487
335489
  debug: false,
335488
335490
  traceResolution: false
335489
335491
  };
@@ -335543,6 +335545,14 @@ const unpluginFactory = (options2) => {
335543
335545
  defaultOptions,
335544
335546
  options2 || {}
335545
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);
335546
335556
  const runtimeConfiguration = {
335547
335557
  entries: /* @__PURE__ */ new Map(),
335548
335558
  entryFileNameToEntryName: /* @__PURE__ */ new Map(),
@@ -335884,7 +335894,7 @@ const unpluginFactory = (options2) => {
335884
335894
  outDir: runtimeConfiguration.tempDirPath
335885
335895
  }
335886
335896
  };
335887
- const tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335897
+ let tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335888
335898
  const seenVendorLibPaths = /* @__PURE__ */ new Map();
335889
335899
  const seenPreBundledVendorLibSourceFiles = /* @__PURE__ */ new Map();
335890
335900
  const seeVendorLibPath = (node, sourceFilePath) => {
@@ -336052,14 +336062,46 @@ const unpluginFactory = (options2) => {
336052
336062
  console.log("[dts_complex] tmpDirRootNames sample (first 5):");
336053
336063
  Array.from(tmpDirRootNames).slice(0, 5).forEach((p) => console.log(" ", p));
336054
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
+ }
336055
336074
  const tmpDirTypeChecker = tmpDirProgram.getTypeChecker();
336056
336075
  const tmpDirTransformer = (context) => (sourceFile) => {
336057
336076
  const computeRelativePath = (targetPath) => {
336077
+ if (resolve(targetPath) === resolve(sourceFile.fileName)) return void 0;
336078
+ const withoutExtension = targetPath.replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336079
+ if (mergedOptions.internalImports === "subpath") {
336080
+ return `${mergedOptions.subpathPrefix}/${relative(
336081
+ runtimeConfiguration.tempDirPath,
336082
+ withoutExtension
336083
+ ).replace(/\\/g, "/")}`;
336084
+ }
336058
336085
  let relativeSpec = relative(dirname(sourceFile.fileName), targetPath).replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336059
336086
  if (!relativeSpec.startsWith(".")) relativeSpec = `./${relativeSpec}`;
336060
336087
  return relativeSpec;
336061
336088
  };
336089
+ const resolveRelativeSpecifier = (moduleName) => {
336090
+ if (!moduleName.startsWith("./") && !moduleName.startsWith("../")) return void 0;
336091
+ const candidate = resolve(dirname(sourceFile.fileName), moduleName);
336092
+ const targets = [candidate, `${candidate}.d.ts`, join(candidate, "index.d.ts")];
336093
+ const target = targets.find((path2) => tmpDirRootNames.has(path2));
336094
+ return target ? computeRelativePath(target) : void 0;
336095
+ };
336062
336096
  const resolveModuleSpecifier = (moduleName, moduleSpecifierNode) => {
336097
+ if (mergedOptions.internalImports === "subpath") {
336098
+ const packageName = runtimeConfiguration.packageJson.name;
336099
+ if (packageName && (moduleName === packageName || moduleName.startsWith(`${packageName}/`))) {
336100
+ return void 0;
336101
+ }
336102
+ const relativePath = resolveRelativeSpecifier(moduleName);
336103
+ if (relativePath) return relativePath;
336104
+ }
336063
336105
  if (isBundledVendorLib(moduleName)) {
336064
336106
  const defPath = rollupResults[moduleName];
336065
336107
  return defPath ? computeRelativePath(defPath) : void 0;
@@ -336075,7 +336117,7 @@ const unpluginFactory = (options2) => {
336075
336117
  console.log("[dts_complex] From file:", sourceFile.fileName);
336076
336118
  console.log("[dts_complex] Symbol target:", targetFile);
336077
336119
  }
336078
- if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts")) {
336120
+ if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts") && (mergedOptions.internalImports !== "subpath" || tmpDirRootNames.has(targetFile))) {
336079
336121
  const result = computeRelativePath(targetFile);
336080
336122
  if (runtimeConfiguration.debug) {
336081
336123
  console.log("[dts_complex] -> Using temp .d.ts:", result);
@@ -336168,7 +336210,7 @@ const unpluginFactory = (options2) => {
336168
336210
  if (newPath) {
336169
336211
  const newLiteral = ts.factory.createStringLiteral(newPath);
336170
336212
  const newLiteralType = ts.factory.createLiteralTypeNode(newLiteral);
336171
- return ts.factory.updateImportTypeNode(
336213
+ const updated = ts.factory.updateImportTypeNode(
336172
336214
  node,
336173
336215
  newLiteralType,
336174
336216
  node.attributes,
@@ -336176,6 +336218,7 @@ const unpluginFactory = (options2) => {
336176
336218
  node.typeArguments,
336177
336219
  node.isTypeOf
336178
336220
  );
336221
+ return mergedOptions.internalImports === "subpath" ? ts.visitEachChild(updated, visitor, context) : updated;
336179
336222
  }
336180
336223
  }
336181
336224
  }
@@ -336211,6 +336254,49 @@ const unpluginFactory = (options2) => {
336211
336254
  }
336212
336255
  }
336213
336256
  logger.succeed(`Fixed import and export references in generated declaration files`);
336257
+ if (mergedOptions.internalImports === "subpath") {
336258
+ const relativeSpecifiers = [];
336259
+ const selfSpecifiers = [];
336260
+ for (const absolutePath of tmpDirRootNames) {
336261
+ const source = ts.createSourceFile(
336262
+ absolutePath,
336263
+ await readFile(absolutePath, "utf-8"),
336264
+ ts.ScriptTarget.Latest
336265
+ );
336266
+ const visit = (node) => {
336267
+ const specifier = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) ? node.argument.literal : void 0;
336268
+ if (specifier && ts.isStringLiteral(specifier) && /^(\.\/|\.\.\/)/.test(specifier.text)) {
336269
+ relativeSpecifiers.push(
336270
+ `${relative(runtimeConfiguration.tempDirPath, absolutePath)}: ${specifier.text}`
336271
+ );
336272
+ }
336273
+ if (specifier && ts.isStringLiteral(specifier) && specifier.text.startsWith(`${mergedOptions.subpathPrefix}/`) && resolve(
336274
+ runtimeConfiguration.tempDirPath,
336275
+ `${specifier.text.slice(mergedOptions.subpathPrefix.length + 1)}.d.ts`
336276
+ ) === resolve(absolutePath)) {
336277
+ selfSpecifiers.push(
336278
+ `${relative(runtimeConfiguration.tempDirPath, absolutePath)}: ${specifier.text}`
336279
+ );
336280
+ }
336281
+ ts.forEachChild(node, visit);
336282
+ };
336283
+ visit(source);
336284
+ }
336285
+ if (selfSpecifiers.length) {
336286
+ await cleanup();
336287
+ return this.error(
336288
+ `subpath imports contain self-referencing declaration specifiers:
336289
+ ${selfSpecifiers.join("\n")}`
336290
+ );
336291
+ }
336292
+ if (relativeSpecifiers.length) {
336293
+ await cleanup();
336294
+ return this.error(
336295
+ `subpath imports left relative declaration specifiers:
336296
+ ${relativeSpecifiers.join("\n")}`
336297
+ );
336298
+ }
336299
+ }
336214
336300
  logger.info("Adding type definitions to the build output");
336215
336301
  logger.start("Generating Typescript Definition Files");
336216
336302
  const finalDirents = await readdir(runtimeConfiguration.tempDirPath, {
@@ -336246,6 +336332,18 @@ const unpluginFactory = (options2) => {
336246
336332
  return this.error(`Failed to add type definitions to the build output: ${String(e2)}`);
336247
336333
  }
336248
336334
  }
336335
+ if (mergedOptions.internalImports === "subpath") {
336336
+ const manifest = `${JSON.stringify({ [`${mergedOptions.subpathPrefix}/*`]: { types: "./*.d.ts" } }, null, 2)}
336337
+ `;
336338
+ this.emitFile({
336339
+ type: "asset",
336340
+ name: "dts-imports.json",
336341
+ needsCodeReference: false,
336342
+ originalFileName: "dts-imports.json",
336343
+ fileName: "dts-imports.json",
336344
+ source: manifest
336345
+ });
336346
+ }
336249
336347
  await cleanup();
336250
336348
  logger.succeed(`Generated Typescript Definition Files`);
336251
336349
  },
@@ -336259,4 +336357,4 @@ const dtsComplex = /* @__PURE__ */ createVitePlugin(unpluginFactory);
336259
336357
  export {
336260
336358
  dtsComplex as d
336261
336359
  };
336262
- //# sourceMappingURL=index-C3j0_U_i.mjs.map
336360
+ //# sourceMappingURL=index-D70JB0pM.mjs.map