@kubb/core 4.5.1 → 4.5.3

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 (66) hide show
  1. package/dist/EventEmitter-3-rxpjGN.cjs +32 -0
  2. package/dist/EventEmitter-3-rxpjGN.cjs.map +1 -0
  3. package/dist/EventEmitter-IlDflnd2.js +25 -0
  4. package/dist/EventEmitter-IlDflnd2.js.map +1 -0
  5. package/dist/getBarrelFiles-B9LswRVo.d.cts +37 -0
  6. package/dist/getBarrelFiles-CB-XIF32.d.ts +37 -0
  7. package/dist/getBarrelFiles-D7p4n7Ug.js +962 -0
  8. package/dist/getBarrelFiles-D7p4n7Ug.js.map +1 -0
  9. package/dist/getBarrelFiles-o9ETjpTV.cjs +1017 -0
  10. package/dist/getBarrelFiles-o9ETjpTV.cjs.map +1 -0
  11. package/dist/hooks.d.cts +1 -2
  12. package/dist/hooks.d.ts +2 -3
  13. package/dist/index.cjs +83 -953
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +45 -62
  16. package/dist/index.d.ts +46 -63
  17. package/dist/index.js +51 -921
  18. package/dist/index.js.map +1 -1
  19. package/dist/{logger-Bxe022ug.js → logger-BGuor9Uu.js} +5 -26
  20. package/dist/logger-BGuor9Uu.js.map +1 -0
  21. package/dist/{logger-BIzTtBYJ.cjs → logger-CLbtdL9m.cjs} +4 -32
  22. package/dist/logger-CLbtdL9m.cjs.map +1 -0
  23. package/dist/{logger-BwhJWK-H.d.ts → logger-weazBKCW.d.ts} +1 -1
  24. package/dist/logger.cjs +2 -1
  25. package/dist/logger.d.ts +1 -1
  26. package/dist/logger.js +2 -1
  27. package/dist/{prompt-D5DZPtWc.cjs → prompt-39QFDCh6.cjs} +1 -1
  28. package/dist/{prompt-D5DZPtWc.cjs.map → prompt-39QFDCh6.cjs.map} +1 -1
  29. package/dist/{prompt-xM0onfy8.js → prompt-CIYhgpSM.js} +1 -1
  30. package/dist/{prompt-xM0onfy8.js.map → prompt-CIYhgpSM.js.map} +1 -1
  31. package/dist/{transformers-CeNW0G32.js → transformers-BaV4FwQd.js} +1 -1
  32. package/dist/{transformers-CeNW0G32.js.map → transformers-BaV4FwQd.js.map} +1 -1
  33. package/dist/{transformers-DWLXDYKb.cjs → transformers-BpnIvSiH.cjs} +1 -1
  34. package/dist/{transformers-DWLXDYKb.cjs.map → transformers-BpnIvSiH.cjs.map} +1 -1
  35. package/dist/transformers.cjs +1 -1
  36. package/dist/transformers.js +1 -1
  37. package/dist/{types-CyDeSlGF.d.ts → types-CqYAL0CK.d.ts} +29 -38
  38. package/dist/{types-CVONMhN_.d.cts → types-DqHtLxpp.d.cts} +28 -37
  39. package/dist/utils.cjs +7 -5
  40. package/dist/utils.cjs.map +1 -1
  41. package/dist/utils.d.cts +4 -2
  42. package/dist/utils.d.ts +4 -2
  43. package/dist/utils.js +4 -3
  44. package/dist/utils.js.map +1 -1
  45. package/package.json +4 -4
  46. package/src/BarrelManager.ts +1 -1
  47. package/src/PluginManager.ts +74 -76
  48. package/src/build.ts +24 -13
  49. package/src/config.ts +35 -29
  50. package/src/definePlugin.ts +12 -0
  51. package/src/index.ts +5 -5
  52. package/src/types.ts +19 -40
  53. package/src/utils/AsyncEventEmitter.ts +45 -0
  54. package/src/utils/TreeNode.ts +1 -1
  55. package/src/utils/__snapshots__/barrel.json +147 -0
  56. package/src/{FileManager.ts → utils/getBarrelFiles.ts} +4 -11
  57. package/src/utils/index.ts +1 -0
  58. package/dist/URLPath-DbWtfVa1.js +0 -116
  59. package/dist/URLPath-DbWtfVa1.js.map +0 -1
  60. package/dist/URLPath-Dir2mxRT.cjs +0 -133
  61. package/dist/URLPath-Dir2mxRT.cjs.map +0 -1
  62. package/dist/logger-BIzTtBYJ.cjs.map +0 -1
  63. package/dist/logger-Bxe022ug.js.map +0 -1
  64. package/dist/types-DCR_QgGt.d.ts +0 -5
  65. package/dist/types-DueAg3XP.d.cts +0 -5
  66. package/src/plugin.ts +0 -80
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { a as EventEmitter, n as createLogger, o as write } from "./logger-Bxe022ug.js";
2
- import { g as trim, y as transformReservedWord } from "./transformers-CeNW0G32.js";
3
- import { r as setUniqueName, t as URLPath } from "./URLPath-DbWtfVa1.js";
1
+ import { c as Queue, i as getMode, l as getRelativePath, n as URLPath, r as PluginManager, s as PromiseManager, t as getBarrelFiles } from "./getBarrelFiles-D7p4n7Ug.js";
2
+ import { a as write, n as createLogger } from "./logger-BGuor9Uu.js";
3
+ import "./EventEmitter-IlDflnd2.js";
4
+ import "./transformers-BaV4FwQd.js";
4
5
  import mod from "node:module";
