@reliverse/dler 1.2.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +312 -0
  3. package/bin/cli/args/agg/main.js +0 -0
  4. package/bin/cli/args/conv/README.md +3 -0
  5. package/bin/cli/args/conv/main.js +0 -0
  6. package/bin/cli/args/deps/analyzer.js +42 -0
  7. package/bin/cli/args/deps/filesystem.js +42 -0
  8. package/bin/cli/args/deps/formatter.js +65 -0
  9. package/bin/cli/args/deps/mod.js +48 -0
  10. package/bin/cli/args/deps/parser.js +59 -0
  11. package/bin/cli/args/deps/types.js +0 -0
  12. package/bin/cli/args/init/README.md +121 -0
  13. package/bin/cli/args/init/libs/reinit/reinit-main.js +5 -0
  14. package/bin/cli/args/init/libs/reinit/reint-impl/const.js +26 -0
  15. package/bin/cli/args/init/libs/reinit/reint-impl/mod.txt +395 -0
  16. package/bin/cli/args/init/libs/reinit/reint-impl/templates/t-gitignore.js +9 -0
  17. package/bin/cli/args/init/libs/reinit/reint-impl/templates/t-license.js +22 -0
  18. package/bin/cli/args/init/libs/reinit/reint-impl/templates/t-readme.js +59 -0
  19. package/bin/cli/args/init/libs/reinit/reint-impl/types.js +0 -0
  20. package/bin/cli/args/init/libs/reinit/reint-impl/utils.js +3 -0
  21. package/bin/cli/args/init/main.txt +121 -0
  22. package/bin/cli/args/init/types.js +1 -0
  23. package/bin/cli/args/inject/README.md +148 -0
  24. package/bin/cli/args/inject/arg-ts-expect-error.txt +49 -0
  25. package/bin/cli/args/inject/cli-mod.js +32 -0
  26. package/bin/cli/args/inject/main.txt +28 -0
  27. package/bin/cli/args/inject/reinject.config.js +4 -0
  28. package/bin/cli/args/inject/ts-expect-error.txt +277 -0
  29. package/bin/cli/args/merger/README.md +125 -0
  30. package/bin/cli/args/merger/main.txt +306 -0
  31. package/bin/cli/args/mono/main.js +0 -0
  32. package/bin/cli/args/spells/mod.js +44 -0
  33. package/bin/cli/args/split/README.md +13 -0
  34. package/bin/cli/args/split/split-main.js +26 -0
  35. package/bin/cli/args/split/split-mod.js +117 -0
  36. package/bin/cli/args/tools/index.js +81 -0
  37. package/bin/cli/args/tools/tools-impl.js +296 -0
  38. package/bin/cli.js +111 -0
  39. package/bin/init.js +157 -0
  40. package/bin/libs/cfg/cfg-default.js +50 -0
  41. package/bin/libs/cfg/cfg-main.js +1 -0
  42. package/bin/libs/cfg/cfg-mod.js +4 -0
  43. package/bin/libs/cfg/cfg-types.js +1 -0
  44. package/bin/libs/sdk/sdk-impl/build/build-library.js +865 -0
  45. package/bin/libs/sdk/sdk-impl/build/build-regular.js +373 -0
  46. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/auto.js +110 -0
  47. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/build.js +322 -0
  48. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/copy/copy.js +62 -0
  49. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/copy/types.js +0 -0
  50. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/mkdist/mkdist.js +57 -0
  51. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/mkdist/types.js +0 -0
  52. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/build.js +104 -0
  53. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/config.js +124 -0
  54. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/plugins/cjs.js +48 -0
  55. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/plugins/esbuild.js +91 -0
  56. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/plugins/json.js +17 -0
  57. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/plugins/raw.js +20 -0
  58. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/plugins/shebang.js +42 -0
  59. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/stub.js +137 -0
  60. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/types.js +0 -0
  61. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/utils.js +41 -0
  62. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/rollup/watch.js +33 -0
  63. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/types.js +6 -0
  64. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/untyped/index.js +125 -0
  65. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/untyped/types.js +0 -0
  66. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/utils.js +158 -0
  67. package/bin/libs/sdk/sdk-impl/build/bundlers/unified/validate.js +68 -0
  68. package/bin/libs/sdk/sdk-impl/library-flow.js +169 -0
  69. package/bin/libs/sdk/sdk-impl/pub/pub-library.js +132 -0
  70. package/bin/libs/sdk/sdk-impl/pub/pub-regular.js +69 -0
  71. package/bin/libs/sdk/sdk-impl/regular-flow.js +219 -0
  72. package/bin/libs/sdk/sdk-impl/spells/spells-executors.js +307 -0
  73. package/bin/libs/sdk/sdk-impl/spells/spells-filesystem.js +72 -0
  74. package/bin/libs/sdk/sdk-impl/spells/spells-main.js +87 -0
  75. package/bin/libs/sdk/sdk-impl/spells/spells-parser.js +60 -0
  76. package/bin/libs/sdk/sdk-impl/spells/spells-types.js +0 -0
  77. package/bin/libs/sdk/sdk-impl/utils/tools/tools-agg.js +149 -0
  78. package/bin/libs/sdk/sdk-impl/utils/tools/tools-impl.js +21 -0
  79. package/bin/libs/sdk/sdk-impl/utils/utils-build.js +102 -0
  80. package/bin/libs/sdk/sdk-impl/utils/utils-bump.js +238 -0
  81. package/bin/libs/sdk/sdk-impl/utils/utils-clean.js +35 -0
  82. package/bin/libs/sdk/sdk-impl/utils/utils-consts.js +17 -0
  83. package/bin/libs/sdk/sdk-impl/utils/utils-cwd.js +36 -0
  84. package/bin/libs/sdk/sdk-impl/utils/utils-deps.js +73 -0
  85. package/bin/libs/sdk/sdk-impl/utils/utils-determine.js +25 -0
  86. package/bin/libs/sdk/sdk-impl/utils/utils-error.js +17 -0
  87. package/bin/libs/sdk/sdk-impl/utils/utils-fs.js +202 -0
  88. package/bin/libs/sdk/sdk-impl/utils/utils-info.js +42 -0
  89. package/bin/libs/sdk/sdk-impl/utils/utils-jsr-json.js +51 -0
  90. package/bin/libs/sdk/sdk-impl/utils/utils-paths.js +658 -0
  91. package/bin/libs/sdk/sdk-impl/utils/utils-perf.js +22 -0
  92. package/bin/libs/sdk/sdk-impl/utils/utils-pkg-json-libs.js +259 -0
  93. package/bin/libs/sdk/sdk-impl/utils/utils-pkg-json-reg.js +207 -0
  94. package/bin/libs/sdk/sdk-impl/utils/utils-tsconfig.js +44 -0
  95. package/bin/libs/sdk/sdk-main.js +114 -0
  96. package/bin/libs/sdk/sdk-types.js +1 -0
  97. package/bin/load.js +27 -0
  98. package/bin/main.js +46 -0
  99. package/bin/tools.txt +92 -0
  100. package/bin/types.js +0 -0
  101. package/package.json +93 -0
