@kubb/core 4.33.0 → 4.33.1

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 (85) hide show
  1. package/dist/hooks.d.ts +1 -1
  2. package/dist/index.cjs +1695 -82
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +150 -20
  5. package/dist/index.js +1673 -65
  6. package/dist/index.js.map +1 -1
  7. package/dist/{types-f_no0d7G.d.ts → types-DfjjJb2r.d.ts} +70 -27
  8. package/package.json +3 -24
  9. package/src/BarrelManager.ts +10 -31
  10. package/src/PackageManager.ts +13 -21
  11. package/src/PluginManager.ts +65 -87
  12. package/src/PromiseManager.ts +3 -5
  13. package/src/build.ts +61 -47
  14. package/src/config.ts +1 -1
  15. package/src/constants.ts +60 -0
  16. package/src/errors.ts +1 -14
  17. package/src/index.ts +6 -3
  18. package/src/types.ts +5 -14
  19. package/src/utils/FunctionParams.ts +7 -8
  20. package/src/utils/TreeNode.ts +12 -23
  21. package/src/utils/executeStrategies.ts +5 -3
  22. package/src/utils/formatters.ts +3 -20
  23. package/src/utils/getBarrelFiles.ts +8 -2
  24. package/src/utils/getConfigs.ts +6 -15
  25. package/src/utils/getPlugins.ts +7 -7
  26. package/src/utils/linters.ts +3 -20
  27. package/dist/fs-D4eqq6bR.cjs +0 -103
  28. package/dist/fs-D4eqq6bR.cjs.map +0 -1
  29. package/dist/fs-TVBCPkE-.js +0 -67
  30. package/dist/fs-TVBCPkE-.js.map +0 -1
  31. package/dist/fs.cjs +0 -8
  32. package/dist/fs.d.ts +0 -23
  33. package/dist/fs.js +0 -2
  34. package/dist/packageManager-_7I0WFQU.d.ts +0 -82
  35. package/dist/packageManager-jzjuEj2U.cjs +0 -1103
  36. package/dist/packageManager-jzjuEj2U.cjs.map +0 -1
  37. package/dist/packageManager-wMCQlgd6.js +0 -1024
  38. package/dist/packageManager-wMCQlgd6.js.map +0 -1
  39. package/dist/transformers-BwSpAhvT.js +0 -267
  40. package/dist/transformers-BwSpAhvT.js.map +0 -1
  41. package/dist/transformers-BweFhqh-.cjs +0 -380
  42. package/dist/transformers-BweFhqh-.cjs.map +0 -1
  43. package/dist/transformers.cjs +0 -24
  44. package/dist/transformers.d.ts +0 -108
  45. package/dist/transformers.js +0 -2
  46. package/dist/utils.cjs +0 -430
  47. package/dist/utils.cjs.map +0 -1
  48. package/dist/utils.d.ts +0 -290
  49. package/dist/utils.js +0 -402
  50. package/dist/utils.js.map +0 -1
  51. package/src/BaseGenerator.ts +0 -34
  52. package/src/fs/clean.ts +0 -5
  53. package/src/fs/exists.ts +0 -16
  54. package/src/fs/index.ts +0 -5
  55. package/src/fs/read.ts +0 -13
  56. package/src/fs/utils.ts +0 -32
  57. package/src/fs/write.ts +0 -46
  58. package/src/transformers/casing.ts +0 -62
  59. package/src/transformers/combineCodes.ts +0 -3
  60. package/src/transformers/createJSDocBlockText.ts +0 -9
  61. package/src/transformers/escape.ts +0 -31
  62. package/src/transformers/indent.ts +0 -3
  63. package/src/transformers/index.ts +0 -46
  64. package/src/transformers/nameSorter.ts +0 -9
  65. package/src/transformers/searchAndReplace.ts +0 -25
  66. package/src/transformers/stringify.ts +0 -25
  67. package/src/transformers/toRegExp.ts +0 -22
  68. package/src/transformers/transformReservedWord.ts +0 -106
  69. package/src/transformers/trim.ts +0 -18
  70. package/src/utils/AsyncEventEmitter.ts +0 -48
  71. package/src/utils/Cache.ts +0 -31
  72. package/src/utils/URLPath.ts +0 -146
  73. package/src/utils/buildJSDoc.ts +0 -34
  74. package/src/utils/checkOnlineStatus.ts +0 -40
  75. package/src/utils/formatHrtime.ts +0 -33
  76. package/src/utils/getNestedAccessor.ts +0 -25
  77. package/src/utils/index.ts +0 -26
  78. package/src/utils/packageManager.ts +0 -58
  79. package/src/utils/promise.ts +0 -13
  80. package/src/utils/renderTemplate.ts +0 -31
  81. package/src/utils/serializePluginOptions.ts +0 -29
  82. package/src/utils/timeout.ts +0 -11
  83. package/src/utils/tokenize.ts +0 -23
  84. package/src/utils/types.ts +0 -1
  85. package/src/utils/uniqueName.ts +0 -20