5
- import path, { extname, join, normalize, relative, resolve } from "node:path";
6
+ import path, { join, relative, resolve } from "node:path";
6
7
  import { createFabric } from "@kubb/react-fabric";
7
8
  import { typescriptParser } from "@kubb/react-fabric/parsers";
8
9
  import { fsPlugin } from "@kubb/react-fabric/plugins";
@@ -46,13 +47,27 @@ var BaseGenerator = class {
46
47
  //#endregion
47
48
  //#region src/config.ts
48
49
  /**
49
- * Type helper to make it easier to use vite.config.ts accepts a direct UserConfig object, or a function that returns it. The function receives a ConfigEnv object.
50
+ * Helper for defining a Kubb configuration.
51
+ *
52
+ * Accepts either:
53
+ * - A config object or array of configs
54
+ * - A function returning the config(s), optionally async,
55
+ * receiving the CLI options as argument
56
+ *
57
+ * @example
58
+ * export default defineConfig(({ logLevel }) => ({
59
+ * root: 'src',
60
+ * plugins: [myPlugin()],
61
+ * }))
50
62
  */
51
- function defineConfig(options) {
52
- return options;
63
+ function defineConfig(config) {
64
+ return config;
53
65
  }
54
- function isInputPath(result) {
55
- return !!result && "path" in result?.input;
66
+ /**
67
+ * Type guard to check if a given config has an `input.path`.
68
+ */
69
+ function isInputPath(config) {
70
+ return typeof config?.input === "object" && config.input !== null && "path" in config.input;
56
71
  }
57
72
 
58
73
  //#endregion
@@ -108,687 +123,6 @@ function readSync(path$1) {
108
123
  return syncReader(path$1);
109
124
  }
110
125
 
111
- //#endregion
112
- //#region src/fs/utils.ts
113
- function slash(path$1, platform = "linux") {
114
- const isWindowsPath = /^\\\\\?\\/.test(path$1);
115
- const normalizedPath = normalize(path$1);
116
- if (["linux", "mac"].includes(platform) && !isWindowsPath) return normalizedPath.replaceAll(/\\/g, "/").replace("../", "");
117
- return normalizedPath.replaceAll(/\\/g, "/").replace("../", "");
118
- }
119
- function getRelativePath(rootDir, filePath, platform = "linux") {
120
- if (!rootDir || !filePath) throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
121
- const slashedPath = slash(relative(rootDir, filePath), platform);
122
- if (slashedPath.startsWith("../")) return slashedPath;
123
- return `./${slashedPath}`;
124
- }
125
-
126
- //#endregion
127
- //#region src/errors.ts
128
- var ValidationPluginError = class extends Error {};
129
-
130
- //#endregion
131
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.1/node_modules/yocto-queue/index.js
132
- var Node = class {
133
- value;
134
- next;
135
- constructor(value) {
136
- this.value = value;
137
- }
138
- };
139
- var Queue = class {
140
- #head;
141
- #tail;
142
- #size;
143
- constructor() {
144
- this.clear();
145
- }
146
- enqueue(value) {
147
- const node = new Node(value);
148
- if (this.#head) {
149
- this.#tail.next = node;
150
- this.#tail = node;
151
- } else {
152
- this.#head = node;
153
- this.#tail = node;
154
- }
155
- this.#size++;
156
- }
157
- dequeue() {
158
- const current = this.#head;
159
- if (!current) return;
160
- this.#head = this.#head.next;
161
- this.#size--;
162
- return current.value;
163
- }
164
- peek() {
165
- if (!this.#head) return;
166
- return this.#head.value;
167
- }
168
- clear() {
169
- this.#head = void 0;
170
- this.#tail = void 0;
171
- this.#size = 0;
172
- }
173
- get size() {
174
- return this.#size;
175
- }
176
- *[Symbol.iterator]() {
177
- let current = this.#head;
178
- while (current) {
179
- yield current.value;
180
- current = current.next;
181
- }
182
- }
183
- *drain() {
184
- while (this.#head) yield this.dequeue();
185
- }
186
- };
187
-
188
- //#endregion
189
- //#region ../../node_modules/.pnpm/p-limit@7.2.0/node_modules/p-limit/index.js
190
- function pLimit$1(concurrency) {
191
- validateConcurrency(concurrency);
192
- const queue = new Queue();
193
- let activeCount = 0;
194
- const resumeNext = () => {
195
- if (activeCount < concurrency && queue.size > 0) {
196
- activeCount++;
197
- queue.dequeue()();
198
- }
199
- };
200
- const next = () => {
201
- activeCount--;
202
- resumeNext();
203
- };
204
- const run = async (function_, resolve$1, arguments_) => {
205
- const result = (async () => function_(...arguments_))();
206
- resolve$1(result);
207
- try {
208
- await result;
209
- } catch {}
210
- next();
211
- };
212
- const enqueue = (function_, resolve$1, arguments_) => {
213
- new Promise((internalResolve) => {
214
- queue.enqueue(internalResolve);
215
- }).then(run.bind(void 0, function_, resolve$1, arguments_));
216
- if (activeCount < concurrency) resumeNext();
217
- };
218
- const generator = (function_, ...arguments_) => new Promise((resolve$1) => {
219
- enqueue(function_, resolve$1, arguments_);
220
- });
221
- Object.defineProperties(generator, {
222
- activeCount: { get: () => activeCount },
223
- pendingCount: { get: () => queue.size },
224
- clearQueue: { value() {
225
- queue.clear();
226
- } },
227
- concurrency: {
228
- get: () => concurrency,
229
- set(newConcurrency) {
230
- validateConcurrency(newConcurrency);
231
- concurrency = newConcurrency;
232
- queueMicrotask(() => {
233
- while (activeCount < concurrency && queue.size > 0) resumeNext();
234
- });
235
- }
236
- },
237
- map: { async value(iterable, function_) {
238
- const promises$1 = Array.from(iterable, (value, index) => this(function_, value, index));
239
- return Promise.all(promises$1);
240
- } }
241
- });
242
- return generator;
243
- }
244
- function validateConcurrency(concurrency) {
245
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
246
- }
247
-
248
- //#endregion
249
- //#region src/utils/executeStrategies.ts
250
- /**
251
- * Chains promises
252
- */
253
- function hookSeq(promises$1) {
254
- return promises$1.filter(Boolean).reduce((promise, func) => {
255
- if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
256
- return promise.then((state) => {
257
- const calledFunc = func(state);
258
- if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
259
- });
260
- }, Promise.resolve([]));
261
- }
262
- /**
263
- * Chains promises, first non-null result stops and returns
264
- */
265
- function hookFirst(promises$1, nullCheck = (state) => state !== null) {
266
- let promise = Promise.resolve(null);
267
- for (const func of promises$1.filter(Boolean)) promise = promise.then((state) => {
268
- if (nullCheck(state)) return state;
269
- return func(state);
270
- });
271
- return promise;
272
- }
273
- /**
274
- * Runs an array of promise functions with optional concurrency limit.
275
- */
276
- function hookParallel(promises$1, concurrency = Number.POSITIVE_INFINITY) {
277
- const limit = pLimit$1(concurrency);
278
- const tasks = promises$1.filter(Boolean).map((promise) => limit(() => promise()));
279
- return Promise.allSettled(tasks);
280
- }
281
-
282
- //#endregion
283
- //#region src/PromiseManager.ts
284
- var PromiseManager = class {
285
- #options = {};
286
- constructor(options = {}) {
287
- this.#options = options;
288
- return this;
289
- }
290
- run(strategy, promises$1, { concurrency = Number.POSITIVE_INFINITY } = {}) {
291
- if (strategy === "seq") return hookSeq(promises$1);
292
- if (strategy === "first") return hookFirst(promises$1, this.#options.nullCheck);
293
- if (strategy === "parallel") return hookParallel(promises$1, concurrency);
294
- throw new Error(`${strategy} not implemented`);
295
- }
296
- };
297
- function isPromiseRejectedResult(result) {
298
- return result.status === "rejected";
299
- }
300
-
301
- //#endregion
302
- //#region src/plugin.ts
303
- function createPlugin(factory) {
304
- return (options = {}) => {
305
- return factory(options);
306
- };
307
- }
308
- const pluginCore = createPlugin((options) => {
309
- const { fabric, pluginManager, resolvePath, resolveName, logger } = options;
310
- return {
311
- name: "core",
312
- options,
313
- key: ["core"],
314
- context() {
315
- return {
316
- get fabric() {
317
- return fabric;
318
- },
319
- get config() {
320
- return options.config;
321
- },
322
- get plugins() {
323
- return options.getPlugins();
324
- },
325
- get plugin() {
326
- return options.plugin;
327
- },
328
- logger,
329
- get fileManager() {
330
- return fabric.context.fileManager;
331
- },
332
- pluginManager,
333
- async addFile(...files) {
334
- const resolvedFiles = await fabric.context.fileManager.add(...files);
335
- if (!Array.isArray(resolvedFiles)) return [resolvedFiles];
336
- return resolvedFiles;
337
- },
338
- resolvePath,
339
- resolveName
340
- };
341
- },
342
- resolvePath(baseName) {
343
- const root = path.resolve(options.config.root, options.config.output.path);
344
- return path.resolve(root, baseName);
345
- },
346
- resolveName(name) {
347
- return name;
348
- }
349
- };
350
- });
351
-
352
- //#endregion
353
- //#region src/PluginManager.ts
354
- var PluginManager = class {
355
- plugins = /* @__PURE__ */ new Set();
356
- events = new EventEmitter();
357
- config;
358
- executed = [];
359
- logger;
360
- options;
361
- #core;
362
- #usedPluginNames = {};
363
- #promiseManager;
364
- constructor(config, options) {
365
- this.config = config;
366
- this.options = options;
367
- this.logger = options.logger;
368
- this.#promiseManager = new PromiseManager({ nullCheck: (state) => !!state?.result });
369
- const core = pluginCore({
370
- fabric: options.fabric,
371
- config,
372
- logger: this.logger,
373
- pluginManager: this,
374
- resolvePath: this.resolvePath.bind(this),
375
- resolveName: this.resolveName.bind(this),
376
- getPlugins: this.#getSortedPlugins.bind(this)
377
- });
378
- this.#core = this.#parse(core, this, core.context.call(null));
379
- [this.#core, ...config.plugins || []].forEach((plugin) => {
380
- const parsedPlugin = this.#parse(plugin, this, this.#core.context);
381
- this.plugins.add(parsedPlugin);
382
- });
383
- return this;
384
- }
385
- getFile({ name, mode, extname: extname$1, pluginKey, options }) {
386
- const baseName = `${name}${extname$1}`;
387
- const path$1 = this.resolvePath({
388
- baseName,
389
- mode,
390
- pluginKey,
391
- options
392
- });
393
- if (!path$1) throw new Error(`Filepath should be defined for resolvedName "${name}" and pluginKey [${JSON.stringify(pluginKey)}]`);
394
- return {
395
- path: path$1,
396
- baseName,
397
- meta: { pluginKey },
398
- sources: []
399
- };
400
- }
401
- resolvePath = (params) => {
402
- if (params.pluginKey) {
403
- const paths = this.hookForPluginSync({
404
- pluginKey: params.pluginKey,
405
- hookName: "resolvePath",
406
- parameters: [
407
- params.baseName,
408
- params.mode,
409
- params.options
410
- ],
411
- message: `Resolving path '${params.baseName}'`
412
- });
413
- if (paths && paths?.length > 1) this.logger.emit("debug", {
414
- date: /* @__PURE__ */ new Date(),
415
- logs: [`Cannot return a path where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : "\""} is not unique enough\n\nPaths: ${JSON.stringify(paths, void 0, 2)}\n\nFalling back on the first item.\n`]
416
- });
417
- return paths?.at(0);
418
- }
419
- return this.hookFirstSync({
420
- hookName: "resolvePath",
421
- parameters: [
422
- params.baseName,
423
- params.mode,
424
- params.options
425
- ],
426
- message: `Resolving path '${params.baseName}'`
427
- }).result;
428
- };
429
- resolveName = (params) => {
430
- if (params.pluginKey) {
431
- const names = this.hookForPluginSync({
432
- pluginKey: params.pluginKey,
433
- hookName: "resolveName",
434
- parameters: [trim(params.name), params.type],
435
- message: `Resolving name '${params.name}' and type '${params.type}'`
436
- });
437
- if (names && names?.length > 1) this.logger.emit("debug", {
438
- date: /* @__PURE__ */ new Date(),
439
- logs: [`Cannot return a name where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : "\""} is not unique enough\n\nNames: ${JSON.stringify(names, void 0, 2)}\n\nFalling back on the first item.\n`]
440
- });
441
- return transformReservedWord(names?.at(0) || params.name);
442
- }
443
- const name = this.hookFirstSync({
444
- hookName: "resolveName",
445
- parameters: [trim(params.name), params.type],
446
- message: `Resolving name '${params.name}' and type '${params.type}'`
447
- }).result;
448
- return transformReservedWord(name);
449
- };
450
- /**
451
- * Instead of calling `pluginManager.events.on` you can use `pluginManager.on`. This one also has better types.
452
- */
453
- on(eventName, handler) {
454
- this.events.on(eventName, handler);
455
- }
456
- /**
457
- * Run a specific hookName for plugin x.
458
- */
459
- async hookForPlugin({ pluginKey, hookName, parameters, message }) {
460
- const plugins = this.getPluginsByKey(hookName, pluginKey);
461
- this.logger.emit("progress_start", {
462
- id: hookName,
463
- size: plugins.length,
464
- message: "Running plugins..."
465
- });
466
- const items = [];
467
- for (const plugin of plugins) {
468
- const result = await this.#execute({
469
- strategy: "hookFirst",
470
- hookName,
471
- parameters,
472
- plugin,
473
- message
474
- });
475
- if (result !== void 0 && result !== null) items.push(result);
476
- }
477
- this.logger.emit("progress_stop", { id: hookName });
478
- return items;
479
- }
480
- /**
481
- * Run a specific hookName for plugin x.
482
- */
483
- hookForPluginSync({ pluginKey, hookName, parameters, message }) {
484
- return this.getPluginsByKey(hookName, pluginKey).map((plugin) => {
485
- return this.#executeSync({
486
- strategy: "hookFirst",
487
- hookName,
488
- parameters,
489
- plugin,
490
- message
491
- });
492
- }).filter(Boolean);
493
- }
494
- /**
495
- * First non-null result stops and will return it's value.
496
- */
497
- async hookFirst({ hookName, parameters, skipped, message }) {
498
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
499
- return skipped ? skipped.has(plugin) : true;
500
- });
501
- this.logger.emit("progress_start", {
502
- id: hookName,
503
- size: plugins.length
504
- });
505
- const promises$1 = plugins.map((plugin) => {
506
- return async () => {
507
- const value = await this.#execute({
508
- strategy: "hookFirst",
509
- hookName,
510
- parameters,
511
- plugin,
512
- message
513
- });
514
- return Promise.resolve({
515
- plugin,
516
- result: value
517
- });
518
- };
519
- });
520
- const result = await this.#promiseManager.run("first", promises$1);
521
- this.logger.emit("progress_stop", { id: hookName });
522
- return result;
523
- }
524
- /**
525
- * First non-null result stops and will return it's value.
526
- */
527
- hookFirstSync({ hookName, parameters, skipped, message }) {
528
- let parseResult = null;
529
- const plugins = this.#getSortedPlugins(hookName).filter((plugin) => {
530
- return skipped ? skipped.has(plugin) : true;
531
- });
532
- for (const plugin of plugins) {
533
- parseResult = {
534
- result: this.#executeSync({
535
- strategy: "hookFirst",
536
- hookName,
537
- parameters,
538
- plugin,
539
- message
540
- }),
541
- plugin
542
- };
543
- if (parseResult?.result != null) break;
544
- }
545
- return parseResult;
546
- }
547
- /**
548
- * Run all plugins in parallel(order will be based on `this.plugin` and if `pre` or `post` is set).
549
- */
550
- async hookParallel({ hookName, parameters, message }) {
551
- const plugins = this.#getSortedPlugins(hookName);
552
- this.logger.emit("progress_start", {
553
- id: hookName,
554
- size: plugins.length
555
- });
556
- const promises$1 = plugins.map((plugin) => {
557
- return () => this.#execute({
558
- strategy: "hookParallel",
559
- hookName,
560
- parameters,
561
- plugin,
562
- message
563
- });
564
- });
565
- const results = await this.#promiseManager.run("parallel", promises$1, { concurrency: this.options.concurrency });
566
- results.forEach((result, index) => {
567
- if (isPromiseRejectedResult(result)) {
568
- const plugin = this.#getSortedPlugins(hookName)[index];
569
- this.#catcher(result.reason, plugin, hookName);
570
- }
571
- });
572
- this.logger.emit("progress_stop", { id: hookName });
573
- return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
574
- }
575
- /**
576
- * Chains plugins
577
- */
578
- async hookSeq({ hookName, parameters, message }) {
579
- const plugins = this.#getSortedPlugins(hookName);
580
- this.logger.emit("progress_start", {
581
- id: hookName,
582
- size: plugins.length
583
- });
584
- const promises$1 = plugins.map((plugin) => {
585
- return () => this.#execute({
586
- strategy: "hookSeq",
587
- hookName,
588
- parameters,
589
- plugin,
590
- message
591
- });
592
- });
593
- await this.#promiseManager.run("seq", promises$1);
594
- this.logger.emit("progress_stop", { id: hookName });
595
- }
596
- #getSortedPlugins(hookName) {
597
- const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
598
- if (hookName) return plugins.filter((plugin) => hookName in plugin);
599
- return plugins.map((plugin) => {
600
- if (plugin.pre) {
601
- if (!plugin.pre.every((pluginName) => plugins.find((pluginToFind) => pluginToFind.name === pluginName))) throw new ValidationPluginError(`This plugin has a pre set that is not valid(${JSON.stringify(plugin.pre, void 0, 2)})`);
602
- }
603
- return plugin;
604
- }).sort((a, b) => {
605
- if (b.pre?.includes(a.name)) return 1;
606
- if (b.post?.includes(a.name)) return -1;
607
- return 0;
608
- });
609
- }
610
- getPluginByKey(pluginKey) {
611
- const plugins = [...this.plugins];
612
- const [searchPluginName] = pluginKey;
613
- return plugins.find((item) => {
614
- const [name] = item.key;
615
- return name === searchPluginName;
616
- });
617
- }
618
- getPluginsByKey(hookName, pluginKey) {
619
- const plugins = [...this.plugins];
620
- const [searchPluginName, searchIdentifier] = pluginKey;
621
- const pluginByPluginName = plugins.filter((plugin) => hookName in plugin).filter((item) => {
622
- const [name, identifier] = item.key;
623
- const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
624
- const nameCheck = name === searchPluginName;
625
- if (searchIdentifier) return identifierCheck && nameCheck;
626
- return nameCheck;
627
- });
628
- if (!pluginByPluginName?.length) {
629
- const corePlugin = plugins.find((plugin) => plugin.name === "core" && hookName in plugin);
630
- if (corePlugin) this.logger.emit("debug", {
631
- date: /* @__PURE__ */ new Date(),
632
- logs: [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`]
633
- });
634
- else this.logger.emit("debug", {
635
- date: /* @__PURE__ */ new Date(),
636
- logs: [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`]
637
- });
638
- return corePlugin ? [corePlugin] : [];
639
- }
640
- return pluginByPluginName;
641
- }
642
- #addExecutedToCallStack(executer) {
643
- if (executer) {
644
- this.events.emit("executed", executer);
645
- this.executed.push(executer);
646
- this.logger.emit("progressed", {
647
- id: executer.hookName,
648
- message: `${executer.plugin.name}: ${executer.message}`
649
- });
650
- }
651
- }
652
- /**
653
- * Run an async plugin hook and return the result.
654
- * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
655
- * @param args Arguments passed to the plugin hook.
656
- * @param plugin The actual pluginObject to run.
657
- */
658
- #execute({ strategy, hookName, parameters, plugin, message }) {
659
- const hook = plugin[hookName];
660
- let output;
661
- if (!hook) return null;
662
- this.events.emit("executing", {
663
- strategy,
664
- hookName,
665
- parameters,
666
- plugin,
667
- message
668
- });
669
- return (async () => {
670
- try {
671
- if (typeof hook === "function") {
672
- const result = await Promise.resolve(hook.apply({
673
- ...this.#core.context,
674
- plugin
675
- }, parameters));
676
- output = result;
677
- this.#addExecutedToCallStack({
678
- parameters,
679
- output,
680
- strategy,
681
- hookName,
682
- plugin,
683
- message
684
- });
685
- return result;
686
- }
687
- output = hook;
688
- this.#addExecutedToCallStack({
689
- parameters,
690
- output,
691
- strategy,
692
- hookName,
693
- plugin,
694
- message
695
- });
696
- return hook;
697
- } catch (e) {
698
- this.#catcher(e, plugin, hookName);
699
- return null;
700
- }
701
- })();
702
- }
703
- /**
704
- * Run a sync plugin hook and return the result.
705
- * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
706
- * @param args Arguments passed to the plugin hook.
707
- * @param plugin The acutal plugin
708
- * @param replaceContext When passed, the plugin context can be overridden.
709
- */
710
- #executeSync({ strategy, hookName, parameters, plugin, message }) {
711
- const hook = plugin[hookName];
712
- let output;
713
- if (!hook) return null;
714
- this.events.emit("executing", {
715
- strategy,
716
- hookName,
717
- parameters,
718
- plugin,
719
- message
720
- });
721
- try {
722
- if (typeof hook === "function") {
723
- const fn = hook.apply({
724
- ...this.#core.context,
725
- plugin
726
- }, parameters);
727
- output = fn;
728
- this.#addExecutedToCallStack({
729
- parameters,
730
- output,
731
- strategy,
732
- hookName,
733
- plugin,
734
- message
735
- });
736
- return fn;
737
- }
738
- output = hook;
739
- this.#addExecutedToCallStack({
740
- parameters,
741
- output,
742
- strategy,
743
- hookName,
744
- plugin,
745
- message
746
- });
747
- return hook;
748
- } catch (e) {
749
- this.#catcher(e, plugin, hookName);
750
- return null;
751
- }
752
- }
753
- #catcher(cause, plugin, hookName) {
754
- const text = `${cause.message} (plugin: ${plugin?.name || "unknown"}, hook: ${hookName || "unknown"})`;
755
- this.logger.emit("error", text, cause);
756
- this.events.emit("error", cause);
757
- }
758
- #parse(plugin, pluginManager, context) {
759
- const usedPluginNames = pluginManager.#usedPluginNames;
760
- setUniqueName(plugin.name, usedPluginNames);
761
- const key = [plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
762
- if (plugin.context && typeof plugin.context === "function") return {
763
- ...plugin,
764
- key,
765
- context: plugin.context.call(context)
766
- };
767
- return {
768
- ...plugin,
769
- key
770
- };
771
- }
772
- static getDependedPlugins(plugins, dependedPluginNames) {
773
- let pluginNames = [];
774
- if (typeof dependedPluginNames === "string") pluginNames = [dependedPluginNames];
775
- else pluginNames = dependedPluginNames;
776
- return pluginNames.map((pluginName) => {
777
- const plugin = plugins.find((plugin$1) => plugin$1.name === pluginName);
778
- if (!plugin) throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
779
- return plugin;
780
- });
781
- }
782
- static get hooks() {
783
- return [
784
- "buildStart",
785
- "resolvePath",
786
- "resolveName",
787
- "buildEnd"
788
- ];
789
- }
790
- };
791
-
792
126
  //#endregion