@@ -0,0 +1,373 @@
1
+ import { relinka } from "@reliverse/relinka";
2
+ import { build as bunBuild } from "bun";
3
+ import fs from "fs-extra";
4
+ import path from "pathe";
5
+ import prettyBytes from "pretty-bytes";
6
+ import prettyMilliseconds from "pretty-ms";
7
+ import { build as unifiedBuild } from "./bundlers/unified/build.js";
8
+ import {
9
+ getBunSourcemapOption,
10
+ getUnifiedSourcemapOption
11
+ } from "../utils/utils-build.js";
12
+ import {
13
+ CONCURRENCY_DEFAULT,
14
+ PROJECT_ROOT,
15
+ validExtensions
16
+ } from "../utils/utils-consts.js";
17
+ import {
18
+ copyRootFile,
19
+ deleteSpecificFiles,
20
+ getDirectorySize,
21
+ outDirBinFilesCount
22
+ } from "../utils/utils-fs.js";
23
+ import {
24
+ createJsrJSON,
25
+ renameTsxFiles
26
+ } from "../utils/utils-jsr-json.js";
27
+ import {
28
+ convertImportExtensionsJsToTs,
29
+ convertImportPaths
30
+ } from "../utils/utils-paths.js";
31
+ import {
32
+ getElapsedPerfTime
33
+ } from "../utils/utils-perf.js";
34
+ import { regular_createPackageJSON } from "../utils/utils-pkg-json-reg.js";
35
+ import { createTSConfig } from "../utils/utils-tsconfig.js";
36
+ import { ensuredir } from "./bundlers/unified/utils.js";
37
+ export async function regular_buildJsrDist(isDev, isJsr, coreIsCLI, coreEntrySrcDir, distJsrDirName, distJsrBuilder, coreEntryFile, transpileTarget, transpileFormat, transpileSplitting, transpileMinify, transpileSourcemap, transpilePublicPath, unifiedBundlerOutExt, rmDepsMode, timer, transpileStub, transpileWatch, distJsrGenTsconfig, coreDeclarations) {
38
+ relinka("info", "Building JSR distribution...");
39
+ const coreEntrySrcDirResolved = path.resolve(PROJECT_ROOT, coreEntrySrcDir);
40
+ const coreEntryFilePath = path.join(coreEntrySrcDirResolved, coreEntryFile);
41
+ const distJsrDirNameResolved = path.resolve(PROJECT_ROOT, distJsrDirName);
42
+ const outDirBin = path.resolve(distJsrDirNameResolved, "bin");
43
+ await ensuredir(distJsrDirNameResolved);
44
+ await ensuredir(outDirBin);
45
+ relinka("info", `Using JSR builder: ${distJsrBuilder}`);
46
+ await regular_bundleWithBuilder(distJsrBuilder, {
47
+ coreDeclarations,
48
+ outDir: outDirBin,
49
+ packageName: "",
50
+ // not strictly needed, keeping it for logs
51
+ singleFile: coreEntryFilePath,
52
+ // single entry (used if "bun"/"unified")
53
+ srcDir: coreEntrySrcDirResolved,
54
+ // entire dir (used if "jsr")
55
+ timer,
56
+ transpileFormat,
57
+ transpileMinify,
58
+ transpilePublicPath,
59
+ transpileSourcemap,
60
+ transpileSplitting,
61
+ transpileStub,
62
+ transpileTarget,
63
+ transpileWatch,
64
+ unifiedBundlerOutExt
65
+ });
66
+ await regular_performCommonBuildSteps({
67
+ coreIsCLI,
68
+ isJsr,
69
+ outDirBin,
70
+ outDirRoot: distJsrDirNameResolved,
71
+ rmDepsMode,
72
+ unifiedBundlerOutExt
73
+ });
74
+ await convertImportExtensionsJsToTs({ dirPath: outDirBin });
75
+ await renameTsxFiles(outDirBin);
76
+ await createJsrJSON(distJsrDirNameResolved, false);
77
+ if (coreIsCLI && isJsr && distJsrGenTsconfig) {
78
+ await createTSConfig(distJsrDirNameResolved, true);
79
+ }
80
+ const dirSize = await getDirectorySize(distJsrDirNameResolved, isDev);
81
+ const filesCount = await outDirBinFilesCount(outDirBin);
82
+ relinka(
83
+ "success",
84
+ `[${distJsrDirNameResolved}] Successfully created regular distribution: "dist-jsr" (${outDirBin}/main.ts) with (${filesCount} files (${prettyBytes(
85
+ dirSize
86
+ )}))`
87
+ );
88
+ }
89
+ export async function regular_buildNpmDist(isDev, coreEntrySrcDir, distNpmDirName, distNpmBuilder, coreEntryFile, unifiedBundlerOutExt, rmDepsMode, coreIsCLI, transpileTarget, transpileFormat, transpileSplitting, transpileMinify, transpileSourcemap, transpilePublicPath, transpileStub, transpileWatch, timer, coreDeclarations) {
90
+ relinka("info", "Building NPM distribution...");
91
+ const coreEntrySrcDirResolved = path.resolve(PROJECT_ROOT, coreEntrySrcDir);
92
+ const coreEntryFilePath = path.join(coreEntrySrcDirResolved, coreEntryFile);
93
+ const distNpmDirNameResolved = path.resolve(PROJECT_ROOT, distNpmDirName);
94
+ const outDirBin = path.resolve(distNpmDirNameResolved, "bin");
95
+ await ensuredir(distNpmDirNameResolved);
96
+ await ensuredir(outDirBin);
97
+ relinka("info", `Using NPM builder: ${distNpmBuilder}`);
98
+ await regular_bundleWithBuilder(distNpmBuilder, {
99
+ coreDeclarations,
100
+ outDir: outDirBin,
101
+ packageName: "",
102
+ // For logging
103
+ singleFile: coreEntryFilePath,
104
+ srcDir: coreEntrySrcDirResolved,
105
+ timer,
106
+ transpileFormat,
107
+ transpileMinify,
108
+ transpilePublicPath,
109
+ transpileSourcemap,
110
+ transpileSplitting,
111
+ transpileStub,
112
+ transpileTarget,
113
+ transpileWatch,
114
+ unifiedBundlerOutExt
115
+ });
116
+ await regular_performCommonBuildSteps({
117
+ coreIsCLI,
118
+ isJsr: false,
119
+ outDirBin,
120
+ outDirRoot: distNpmDirNameResolved,
121
+ rmDepsMode,
122
+ unifiedBundlerOutExt
123
+ });
124
+ const dirSize = await getDirectorySize(distNpmDirNameResolved, isDev);
125
+ const filesCount = await outDirBinFilesCount(outDirBin);
126
+ relinka(
127
+ "success",
128
+ `NPM distribution built successfully (${filesCount} files, ${prettyBytes(dirSize)})`
129
+ );
130
+ relinka(
131
+ "success",
132
+ `[${distNpmDirNameResolved}] Successfully created regular distribution: "dist-npm" (${outDirBin}/main.js) with (${filesCount} files (${prettyBytes(
133
+ dirSize
134
+ )}))`
135
+ );
136
+ }
137
+ async function regular_bundleUsingBun(coreEntryFile, outDirBin, transpileTarget, transpileFormat, transpileSplitting, transpileMinify, transpileSourcemap, transpilePublicPath, timer) {
138
+ relinka(
139
+ "verbose",
140
+ `Bundling regular project using Bun (entry: ${coreEntryFile}, outDir: ${outDirBin})`
141
+ );
142
+ if (!await fs.pathExists(coreEntryFile)) {
143
+ relinka("error", `Could not find entry file at: ${coreEntryFile}`);
144
+ throw new Error(`Entry file not found: ${coreEntryFile}`);
145
+ }
146
+ try {
147
+ const buildResult = await bunBuild({
148
+ banner: "/* Bundled by @reliverse/dler */",
149
+ define: {
150
+ "process.env.NODE_ENV": JSON.stringify(
151
+ process.env.NODE_ENV || "production"
152
+ )
153
+ },
154
+ drop: ["debugger"],
155
+ entrypoints: [coreEntryFile],
156
+ footer: "/* End of bundle */",
157
+ format: transpileFormat,
158
+ minify: transpileMinify,
159
+ naming: {
160
+ asset: "[name]-[hash].[ext]",
161
+ chunk: "[name]-[hash].[ext]",
162
+ entry: "[dir]/[name]-[hash].[ext]"
163
+ },
164
+ outdir: outDirBin,
165
+ publicPath: transpilePublicPath || "/",
166
+ sourcemap: getBunSourcemapOption(transpileSourcemap),
167
+ splitting: transpileSplitting,
168
+ target: transpileTarget,
169
+ throw: true
170
+ });
171
+ const duration = getElapsedPerfTime(timer);
172
+ const transpileFormattedDuration = prettyMilliseconds(duration, {
173
+ verbose: true
174
+ });
175
+ relinka(
176
+ "success",
177
+ `Regular bun build completed in ${transpileFormattedDuration} with ${buildResult.outputs.length} output file(s).`
178
+ );
179
+ if (buildResult.logs && buildResult.logs.length > 0) {
180
+ buildResult.logs.forEach((log, index) => {
181
+ relinka("verbose", `Log ${index + 1}: ${JSON.stringify(log)}`);
182
+ });
183
+ }
184
+ } catch (error) {
185
+ const errorMessage = error instanceof Error ? error.message : String(error);
186
+ relinka(
187
+ "error",
188
+ `Regular build failed while using bun bundler: ${errorMessage}`
189
+ );
190
+ const enhancedError = new Error(
191
+ `Regular bundle failed for ${outDirBin}: ${errorMessage}`
192
+ );
193
+ if (error instanceof Error && error.stack) {
194
+ enhancedError.stack = error.stack;
195
+ }
196
+ throw enhancedError;
197
+ }
198
+ }
199
+ async function regular_bundleUsingJsr(src, dest) {
200
+ relinka("info", `Starting regular_bundleUsingJsr: ${src} -> ${dest}`);
201
+ await ensuredir(path.dirname(dest));
202
+ const stats = await fs.stat(src);
203
+ if (!stats.isDirectory()) {
204
+ throw new Error(
205
+ "You are using the 'jsr' builder, but path to file was provided. Please provide path to directory instead."
206
+ );
207
+ }
208
+ try {
209
+ await fs.copy(src, dest);
210
+ relinka("verbose", `Copied directory from ${src} to ${dest}`);
211
+ relinka("success", "Completed regular JSR bundling");
212
+ } catch (error) {
213
+ const errorMessage = error instanceof Error ? error.message : String(error);
214
+ relinka("warn", `${errorMessage}, falling back to copying ${src}`);
215
+ await fs.copy(src, dest);
216
+ }
217
+ }
218
+ async function regular_bundleUsingUnified(coreEntryFile, outDirBin, builder, unifiedBundlerOutExt, coreEntrySrcDir, transpileStub, transpileWatch, transpileTarget, transpileMinify, transpileSourcemap, timer, coreDeclarations) {
219
+ if (builder === "jsr" || builder === "bun") {
220
+ throw new Error(
221
+ "'jsr'/'bun' builder not supported for regular_bundleUsingUnified"
222
+ );
223
+ }
224
+ try {
225
+ relinka(
226
+ "verbose",
227
+ `Starting regular_bundleUsingUnified (builder: ${builder}): ${coreEntryFile} -> ${outDirBin}`
228
+ );
229
+ const rootDir = path.resolve(PROJECT_ROOT, coreEntrySrcDir || ".");
230
+ if (!validExtensions.includes(unifiedBundlerOutExt)) {
231
+ throw new Error(`Invalid output extension: ${unifiedBundlerOutExt}`);
232
+ }
233
+ const input = builder === "mkdist" ? path.dirname(coreEntryFile) : coreEntryFile;
234
+ const unifiedBuildConfig = {
235
+ clean: false,
236
+ concurrency: CONCURRENCY_DEFAULT,
237
+ declaration: coreDeclarations,
238
+ entries: [
239
+ {
240
+ builder,
241
+ ext: unifiedBundlerOutExt,
242
+ input: builder === "mkdist" ? rootDir : input,
243
+ outDir: outDirBin
244
+ }
245
+ ],
246
+ rollup: {
247
+ emitCJS: false,
248
+ esbuild: {
249
+ minify: transpileMinify,
250
+ target: transpileTarget
251
+ },
252
+ inlineDependencies: true,
253
+ output: {
254
+ sourcemap: getUnifiedSourcemapOption(transpileSourcemap)
255
+ }
256
+ },
257
+ showOutLog: true,
258
+ transpileStub,
259
+ transpileWatch: transpileWatch ?? false
260
+ };
261
+ await unifiedBuild(rootDir, unifiedBuildConfig, outDirBin);
262
+ const duration = getElapsedPerfTime(timer);
263
+ const transpileFormattedDuration = prettyMilliseconds(duration, {
264
+ verbose: true
265
+ });
266
+ relinka(
267
+ "success",
268
+ `Regular bundle completed in ${transpileFormattedDuration} using ${builder} builder`
269
+ );
270
+ } catch (error) {
271
+ const errorMessage = error instanceof Error ? error.message : String(error);
272
+ relinka(
273
+ "error",
274
+ `Failed to bundle regular project using ${builder}: ${errorMessage}`
275
+ );
276
+ const enhancedError = new Error(
277
+ `Regular bundle failed for ${outDirBin}: ${errorMessage}`
278
+ );
279
+ if (error instanceof Error && error.stack) {
280
+ enhancedError.stack = error.stack;
281
+ }
282
+ throw enhancedError;
283
+ }
284
+ }
285
+ async function regular_bundleWithBuilder(builder, params) {
286
+ const {
287
+ coreDeclarations,
288
+ outDir,
289
+ singleFile,
290
+ srcDir,
291
+ timer,
292
+ transpileFormat,
293
+ transpileMinify,
294
+ transpilePublicPath,
295
+ transpileSourcemap,
296
+ transpileSplitting,
297
+ transpileStub,
298
+ transpileTarget,
299
+ transpileWatch,
300
+ unifiedBundlerOutExt
301
+ } = params;
302
+ if (builder === "jsr") {
303
+ await regular_bundleUsingJsr(srcDir, outDir);
304
+ return;
305
+ }
306
+ if (builder === "bun") {
307
+ await regular_bundleUsingBun(
308
+ singleFile,
309
+ outDir,
310
+ transpileTarget,
311
+ transpileFormat,
312
+ transpileSplitting,
313
+ transpileMinify,
314
+ transpileSourcemap,
315
+ transpilePublicPath,
316
+ timer
317
+ );
318
+ return;
319
+ }
320
+ await regular_bundleUsingUnified(
321
+ singleFile,
322
+ outDir,
323
+ builder,
324
+ unifiedBundlerOutExt,
325
+ // For mkdist, we pass the directory. For others, we pass the single file
326
+ path.dirname(singleFile),
327
+ transpileStub,
328
+ transpileWatch,
329
+ transpileTarget,
330
+ transpileMinify,
331
+ transpileSourcemap,
332
+ timer,
333
+ coreDeclarations
334
+ );
335
+ }
336
+ async function regular_performCommonBuildSteps({
337
+ coreIsCLI,
338
+ deleteFiles = true,
339
+ isJsr,
340
+ outDirBin,
341
+ outDirRoot,
342
+ rmDepsMode,
343
+ unifiedBundlerOutExt
344
+ }) {
345
+ await convertImportPaths({
346
+ aliasPrefix: "~/",
347
+ baseDir: outDirBin,
348
+ fromType: "alias",
349
+ libsList: {},
350
+ toType: "relative"
351
+ });
352
+ if (deleteFiles) {
353
+ await deleteSpecificFiles(outDirBin);
354
+ }
355
+ await regular_createPackageJSON(
356
+ outDirRoot,
357
+ isJsr,
358
+ coreIsCLI,
359
+ unifiedBundlerOutExt,
360
+ rmDepsMode,
361
+ []
362
+ );
363
+ await copyRootFile(outDirRoot, ["README.md", "LICENSE"]);
364
+ if (isJsr) {
365
+ await copyRootFile(outDirRoot, [
366
+ ".gitignore",
367
+ ".config/rse.ts",
368
+ ".config/rse.jsonc",
369
+ "drizzle.config.ts",
370
+ "schema.json"
371
+ ]);
372
+ }
373
+ }
@@ -0,0 +1,110 @@
1
+ import { relinka } from "@reliverse/relinka";
2
+ import { existsSync } from "node:fs";
3
+ import { join, normalize, resolve } from "pathe";
4
+ import { definePreset } from "./types.js";
5
+ import { extractExportFilenames, listRecursively, warn } from "./utils.js";
6
+ export const autoPreset = definePreset(() => {
7
+ return {
8
+ hooks: {
9
+ "build:prepare"(ctx) {
10
+ if (!ctx.pkg || ctx.options.entries.length > 0) {
11
+ return;
12
+ }
13
+ const sourceFiles = listRecursively(join(ctx.options.rootDir, "src"));
14
+ const res = inferEntries(ctx.pkg, sourceFiles, ctx.options.rootDir);
15
+ for (const message of res.warnings) {
16
+ warn(ctx, message);
17
+ }
18
+ ctx.options.entries.push(...res.entries);
19
+ if (res.cjs) {
20
+ ctx.options.rollup.emitCJS = true;
21
+ }
22
+ if (ctx.options.declaration === void 0) {
23
+ ctx.options.declaration = res.dts ? "compatible" : false;
24
+ }
25
+ relinka(
26
+ "info",
27
+ "Automatically detected entries:",
28
+ ctx.options.entries.map(
29
+ (e) => e.input.replace(`${ctx.options.rootDir}/`, "").replace(/\/$/, "/*")
30
+ ).join(", "),
31
+ ["esm", res.cjs && "cjs", res.dts && "dts"].filter(Boolean).map((tag) => `[${tag}]`).join(" ")
32
+ );
33
+ }
34
+ }
35
+ };
36
+ });
37
+ const getEntrypointPaths = (path) => {
38
+ const segments = normalize(path).split("/");
39
+ return segments.map((_, index) => segments.slice(index).join("/")).filter(Boolean);
40
+ };
41
+ function inferEntries(pkg, sourceFiles, rootDir) {
42
+ const warnings = [];
43
+ sourceFiles.sort((a, b) => a.split("/").length - b.split("/").length);
44
+ const outputs = extractExportFilenames(pkg.exports);
45
+ if (pkg.bin) {
46
+ const binaries = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin);
47
+ for (const file of binaries) {
48
+ outputs.push({ file });
49
+ }
50
+ }
51
+ if (pkg.main) {
52
+ outputs.push({ file: pkg.main });
53
+ }
54
+ if (pkg.module) {
55
+ outputs.push({ file: pkg.module, type: "esm" });
56
+ }
57
+ if (pkg.types || pkg.typings) {
58
+ outputs.push({ file: pkg.types || pkg.typings });
59
+ }
60
+ const isESMPkg = pkg.type === "module";
61
+ for (const output of outputs.filter((o) => !o.type)) {
62
+ const isJS = output.file.endsWith(".js");
63
+ if (isESMPkg && isJS || output.file.endsWith(".mjs")) {
64
+ output.type = "esm";
65
+ } else if (!isESMPkg && isJS || output.file.endsWith(".cjs")) {
66
+ output.type = "cjs";
67
+ }
68
+ }
69
+ let cjs = false;
70
+ let dts = false;
71
+ const entries = [];
72
+ for (const output of outputs) {
73
+ const outputSlug = output.file.replace(
74
+ /(\*[^/\\]*|\.d\.(m|c)?ts|\.\w+)$/,
75
+ ""
76
+ );
77
+ const isDir = outputSlug.endsWith("/");
78
+ if (isDir && ["./", "/"].includes(outputSlug)) {
79
+ continue;
80
+ }
81
+ const possiblePaths = getEntrypointPaths(outputSlug);
82
+ const input = possiblePaths.reduce((source, d) => {
83
+ if (source) {
84
+ return source;
85
+ }
86
+ const SOURCE_RE = new RegExp(
87
+ `(?<=/|$)${d}${isDir ? "" : String.raw`\.\w+`}$`
88
+ );
89
+ return sourceFiles.find((i) => SOURCE_RE.test(i))?.replace(/(\.d\.(m|c)?ts|\.\w+)$/, "");
90
+ }, void 0);
91
+ if (!input) {
92
+ if (!existsSync(resolve(rootDir || ".", output.file))) {
93
+ warnings.push(`Could not find entrypoint for \`${output.file}\``);
94
+ }
95
+ continue;
96
+ }
97
+ if (output.type === "cjs") {
98
+ cjs = true;
99
+ }
100
+ const entry = entries.find((i) => i.input === input) || entries[entries.push({ input }) - 1];
101
+ if (/\.d\.(m|c)?ts$/.test(output.file)) {
102
+ dts = true;
103
+ }
104
+ if (isDir && entry) {
105
+ entry.outDir = outputSlug;
106
+ entry.format = output.type;
107
+ }
108
+ }
109
+ return { cjs, dts, entries, warnings };
110
+ }