@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,865 @@
1
+ import { relinka } from "@reliverse/relinka";
2
+ import { build as bunBuild } from "bun";
3
+ import fs from "fs-extra";
4
+ import MagicString from "magic-string";
5
+ import pAll from "p-all";
6
+ import path from "pathe";
7
+ import prettyBytes from "pretty-bytes";
8
+ import prettyMilliseconds from "pretty-ms";
9
+ import { build as unifiedBuild } from "./bundlers/unified/build.js";
10
+ import { ensuredir } from "./bundlers/unified/utils.js";
11
+ import {
12
+ getBunSourcemapOption,
13
+ getUnifiedSourcemapOption,
14
+ renameEntryFile
15
+ } from "../utils/utils-build.js";
16
+ import {
17
+ CONCURRENCY_DEFAULT,
18
+ PROJECT_ROOT,
19
+ validExtensions
20
+ } from "../utils/utils-consts.js";
21
+ import { determineDistName } from "../utils/utils-determine.js";
22
+ import {
23
+ copyRootFile,
24
+ deleteSpecificFiles,
25
+ getDirectorySize,
26
+ outDirBinFilesCount
27
+ } from "../utils/utils-fs.js";
28
+ import {
29
+ createJsrJSON,
30
+ renameTsxFiles
31
+ } from "../utils/utils-jsr-json.js";
32
+ import {
33
+ convertImportExtensionsJsToTs,
34
+ convertImportPaths
35
+ } from "../utils/utils-paths.js";
36
+ import {
37
+ getElapsedPerfTime
38
+ } from "../utils/utils-perf.js";
39
+ import { library_createPackageJSON } from "../utils/utils-pkg-json-libs.js";
40
+ const BIN_DIR_NAME = "bin";
41
+ const REPLACEMENT_MARKER = "// dler-replace-me";
42
+ const FILES_TO_COPY_ROOT = ["README.md", "LICENSE"];
43
+ const TYPES_REPLACEMENT_PATH = "src/types.ts";
44
+ const ALIAS_PREFIX_TO_CONVERT = "~/";
45
+ export async function library_buildLibrary(options) {
46
+ const { libName, mainDir } = options;
47
+ let replacedFiles = [];
48
+ const replacementConfig = {
49
+ librarySrcDir: path.resolve(PROJECT_ROOT, mainDir),
50
+ replacementFilePath: path.resolve(PROJECT_ROOT, TYPES_REPLACEMENT_PATH),
51
+ replacementMarker: REPLACEMENT_MARKER
52
+ };
53
+ try {
54
+ relinka("info", `Running pre-build replacements for ${libName}...`);
55
+ replacedFiles = await preBuildReplacements(replacementConfig);
56
+ relinka("verbose", `Pre-build: ${replacedFiles.length} files modified.`);
57
+ await executeBuildTasks(options);
58
+ } catch (err) {
59
+ const error = err instanceof Error ? err : new Error(String(err));
60
+ relinka(
61
+ "error",
62
+ `Build process for ${libName} failed: ${error.message}`,
63
+ error.stack
64
+ );
65
+ throw error;
66
+ } finally {
67
+ if (replacedFiles.length > 0) {
68
+ relinka(
69
+ "verbose",
70
+ `Reverting ${replacedFiles.length} pre-build changes for ${libName}...`
71
+ );
72
+ try {
73
+ await postBuildReplacements(replacedFiles);
74
+ relinka("verbose", `Done reverting changes for ${libName}.`);
75
+ } catch (revertError) {
76
+ const error = revertError instanceof Error ? revertError : new Error(String(revertError));
77
+ relinka(
78
+ "error",
79
+ `CRITICAL: Failed to revert pre-build changes for ${libName}: ${error.message}. Source files may be left modified!`,
80
+ error.stack
81
+ );
82
+ }
83
+ } else {
84
+ relinka("verbose", `No pre-build changes to revert for ${libName}.`);
85
+ }
86
+ }
87
+ }
88
+ async function executeBuildTasks(options) {
89
+ const { commonPubRegistry, libName } = options;
90
+ const buildTasks = [];
91
+ if (commonPubRegistry === "jsr" || commonPubRegistry === "npm-jsr") {
92
+ if (!options.jsr) {
93
+ throw new Error(
94
+ `JSR build requested for ${libName} but 'options.jsr' is missing.`
95
+ );
96
+ }
97
+ relinka("info", `Queueing JSR build for lib ${libName}...`);
98
+ buildTasks.push(() => library_buildJsrDist(options));
99
+ }
100
+ if (commonPubRegistry === "npm" || commonPubRegistry === "npm-jsr") {
101
+ if (!options.npm) {
102
+ throw new Error(
103
+ `NPM build requested for ${libName} but 'options.npm' is missing.`
104
+ );
105
+ }
106
+ relinka("info", `Queueing NPM build for lib ${libName}...`);
107
+ buildTasks.push(() => library_buildNpmDist(options));
108
+ }
109
+ if (buildTasks.length === 0) {
110
+ relinka(
111
+ "warn",
112
+ `No valid build targets specified by 'commonPubRegistry' ("${commonPubRegistry}") for lib ${libName}. Skipping build.`
113
+ );
114
+ return;
115
+ }
116
+ if (buildTasks.length > 1) {
117
+ relinka("info", `Building lib ${libName} for NPM and JSR concurrently...`);
118
+ await pAll(buildTasks, { concurrency: CONCURRENCY_DEFAULT });
119
+ } else {
120
+ relinka(
121
+ "info",
122
+ `Building lib ${libName} for ${options.commonPubRegistry || "single target"}...`
123
+ );
124
+ const task = buildTasks[0];
125
+ if (task) {
126
+ await task();
127
+ }
128
+ }
129
+ }
130
+ async function library_buildJsrDist(options) {
131
+ const { libName, libMainFile, libsList } = options;
132
+ if (!options.jsr) {
133
+ throw new Error(
134
+ `Internal Error: library_buildJsrDist called for ${libName} but options.jsr is missing.`
135
+ );
136
+ }
137
+ const jsrOptions = options.jsr;
138
+ const { jsrOutDir, distJsrBuilder, distJsrOutFilesExt } = jsrOptions;
139
+ const targetType = "jsr";
140
+ relinka("info", `[JSR] Initializing JSR build for ${libName}...`);
141
+ const libSourceDirResolved = path.resolve(PROJECT_ROOT, options.mainDir);
142
+ const entryFilePathResolved = path.resolve(libSourceDirResolved, libMainFile);
143
+ const outputDirRootResolved = path.resolve(PROJECT_ROOT, jsrOutDir);
144
+ const outputDirBinResolved = path.resolve(
145
+ outputDirRootResolved,
146
+ BIN_DIR_NAME
147
+ );
148
+ const bundlerEntryPoint = distJsrBuilder === "jsr" ? libSourceDirResolved : entryFilePathResolved;
149
+ const libConfig = libsList[libName];
150
+ const libDeclarations = libConfig?.libDeclarations ?? false;
151
+ const buildParams = {
152
+ targetType,
153
+ builder: distJsrBuilder,
154
+ libSourceDir: libSourceDirResolved,
155
+ entryFilePath: bundlerEntryPoint,
156
+ outputDirRoot: outputDirRootResolved,
157
+ outputDirBin: outputDirBinResolved,
158
+ libDeclarations,
159
+ distJsrOutFilesExt,
160
+ options
161
+ // libDirName is generally not needed/used for JSR target logic
162
+ };
163
+ await buildDistributionTarget(buildParams);
164
+ relinka(
165
+ "verbose",
166
+ `[JSR] Performing JSR-specific transformations in ${outputDirBinResolved}`
167
+ );
168
+ await convertImportExtensionsJsToTs({ dirPath: outputDirBinResolved });
169
+ await renameTsxFiles(outputDirBinResolved);
170
+ await createJsrJSON(
171
+ outputDirRootResolved,
172
+ true,
173
+ libName,
174
+ libConfig?.libDescription ?? ""
175
+ );
176
+ const dirSize = await getDirectorySize(outputDirRootResolved, options.isDev);
177
+ const filesCount = await outDirBinFilesCount(outputDirBinResolved);
178
+ relinka(
179
+ "success",
180
+ `[JSR] JSR distribution for ${libName} built successfully (${filesCount} files, ${prettyBytes(dirSize)}) -> ${outputDirRootResolved}`
181
+ );
182
+ }
183
+ async function library_buildNpmDist(options) {
184
+ const { libName, libMainFile, libsList } = options;
185
+ if (!options.npm) {
186
+ throw new Error(
187
+ `Internal Error: library_buildNpmDist called for ${libName} but options.npm is missing.`
188
+ );
189
+ }
190
+ const npmOptions = options.npm;
191
+ const { npmOutDir, distNpmBuilder, coreEntrySrcDir } = npmOptions;
192
+ const distJsrOutFilesExt = options.jsr?.distJsrOutFilesExt || "ts";
193
+ const targetType = "npm";
194
+ const distName = determineDistName(npmOutDir, false, libsList);
195
+ relinka("info", `[NPM:${distName}] Initializing NPM build for ${libName}...`);
196
+ const coreEntrySrcDirResolved = path.resolve(PROJECT_ROOT, coreEntrySrcDir);
197
+ const outputDirRootResolved = path.resolve(PROJECT_ROOT, npmOutDir);
198
+ const outputDirBinResolved = path.resolve(
199
+ outputDirRootResolved,
200
+ BIN_DIR_NAME
201
+ );
202
+ const { libSpecificSrcDir, libDirName } = await determineNpmSourceDirectory(
203
+ libName,
204
+ libMainFile,
205
+ coreEntrySrcDirResolved,
206
+ libsList,
207
+ distName
208
+ );
209
+ const entryFilePathResolved = path.resolve(
210
+ libSpecificSrcDir,
211
+ path.basename(libMainFile)
212
+ );
213
+ if (!await fs.pathExists(entryFilePathResolved)) {
214
+ const relativeEntryPath = path.relative(
215
+ PROJECT_ROOT,
216
+ entryFilePathResolved
217
+ );
218
+ const relativeSrcDir = path.relative(PROJECT_ROOT, libSpecificSrcDir);
219
+ throw new Error(
220
+ `[NPM:${distName}] Library entry file not found: ${relativeEntryPath} (expected in: ${relativeSrcDir})`
221
+ );
222
+ }
223
+ relinka(
224
+ "verbose",
225
+ `[NPM:${distName}] Using entry file: ${entryFilePathResolved}`
226
+ );
227
+ const libConfig = libsList[libName];
228
+ const libDeclarations = libConfig?.libDeclarations ?? false;
229
+ const buildParams = {
230
+ targetType,
231
+ builder: distNpmBuilder,
232
+ libSourceDir: libSpecificSrcDir,
233
+ entryFilePath: entryFilePathResolved,
234
+ outputDirRoot: outputDirRootResolved,
235
+ outputDirBin: outputDirBinResolved,
236
+ libDeclarations,
237
+ distJsrOutFilesExt,
238
+ options,
239
+ libDirName
240
+ // Pass determined libDirName
241
+ };
242
+ await buildDistributionTarget(buildParams);
243
+ const dirSize = await getDirectorySize(outputDirRootResolved, options.isDev);
244
+ const filesCount = await outDirBinFilesCount(outputDirBinResolved);
245
+ relinka(
246
+ "success",
247
+ `[NPM:${distName}] NPM distribution for ${libName} built successfully (${filesCount} files, ${prettyBytes(dirSize)}) -> ${outputDirRootResolved}`
248
+ );
249
+ }
250
+ async function buildDistributionTarget(params) {
251
+ const {
252
+ targetType,
253
+ builder,
254
+ entryFilePath,
255
+ // Entry for bundler (file path or dir path for 'jsr' copy)
256
+ outputDirRoot,
257
+ outputDirBin,
258
+ libDeclarations,
259
+ distJsrOutFilesExt,
260
+ options,
261
+ libDirName
262
+ } = params;
263
+ const {
264
+ libName,
265
+ timer,
266
+ libMainFile,
267
+ libsList,
268
+ rmDepsMode,
269
+ rmDepsPatterns,
270
+ // Transpile/Bundle Options from `options`
271
+ libTranspileMinify,
272
+ transpileTarget,
273
+ transpileFormat,
274
+ transpileSplitting,
275
+ transpileSourcemap,
276
+ transpilePublicPath,
277
+ transpileEsbuild,
278
+ transpileStub,
279
+ transpileWatch,
280
+ unifiedBundlerOutExt
281
+ } = options;
282
+ const isJsr = targetType === "jsr";
283
+ const logPrefix = isJsr ? "[JSR]" : `[NPM:${determineDistName(path.relative(PROJECT_ROOT, outputDirRoot), false, libsList)}]`;
284
+ relinka("info", `${logPrefix} Starting build target processing...`);
285
+ await ensuredir(outputDirRoot);
286
+ await ensuredir(outputDirBin);
287
+ relinka("info", `${logPrefix} Using builder: ${builder}`);
288
+ const bundleRequest = {
289
+ builder,
290
+ entryPoint: entryFilePath,
291
+ outDir: outputDirBin,
292
+ libName,
293
+ timer,
294
+ libDeclarations,
295
+ libTranspileMinify,
296
+ transpileTarget,
297
+ transpileFormat,
298
+ transpileSplitting,
299
+ transpileSourcemap,
300
+ transpilePublicPath,
301
+ transpileEsbuild,
302
+ transpileStub,
303
+ transpileWatch,
304
+ unifiedBundlerOutExt
305
+ };
306
+ await library_bundleWithBuilder(bundleRequest);
307
+ const commonStepsParams = {
308
+ coreEntryFileName: path.basename(libMainFile),
309
+ outDirRoot: outputDirRoot,
310
+ outDirBin: outputDirBin,
311
+ isJsr,
312
+ libName,
313
+ libsList,
314
+ rmDepsMode,
315
+ rmDepsPatterns,
316
+ unifiedBundlerOutExt,
317
+ distJsrOutFilesExt,
318
+ deleteFiles: isJsr,
319
+ libDirName
320
+ };
321
+ await library_performCommonBuildSteps(commonStepsParams);
322
+ relinka("info", `${logPrefix} Completed build target processing.`);
323
+ }
324
+ async function library_bundleWithBuilder(params) {
325
+ const { builder, ...executorParams } = params;
326
+ const { entryPoint, outDir, libName } = executorParams;
327
+ relinka(
328
+ "verbose",
329
+ `[${libName}] Bundling using '${builder}' builder... Entry: ${entryPoint}, Out: ${outDir}`
330
+ );
331
+ switch (builder) {
332
+ case "jsr":
333
+ await library_bundleUsingJsrCopy(entryPoint, outDir, libName);
334
+ break;
335
+ case "bun":
336
+ await library_bundleUsingBun(entryPoint, outDir, libName, {
337
+ timer: executorParams.timer,
338
+ libTranspileMinify: executorParams.libTranspileMinify,
339
+ transpileTarget: executorParams.transpileTarget,
340
+ transpileFormat: executorParams.transpileFormat,
341
+ transpileSplitting: executorParams.transpileSplitting,
342
+ transpileSourcemap: executorParams.transpileSourcemap,
343
+ transpilePublicPath: executorParams.transpilePublicPath
344
+ });
345
+ break;
346
+ case "rollup":
347
+ case "mkdist":
348
+ await library_bundleUsingUnified(
349
+ entryPoint,
350
+ outDir,
351
+ builder,
352
+ // Pass the specific unified builder name
353
+ path.dirname(entryPoint),
354
+ // Source directory context
355
+ {
356
+ timer: executorParams.timer,
357
+ libDeclarations: executorParams.libDeclarations,
358
+ libTranspileMinify: executorParams.libTranspileMinify,
359
+ transpileSourcemap: executorParams.transpileSourcemap,
360
+ transpileEsbuild: executorParams.transpileEsbuild,
361
+ transpileStub: executorParams.transpileStub,
362
+ unifiedBundlerOutExt: executorParams.unifiedBundlerOutExt
363
+ }
364
+ );
365
+ break;
366
+ default:
367
+ throw new Error(`Unsupported library builder specified: ${builder}`);
368
+ }
369
+ relinka("verbose", `[${libName}] Bundling finished using '${builder}'.`);
370
+ }
371
+ async function library_bundleUsingJsrCopy(srcDir, destDir, libName) {
372
+ relinka(
373
+ "verbose",
374
+ `[JSR Copy:${libName}] Starting copy: ${srcDir} -> ${destDir}`
375
+ );
376
+ await ensuredir(destDir);
377
+ try {
378
+ const copyOptions = { overwrite: true };
379
+ await fs.copy(srcDir, destDir, copyOptions);
380
+ relinka(
381
+ "success",
382
+ `[JSR Copy:${libName}] Completed copying library source from ${srcDir} to ${destDir}`
383
+ );
384
+ } catch (error) {
385
+ const errorMessage = error instanceof Error ? error.message : String(error);
386
+ relinka(
387
+ "error",
388
+ `[JSR Copy:${libName}] Failed to copy library source from ${srcDir} to ${destDir}: ${errorMessage}`,
389
+ error instanceof Error ? error.stack : void 0
390
+ );
391
+ throw new Error(`[JSR Copy:${libName}] Failed: ${errorMessage}`);
392
+ }
393
+ }
394
+ async function library_bundleUsingBun(entryPoint, outDirBin, libName, options) {
395
+ const {
396
+ timer,
397
+ libTranspileMinify,
398
+ transpileTarget,
399
+ transpileFormat,
400
+ transpileSplitting,
401
+ transpileSourcemap,
402
+ transpilePublicPath
403
+ } = options;
404
+ relinka("verbose", `[Bun:${libName}] Starting Bun build...`);
405
+ if (!await fs.pathExists(entryPoint)) {
406
+ throw new Error(
407
+ `[Bun:${libName}] Library entry file not found: ${entryPoint}`
408
+ );
409
+ }
410
+ if (!(await fs.stat(entryPoint)).isFile()) {
411
+ throw new Error(
412
+ `[Bun:${libName}] Entry point must be a file for Bun bundler: ${entryPoint}`
413
+ );
414
+ }
415
+ try {
416
+ const buildConfig = {
417
+ entrypoints: [entryPoint],
418
+ outdir: outDirBin,
419
+ target: transpileTarget,
420
+ format: transpileFormat,
421
+ splitting: transpileSplitting,
422
+ minify: libTranspileMinify,
423
+ sourcemap: getBunSourcemapOption(transpileSourcemap),
424
+ publicPath: transpilePublicPath,
425
+ naming: {
426
+ entry: "[dir]/[name].[ext]",
427
+ chunk: "[name]-[hash].[ext]",
428
+ asset: "[name]-[hash].[ext]"
429
+ },
430
+ define: {
431
+ "process.env.NODE_ENV": JSON.stringify(
432
+ process.env.NODE_ENV || "production"
433
+ )
434
+ },
435
+ plugins: [],
436
+ loader: {},
437
+ banner: `/* ${libName} - Bundled by @reliverse/dler (Bun) */`,
438
+ throw: true
439
+ // Ensure build errors are thrown
440
+ };
441
+ const buildResult = await bunBuild(buildConfig);
442
+ const duration = getElapsedPerfTime(timer);
443
+ if (buildResult.success) {
444
+ relinka(
445
+ "success",
446
+ `[Bun:${libName}] Library build completed in ${prettyMilliseconds(duration)} (${buildResult.outputs.length} outputs).`
447
+ );
448
+ if (buildResult.logs?.length > 0) {
449
+ for (const log of buildResult.logs) {
450
+ relinka("verbose", `[Bun Log:${log.level}] ${log.message}`);
451
+ }
452
+ }
453
+ } else {
454
+ relinka(
455
+ "error",
456
+ `[Bun:${libName}] Library build failed after ${prettyMilliseconds(duration)}.`
457
+ );
458
+ if (buildResult.logs?.length > 0) {
459
+ for (const log of buildResult.logs) {
460
+ relinka("error", `[Bun Log:${log.level}] ${log.message}`);
461
+ }
462
+ }
463
+ throw new Error(
464
+ `[Bun:${libName}] Build process reported failure. Check logs.`
465
+ );
466
+ }
467
+ } catch (error) {
468
+ const errorMessage = error instanceof Error ? error.message : String(error);
469
+ relinka(
470
+ "error",
471
+ `[Bun:${libName}] Library build threw an error: ${errorMessage}`,
472
+ error instanceof Error ? error.stack : void 0
473
+ );
474
+ throw new Error(`[Bun:${libName}] Bundle failed: ${errorMessage}`);
475
+ }
476
+ }
477
+ async function library_bundleUsingUnified(entryPoint, outDirBin, builder, sourceDirContext, options) {
478
+ const {
479
+ timer,
480
+ libDeclarations,
481
+ libTranspileMinify,
482
+ transpileSourcemap,
483
+ transpileEsbuild,
484
+ transpileStub,
485
+ unifiedBundlerOutExt
486
+ } = options;
487
+ relinka("verbose", `[Unified:${builder}] Starting ${builder} build...`);
488
+ const rootDir = PROJECT_ROOT;
489
+ let validatedExt = unifiedBundlerOutExt;
490
+ if (!validExtensions.includes(validatedExt)) {
491
+ relinka(
492
+ "warn",
493
+ `[Unified:${builder}] Invalid output extension '${validatedExt}', defaulting to 'js'.`
494
+ );
495
+ validatedExt = "js";
496
+ }
497
+ const inputRelative = path.relative(rootDir, entryPoint);
498
+ const outDirRelative = path.relative(rootDir, outDirBin);
499
+ const unifiedBuildConfig = {
500
+ clean: false,
501
+ declaration: libDeclarations ? "compatible" : false,
502
+ entries: [
503
+ {
504
+ builder,
505
+ input: inputRelative,
506
+ outDir: outDirRelative,
507
+ ext: validatedExt
508
+ }
509
+ ],
510
+ rollup: {
511
+ emitCJS: false,
512
+ esbuild: {
513
+ minify: libTranspileMinify,
514
+ target: transpileEsbuild
515
+ },
516
+ inlineDependencies: true,
517
+ output: {
518
+ sourcemap: getUnifiedSourcemapOption(transpileSourcemap)
519
+ }
520
+ },
521
+ hooks: {},
522
+ stub: transpileStub
523
+ };
524
+ try {
525
+ await unifiedBuild(rootDir, unifiedBuildConfig, outDirBin);
526
+ const duration = getElapsedPerfTime(timer);
527
+ relinka(
528
+ "success",
529
+ `[Unified:${builder}] Library build completed in ${prettyMilliseconds(duration)}.`
530
+ );
531
+ } catch (error) {
532
+ const errorMessage = error instanceof Error ? error.message : String(error);
533
+ relinka(
534
+ "error",
535
+ `[Unified:${builder}] Library build failed: ${errorMessage}`,
536
+ error instanceof Error ? error.stack : void 0
537
+ );
538
+ throw new Error(`[Unified:${builder}] Bundle failed: ${errorMessage}`);
539
+ }
540
+ }
541
+ async function library_performCommonBuildSteps(params) {
542
+ const {
543
+ coreEntryFileName,
544
+ outDirRoot,
545
+ outDirBin,
546
+ isJsr,
547
+ libName,
548
+ libsList,
549
+ rmDepsMode,
550
+ rmDepsPatterns,
551
+ unifiedBundlerOutExt,
552
+ distJsrOutFilesExt,
553
+ deleteFiles = false,
554
+ libDirName
555
+ } = params;
556
+ const targetType = isJsr ? "JSR" : "NPM";
557
+ const logPrefix = `[Common:${targetType}:${libName}]`;
558
+ relinka("verbose", `${logPrefix} Performing common steps in ${outDirRoot}`);
559
+ await library_createPackageJSON(
560
+ libName,
561
+ outDirRoot,
562
+ isJsr,
563
+ libsList,
564
+ rmDepsMode,
565
+ rmDepsPatterns,
566
+ unifiedBundlerOutExt
567
+ );
568
+ relinka("verbose", `${logPrefix} Created package.json.`);
569
+ if (deleteFiles) {
570
+ await deleteSpecificFiles(outDirBin);
571
+ relinka(
572
+ "verbose",
573
+ `${logPrefix} Deleted specific files from ${outDirBin}.`
574
+ );
575
+ }
576
+ await copyRootFile(outDirRoot, FILES_TO_COPY_ROOT);
577
+ relinka(
578
+ "verbose",
579
+ `${logPrefix} Copied root files (${FILES_TO_COPY_ROOT.join(", ")}) to ${outDirRoot}`
580
+ );
581
+ const stripSegments = libDirName ? [`libs/${libDirName}`] : [];
582
+ relinka(
583
+ "verbose",
584
+ `${logPrefix} Converting alias paths in ${outDirBin}, stripping: [${stripSegments.join(", ")}]`
585
+ );
586
+ await convertImportPaths({
587
+ baseDir: outDirBin,
588
+ aliasPrefix: ALIAS_PREFIX_TO_CONVERT,
589
+ fromType: "alias",
590
+ toType: "relative",
591
+ libsList,
592
+ strip: stripSegments
593
+ });
594
+ relinka("verbose", `${logPrefix} Renaming entry file in ${outDirBin}.`);
595
+ await renameEntryFile(
596
+ isJsr,
597
+ outDirBin,
598
+ coreEntryFileName,
599
+ unifiedBundlerOutExt,
600
+ distJsrOutFilesExt
601
+ );
602
+ relinka("verbose", `${logPrefix} Completed common build steps.`);
603
+ }
604
+ async function determineNpmSourceDirectory(libName, mainFile, coreEntrySrcDirResolved, libsList, distName) {
605
+ const logPrefix = `[NPM:${distName}:${libName}]`;
606
+ const libConfig = libsList?.[libName];
607
+ let libSpecificSrcDir = coreEntrySrcDirResolved;
608
+ let libDirName;
609
+ if (libConfig?.libMainFile) {
610
+ if (libConfig.libDirName) {
611
+ const potentialLibDirName = libConfig.libDirName;
612
+ const potentialPath = path.join(
613
+ coreEntrySrcDirResolved,
614
+ "libs",
615
+ potentialLibDirName
616
+ );
617
+ if (await fs.pathExists(potentialPath)) {
618
+ libSpecificSrcDir = potentialPath;
619
+ libDirName = potentialLibDirName;
620
+ relinka(
621
+ "verbose",
622
+ `${logPrefix} Using explicit libDirName '${libDirName}' to set source dir: ${libSpecificSrcDir}`
623
+ );
624
+ } else {
625
+ relinka(
626
+ "warn",
627
+ `${logPrefix} Explicit libDirName '${potentialLibDirName}' provided, but path not found: ${potentialPath}. Falling back.`
628
+ );
629
+ libDirName = void 0;
630
+ }
631
+ } else {
632
+ const baseLibsDir = path.join(PROJECT_ROOT, "src", "libs");
633
+ try {
634
+ const absoluteLibMainFile = path.resolve(
635
+ PROJECT_ROOT,
636
+ libConfig.libMainFile
637
+ );
638
+ if (absoluteLibMainFile.startsWith(baseLibsDir + path.sep)) {
639
+ const mainFilePathRelative = path.relative(
640
+ baseLibsDir,
641
+ absoluteLibMainFile
642
+ );
643
+ const pathSegments = mainFilePathRelative.split(path.sep);
644
+ if (pathSegments.length > 1) {
645
+ const inferredDirName = pathSegments[0];
646
+ const potentialPath = inferredDirName ? path.join(baseLibsDir, inferredDirName) : baseLibsDir;
647
+ if (await fs.pathExists(potentialPath)) {
648
+ libDirName = inferredDirName;
649
+ libSpecificSrcDir = potentialPath;
650
+ relinka(
651
+ "verbose",
652
+ `${logPrefix} Inferred libDirName '${libDirName}' from libMainFile. Source dir: ${libSpecificSrcDir}`
653
+ );
654
+ } else {
655
+ relinka(
656
+ "verbose",
657
+ `${logPrefix} Inferred directory '${inferredDirName}' from libMainFile does not exist. Falling back.`
658
+ );
659
+ libDirName = void 0;
660
+ }
661
+ } else {
662
+ relinka(
663
+ "verbose",
664
+ `${logPrefix} libMainFile '${libConfig.libMainFile}' is directly in base libs dir? No specific subdir inferred.`
665
+ );
666
+ }
667
+ } else {
668
+ relinka(
669
+ "verbose",
670
+ `${logPrefix} libMainFile '${libConfig.libMainFile}' is outside the expected '${baseLibsDir}' structure.`
671
+ );
672
+ }
673
+ } catch (pathError) {
674
+ relinka(
675
+ "warn",
676
+ `${logPrefix} Could not reliably determine relative path for ${libConfig.libMainFile}. Falling back. Error: ${pathError instanceof Error ? pathError.message : String(pathError)}`
677
+ );
678
+ }
679
+ }
680
+ } else {
681
+ relinka(
682
+ "verbose",
683
+ `${logPrefix} No libMainFile configured. Using core source directory: ${coreEntrySrcDirResolved}`
684
+ );
685
+ }
686
+ if (!await fs.pathExists(libSpecificSrcDir)) {
687
+ relinka(
688
+ "warn",
689
+ `${logPrefix} Determined source directory does not exist: ${libSpecificSrcDir}. Falling back to core source dir: ${coreEntrySrcDirResolved}`
690
+ );
691
+ libSpecificSrcDir = coreEntrySrcDirResolved;
692
+ libDirName = void 0;
693
+ }
694
+ relinka(
695
+ "verbose",
696
+ `${logPrefix} Final determined library source directory: ${libSpecificSrcDir}`
697
+ );
698
+ return { libSpecificSrcDir, libDirName };
699
+ }
700
+ async function preBuildReplacements(config) {
701
+ const { librarySrcDir, replacementFilePath, replacementMarker } = config;
702
+ const replacedFiles = [];
703
+ if (!await fs.pathExists(replacementFilePath)) {
704
+ relinka(
705
+ "warn",
706
+ `Replacement content file not found: ${replacementFilePath}. Skipping pre-build replacements.`
707
+ );
708
+ return [];
709
+ }
710
+ if (!await fs.pathExists(librarySrcDir)) {
711
+ relinka(
712
+ "warn",
713
+ `Library source directory for replacement scan not found: ${librarySrcDir}. Skipping pre-build replacements.`
714
+ );
715
+ return [];
716
+ }
717
+ relinka(
718
+ "verbose",
719
+ `Reading replacement content from: ${replacementFilePath}`
720
+ );
721
+ const replacementContent = await fs.readFile(replacementFilePath, "utf-8");
722
+ const allFiles = [];
723
+ relinka("verbose", `Scanning for .ts/.tsx files in: ${librarySrcDir}`);
724
+ await collectTsFilesRecursively(librarySrcDir, allFiles);
725
+ relinka(
726
+ "verbose",
727
+ `Found ${allFiles.length} potential files for replacement scan.`
728
+ );
729
+ const escapedMarker = replacementMarker.replace(
730
+ /[.*+?^${}()|[\]\\]/g,
731
+ "\\$&"
732
+ );
733
+ const regex = new RegExp(`^.*${escapedMarker}\\s*$`, "gm");
734
+ for (const filePath of allFiles) {
735
+ try {
736
+ const originalCode = await fs.readFile(filePath, "utf-8");
737
+ if (!originalCode.includes(replacementMarker)) {
738
+ continue;
739
+ }
740
+ const magic = new MagicString(originalCode);
741
+ let replacementOccurred = false;
742
+ let match;
743
+ while (true) {
744
+ match = regex.exec(originalCode);
745
+ if (match === null) break;
746
+ replacementOccurred = true;
747
+ const lineContent = match[0];
748
+ const matchStartIndex = match.index;
749
+ const matchEndIndex = matchStartIndex + lineContent.length;
750
+ let lineStartIndex = matchStartIndex;
751
+ while (lineStartIndex > 0 && originalCode[lineStartIndex - 1] !== "\n") {
752
+ lineStartIndex--;
753
+ }
754
+ let lineEndIndex = matchEndIndex;
755
+ while (lineEndIndex > lineStartIndex && lineEndIndex - 1 < originalCode.length && originalCode[lineEndIndex - 1] !== void 0 && originalCode[lineEndIndex - 1] !== null && typeof originalCode[lineEndIndex - 1] === "string" && /\s/.test(originalCode[lineEndIndex - 1])) {
756
+ lineEndIndex--;
757
+ }
758
+ if (lineEndIndex < originalCode.length && originalCode[lineEndIndex] === "\r")
759
+ lineEndIndex++;
760
+ if (lineEndIndex < originalCode.length && originalCode[lineEndIndex] === "\n")
761
+ lineEndIndex++;
762
+ relinka(
763
+ "verbose",
764
+ `Replacing line in ${path.relative(PROJECT_ROOT, filePath)} (range ${lineStartIndex}-${lineEndIndex})`
765
+ );
766
+ const contentToInsert = replacementContent.endsWith("\n") ? replacementContent : `${replacementContent}
767
+ `;
768
+ magic.overwrite(lineStartIndex, lineEndIndex, contentToInsert);
769
+ }
770
+ if (replacementOccurred) {
771
+ const updatedCode = magic.toString();
772
+ if (updatedCode !== originalCode) {
773
+ replacedFiles.push({
774
+ filePath,
775
+ newContent: updatedCode,
776
+ originalContent: originalCode
777
+ });
778
+ await fs.writeFile(filePath, updatedCode, "utf-8");
779
+ relinka(
780
+ "info",
781
+ `Applied pre-build replacement in ${path.relative(PROJECT_ROOT, filePath)}`
782
+ );
783
+ } else {
784
+ relinka(
785
+ "verbose",
786
+ `Replacement marker found but content identical after processing ${filePath}. Skipping write.`
787
+ );
788
+ }
789
+ }
790
+ } catch (fileError) {
791
+ relinka(
792
+ "error",
793
+ `Failed processing file for replacement ${filePath}: ${fileError instanceof Error ? fileError.message : String(fileError)}`
794
+ );
795
+ }
796
+ }
797
+ return replacedFiles;
798
+ }
799
+ async function postBuildReplacements(replacedFiles) {
800
+ if (replacedFiles.length === 0) {
801
+ return;
802
+ }
803
+ relinka(
804
+ "verbose",
805
+ `Reverting modifications in ${replacedFiles.length} files...`
806
+ );
807
+ const revertTasks = replacedFiles.map((record) => async () => {
808
+ try {
809
+ await fs.writeFile(record.filePath, record.originalContent, "utf-8");
810
+ relinka(
811
+ "verbose",
812
+ `Reverted changes in ${path.relative(PROJECT_ROOT, record.filePath)}`
813
+ );
814
+ } catch (err) {
815
+ const error = err instanceof Error ? err : new Error(String(err));
816
+ relinka(
817
+ "error",
818
+ `Failed to revert file ${record.filePath}: ${error.message}`,
819
+ error.stack
820
+ );
821
+ throw new Error(`Failed to revert ${record.filePath}`);
822
+ }
823
+ });
824
+ try {
825
+ await pAll(revertTasks, { concurrency: 1, stopOnError: false });
826
+ relinka("verbose", "Attempted revert for all modified files.");
827
+ } catch (aggregateError) {
828
+ relinka(
829
+ "error",
830
+ "One or more files failed to revert during post-build cleanup. Check preceding error logs.",
831
+ aggregateError instanceof Error ? aggregateError : void 0
832
+ );
833
+ throw aggregateError;
834
+ }
835
+ }
836
+ async function collectTsFilesRecursively(dir, fileList) {
837
+ try {
838
+ if (!await fs.pathExists(dir)) {
839
+ relinka("warn", `Directory not found for scanning: ${dir}`);
840
+ return;
841
+ }
842
+ if (!(await fs.stat(dir)).isDirectory()) {
843
+ relinka("warn", `Path is not a directory, cannot scan: ${dir}`);
844
+ return;
845
+ }
846
+ const entries = await fs.readdir(dir, { withFileTypes: true });
847
+ for (const entry of entries) {
848
+ const fullPath = path.join(dir, entry.name);
849
+ if (entry.isDirectory()) {
850
+ if (entry.name !== "node_modules" && !entry.name.startsWith("dist") && entry.name !== ".git" && entry.name !== ".svn" && entry.name !== ".hg" && entry.name !== ".turbo" && entry.name !== ".next" && entry.name !== ".nuxt") {
851
+ await collectTsFilesRecursively(fullPath, fileList);
852
+ }
853
+ } else if (entry.isFile() && /\.(ts|tsx)$/i.test(entry.name)) {
854
+ fileList.push(fullPath);
855
+ }
856
+ }
857
+ } catch (error) {
858
+ relinka(
859
+ "error",
860
+ `Failed to read directory during file collection: ${dir}`,
861
+ error instanceof Error ? error : void 0
862
+ );
863
+ throw error;
864
+ }
865
+ }