793
127
  //#region src/build.ts
794
128
  async function setup(options) {
@@ -828,9 +162,10 @@ async function setup(options) {
828
162
  };
829
163
  }
830
164
  async function build(options, overrides) {
831
- const { fabric, files, pluginManager, error } = await safeBuild(options, overrides);
165
+ const { fabric, files, pluginManager, failedPlugins, error } = await safeBuild(options, overrides);
832
166
  if (error) throw error;
833
167
  return {
168
+ failedPlugins,
834
169
  fabric,
835
170
  files,
836
171
  pluginManager,
@@ -839,13 +174,21 @@ async function build(options, overrides) {
839
174
  }
840
175
  async function safeBuild(options, overrides) {
841
176
  const { fabric, pluginManager } = overrides ? overrides : await setup(options);
177
+ const failedPlugins = /* @__PURE__ */ new Set();
842
178
  const config = pluginManager.config;
843
179
  try {
844
- await pluginManager.hookParallel({
845
- hookName: "buildStart",
846
- parameters: [config],
847
- message: "buildStart"
848
- });
180
+ for (const plugin of pluginManager.plugins) {
181
+ const context = pluginManager.getContext(plugin);
182
+ const installer = plugin.install.bind(context);
183
+ try {
184
+ await installer(context);
185
+ } catch (e) {
186
+ failedPlugins.add({
187
+ plugin,
188
+ error: e
189
+ });
190
+ }
191
+ }
849
192
  if (config.output.barrelType) {
850
193
  const rootPath = resolve(resolve(config.root), config.output.path, "index.ts");
851
194
  const rootFile = {
@@ -874,14 +217,14 @@ async function safeBuild(options, overrides) {
874
217
  };
875
218
  await fabric.addFile(rootFile);
876
219
  }
877
- fabric.context.events.on("process:start", ({ files: files$1 }) => {
220
+ fabric.context.on("process:start", ({ files: files$1 }) => {
878
221
  pluginManager.logger.emit("progress_start", {
879
222
  id: "files",
880
223
  size: files$1.length,
881
224
  message: "Writing files ..."
882
225
  });
883
226
  });
884
- fabric.context.events.on("process:progress", async ({ file, source }) => {
227
+ fabric.context.on("process:progress", async ({ file, source }) => {
885
228
  const message = file ? `Writing ${relative(config.root, file.path)}` : "";
886
229
  pluginManager.logger.emit("progressed", {
887
230
  id: "files",
@@ -889,22 +232,20 @@ async function safeBuild(options, overrides) {
889
232
  });
890
233
  if (source) await write(file.path, source, { sanity: false });
891
234
  });
892
- fabric.context.events.on("process:end", () => {
235
+ fabric.context.on("process:end", () => {
893
236
  pluginManager.logger.emit("progress_stop", { id: "files" });
894
237
  });
895
238
  const files = [...fabric.files];
896
239
  await fabric.write({ extension: config.output.extension });
897
- await pluginManager.hookParallel({
898
- hookName: "buildEnd",
899
- message: `Build stopped for ${config.name}`
900
- });
901
240
  return {
241
+ failedPlugins,
902
242
  fabric,
903
243
  files,
904
244
  pluginManager
905
245
  };
906
246
  } catch (e) {
907
247
  return {
248
+ failedPlugins,
908
249
  fabric,
909
250
  files: [],
910
251
  pluginManager,
@@ -914,223 +255,12 @@ async function safeBuild(options, overrides) {
914
255
  }
915
256
 
916
257
  //#endregion
917
- //#region src/utils/TreeNode.ts
918
- var TreeNode = class TreeNode {
919
- data;
920
- parent;
921
- children = [];
922
- #cachedLeaves = void 0;
923
- constructor(data, parent) {
924
- this.data = data;
925
- this.parent = parent;
926
- return this;
927
- }
928
- addChild(data) {
929
- const child = new TreeNode(data, this);
930
- if (!this.children) this.children = [];
931
- this.children.push(child);
932
- return child;
933
- }
934
- get root() {
935
- if (!this.parent) return this;
936
- return this.parent.root;
937
- }
938
- get leaves() {
939
- if (!this.children || this.children.length === 0) return [this];
940
- if (this.#cachedLeaves) return this.#cachedLeaves;
941
- const leaves = [];
942
- if (this.children) for (let i = 0, { length } = this.children; i < length; i++) leaves.push.apply(leaves, this.children[i].leaves);
943
- this.#cachedLeaves = leaves;
944
- return leaves;
945
- }
946
- forEach(callback) {
947
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
948
- callback(this);
949
- if (this.children) for (let i = 0, { length } = this.children; i < length; i++) this.children[i]?.forEach(callback);
950
- return this;
951
- }
952
- findDeep(predicate) {
953
- if (typeof predicate !== "function") throw new TypeError("find() predicate must be a function");
954
- return this.leaves.find(predicate);
955
- }
956
- forEachDeep(callback) {
957
- if (typeof callback !== "function") throw new TypeError("forEach() callback must be a function");
958
- this.leaves.forEach(callback);
959
- }
960
- filterDeep(callback) {
961
- if (typeof callback !== "function") throw new TypeError("filter() callback must be a function");
962
- return this.leaves.filter(callback);
963
- }
964
- mapDeep(callback) {
965
- if (typeof callback !== "function") throw new TypeError("map() callback must be a function");
966
- return this.leaves.map(callback);
967
- }
968
- static build(files, root) {
969
- try {
970
- const filteredTree = buildDirectoryTree(files, root);
971
- if (!filteredTree) return null;
972
- const treeNode = new TreeNode({
973
- name: filteredTree.name,
974
- path: filteredTree.path,
975
- file: filteredTree.file,
976
- type: getMode(filteredTree.path)
977
- });
978
- const recurse = (node, item) => {
979
- const subNode = node.addChild({
980
- name: item.name,
981
- path: item.path,
982
- file: item.file,
983
- type: getMode(item.path)
984
- });
985
- if (item.children?.length) item.children?.forEach((child) => {
986
- recurse(subNode, child);
987
- });
988
- };
989
- filteredTree.children?.forEach((child) => {
990
- recurse(treeNode, child);
991
- });
992
- return treeNode;
993
- } catch (e) {
994
- throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: e });
995
- }
996
- }
997
- };
998
- const normalizePath = (p) => p.replace(/\\/g, "/");
999
- function buildDirectoryTree(files, rootFolder = "") {
1000
- const normalizedRootFolder = normalizePath(rootFolder);
1001
- const rootPrefix = normalizedRootFolder.endsWith("/") ? normalizedRootFolder : `${normalizedRootFolder}/`;
1002
- const filteredFiles = files.filter((file) => {
1003
- const normalizedFilePath = normalizePath(file.path);
1004
- return rootFolder ? normalizedFilePath.startsWith(rootPrefix) && !normalizedFilePath.endsWith(".json") : !normalizedFilePath.endsWith(".json");
1005
- });
1006
- if (filteredFiles.length === 0) return null;
1007
- const root = {
1008
- name: rootFolder || "",
1009
- path: rootFolder || "",
1010
- children: []
1011
- };
1012
- filteredFiles.forEach((file) => {
1013
- const parts = file.path.slice(rootFolder.length).split("/");
1014
- let currentLevel = root.children;
1015
- let currentPath = rootFolder;
1016
- parts.forEach((part, index) => {
1017
- if (index !== 0) currentPath += `/${part}`;
1018
- else currentPath += `${part}`;
1019
- let existingNode = currentLevel.find((node) => node.name === part);
1020
- if (!existingNode) {
1021
- if (index === parts.length - 1) existingNode = {
1022
- name: part,
1023
- file,
1024
- path: currentPath
1025
- };
1026
- else existingNode = {
1027
- name: part,
1028
- path: currentPath,
1029
- children: []
1030
- };
1031
- currentLevel.push(existingNode);
1032
- }
1033
- if (!existingNode.file) currentLevel = existingNode.children;
1034
- });
1035
- });
1036
- return root;
1037
- }
1038
-
1039
- //#endregion
1040
- //#region src/BarrelManager.ts
1041
- var BarrelManager = class {
1042
- #options;
1043
- constructor(options = {}) {
1044
- this.#options = options;
1045
- return this;
1046
- }
1047
- getFiles({ files: generatedFiles, root }) {
1048
- const { logger } = this.#options;
1049
- const cachedFiles = /* @__PURE__ */ new Map();
1050
- TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
1051
- if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) return;
1052
- const barrelFile = {
1053
- path: join(treeNode.parent?.data.path, "index.ts"),
1054
- baseName: "index.ts",
1055
- exports: [],
1056
- sources: []
1057
- };
1058
- const previousBarrelFile = cachedFiles.get(barrelFile.path);
1059
- treeNode.leaves.forEach((item) => {
1060
- if (!item.data.name) return;
1061
- const sources = item.data.file?.sources || [];
1062
- if (!sources.some((source) => source.isIndexable)) logger?.emit("warning", `No isIndexable source found(source should have a name and isIndexable):\nFile: ${JSON.stringify(item.data.file, void 0, 2)}`);
1063
- sources.forEach((source) => {
1064
- if (!item.data.file?.path || !source.isIndexable || !source.name) return;
1065
- if (previousBarrelFile?.sources.some((item$1) => item$1.name === source.name && item$1.isTypeOnly === source.isTypeOnly)) return;
1066
- if (!barrelFile.exports) barrelFile.exports = [];
1067
- if (!!treeNode.parent?.data.path?.split?.("/")?.length) barrelFile.exports.push({
1068
- name: [source.name],
1069
- path: getRelativePath(treeNode.parent?.data.path, item.data.path),
1070
- isTypeOnly: source.isTypeOnly
1071
- });
1072
- else barrelFile.exports.push({
1073
- name: [source.name],
1074
- path: `./${item.data.file.baseName}`,
1075
- isTypeOnly: source.isTypeOnly
1076
- });
1077
- barrelFile.sources.push({
1078
- name: source.name,
1079
- isTypeOnly: source.isTypeOnly,
1080
- value: "",
1081
- isExportable: false,
1082
- isIndexable: false
1083
- });
1084
- });
1085
- });
1086
- if (previousBarrelFile) {
1087
- previousBarrelFile.sources.push(...barrelFile.sources);
1088
- previousBarrelFile.exports?.push(...barrelFile.exports || []);
1089
- } else cachedFiles.set(barrelFile.path, barrelFile);
1090
- });
1091
- return [...cachedFiles.values()];
1092
- }
1093
- };
1094
-
1095
- //#endregion
1096
- //#region src/FileManager.ts
1097
- function getMode(path$1) {
1098
- if (!path$1) return "split";
1099
- return extname(path$1) ? "single" : "split";
1100
- }
1101
- function trimExtName(text) {
1102
- return text.replace(/\.[^/.]+$/, "");
1103
- }
1104
- async function getBarrelFiles(files, { type, meta = {}, root, output, logger }) {
1105
- if (!type || type === "propagate") return [];
1106
- const barrelManager = new BarrelManager({ logger });
1107
- const pathToBuildFrom = join(root, output.path);
1108
- if (trimExtName(pathToBuildFrom).endsWith("index")) {
1109
- logger?.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
1110
- return [];
1111
- }
1112
- const barrelFiles = barrelManager.getFiles({
1113
- files,
1114
- root: pathToBuildFrom,
1115
- meta
1116
- });
1117
- if (type === "all") return barrelFiles.map((file) => {
1118
- return {
1119
- ...file,
1120
- exports: file.exports?.map((exportItem) => {
1121
- return {
1122
- ...exportItem,
1123
- name: void 0
1124
- };
1125
- })
1126
- };
1127
- });
1128
- return barrelFiles.map((indexFile) => {
1129
- return {
1130
- ...indexFile,
1131
- meta
1132
- };
1133
- });
258
+ //#region src/definePlugin.ts
259
+ /**
260
+ * Wraps a plugin builder to make the options parameter optional.
261
+ */
262
+ function definePlugin(build$1) {
263
+ return (options) => build$1(options ?? {});
1134
264
  }
1135
265
 
1136
266
  //#endregion
@@ -1399,5 +529,5 @@ var PackageManager = class PackageManager {
1399
529
  };
1400
530
 
1401
531
  //#endregion
1402
- export { BaseGenerator, PackageManager, PluginManager, PromiseManager, build, build as default, createPlugin, defineConfig, getBarrelFiles, getMode, isInputPath, safeBuild, setup };
532
+ export { BaseGenerator, PackageManager, PluginManager, PromiseManager, build, build as default, defineConfig, definePlugin, getBarrelFiles, getMode, isInputPath, safeBuild, setup };
1403
533
  //# sourceMappingURL=index.js.map