@@ -1,1103 +0,0 @@
1
- const require_chunk = require("./chunk-ByKO4r7w.cjs");
2
- const require_fs = require("./fs-D4eqq6bR.cjs");
3
- const require_transformers = require("./transformers-BweFhqh-.cjs");
4
- let node_path = require("node:path");
5
- node_path = require_chunk.__toESM(node_path);
6
- let node_fs = require("node:fs");
7
- node_fs = require_chunk.__toESM(node_fs);
8
- let node_perf_hooks = require("node:perf_hooks");
9
- let node_events = require("node:events");
10
- //#region src/errors.ts
11
- var ValidationPluginError = class extends Error {};
12
- var BuildError = class extends Error {
13
- cause;
14
- errors;
15
- constructor(message, options) {
16
- super(message, { cause: options.cause });
17
- this.name = "BuildError";
18
- this.cause = options.cause;
19
- this.errors = options.errors;
20
- }
21
- };
22
- //#endregion
23
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
24
- var Node = class {
25
- value;
26
- next;
27
- constructor(value) {
28
- this.value = value;
29
- }
30
- };
31
- var Queue = class {
32
- #head;
33
- #tail;
34
- #size;
35
- constructor() {
36
- this.clear();
37
- }
38
- enqueue(value) {
39
- const node = new Node(value);
40
- if (this.#head) {
41
- this.#tail.next = node;
42
- this.#tail = node;
43
- } else {
44
- this.#head = node;
45
- this.#tail = node;
46
- }
47
- this.#size++;
48
- }
49
- dequeue() {
50
- const current = this.#head;
51
- if (!current) return;
52
- this.#head = this.#head.next;
53
- this.#size--;
54
- if (!this.#head) this.#tail = void 0;
55
- return current.value;
56
- }
57
- peek() {
58
- if (!this.#head) return;
59
- return this.#head.value;
60
- }
61
- clear() {
62
- this.#head = void 0;
63
- this.#tail = void 0;
64
- this.#size = 0;
65
- }
66
- get size() {
67
- return this.#size;
68
- }
69
- *[Symbol.iterator]() {
70
- let current = this.#head;
71
- while (current) {
72
- yield current.value;
73
- current = current.next;
74
- }
75
- }
76
- *drain() {
77
- while (this.#head) yield this.dequeue();
78
- }
79
- };
80
- //#endregion
81
- //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
82
- function pLimit(concurrency) {
83
- let rejectOnClear = false;
84
- if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
85
- validateConcurrency(concurrency);
86
- if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
87
- const queue = new Queue();
88
- let activeCount = 0;
89
- const resumeNext = () => {
90
- if (activeCount < concurrency && queue.size > 0) {
91
- activeCount++;
92
- queue.dequeue().run();
93
- }
94
- };
95
- const next = () => {
96
- activeCount--;
97
- resumeNext();
98
- };
99
- const run = async (function_, resolve, arguments_) => {
100
- const result = (async () => function_(...arguments_))();
101
- resolve(result);
102
- try {
103
- await result;
104
- } catch {}
105
- next();
106
- };
107
- const enqueue = (function_, resolve, reject, arguments_) => {
108
- const queueItem = { reject };
109
- new Promise((internalResolve) => {
110
- queueItem.run = internalResolve;
111
- queue.enqueue(queueItem);
112
- }).then(run.bind(void 0, function_, resolve, arguments_));
113
- if (activeCount < concurrency) resumeNext();
114
- };
115
- const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
116
- enqueue(function_, resolve, reject, arguments_);
117
- });
118
- Object.defineProperties(generator, {
119
- activeCount: { get: () => activeCount },
120
- pendingCount: { get: () => queue.size },
121
- clearQueue: { value() {
122
- if (!rejectOnClear) {
123
- queue.clear();
124
- return;
125
- }
126
- const abortError = AbortSignal.abort().reason;
127
- while (queue.size > 0) queue.dequeue().reject(abortError);
128
- } },
129
- concurrency: {
130
- get: () => concurrency,
131
- set(newConcurrency) {
132
- validateConcurrency(newConcurrency);
133
- concurrency = newConcurrency;
134
- queueMicrotask(() => {
135
- while (activeCount < concurrency && queue.size > 0) resumeNext();
136
- });
137
- }
138
- },
139
- map: { async value(iterable, function_) {
140
- const promises = Array.from(iterable, (value, index) => this(function_, value, index));
141
- return Promise.all(promises);
142
- } }
143
- });
144
- return generator;
145
- }
146
- function validateConcurrency(concurrency) {
147
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
148
- }
149
- //#endregion
150
- //#region src/utils/executeStrategies.ts
151
- /**
152
- * Chains promises
153
- */
154
- function hookSeq(promises) {
155
- return promises.filter(Boolean).reduce((promise, func) => {
156
- if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
157
- return promise.then((state) => {
158
- const calledFunc = func(state);
159
- if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
160
- });
161
- }, Promise.resolve([]));
162
- }
163
- /**
164
- * Chains promises, first non-null result stops and returns
165
- */
166
- function hookFirst(promises, nullCheck = (state) => state !== null) {
167
- let promise = Promise.resolve(null);
168
- for (const func of promises.filter(Boolean)) promise = promise.then((state) => {
169
- if (nullCheck(state)) return state;
170
- return func(state);
171
- });
172
- return promise;
173
- }
174
- /**
175
- * Runs an array of promise functions with optional concurrency limit.
176
- */
177
- function hookParallel(promises, concurrency = Number.POSITIVE_INFINITY) {
178
- const limit = pLimit(concurrency);
179
- const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()));
180
- return Promise.allSettled(tasks);
181
- }
182
- //#endregion
183
- //#region src/PromiseManager.ts
184
- var PromiseManager = class {
185
- #options = {};
186
- constructor(options = {}) {
187
- this.#options = options;
188
- return this;
189
- }
190
- run(strategy, promises, { concurrency = Number.POSITIVE_INFINITY } = {}) {
191
- if (strategy === "seq") return hookSeq(promises);
192
- if (strategy === "first") return hookFirst(promises, this.#options.nullCheck);
193
- if (strategy === "parallel") return hookParallel(promises, concurrency);
194
- throw new Error(`${strategy} not implemented`);
195
- }
196
- };
197
- function isPromiseRejectedResult(result) {
198
- return result.status === "rejected";
199
- }
200
- //#endregion
201
- //#region src/utils/uniqueName.ts
202
- function getUniqueName(originalName, data) {
203
- let used = data[originalName] || 0;
204
- if (used) {
205
- data[originalName] = ++used;
206
- originalName += used;
207
- }
208
- data[originalName] = 1;
209
- return originalName;
210
- }
211
- function setUniqueName(originalName, data) {
212
- let used = data[originalName] || 0;
213
- if (used) {
214
- data[originalName] = ++used;
215
- return originalName;
216
- }
217
- data[originalName] = 1;
218
- return originalName;
219
- }
220
- //#endregion
221
- //#region src/PluginManager.ts
222
- function getMode(fileOrFolder) {
223
- if (!fileOrFolder) return "split";
224
- return node_path.default.extname(fileOrFolder) ? "single" : "split";
225
- }
226
- var PluginManager = class {
227
- config;
228
- options;
229
- #plugins = /* @__PURE__ */ new Set();
230
- #usedPluginNames = {};
231
- #promiseManager;
232
- constructor(config, options) {
233
- this.config = config;
234
- this.options = options;
235
- this.#promiseManager = new PromiseManager({ nullCheck: (state) => !!state?.result });
236
- [...config.plugins || []].forEach((plugin) => {
237
- const parsedPlugin = this.#parse(plugin);
238
- this.#plugins.add(parsedPlugin);
239
- });
240
- return this;
241
- }
242
- get events() {
243
- return this.options.events;
244
- }
245
- getContext(plugin) {
246
- const plugins = [...this.#plugins];
247
- const baseContext = {
248
- fabric: this.options.fabric,
249
- config: this.config,
250
- plugin,
251
- events: this.options.events,
252
- pluginManager: this,
253
- mode: getMode(node_path.default.resolve(this.config.root, this.config.output.path)),
254
- addFile: async (...files) => {
255
- await this.options.fabric.addFile(...files);
256
- },
257
- upsertFile: async (...files) => {
258
- await this.options.fabric.upsertFile(...files);
259
- }
260
- };
261
- const mergedExtras = {};
262
- for (const p of plugins) if (typeof p.inject === "function") {
263
- const result = p.inject.bind(baseContext)(baseContext);
264
- if (result && typeof result === "object") Object.assign(mergedExtras, result);
265
- }
266
- return {
267
- ...baseContext,
268
- ...mergedExtras
269
- };
270
- }
271
- get plugins() {
272
- return this.#getSortedPlugins();
273
- }
274
- getFile({ name, mode, extname, pluginKey, options }) {
275
- const baseName = `${name}${extname}`;
276
- const path = this.resolvePath({
277
- baseName,
278
- mode,
279
- pluginKey,
280
- options
281
- });
282
- if (!path) throw new Error(`Filepath should be defined for resolvedName "${name}" and pluginKey [${JSON.stringify(pluginKey)}]`);
283
- return {
284
- path,
285
- baseName,
286
- meta: { pluginKey },
287
- sources: [],
288
- imports: [],
289
- exports: []
290
- };
291
- }
292
- resolvePath = (params) => {
293
- const root = node_path.default.resolve(this.config.root, this.config.output.path);
294
- const defaultPath = node_path.default.resolve(root, params.baseName);
295
- if (params.pluginKey) return this.hookForPluginSync({
296
- pluginKey: params.pluginKey,
297
- hookName: "resolvePath",
298
- parameters: [
299
- params.baseName,
300
- params.mode,
301
- params.options
302
- ]
303
- })?.at(0) || defaultPath;
304
- return this.hookFirstSync({
305
- hookName: "resolvePath",
306
- parameters: [
307
- params.baseName,
308
- params.mode,
309
- params.options
310
- ]
311
- })?.result || defaultPath;
312
- };
313
- resolveName = (params) => {
314
- if (params.pluginKey) {
315
- const names = this.hookForPluginSync({
316
- pluginKey: params.pluginKey,
317
- hookName: "resolveName",
318
- parameters: [require_transformers.trim(params.name), params.type]
319
- });
320
- return require_transformers.transformReservedWord([...new Set(names)].at(0) || params.name);
321
- }
322
- const name = this.hookFirstSync({
323
- hookName: "resolveName",
324
- parameters: [require_transformers.trim(params.name), params.type]
325
- }).result;
326
- return require_transformers.transformReservedWord(name);
327
- };
328
- /**
329
- * Run a specific hookName for plugin x.
330
- */
331
- async hookForPlugin({ pluginKey, hookName, parameters }) {
332
- const plugins = this.getPluginsByKey(hookName, pluginKey);
333
- this.events.emit("plugins:hook:progress:start", {
334
- hookName,
335
- plugins
336
- });
337
- const items = [];
338
- for (const plugin of plugins) {
339
- const result = await this.#execute({
340
- strategy: "hookFirst",
341
- hookName,
342
- parameters,
343
- plugin
344
- });
345
- if (result !== void 0 && result !== null) items.push(result);
346
- }
347
- this.events.emit("plugins:hook:progress:end", { hookName });
348
- return items;
349
- }
350
- /**
351
- * Run a specific hookName for plugin x.
352
- */
353
- hookForPluginSync({ pluginKey, hookName, parameters }) {
354
- return this.getPluginsByKey(hookName, pluginKey).map((plugin) => {
355
- return this.#executeSync({
356
- strategy: "hookFirst",
357
- hookName,
358
- parameters,
359
- plugin
360
- });
361
- }).filter(Boolean);
362
- }
363
- /**
364
- * Returns the first non-null result.
365
- */
366
- async hookFirst({ hookName, parameters, skipped }) {
367
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
368
- return skipped ? skipped.has(plugin) : true;
369
- });
370
- this.events.emit("plugins:hook:progress:start", {
371
- hookName,
372
- plugins
373
- });
374
- const promises = plugins.map((plugin) => {
375
- return async () => {
376
- const value = await this.#execute({
377
- strategy: "hookFirst",
378
- hookName,
379
- parameters,
380
- plugin
381
- });
382
- return Promise.resolve({
383
- plugin,
384
- result: value
385
- });
386
- };
387
- });
388
- const result = await this.#promiseManager.run("first", promises);
389
- this.events.emit("plugins:hook:progress:end", { hookName });
390
- return result;
391
- }
392
- /**
393
- * Returns the first non-null result.
394
- */
395
- hookFirstSync({ hookName, parameters, skipped }) {
396
- let parseResult = null;
397
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
398
- return skipped ? skipped.has(plugin) : true;
399
- });
400
- for (const plugin of plugins) {
401
- parseResult = {
402
- result: this.#executeSync({
403
- strategy: "hookFirst",
404
- hookName,
405
- parameters,
406
- plugin
407
- }),
408
- plugin
409
- };
410
- if (parseResult?.result != null) break;
411
- }
412
- return parseResult;
413
- }
414
- /**
415
- * Runs all plugins in parallel based on `this.plugin` order and `pre`/`post` settings.
416
- */
417
- async hookParallel({ hookName, parameters }) {
418
- const plugins = this.#getSortedPlugins(hookName);
419
- this.events.emit("plugins:hook:progress:start", {
420
- hookName,
421
- plugins
422
- });
423
- const promises = plugins.map((plugin) => {
424
- return () => this.#execute({
425
- strategy: "hookParallel",
426
- hookName,
427
- parameters,
428
- plugin
429
- });
430
- });
431
- const results = await this.#promiseManager.run("parallel", promises, { concurrency: this.options.concurrency });
432
- results.forEach((result, index) => {
433
- if (isPromiseRejectedResult(result)) {
434
- const plugin = this.#getSortedPlugins(hookName)[index];
435
- if (plugin) this.events.emit("error", result.reason, {
436
- plugin,
437
- hookName,
438
- strategy: "hookParallel",
439
- duration: 0,
440
- parameters
441
- });
442
- }
443
- });
444
- this.events.emit("plugins:hook:progress:end", { hookName });
445
- return results.reduce((acc, result) => {
446
- if (result.status === "fulfilled") acc.push(result.value);
447
- return acc;
448
- }, []);
449
- }
450
- /**
451
- * Chains plugins
452
- */
453
- async hookSeq({ hookName, parameters }) {
454
- const plugins = this.#getSortedPlugins(hookName);
455
- this.events.emit("plugins:hook:progress:start", {
456
- hookName,
457
- plugins
458
- });
459
- const promises = plugins.map((plugin) => {
460
- return () => this.#execute({
461
- strategy: "hookSeq",
462
- hookName,
463
- parameters,
464
- plugin
465
- });
466
- });
467
- await this.#promiseManager.run("seq", promises);
468
- this.events.emit("plugins:hook:progress:end", { hookName });
469
- }
470
- #getSortedPlugins(hookName) {
471
- const plugins = [...this.#plugins];
472
- if (hookName) return plugins.filter((plugin) => hookName in plugin);
473
- return plugins.map((plugin) => {
474
- if (plugin.pre) {
475
- const missingPlugins = plugin.pre.filter((pluginName) => !plugins.find((pluginToFind) => pluginToFind.name === pluginName));
476
- if (missingPlugins.length > 0) throw new ValidationPluginError(`The plugin '${plugin.name}' has a pre set that references missing plugins for '${missingPlugins.join(", ")}'`);
477
- }
478
- return plugin;
479
- }).sort((a, b) => {
480
- if (b.pre?.includes(a.name)) return 1;
481
- if (b.post?.includes(a.name)) return -1;
482
- return 0;
483
- });
484
- }
485
- getPluginByKey(pluginKey) {
486
- const plugins = [...this.#plugins];
487
- const [searchPluginName] = pluginKey;
488
- return plugins.find((item) => {
489
- const [name] = item.key;
490
- return name === searchPluginName;
491
- });
492
- }
493
- getPluginsByKey(hookName, pluginKey) {
494
- const plugins = [...this.plugins];
495
- const [searchPluginName, searchIdentifier] = pluginKey;
496
- const pluginByPluginName = plugins.filter((plugin) => hookName in plugin).filter((item) => {
497
- const [name, identifier] = item.key;
498
- const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
499
- const nameCheck = name === searchPluginName;
500
- if (searchIdentifier) return identifierCheck && nameCheck;
501
- return nameCheck;
502
- });
503
- if (!pluginByPluginName?.length) {
504
- const corePlugin = plugins.find((plugin) => plugin.name === "core" && hookName in plugin);
505
- return corePlugin ? [corePlugin] : [];
506
- }
507
- return pluginByPluginName;
508
- }
509
- /**
510
- * Run an async plugin hook and return the result.
511
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
512
- * @param args Arguments passed to the plugin hook.
513
- * @param plugin The actual pluginObject to run.
514
- */
515
- #execute({ strategy, hookName, parameters, plugin }) {
516
- const hook = plugin[hookName];
517
- let output;
518
- if (!hook) return null;
519
- this.events.emit("plugins:hook:processing:start", {
520
- strategy,
521
- hookName,
522
- parameters,
523
- plugin
524
- });
525
- const startTime = node_perf_hooks.performance.now();
526
- return (async () => {
527
- try {
528
- if (typeof hook === "function") {
529
- const context = this.getContext(plugin);
530
- const result = await Promise.resolve(hook.apply(context, parameters));
531
- output = result;
532
- this.events.emit("plugins:hook:processing:end", {
533
- duration: Math.round(node_perf_hooks.performance.now() - startTime),
534
- parameters,
535
- output,
536
- strategy,
537
- hookName,
538
- plugin
539
- });
540
- return result;
541
- }
542
- output = hook;
543
- this.events.emit("plugins:hook:processing:end", {
544
- duration: Math.round(node_perf_hooks.performance.now() - startTime),
545
- parameters,
546
- output,
547
- strategy,
548
- hookName,
549
- plugin
550
- });
551
- return hook;
552
- } catch (error) {
553
- this.events.emit("error", error, {
554
- plugin,
555
- hookName,
556
- strategy,
557
- duration: Math.round(node_perf_hooks.performance.now() - startTime)
558
- });
559
- return null;
560
- }
561
- })();
562
- }
563
- /**
564
- * Run a sync plugin hook and return the result.
565
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
566
- * @param args Arguments passed to the plugin hook.
567
- * @param plugin The actual plugin
568
- * @param replaceContext When passed, the plugin context can be overridden.
569
- */
570
- #executeSync({ strategy, hookName, parameters, plugin }) {
571
- const hook = plugin[hookName];
572
- let output;
573
- if (!hook) return null;
574
- this.events.emit("plugins:hook:processing:start", {
575
- strategy,
576
- hookName,
577
- parameters,
578
- plugin
579
- });
580
- const startTime = node_perf_hooks.performance.now();
581
- try {
582
- if (typeof hook === "function") {
583
- const context = this.getContext(plugin);
584
- const fn = hook.apply(context, parameters);
585
- output = fn;
586
- this.events.emit("plugins:hook:processing:end", {
587
- duration: Math.round(node_perf_hooks.performance.now() - startTime),
588
- parameters,
589
- output,
590
- strategy,
591
- hookName,
592
- plugin
593
- });
594
- return fn;
595
- }
596
- output = hook;
597
- this.events.emit("plugins:hook:processing:end", {
598
- duration: Math.round(node_perf_hooks.performance.now() - startTime),
599
- parameters,
600
- output,
601
- strategy,
602
- hookName,
603
- plugin
604
- });
605
- return hook;
606
- } catch (error) {
607
- this.events.emit("error", error, {
608
- plugin,
609
- hookName,
610
- strategy,
611
- duration: Math.round(node_perf_hooks.performance.now() - startTime)
612
- });
613
- return null;
614
- }
615
- }
616
- #parse(plugin) {
617
- const usedPluginNames = this.#usedPluginNames;
618
- setUniqueName(plugin.name, usedPluginNames);
619
- const usageCount = usedPluginNames[plugin.name];
620
- if (usageCount && usageCount > 1) this.events.emit("warn", `Multiple instances of plugin "${plugin.name}" detected. This behavior is deprecated and will be removed in v5.`, `Plugin key: [${plugin.name}, ${usageCount}]`);
621
- return {
622
- install() {},
623
- ...plugin,
624
- key: [plugin.name, usedPluginNames[plugin.name]].filter(Boolean)
625
- };
626
- }
627
- };
628
- //#endregion
629
- //#region src/utils/AsyncEventEmitter.ts
630
- var AsyncEventEmitter = class {
631
- constructor(maxListener = 100) {
632
- this.#emitter.setMaxListeners(maxListener);
633
- }
634
- #emitter = new node_events.EventEmitter();
635
- async emit(eventName, ...eventArgs) {
636
- const listeners = this.#emitter.listeners(eventName);
637
- if (listeners.length === 0) return;
638
- await Promise.all(listeners.map(async (listener) => {
639
- try {
640
- return await listener(...eventArgs);
641
- } catch (err) {
642
- const causedError = err;
643
- throw new Error(`Error in async listener for "${eventName}" with eventArgs "${eventArgs}"`, { cause: causedError });
644
- }
645
- }));
646
- }
647
- on(eventName, handler) {
648
- this.#emitter.on(eventName, handler);
649
- }
650
- onOnce(eventName, handler) {
651
- const wrapper = (...args) => {
652
- this.off(eventName, wrapper);
653
- handler(...args);
654
- };
655
- this.on(eventName, wrapper);
656
- }
657
- off(eventName, handler) {
658
- this.#emitter.off(eventName, handler);
659
- }
660
- removeAll() {
661
- this.#emitter.removeAllListeners();
662
- }
663
- };
664
- //#endregion
665
- //#region src/utils/formatHrtime.ts
666
- /**
667
- * Calculates elapsed time in milliseconds from a high-resolution start time.
668
- * Rounds to 2 decimal places to provide sub-millisecond precision without noise.
669
- */
670
- function getElapsedMs(hrStart) {
671
- const [seconds, nanoseconds] = process.hrtime(hrStart);
672
- const ms = seconds * 1e3 + nanoseconds / 1e6;
673
- return Math.round(ms * 100) / 100;
674
- }
675
- /**
676
- * Converts a millisecond duration into a human-readable string.
677
- * Adjusts units (ms, s, m s) based on the magnitude of the duration.
678
- */
679
- function formatMs(ms) {
680
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
681
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
682
- return `${Math.round(ms).toFixed(0)}ms`;
683
- }
684
- /**
685
- * Convenience helper to get and format elapsed time in one step.
686
- */
687
- function formatHrtime(hrStart) {
688
- return formatMs(getElapsedMs(hrStart));
689
- }
690
- //#endregion
691
- //#region src/utils/URLPath.ts
692
- var URLPath = class {
693
- path;
694
- #options;
695
- constructor(path, options = {}) {
696
- this.path = path;
697
- this.#options = options;
698
- return this;
699
- }
700
- /**
701
- * Convert Swagger path to URLPath(syntax of Express)
702
- * @example /pet/{petId} => /pet/:petId
703
- */
704
- get URL() {
705
- return this.toURLPath();
706
- }
707
- get isURL() {
708
- try {
709
- if (new URL(this.path)?.href) return true;
710
- } catch (_error) {
711
- return false;
712
- }
713
- return false;
714
- }
715
- /**
716
- * Convert Swagger path to template literals/ template strings(camelcase)
717
- * @example /pet/{petId} => `/pet/${petId}`
718
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
719
- * @example /account/userID => `/account/${userId}`
720
- */
721
- get template() {
722
- return this.toTemplateString();
723
- }
724
- get object() {
725
- return this.toObject();
726
- }
727
- get params() {
728
- return this.getParams();
729
- }
730
- toObject({ type = "path", replacer, stringify } = {}) {
731
- const object = {
732
- url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
733
- params: this.getParams()
734
- };
735
- if (stringify) {
736
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
737
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
738
- return `{ url: '${object.url}' }`;
739
- }
740
- return object;
741
- }
742
- /**
743
- * Convert Swagger path to template literals/ template strings(camelcase)
744
- * @example /pet/{petId} => `/pet/${petId}`
745
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
746
- * @example /account/userID => `/account/${userId}`
747
- */
748
- toTemplateString({ prefix = "", replacer } = {}) {
749
- const found = this.path.match(/{(\w|-)*}/g);
750
- let newPath = this.path.replaceAll("{", "${");
751
- if (found) newPath = found.reduce((prev, path) => {
752
- const pathWithoutBrackets = path.replaceAll("{", "").replaceAll("}", "");
753
- let param = require_transformers.isValidVarName(pathWithoutBrackets) ? pathWithoutBrackets : require_transformers.camelCase(pathWithoutBrackets);
754
- if (this.#options.casing === "camelcase") param = require_transformers.camelCase(param);
755
- return prev.replace(path, `\${${replacer ? replacer(param) : param}}`);
756
- }, this.path);
757
- return `\`${prefix}${newPath}\``;
758
- }
759
- getParams(replacer) {
760
- const found = this.path.match(/{(\w|-)*}/g);
761
- if (!found) return;
762
- const params = {};
763
- found.forEach((item) => {
764
- item = item.replaceAll("{", "").replaceAll("}", "");
765
- let param = require_transformers.isValidVarName(item) ? item : require_transformers.camelCase(item);
766
- if (this.#options.casing === "camelcase") param = require_transformers.camelCase(param);
767
- const key = replacer ? replacer(param) : param;
768
- params[key] = key;
769
- }, this.path);
770
- return params;
771
- }
772
- /**
773
- * Convert Swagger path to URLPath(syntax of Express)
774
- * @example /pet/{petId} => /pet/:petId
775
- */
776
- toURLPath() {
777
- return this.path.replaceAll("{", ":").replaceAll("}", "");
778
- }
779
- };
780
- //#endregion
781
- //#region src/utils/TreeNode.ts
782
- var TreeNode = class TreeNode {
783
- data;
784
- parent;
785
- children = [];
786
- #cachedLeaves = void 0;
787
- constructor(data, parent) {
788
- this.data = data;
789
- this.parent = parent;
790
- return this;
791
- }
792
- addChild(data) {
793
- const child = new TreeNode(data, this);
794
- if (!this.children) this.children = [];
795
- this.children.push(child);
796
- return child;
797
- }
798
- get root() {
799
- if (!this.parent) return this;
800
- return this.parent.root;
801
- }
802
- get leaves() {
803
- if (!this.children || this.children.length === 0) return [this];
804
- if (this.#cachedLeaves) return this.#cachedLeaves;
805
- const leaves = [];
806
- if (this.children) for (let childIndex = 0, { length } = this.children; childIndex < length; childIndex++) leaves.push.apply(leaves, this.children[childIndex].leaves);
807
- this.#cachedLeaves = leaves;
808
- return leaves;
809
- }
810
- forEach(callback) {
811
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
812
- callback(this);
813
- if (this.children) for (let childIndex = 0, { length } = this.children; childIndex < length; childIndex++) this.children[childIndex]?.forEach(callback);
814
- return this;
815
- }
816
- findDeep(predicate) {
817
- if (typeof predicate !== "function") throw new TypeError("find() predicate must be a function");
818
- return this.leaves.find(predicate);
819
- }
820
- forEachDeep(callback) {
821
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
822
- this.leaves.forEach(callback);
823
- }
824
- filterDeep(callback) {
825
- if (typeof callback !== "function") throw new TypeError("filter() callback must be a function");
826
- return this.leaves.filter(callback);
827
- }
828
- mapDeep(callback) {
829
- if (typeof callback !== "function") throw new TypeError("map() callback must be a function");
830
- return this.leaves.map(callback);
831
- }
832
- static build(files, root) {
833
- try {
834
- const filteredTree = buildDirectoryTree(files, root);
835
- if (!filteredTree) return null;
836
- const treeNode = new TreeNode({
837
- name: filteredTree.name,
838
- path: filteredTree.path,
839
- file: filteredTree.file,
840
- type: getMode(filteredTree.path)
841
- });
842
- const recurse = (node, item) => {
843
- const subNode = node.addChild({
844
- name: item.name,
845
- path: item.path,
846
- file: item.file,
847
- type: getMode(item.path)
848
- });
849
- if (item.children?.length) item.children?.forEach((child) => {
850
- recurse(subNode, child);
851
- });
852
- };
853
- filteredTree.children?.forEach((child) => {
854
- recurse(treeNode, child);
855
- });
856
- return treeNode;
857
- } catch (error) {
858
- throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: error });
859
- }
860
- }
861
- };
862
- const normalizePath = (p) => p.replace(/\\/g, "/");
863
- function buildDirectoryTree(files, rootFolder = "") {
864
- const normalizedRootFolder = normalizePath(rootFolder);
865
- const rootPrefix = normalizedRootFolder.endsWith("/") ? normalizedRootFolder : `${normalizedRootFolder}/`;
866
- const filteredFiles = files.filter((file) => {
867
- const normalizedFilePath = normalizePath(file.path);
868
- return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith(".json") : !normalizedFilePath.endsWith(".json");
869
- });
870
- if (filteredFiles.length === 0) return null;
871
- const root = {
872
- name: rootFolder || "",
873
- path: rootFolder || "",
874
- children: []
875
- };
876
- filteredFiles.forEach((file) => {
877
- const parts = file.path.slice(rootFolder.length).split("/");
878
- let currentLevel = root.children;
879
- let currentPath = rootFolder;
880
- parts.forEach((part, index) => {
881
- if (index !== 0) currentPath += `/${part}`;
882
- else currentPath += `${part}`;
883
- let existingNode = currentLevel.find((node) => node.name === part);
884
- if (!existingNode) {
885
- if (index === parts.length - 1) existingNode = {
886
- name: part,
887
- file,
888
- path: currentPath
889
- };
890
- else existingNode = {
891
- name: part,
892
- path: currentPath,
893
- children: []
894
- };
895
- currentLevel.push(existingNode);
896
- }
897
- if (!existingNode.file) currentLevel = existingNode.children;
898
- });
899
- });
900
- return root;
901
- }
902
- //#endregion
903
- //#region src/BarrelManager.ts
904
- /** biome-ignore-all lint/suspicious/useIterableCallbackReturn: not needed */
905
- var BarrelManager = class {
906
- constructor(_options = {}) {
907
- return this;
908
- }
909
- getFiles({ files: generatedFiles, root }) {
910
- const cachedFiles = /* @__PURE__ */ new Map();
911
- TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
912
- if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) return;
913
- const barrelFile = {
914
- path: (0, node_path.join)(treeNode.parent?.data.path, "index.ts"),
915
- baseName: "index.ts",
916
- exports: [],
917
- imports: [],
918
- sources: []
919
- };
920
- const previousBarrelFile = cachedFiles.get(barrelFile.path);
921
- treeNode.leaves.forEach((item) => {
922
- if (!item.data.name) return;
923
- (item.data.file?.sources || []).forEach((source) => {
924
- if (!item.data.file?.path || !source.isIndexable || !source.name) return;
925
- if (previousBarrelFile?.sources.some((item) => item.name === source.name && item.isTypeOnly === source.isTypeOnly)) return;
926
- if (!barrelFile.exports) barrelFile.exports = [];
927
- if (!!treeNode.parent?.data.path?.split?.("/")?.length) barrelFile.exports.push({
928
- name: [source.name],
929
- path: require_fs.getRelativePath(treeNode.parent?.data.path, item.data.path),
930
- isTypeOnly: source.isTypeOnly
931
- });
932
- else barrelFile.exports.push({
933
- name: [source.name],
934
- path: `./${item.data.file.baseName}`,
935
- isTypeOnly: source.isTypeOnly
936
- });
937
- barrelFile.sources.push({
938
- name: source.name,
939
- isTypeOnly: source.isTypeOnly,
940
- value: "",
941
- isExportable: false,
942
- isIndexable: false
943
- });
944
- });
945
- });
946
- if (previousBarrelFile) {
947
- previousBarrelFile.sources.push(...barrelFile.sources);
948
- previousBarrelFile.exports?.push(...barrelFile.exports || []);
949
- } else cachedFiles.set(barrelFile.path, barrelFile);
950
- });
951
- return [...cachedFiles.values()];
952
- }
953
- };
954
- //#endregion
955
- //#region src/utils/getBarrelFiles.ts
956
- function trimExtName(text) {
957
- return text.replace(/\.[^/.]+$/, "");
958
- }
959
- async function getBarrelFiles(files, { type, meta = {}, root, output }) {
960
- if (!type || type === "propagate") return [];
961
- const barrelManager = new BarrelManager({});
962
- const pathToBuildFrom = (0, node_path.join)(root, output.path);
963
- if (trimExtName(pathToBuildFrom).endsWith("index")) return [];
964
- const barrelFiles = barrelManager.getFiles({
965
- files,
966
- root: pathToBuildFrom,
967
- meta
968
- });
969
- if (type === "all") return barrelFiles.map((file) => {
970
- return {
971
- ...file,
972
- exports: file.exports?.map((exportItem) => {
973
- return {
974
- ...exportItem,
975
- name: void 0
976
- };
977
- })
978
- };
979
- });
980
- return barrelFiles.map((indexFile) => {
981
- return {
982
- ...indexFile,
983
- meta
984
- };
985
- });
986
- }
987
- //#endregion
988
- //#region src/utils/packageManager.ts
989
- const packageManagers = {
990
- pnpm: {
991
- name: "pnpm",
992
- lockFile: "pnpm-lock.yaml",
993
- installCommand: ["add", "-D"]
994
- },
995
- yarn: {
996
- name: "yarn",
997
- lockFile: "yarn.lock",
998
- installCommand: ["add", "-D"]
999
- },
1000
- bun: {
1001
- name: "bun",
1002
- lockFile: "bun.lockb",
1003
- installCommand: ["add", "-d"]
1004
- },
1005
- npm: {
1006
- name: "npm",
1007
- lockFile: "package-lock.json",
1008
- installCommand: ["install", "--save-dev"]
1009
- }
1010
- };
1011
- function detectPackageManager(cwd = process.cwd()) {
1012
- const packageJsonPath = node_path.default.join(cwd, "package.json");
1013
- if (node_fs.default.existsSync(packageJsonPath)) try {
1014
- const packageJson = JSON.parse(node_fs.default.readFileSync(packageJsonPath, "utf-8"));
1015
- if (packageJson.packageManager) {
1016
- const [name] = packageJson.packageManager.split("@");
1017
- if (name in packageManagers) return packageManagers[name];
1018
- }
1019
- } catch {}
1020
- for (const pm of Object.values(packageManagers)) if (node_fs.default.existsSync(node_path.default.join(cwd, pm.lockFile))) return pm;
1021
- return packageManagers.npm;
1022
- }
1023
- //#endregion
1024
- Object.defineProperty(exports, "AsyncEventEmitter", {
1025
- enumerable: true,
1026
- get: function() {
1027
- return AsyncEventEmitter;
1028
- }
1029
- });
1030
- Object.defineProperty(exports, "BuildError", {
1031
- enumerable: true,
1032
- get: function() {
1033
- return BuildError;
1034
- }
1035
- });
1036
- Object.defineProperty(exports, "PluginManager", {
1037
- enumerable: true,
1038
- get: function() {
1039
- return PluginManager;
1040
- }
1041
- });
1042
- Object.defineProperty(exports, "PromiseManager", {
1043
- enumerable: true,
1044
- get: function() {
1045
- return PromiseManager;
1046
- }
1047
- });
1048
- Object.defineProperty(exports, "URLPath", {
1049
- enumerable: true,
1050
- get: function() {
1051
- return URLPath;
1052
- }
1053
- });
1054
- Object.defineProperty(exports, "detectPackageManager", {
1055
- enumerable: true,
1056
- get: function() {
1057
- return detectPackageManager;
1058
- }
1059
- });
1060
- Object.defineProperty(exports, "formatHrtime", {
1061
- enumerable: true,
1062
- get: function() {
1063
- return formatHrtime;
1064
- }
1065
- });
1066
- Object.defineProperty(exports, "formatMs", {
1067
- enumerable: true,
1068
- get: function() {
1069
- return formatMs;
1070
- }
1071
- });
1072
- Object.defineProperty(exports, "getBarrelFiles", {
1073
- enumerable: true,
1074
- get: function() {
1075
- return getBarrelFiles;
1076
- }
1077
- });
1078
- Object.defineProperty(exports, "getElapsedMs", {
1079
- enumerable: true,
1080
- get: function() {
1081
- return getElapsedMs;
1082
- }
1083
- });
1084
- Object.defineProperty(exports, "getMode", {
1085
- enumerable: true,
1086
- get: function() {
1087
- return getMode;
1088
- }
1089
- });
1090
- Object.defineProperty(exports, "getUniqueName", {
1091
- enumerable: true,
1092
- get: function() {
1093
- return getUniqueName;
1094
- }
1095
- });
1096
- Object.defineProperty(exports, "setUniqueName", {
1097
- enumerable: true,
1098
- get: function() {
1099
- return setUniqueName;
1100
- }
1101
- });
1102
-
1103
- //# sourceMappingURL=packageManager-jzjuEj2U.cjs.map