@kubb/core 2.18.4 → 2.18.5

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 (69) hide show
  1. package/dist/chunk-7TB4GNKF.cjs +1268 -0
  2. package/dist/chunk-7TB4GNKF.cjs.map +1 -0
  3. package/dist/{chunk-TIYJPVUG.js → chunk-7UMWFPXG.js} +1 -9
  4. package/dist/chunk-7UMWFPXG.js.map +1 -0
  5. package/dist/{chunk-GRBLCGB5.cjs → chunk-BE4KSMB4.cjs} +5 -5
  6. package/dist/chunk-EPAC7V2R.js +597 -0
  7. package/dist/chunk-EPAC7V2R.js.map +1 -0
  8. package/dist/{chunk-YTLMG2AN.cjs → chunk-FWUA552W.cjs} +29 -29
  9. package/dist/{chunk-NP7GXHZS.cjs → chunk-JI763CHT.cjs} +18 -18
  10. package/dist/{chunk-GG3XRJX3.cjs → chunk-M6VNU2SJ.cjs} +12 -20
  11. package/dist/chunk-M6VNU2SJ.cjs.map +1 -0
  12. package/dist/{chunk-XUCU53HT.cjs → chunk-TCFN5BZ6.cjs} +3 -11
  13. package/dist/chunk-TCFN5BZ6.cjs.map +1 -0
  14. package/dist/index.cjs +1297 -10
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +26 -148
  17. package/dist/index.d.ts +26 -148
  18. package/dist/index.js +991 -22
  19. package/dist/index.js.map +1 -1
  20. package/dist/logger.cjs +3 -4
  21. package/dist/logger.js +1 -2
  22. package/dist/mocks.cjs +15 -14
  23. package/dist/mocks.cjs.map +1 -1
  24. package/dist/mocks.d.cts +4 -2
  25. package/dist/mocks.d.ts +4 -2
  26. package/dist/mocks.js +7 -6
  27. package/dist/mocks.js.map +1 -1
  28. package/dist/transformers.cjs +4 -4
  29. package/dist/utils.cjs +4 -4
  30. package/package.json +8 -18
  31. package/src/BarrelManager.ts +1 -1
  32. package/src/FileManager.ts +36 -167
  33. package/src/PackageManager.ts +1 -1
  34. package/src/PluginManager.ts +5 -5
  35. package/src/build.ts +6 -8
  36. package/src/index.ts +2 -3
  37. package/src/logger.ts +0 -7
  38. package/src/types.ts +3 -2
  39. package/src/utils/TreeNode.ts +1 -1
  40. package/dist/chunk-2F7E62RD.js +0 -85
  41. package/dist/chunk-2F7E62RD.js.map +0 -1
  42. package/dist/chunk-6NMPKKGV.js +0 -1597
  43. package/dist/chunk-6NMPKKGV.js.map +0 -1
  44. package/dist/chunk-7PBKI3OR.cjs +0 -2584
  45. package/dist/chunk-7PBKI3OR.cjs.map +0 -1
  46. package/dist/chunk-AQJCCWPW.cjs +0 -75
  47. package/dist/chunk-AQJCCWPW.cjs.map +0 -1
  48. package/dist/chunk-GG3XRJX3.cjs.map +0 -1
  49. package/dist/chunk-MDO6MCFJ.js +0 -65
  50. package/dist/chunk-MDO6MCFJ.js.map +0 -1
  51. package/dist/chunk-TIYJPVUG.js.map +0 -1
  52. package/dist/chunk-X5IJHUXJ.cjs +0 -2332
  53. package/dist/chunk-X5IJHUXJ.cjs.map +0 -1
  54. package/dist/chunk-XUCU53HT.cjs.map +0 -1
  55. package/dist/fs.cjs +0 -23
  56. package/dist/fs.cjs.map +0 -1
  57. package/dist/fs.d.cts +0 -5
  58. package/dist/fs.d.ts +0 -5
  59. package/dist/fs.js +0 -18
  60. package/dist/fs.js.map +0 -1
  61. package/dist/write-CN8f7bYv.d.cts +0 -10
  62. package/dist/write-CN8f7bYv.d.ts +0 -10
  63. package/src/fs/clean.ts +0 -5
  64. package/src/fs/index.ts +0 -3
  65. package/src/fs/read.ts +0 -68
  66. package/src/fs/write.ts +0 -83
  67. /package/dist/{chunk-GRBLCGB5.cjs.map → chunk-BE4KSMB4.cjs.map} +0 -0
  68. /package/dist/{chunk-YTLMG2AN.cjs.map → chunk-FWUA552W.cjs.map} +0 -0
  69. /package/dist/{chunk-NP7GXHZS.cjs.map → chunk-JI763CHT.cjs.map} +0 -0
package/dist/index.js CHANGED
@@ -1,30 +1,999 @@
1
1
  import {
2
- FileManager,
3
- Generator,
4
- KubbFile,
5
- PackageManager,
6
- PluginManager,
7
- PromiseManager,
8
- Warning,
9
- build,
10
- createPlugin,
11
- defineConfig,
12
- isInputPath,
13
- kubb_exports,
14
- safeBuild
15
- } from "./chunk-6NMPKKGV.js";
16
- import "./chunk-UCKFXEKM.js";
17
- import "./chunk-FRT5NM5I.js";
2
+ EventEmitter,
3
+ LogLevel,
4
+ createLogger,
5
+ p,
6
+ randomCliColour
7
+ } from "./chunk-7UMWFPXG.js";
8
+ import {
9
+ FileManager
10
+ } from "./chunk-EPAC7V2R.js";
11
+ import {
12
+ transformReservedWord
13
+ } from "./chunk-UCKFXEKM.js";
14
+ import {
15
+ URLPath,
16
+ setUniqueName
17
+ } from "./chunk-FRT5NM5I.js";
18
18
  import "./chunk-4X5FFJPJ.js";
19
- import "./chunk-TIYJPVUG.js";
20
- import "./chunk-MDO6MCFJ.js";
21
- import "./chunk-2F7E62RD.js";
22
- import "./chunk-Z4BLTVTB.js";
19
+ import {
20
+ __privateAdd,
21
+ __privateGet,
22
+ __privateMethod,
23
+ __privateSet
24
+ } from "./chunk-Z4BLTVTB.js";
25
+
26
+ // src/build.ts
27
+ import { clean, read } from "@kubb/fs";
28
+
29
+ // src/PluginManager.ts
30
+ import PQueue from "p-queue";
31
+ import { readSync } from "@kubb/fs";
32
+
33
+ // src/utils/executeStrategies.ts
34
+ function hookSeq(promises) {
35
+ return promises.filter(Boolean).reduce(
36
+ (promise, func) => {
37
+ if (typeof func !== "function") {
38
+ throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
39
+ }
40
+ return promise.then((state) => {
41
+ const calledFunc = func(state);
42
+ if (calledFunc) {
43
+ return calledFunc.then(Array.prototype.concat.bind(state));
44
+ }
45
+ });
46
+ },
47
+ Promise.resolve([])
48
+ );
49
+ }
50
+ function hookFirst(promises, nullCheck = (state) => state !== null) {
51
+ let promise = Promise.resolve(null);
52
+ for (const func of promises.filter(Boolean)) {
53
+ promise = promise.then((state) => {
54
+ if (nullCheck(state)) {
55
+ return state;
56
+ }
57
+ const calledFunc = func(state);
58
+ return calledFunc;
59
+ });
60
+ }
61
+ return promise;
62
+ }
63
+ function hookParallel(promises) {
64
+ return Promise.allSettled(promises.filter(Boolean).map((promise) => promise()));
65
+ }
66
+
67
+ // src/PromiseManager.ts
68
+ var _options;
69
+ var PromiseManager = class {
70
+ constructor(options = {}) {
71
+ __privateAdd(this, _options, {});
72
+ __privateSet(this, _options, options);
73
+ return this;
74
+ }
75
+ run(strategy, promises) {
76
+ if (strategy === "seq") {
77
+ return hookSeq(promises);
78
+ }
79
+ if (strategy === "first") {
80
+ return hookFirst(promises, __privateGet(this, _options).nullCheck);
81
+ }
82
+ if (strategy === "parallel") {
83
+ return hookParallel(promises);
84
+ }
85
+ throw new Error(`${strategy} not implemented`);
86
+ }
87
+ };
88
+ _options = new WeakMap();
89
+ function isPromise(result) {
90
+ return !!result && typeof result?.then === "function";
91
+ }
92
+ function isPromiseRejectedResult(result) {
93
+ return result.status === "rejected";
94
+ }
95
+
96
+ // src/errors.ts
97
+ var Warning = class extends Error {
98
+ constructor(message, options) {
99
+ super(message, { cause: options?.cause });
100
+ this.name = "Warning";
101
+ }
102
+ };
103
+ var ValidationPluginError = class extends Error {
104
+ };
105
+
106
+ // src/plugin.ts
107
+ import path from "path";
108
+
109
+ // src/utils/cache.ts
110
+ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
111
+ return {
112
+ set(id, value) {
113
+ Store[id] = [0, value];
114
+ },
115
+ get(id) {
116
+ const item = Store[id];
117
+ if (!item) {
118
+ return null;
119
+ }
120
+ item[0] = 0;
121
+ return item[1];
122
+ },
123
+ has(id) {
124
+ const item = Store[id];
125
+ if (!item) {
126
+ return false;
127
+ }
128
+ item[0] = 0;
129
+ return true;
130
+ },
131
+ delete(id) {
132
+ return delete Store[id];
133
+ }
134
+ };
135
+ }
136
+
137
+ // src/plugin.ts
138
+ function createPlugin(factory) {
139
+ return (options = {}) => {
140
+ return factory(options);
141
+ };
142
+ }
143
+ var pluginCore = createPlugin((options) => {
144
+ const { fileManager, pluginManager, resolvePath, resolveName, logger } = options;
145
+ return {
146
+ name: "core",
147
+ options,
148
+ key: ["core"],
149
+ api() {
150
+ return {
151
+ get config() {
152
+ return options.config;
153
+ },
154
+ get plugins() {
155
+ return options.getPlugins();
156
+ },
157
+ get plugin() {
158
+ return options.plugin;
159
+ },
160
+ logger,
161
+ fileManager,
162
+ pluginManager,
163
+ async addFile(...files) {
164
+ const resolvedFiles = await fileManager.add(...files);
165
+ if (!Array.isArray(resolvedFiles)) {
166
+ return [resolvedFiles];
167
+ }
168
+ return resolvedFiles;
169
+ },
170
+ resolvePath,
171
+ resolveName,
172
+ cache: createPluginCache()
173
+ };
174
+ },
175
+ resolvePath(baseName) {
176
+ const root = path.resolve(this.config.root, this.config.output.path);
177
+ return path.resolve(root, baseName);
178
+ },
179
+ resolveName(name) {
180
+ return name;
181
+ }
182
+ };
183
+ });
184
+
185
+ // src/PluginManager.ts
186
+ var _core, _usedPluginNames, _promiseManager, _getSortedPlugins, getSortedPlugins_fn, _addExecutedToCallStack, addExecutedToCallStack_fn, _execute, execute_fn, _executeSync, executeSync_fn, _catcher, catcher_fn, _parse, parse_fn;
187
+ var PluginManager = class {
188
+ constructor(config, options) {
189
+ __privateAdd(this, _getSortedPlugins);
190
+ __privateAdd(this, _addExecutedToCallStack);
191
+ /**
192
+ * Run an async plugin hook and return the result.
193
+ * @param hookName Name of the plugin hook. Must be either in `PluginHooks` or `OutputPluginValueHooks`.
194
+ * @param args Arguments passed to the plugin hook.
195
+ * @param plugin The actual pluginObject to run.
196
+ */
197
+ // Implementation signature
198
+ __privateAdd(this, _execute);
199
+ /**
200
+ * Run a sync plugin hook and return the result.
201
+ * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
202
+ * @param args Arguments passed to the plugin hook.
203
+ * @param plugin The acutal plugin
204
+ * @param replaceContext When passed, the plugin context can be overridden.
205
+ */
206
+ __privateAdd(this, _executeSync);
207
+ __privateAdd(this, _catcher);
208
+ __privateAdd(this, _parse);
209
+ this.events = new EventEmitter();
210
+ this.executed = [];
211
+ __privateAdd(this, _core, void 0);
212
+ __privateAdd(this, _usedPluginNames, {});
213
+ __privateAdd(this, _promiseManager, void 0);
214
+ this.resolvePath = (params) => {
215
+ if (params.pluginKey) {
216
+ const paths = this.hookForPluginSync({
217
+ pluginKey: params.pluginKey,
218
+ hookName: "resolvePath",
219
+ parameters: [params.baseName, params.mode, params.options]
220
+ });
221
+ if (paths && paths?.length > 1) {
222
+ this.logger.emit("debug", [
223
+ `Cannot return a path where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
224
+
225
+ Paths: ${JSON.stringify(paths, void 0, 2)}
226
+
227
+ Falling back on the first item.
228
+ `
229
+ ]);
230
+ }
231
+ return paths?.at(0);
232
+ }
233
+ return this.hookFirstSync({
234
+ hookName: "resolvePath",
235
+ parameters: [params.baseName, params.mode, params.options]
236
+ }).result;
237
+ };
238
+ this.resolveName = (params) => {
239
+ if (params.pluginKey) {
240
+ const names = this.hookForPluginSync({
241
+ pluginKey: params.pluginKey,
242
+ hookName: "resolveName",
243
+ parameters: [params.name, params.type]
244
+ });
245
+ if (names && names?.length > 1) {
246
+ this.logger.emit("debug", [
247
+ `Cannot return a name where the 'pluginKey' ${params.pluginKey ? JSON.stringify(params.pluginKey) : '"'} is not unique enough
248
+
249
+ Names: ${JSON.stringify(names, void 0, 2)}
250
+
251
+ Falling back on the first item.
252
+ `
253
+ ]);
254
+ }
255
+ return transformReservedWord(names?.at(0) || params.name);
256
+ }
257
+ const name = this.hookFirstSync({
258
+ hookName: "resolveName",
259
+ parameters: [params.name, params.type]
260
+ }).result;
261
+ return transformReservedWord(name);
262
+ };
263
+ this.config = config;
264
+ this.logger = options.logger;
265
+ this.queue = new PQueue({ concurrency: 1 });
266
+ this.fileManager = new FileManager({
267
+ task: options.task,
268
+ queue: this.queue
269
+ });
270
+ __privateSet(this, _promiseManager, new PromiseManager({
271
+ nullCheck: (state) => !!state?.result
272
+ }));
273
+ const plugins = config.plugins || [];
274
+ const core = pluginCore({
275
+ config,
276
+ logger: this.logger,
277
+ pluginManager: this,
278
+ fileManager: this.fileManager,
279
+ resolvePath: this.resolvePath.bind(this),
280
+ resolveName: this.resolveName.bind(this),
281
+ getPlugins: __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).bind(this)
282
+ });
283
+ __privateSet(this, _core, __privateMethod(this, _parse, parse_fn).call(this, core, this, core.api.call(null)));
284
+ this.plugins = [__privateGet(this, _core), ...plugins].map((plugin) => {
285
+ return __privateMethod(this, _parse, parse_fn).call(this, plugin, this, __privateGet(this, _core).api);
286
+ });
287
+ return this;
288
+ }
289
+ getFile({ name, mode, extName, pluginKey, options }) {
290
+ let source = "";
291
+ const baseName = `${name}${extName}`;
292
+ const path2 = this.resolvePath({ baseName, mode, pluginKey, options });
293
+ if (!path2) {
294
+ throw new Error(`Filepath should be defined for resolvedName "${name}" and pluginKey [${JSON.stringify(pluginKey)}]`);
295
+ }
296
+ try {
297
+ source = readSync(path2);
298
+ } catch (_e) {
299
+ }
300
+ return {
301
+ path: path2,
302
+ baseName,
303
+ meta: {
304
+ pluginKey
305
+ },
306
+ source
307
+ };
308
+ }
309
+ /**
310
+ * Instead of calling `pluginManager.events.on` you can use `pluginManager.on`. This one also has better types.
311
+ */
312
+ on(eventName, handler) {
313
+ this.events.on(eventName, handler);
314
+ }
315
+ /**
316
+ * Run a specific hookName for plugin x.
317
+ */
318
+ hookForPlugin({
319
+ pluginKey,
320
+ hookName,
321
+ parameters
322
+ }) {
323
+ const plugins = this.getPluginsByKey(hookName, pluginKey);
324
+ const promises = plugins.map((plugin) => {
325
+ return __privateMethod(this, _execute, execute_fn).call(this, {
326
+ strategy: "hookFirst",
327
+ hookName,
328
+ parameters,
329
+ plugin
330
+ });
331
+ }).filter(Boolean);
332
+ return Promise.all(promises);
333
+ }
334
+ /**
335
+ * Run a specific hookName for plugin x.
336
+ */
337
+ hookForPluginSync({
338
+ pluginKey,
339
+ hookName,
340
+ parameters
341
+ }) {
342
+ const plugins = this.getPluginsByKey(hookName, pluginKey);
343
+ return plugins.map((plugin) => {
344
+ return __privateMethod(this, _executeSync, executeSync_fn).call(this, {
345
+ strategy: "hookFirst",
346
+ hookName,
347
+ parameters,
348
+ plugin
349
+ });
350
+ }).filter(Boolean);
351
+ }
352
+ /**
353
+ * First non-null result stops and will return it's value.
354
+ */
355
+ async hookFirst({
356
+ hookName,
357
+ parameters,
358
+ skipped
359
+ }) {
360
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).filter((plugin) => {
361
+ return skipped ? skipped.has(plugin) : true;
362
+ }).map((plugin) => {
363
+ return async () => {
364
+ const value = await __privateMethod(this, _execute, execute_fn).call(this, {
365
+ strategy: "hookFirst",
366
+ hookName,
367
+ parameters,
368
+ plugin
369
+ });
370
+ return Promise.resolve({
371
+ plugin,
372
+ result: value
373
+ });
374
+ };
375
+ });
376
+ return __privateGet(this, _promiseManager).run("first", promises);
377
+ }
378
+ /**
379
+ * First non-null result stops and will return it's value.
380
+ */
381
+ hookFirstSync({
382
+ hookName,
383
+ parameters,
384
+ skipped
385
+ }) {
386
+ let parseResult = null;
387
+ for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
388
+ if (skipped?.has(plugin)) {
389
+ continue;
390
+ }
391
+ parseResult = {
392
+ result: __privateMethod(this, _executeSync, executeSync_fn).call(this, {
393
+ strategy: "hookFirst",
394
+ hookName,
395
+ parameters,
396
+ plugin
397
+ }),
398
+ plugin
399
+ };
400
+ if (parseResult?.result != null) {
401
+ break;
402
+ }
403
+ }
404
+ return parseResult;
405
+ }
406
+ /**
407
+ * Run all plugins in parallel(order will be based on `this.plugin` and if `pre` or `post` is set).
408
+ */
409
+ async hookParallel({
410
+ hookName,
411
+ parameters
412
+ }) {
413
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
414
+ return () => __privateMethod(this, _execute, execute_fn).call(this, {
415
+ strategy: "hookParallel",
416
+ hookName,
417
+ parameters,
418
+ plugin
419
+ });
420
+ });
421
+ const results = await __privateGet(this, _promiseManager).run("parallel", promises);
422
+ results.forEach((result, index) => {
423
+ if (isPromiseRejectedResult(result)) {
424
+ const plugin = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)[index];
425
+ __privateMethod(this, _catcher, catcher_fn).call(this, result.reason, plugin, hookName);
426
+ }
427
+ });
428
+ return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
429
+ }
430
+ /**
431
+ * Chain all plugins, `reduce` can be passed through to handle every returned value. The return value of the first plugin will be used as the first parameter for the plugin after that.
432
+ */
433
+ hookReduceArg0({
434
+ hookName,
435
+ parameters,
436
+ reduce
437
+ }) {
438
+ const [argument0, ...rest] = parameters;
439
+ let promise = Promise.resolve(argument0);
440
+ for (const plugin of __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this)) {
441
+ promise = promise.then((arg0) => {
442
+ const value = __privateMethod(this, _execute, execute_fn).call(this, {
443
+ strategy: "hookReduceArg0",
444
+ hookName,
445
+ parameters: [arg0, ...rest],
446
+ plugin
447
+ });
448
+ return value;
449
+ }).then((result) => reduce.call(__privateGet(this, _core).api, argument0, result, plugin));
450
+ }
451
+ return promise;
452
+ }
453
+ /**
454
+ * Chains plugins
455
+ */
456
+ async hookSeq({ hookName, parameters }) {
457
+ const promises = __privateMethod(this, _getSortedPlugins, getSortedPlugins_fn).call(this).map((plugin) => {
458
+ return () => __privateMethod(this, _execute, execute_fn).call(this, {
459
+ strategy: "hookSeq",
460
+ hookName,
461
+ parameters,
462
+ plugin
463
+ });
464
+ });
465
+ return __privateGet(this, _promiseManager).run("seq", promises);
466
+ }
467
+ getPluginsByKey(hookName, pluginKey) {
468
+ const plugins = [...this.plugins];
469
+ const [searchPluginName, searchIdentifier] = pluginKey;
470
+ const pluginByPluginName = plugins.filter((plugin) => plugin[hookName]).filter((item) => {
471
+ const [name, identifier] = item.key;
472
+ const identifierCheck = identifier?.toString() === searchIdentifier?.toString();
473
+ const nameCheck = name === searchPluginName;
474
+ if (searchIdentifier) {
475
+ return identifierCheck && nameCheck;
476
+ }
477
+ return nameCheck;
478
+ });
479
+ if (!pluginByPluginName?.length) {
480
+ const corePlugin = plugins.find((plugin) => plugin.name === "core" && plugin[hookName]);
481
+ if (corePlugin) {
482
+ this.logger.emit("debug", [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, falling back on the '@kubb/core' plugin`]);
483
+ } else {
484
+ this.logger.emit("debug", [`No hook '${hookName}' for pluginKey '${JSON.stringify(pluginKey)}' found, no fallback found in the '@kubb/core' plugin`]);
485
+ }
486
+ return corePlugin ? [corePlugin] : [];
487
+ }
488
+ return pluginByPluginName;
489
+ }
490
+ static getDependedPlugins(plugins, dependedPluginNames) {
491
+ let pluginNames = [];
492
+ if (typeof dependedPluginNames === "string") {
493
+ pluginNames = [dependedPluginNames];
494
+ } else {
495
+ pluginNames = dependedPluginNames;
496
+ }
497
+ return pluginNames.map((pluginName) => {
498
+ const plugin = plugins.find((plugin2) => plugin2.name === pluginName);
499
+ if (!plugin) {
500
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
501
+ }
502
+ return plugin;
503
+ });
504
+ }
505
+ static get hooks() {
506
+ return ["buildStart", "resolvePath", "resolveName", "load", "transform", "writeFile", "buildEnd"];
507
+ }
508
+ };
509
+ _core = new WeakMap();
510
+ _usedPluginNames = new WeakMap();
511
+ _promiseManager = new WeakMap();
512
+ _getSortedPlugins = new WeakSet();
513
+ getSortedPlugins_fn = function(hookName) {
514
+ const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
515
+ if (hookName) {
516
+ if (this.logger.logLevel === LogLevel.info) {
517
+ const containsHookName = plugins.some((item) => item[hookName]);
518
+ if (!containsHookName) {
519
+ this.logger.emit("warning", `No hook ${hookName} found`);
520
+ }
521
+ }
522
+ return plugins.filter((item) => item[hookName]);
523
+ }
524
+ return plugins.map((plugin) => {
525
+ if (plugin.pre) {
526
+ const isValid = plugin.pre.every((pluginName) => plugins.find((pluginToFind) => pluginToFind.name === pluginName));
527
+ if (!isValid) {
528
+ throw new ValidationPluginError(`This plugin has a pre set that is not valid(${JSON.stringify(plugin.pre, void 0, 2)})`);
529
+ }
530
+ }
531
+ return plugin;
532
+ }).sort((a, b) => {
533
+ if (b.pre?.includes(a.name)) {
534
+ return 1;
535
+ }
536
+ if (b.post?.includes(a.name)) {
537
+ return -1;
538
+ }
539
+ return 0;
540
+ });
541
+ };
542
+ _addExecutedToCallStack = new WeakSet();
543
+ addExecutedToCallStack_fn = function(executer) {
544
+ if (executer) {
545
+ this.events.emit("executed", executer);
546
+ this.executed.push(executer);
547
+ }
548
+ };
549
+ _execute = new WeakSet();
550
+ execute_fn = function({
551
+ strategy,
552
+ hookName,
553
+ parameters,
554
+ plugin
555
+ }) {
556
+ const hook = plugin[hookName];
557
+ let output;
558
+ if (!hook) {
559
+ return null;
560
+ }
561
+ this.events.emit("execute", { strategy, hookName, parameters, plugin });
562
+ const task = Promise.resolve().then(() => {
563
+ if (typeof hook === "function") {
564
+ const possiblePromiseResult = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
565
+ if (isPromise(possiblePromiseResult)) {
566
+ return Promise.resolve(possiblePromiseResult);
567
+ }
568
+ return possiblePromiseResult;
569
+ }
570
+ return hook;
571
+ }).then((result) => {
572
+ output = result;
573
+ __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
574
+ parameters,
575
+ output,
576
+ strategy,
577
+ hookName,
578
+ plugin
579
+ });
580
+ return result;
581
+ }).catch((e) => {
582
+ __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
583
+ return null;
584
+ });
585
+ return task;
586
+ };
587
+ _executeSync = new WeakSet();
588
+ executeSync_fn = function({
589
+ strategy,
590
+ hookName,
591
+ parameters,
592
+ plugin
593
+ }) {
594
+ const hook = plugin[hookName];
595
+ let output;
596
+ if (!hook) {
597
+ return null;
598
+ }
599
+ this.events.emit("execute", { strategy, hookName, parameters, plugin });
600
+ try {
601
+ if (typeof hook === "function") {
602
+ const fn = hook.apply({ ...__privateGet(this, _core).api, plugin }, parameters);
603
+ output = fn;
604
+ return fn;
605
+ }
606
+ output = hook;
607
+ __privateMethod(this, _addExecutedToCallStack, addExecutedToCallStack_fn).call(this, {
608
+ parameters,
609
+ output,
610
+ strategy,
611
+ hookName,
612
+ plugin
613
+ });
614
+ return hook;
615
+ } catch (e) {
616
+ __privateMethod(this, _catcher, catcher_fn).call(this, e, plugin, hookName);
617
+ return null;
618
+ }
619
+ };
620
+ _catcher = new WeakSet();
621
+ catcher_fn = function(cause, plugin, hookName) {
622
+ const text = `${cause.message} (plugin: ${plugin?.name || "unknown"}, hook: ${hookName || "unknown"})`;
623
+ this.logger.emit("error", text, cause);
624
+ this.events.emit("error", cause);
625
+ };
626
+ _parse = new WeakSet();
627
+ parse_fn = function(plugin, pluginManager, context) {
628
+ const usedPluginNames = __privateGet(pluginManager, _usedPluginNames);
629
+ setUniqueName(plugin.name, usedPluginNames);
630
+ const key = [plugin.name, usedPluginNames[plugin.name]].filter(Boolean);
631
+ if (!plugin.transform) {
632
+ plugin.transform = function transform(_path, code) {
633
+ return code;
634
+ };
635
+ }
636
+ if (plugin.api && typeof plugin.api === "function") {
637
+ const api = plugin.api.call(context);
638
+ return {
639
+ ...plugin,
640
+ key,
641
+ api
642
+ };
643
+ }
644
+ return {
645
+ ...plugin,
646
+ key
647
+ };
648
+ };
649
+
650
+ // src/config.ts
651
+ function defineConfig(options) {
652
+ return options;
653
+ }
654
+ function isInputPath(result) {
655
+ return !!result && "path" in result;
656
+ }
657
+
658
+ // src/build.ts
659
+ async function transformReducer(_previousCode, result, _plugin) {
660
+ return result;
661
+ }
662
+ async function setup(options) {
663
+ const { config, logger = createLogger({ logLevel: LogLevel.silent }) } = options;
664
+ let count = 0;
665
+ try {
666
+ if (isInputPath(config) && !new URLPath(config.input.path).isURL) {
667
+ await read(config.input.path);
668
+ }
669
+ } catch (e) {
670
+ if (isInputPath(config)) {
671
+ throw new Error(
672
+ `Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${p.dim(config.input.path)}`,
673
+ {
674
+ cause: e
675
+ }
676
+ );
677
+ }
678
+ }
679
+ if (config.output.clean) {
680
+ await clean(config.output.path);
681
+ }
682
+ const task = async (file) => {
683
+ const { path: path2 } = file;
684
+ let source = await FileManager.getSource(file);
685
+ const { result: loadedResult } = await pluginManager.hookFirst({
686
+ hookName: "load",
687
+ parameters: [path2]
688
+ });
689
+ if (loadedResult && isPromise(loadedResult)) {
690
+ source = await loadedResult;
691
+ }
692
+ if (loadedResult && !isPromise(loadedResult)) {
693
+ source = loadedResult;
694
+ }
695
+ if (source) {
696
+ source = await pluginManager.hookReduceArg0({
697
+ hookName: "transform",
698
+ parameters: [path2, source],
699
+ reduce: transformReducer
700
+ });
701
+ if (config.output.write || config.output.write === void 0) {
702
+ if (file.meta?.pluginKey) {
703
+ await pluginManager.hookForPlugin({
704
+ pluginKey: file.meta?.pluginKey,
705
+ hookName: "writeFile",
706
+ parameters: [path2, source]
707
+ });
708
+ }
709
+ await pluginManager.hookFirst({
710
+ hookName: "writeFile",
711
+ parameters: [path2, source]
712
+ });
713
+ }
714
+ }
715
+ return {
716
+ ...file,
717
+ source: source || ""
718
+ };
719
+ };
720
+ const pluginManager = new PluginManager(config, { logger, task });
721
+ pluginManager.on("execute", (executer) => {
722
+ const { hookName, parameters, plugin } = executer;
723
+ if (hookName === "writeFile") {
724
+ const [code] = parameters;
725
+ logger.emit("debug", [`PluginKey ${p.dim(JSON.stringify(plugin.key))}
726
+ with source
727
+
728
+ ${code}`]);
729
+ }
730
+ });
731
+ pluginManager.queue.on("add", () => {
732
+ if (logger.logLevel !== LogLevel.info) {
733
+ return;
734
+ }
735
+ if (count === 0) {
736
+ logger.emit("start", "\u{1F4BE} Writing");
737
+ }
738
+ });
739
+ pluginManager.queue.on("active", () => {
740
+ if (logger.logLevel !== LogLevel.info) {
741
+ return;
742
+ }
743
+ if (logger.spinner && pluginManager.queue.size > 0) {
744
+ const text = `Item: ${count} Size: ${pluginManager.queue.size} Pending: ${pluginManager.queue.pending}`;
745
+ logger.spinner.suffixText = p.dim(text);
746
+ }
747
+ ++count;
748
+ });
749
+ pluginManager.queue.on("completed", () => {
750
+ if (logger.logLevel !== LogLevel.info) {
751
+ return;
752
+ }
753
+ if (logger.spinner) {
754
+ const text = `Item: ${count} Size: ${pluginManager.queue.size} Pending: ${pluginManager.queue.pending}`;
755
+ logger.spinner.suffixText = p.dim(text);
756
+ }
757
+ });
758
+ pluginManager.on("executed", (executer) => {
759
+ const { hookName, plugin, output, parameters } = executer;
760
+ const logs = [
761
+ `${randomCliColour(plugin.name)} Executing ${hookName}`,
762
+ parameters && `${p.bgWhite("Parameters")} ${randomCliColour(plugin.name)} ${hookName}`,
763
+ JSON.stringify(parameters, void 0, 2),
764
+ output && `${p.bgWhite("Output")} ${randomCliColour(plugin.name)} ${hookName}`,
765
+ output
766
+ ].filter(Boolean);
767
+ logger.emit("debug", logs);
768
+ });
769
+ return pluginManager;
770
+ }
771
+ async function build(options) {
772
+ const pluginManager = await setup(options);
773
+ const { fileManager, logger } = pluginManager;
774
+ await pluginManager.hookParallel({
775
+ hookName: "buildStart",
776
+ parameters: [options.config]
777
+ });
778
+ await pluginManager.hookParallel({ hookName: "buildEnd" });
779
+ if (logger.logLevel === LogLevel.info) {
780
+ logger.emit("end", "\u{1F4BE} Writing completed");
781
+ }
782
+ const files = await Promise.all(
783
+ fileManager.files.map(async (file) => ({
784
+ ...file,
785
+ source: await FileManager.getSource(file)
786
+ }))
787
+ );
788
+ return {
789
+ files,
790
+ pluginManager
791
+ };
792
+ }
793
+ async function safeBuild(options) {
794
+ const pluginManager = await setup(options);
795
+ const { fileManager, logger } = pluginManager;
796
+ try {
797
+ await pluginManager.hookParallel({
798
+ hookName: "buildStart",
799
+ parameters: [options.config]
800
+ });
801
+ await pluginManager.hookParallel({ hookName: "buildEnd" });
802
+ if (logger.logLevel === LogLevel.info) {
803
+ logger.emit("end", "\u{1F4BE} Writing completed");
804
+ }
805
+ } catch (e) {
806
+ const files2 = await Promise.all(
807
+ fileManager.files.map(async (file) => ({
808
+ ...file,
809
+ source: await FileManager.getSource(file)
810
+ }))
811
+ );
812
+ return {
813
+ files: files2,
814
+ pluginManager,
815
+ error: e
816
+ };
817
+ }
818
+ const files = await Promise.all(
819
+ fileManager.files.map(async (file) => ({
820
+ ...file,
821
+ source: await FileManager.getSource(file)
822
+ }))
823
+ );
824
+ return {
825
+ files,
826
+ pluginManager
827
+ };
828
+ }
829
+
830
+ // src/Generator.ts
831
+ var _options2, _context;
832
+ var Generator = class {
833
+ constructor(options, context) {
834
+ __privateAdd(this, _options2, {});
835
+ __privateAdd(this, _context, {});
836
+ if (context) {
837
+ __privateSet(this, _context, context);
838
+ }
839
+ if (options) {
840
+ __privateSet(this, _options2, options);
841
+ }
842
+ return this;
843
+ }
844
+ get options() {
845
+ return __privateGet(this, _options2);
846
+ }
847
+ get context() {
848
+ return __privateGet(this, _context);
849
+ }
850
+ set options(options) {
851
+ __privateSet(this, _options2, { ...__privateGet(this, _options2), ...options });
852
+ }
853
+ };
854
+ _options2 = new WeakMap();
855
+ _context = new WeakMap();
856
+
857
+ // src/PackageManager.ts
858
+ import mod from "module";
859
+ import os from "os";
860
+ import { pathToFileURL } from "url";
861
+ import { findUp, findUpSync } from "find-up";
862
+ import { coerce, satisfies } from "semver";
863
+ import { read as read2, readSync as readSync2 } from "@kubb/fs";
864
+ var _cache, _cwd, _SLASHES, _match, match_fn;
865
+ var _PackageManager = class _PackageManager {
866
+ constructor(workspace) {
867
+ __privateAdd(this, _match);
868
+ __privateAdd(this, _cwd, void 0);
869
+ __privateAdd(this, _SLASHES, /* @__PURE__ */ new Set(["/", "\\"]));
870
+ if (workspace) {
871
+ __privateSet(this, _cwd, workspace);
872
+ }
873
+ return this;
874
+ }
875
+ set workspace(workspace) {
876
+ __privateSet(this, _cwd, workspace);
877
+ }
878
+ get workspace() {
879
+ return __privateGet(this, _cwd);
880
+ }
881
+ normalizeDirectory(directory) {
882
+ if (!__privateGet(this, _SLASHES).has(directory[directory.length - 1])) {
883
+ return `${directory}/`;
884
+ }
885
+ return directory;
886
+ }
887
+ getLocation(path2) {
888
+ let location = path2;
889
+ if (__privateGet(this, _cwd)) {
890
+ const require2 = mod.createRequire(this.normalizeDirectory(__privateGet(this, _cwd)));
891
+ location = require2.resolve(path2);
892
+ }
893
+ return location;
894
+ }
895
+ async import(path2) {
896
+ try {
897
+ let location = this.getLocation(path2);
898
+ if (os.platform() === "win32") {
899
+ location = pathToFileURL(location).href;
900
+ }
901
+ const module = await import(location);
902
+ return module?.default ?? module;
903
+ } catch (e) {
904
+ console.log(e);
905
+ return void 0;
906
+ }
907
+ }
908
+ async getPackageJSON() {
909
+ const pkgPath = await findUp(["package.json"], {
910
+ cwd: __privateGet(this, _cwd)
911
+ });
912
+ if (!pkgPath) {
913
+ return void 0;
914
+ }
915
+ const json = await read2(pkgPath);
916
+ return JSON.parse(json);
917
+ }
918
+ getPackageJSONSync() {
919
+ const pkgPath = findUpSync(["package.json"], {
920
+ cwd: __privateGet(this, _cwd)
921
+ });
922
+ if (!pkgPath) {
923
+ return void 0;
924
+ }
925
+ const json = readSync2(pkgPath);
926
+ return JSON.parse(json);
927
+ }
928
+ static setVersion(dependency, version) {
929
+ __privateGet(_PackageManager, _cache)[dependency] = version;
930
+ }
931
+ async getVersion(dependency) {
932
+ if (typeof dependency === "string" && __privateGet(_PackageManager, _cache)[dependency]) {
933
+ return __privateGet(_PackageManager, _cache)[dependency];
934
+ }
935
+ const packageJSON = await this.getPackageJSON();
936
+ if (!packageJSON) {
937
+ return void 0;
938
+ }
939
+ return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
940
+ }
941
+ getVersionSync(dependency) {
942
+ if (typeof dependency === "string" && __privateGet(_PackageManager, _cache)[dependency]) {
943
+ return __privateGet(_PackageManager, _cache)[dependency];
944
+ }
945
+ const packageJSON = this.getPackageJSONSync();
946
+ if (!packageJSON) {
947
+ return void 0;
948
+ }
949
+ return __privateMethod(this, _match, match_fn).call(this, packageJSON, dependency);
950
+ }
951
+ async isValid(dependency, version) {
952
+ const packageVersion = await this.getVersion(dependency);
953
+ if (!packageVersion) {
954
+ return false;
955
+ }
956
+ if (packageVersion === version) {
957
+ return true;
958
+ }
959
+ const semVer = coerce(packageVersion);
960
+ if (!semVer) {
961
+ throw new Error(`${packageVersion} is not valid`);
962
+ }
963
+ return satisfies(semVer, version);
964
+ }
965
+ isValidSync(dependency, version) {
966
+ const packageVersion = this.getVersionSync(dependency);
967
+ if (!packageVersion) {
968
+ return false;
969
+ }
970
+ const semVer = coerce(packageVersion);
971
+ if (!semVer) {
972
+ throw new Error(`${packageVersion} is not valid`);
973
+ }
974
+ return satisfies(semVer, version);
975
+ }
976
+ };
977
+ _cache = new WeakMap();
978
+ _cwd = new WeakMap();
979
+ _SLASHES = new WeakMap();
980
+ _match = new WeakSet();
981
+ match_fn = function(packageJSON, dependency) {
982
+ const dependencies = {
983
+ ...packageJSON["dependencies"] || {},
984
+ ...packageJSON["devDependencies"] || {}
985
+ };
986
+ if (typeof dependency === "string" && dependencies[dependency]) {
987
+ return dependencies[dependency];
988
+ }
989
+ const matchedDependency = Object.keys(dependencies).find((dep) => dep.match(dependency));
990
+ return matchedDependency ? dependencies[matchedDependency] : void 0;
991
+ };
992
+ __privateAdd(_PackageManager, _cache, {});
993
+ var PackageManager = _PackageManager;
23
994
  export {
24
995
  FileManager,
25
996
  Generator,
26
- kubb_exports as Kubb,
27
- KubbFile,
28
997
  PackageManager,
29
998
  PluginManager,
30
999
  PromiseManager,