@kubb/core 1.0.0-beta.1 → 1.0.0-beta.10

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.
package/dist/index.js CHANGED
@@ -2,9 +2,9 @@ import { createRequire } from 'module';
2
2
  import pathParser2 from 'path';
3
3
  import { promises } from 'fs';
4
4
  import rimraf from 'rimraf';
5
- import uniq from 'lodash.uniq';
6
5
  import { v4 } from 'uuid';
7
6
  import dirTree from 'directory-tree';
7
+ import uniq from 'lodash.uniq';
8
8
 
9
9
  createRequire(import.meta.url);
10
10
 
@@ -139,7 +139,7 @@ function nameSorter(a, b) {
139
139
  function createJSDocBlockText({ comments }) {
140
140
  const filteredComments = comments.filter(Boolean);
141
141
  if (!filteredComments.length) {
142
- return void 0;
142
+ return "";
143
143
  }
144
144
  const text = filteredComments.reduce((acc, comment) => {
145
145
  return `${acc}
@@ -197,6 +197,22 @@ var Queue = class {
197
197
  }
198
198
  };
199
199
 
200
+ // src/utils/getEncodedText.ts
201
+ function getEncodedText(text) {
202
+ return text ? text.replaceAll("`", "\\`") : "";
203
+ }
204
+
205
+ // src/utils/renderTemplate.ts
206
+ function renderTemplate(template, data = void 0) {
207
+ if (!data) {
208
+ return template.replace(/{{(.*?)}}/g, "");
209
+ }
210
+ return template.replace(/{{(.*?)}}/g, (match) => {
211
+ const value = data[match.split(/{{|}}/).filter(Boolean)[0].trim()];
212
+ return value || "";
213
+ });
214
+ }
215
+
200
216
  // src/plugin.ts
201
217
  function createPlugin(factory) {
202
218
  return (options) => {
@@ -214,7 +230,7 @@ function createPlugin(factory) {
214
230
  }
215
231
  var name = "core";
216
232
  var definePlugin = createPlugin((options) => {
217
- const { fileManager, resolveId, load } = options;
233
+ const { fileManager, resolvePath, resolveName, load } = options;
218
234
  const api = {
219
235
  get config() {
220
236
  return options.config;
@@ -223,7 +239,8 @@ var definePlugin = createPlugin((options) => {
223
239
  async addFile(file) {
224
240
  return fileManager.addOrAppend(file);
225
241
  },
226
- resolveId,
242
+ resolvePath,
243
+ resolveName,
227
244
  load,
228
245
  cache: createPluginCache(/* @__PURE__ */ Object.create(null))
229
246
  };
@@ -231,11 +248,14 @@ var definePlugin = createPlugin((options) => {
231
248
  name,
232
249
  options,
233
250
  api,
234
- resolveId(fileName, directory) {
251
+ resolvePath(fileName, directory) {
235
252
  if (!directory) {
236
253
  return null;
237
254
  }
238
255
  return pathParser2.resolve(directory, fileName);
256
+ },
257
+ resolveName(name2) {
258
+ return name2;
239
259
  }
240
260
  };
241
261
  });
@@ -261,35 +281,6 @@ var FileManager = class {
261
281
  });
262
282
  return cache;
263
283
  }
264
- getSource(file) {
265
- if (!file.fileName.endsWith(".ts")) {
266
- return file.source;
267
- }
268
- const imports = [];
269
- file.imports?.forEach((curr) => {
270
- const exists = imports.find((imp) => imp.path === curr.path);
271
- if (!exists) {
272
- imports.push(curr);
273
- return;
274
- }
275
- if (exists && Array.isArray(curr.name)) {
276
- exists.name = uniq([...exists.name, ...curr.name]);
277
- }
278
- });
279
- const importSource = imports.reduce((prev, curr) => {
280
- if (Array.isArray(curr.name)) {
281
- return `${prev}
282
- import ${curr.isTypeOnly ? "type " : ""}{ ${curr.name.join(", ")} } from "${curr.path}";`;
283
- }
284
- return `${prev}
285
- import ${curr.isTypeOnly ? "type " : ""}${curr.name} from "${curr.path}";`;
286
- }, "");
287
- if (importSource) {
288
- return `${importSource}
289
- ${file.source}`;
290
- }
291
- return file.source;
292
- }
293
284
  get files() {
294
285
  const files = [];
295
286
  this.cache.forEach((item) => {
@@ -320,26 +311,6 @@ ${file.source}`,
320
311
  }
321
312
  return this.add(file);
322
313
  }
323
- combine(files) {
324
- return files.filter(Boolean).reduce((acc, curr) => {
325
- if (!curr) {
326
- return acc;
327
- }
328
- const prevIndex = acc.findIndex((item) => item.path === curr.path);
329
- if (prevIndex !== -1) {
330
- const prev = acc[prevIndex];
331
- acc[prevIndex] = {
332
- ...curr,
333
- source: `${prev.source}
334
- ${curr.source}`,
335
- imports: [...prev.imports || [], ...curr.imports || []]
336
- };
337
- } else {
338
- acc.push(curr);
339
- }
340
- return acc;
341
- }, []);
342
- }
343
314
  setStatus(id, status) {
344
315
  const cacheItem = this.getCache(id);
345
316
  if (!cacheItem) {
@@ -445,12 +416,69 @@ var TreeNode = class {
445
416
  return treeNode;
446
417
  }
447
418
  };
419
+ function combineFiles(files) {
420
+ return files.filter(Boolean).reduce((acc, curr) => {
421
+ if (!curr) {
422
+ return acc;
423
+ }
424
+ const prevIndex = acc.findIndex((item) => item.path === curr.path);
425
+ if (prevIndex !== -1) {
426
+ const prev = acc[prevIndex];
427
+ acc[prevIndex] = {
428
+ ...curr,
429
+ source: `${prev.source}
430
+ ${curr.source}`,
431
+ imports: [...prev.imports || [], ...curr.imports || []]
432
+ };
433
+ } else {
434
+ acc.push(curr);
435
+ }
436
+ return acc;
437
+ }, []);
438
+ }
439
+ function getFileSource(file) {
440
+ if (!file.fileName.endsWith(".ts")) {
441
+ return file.source;
442
+ }
443
+ const imports = [];
444
+ file.imports?.forEach((curr) => {
445
+ const exists = imports.find((imp) => imp.path === curr.path);
446
+ if (!exists) {
447
+ imports.push({
448
+ ...curr,
449
+ name: Array.isArray(curr.name) ? uniq(curr.name) : curr.name
450
+ });
451
+ }
452
+ if (exists && !Array.isArray(exists.name) && exists.name !== curr.name) {
453
+ imports.push(curr);
454
+ }
455
+ if (exists && Array.isArray(exists.name)) {
456
+ if (Array.isArray(curr.name)) {
457
+ exists.name = uniq([...exists.name, ...curr.name]);
458
+ }
459
+ }
460
+ });
461
+ const importSource = imports.reduce((prev, curr) => {
462
+ if (Array.isArray(curr.name)) {
463
+ return `${prev}
464
+ import ${curr.isTypeOnly ? "type " : ""}{ ${curr.name.join(", ")} } from "${curr.path}";`;
465
+ }
466
+ return `${prev}
467
+ import ${curr.isTypeOnly ? "type " : ""}${curr.name} from "${curr.path}";`;
468
+ }, "");
469
+ if (importSource) {
470
+ return `${importSource}
471
+ ${file.source}`;
472
+ }
473
+ return file.source;
474
+ }
448
475
 
449
476
  // src/managers/pluginManager/PluginManager.ts
450
477
  var hookNames = {
451
478
  validate: 1,
452
479
  buildStart: 1,
453
- resolveId: 1,
480
+ resolvePath: 1,
481
+ resolveName: 1,
454
482
  load: 1,
455
483
  transform: 1,
456
484
  writeFile: 1,
@@ -473,95 +501,196 @@ var PluginManager = class {
473
501
  config,
474
502
  fileManager: this.fileManager,
475
503
  load: this.load,
476
- resolveId: this.resolveId
504
+ resolvePath: this.resolvePath,
505
+ resolveName: this.resolveName
477
506
  });
478
507
  this.plugins = [this.core, ...config.plugins || []];
479
508
  }
480
- resolveId = (params) => {
509
+ resolvePath = (params) => {
481
510
  if (params.pluginName) {
482
- return this.hookForPlugin(params.pluginName, "resolveId", [params.fileName, params.directory, params.options]);
511
+ return this.hookForPluginSync({
512
+ pluginName: params.pluginName,
513
+ hookName: "resolvePath",
514
+ parameters: [params.fileName, params.directory, params.options]
515
+ });
483
516
  }
484
- return this.hookFirst("resolveId", [params.fileName, params.directory, params.options]);
517
+ return this.hookFirstSync({
518
+ hookName: "resolvePath",
519
+ parameters: [params.fileName, params.directory, params.options]
520
+ });
521
+ };
522
+ resolveName = (params) => {
523
+ if (params.pluginName) {
524
+ return this.hookForPluginSync({
525
+ pluginName: params.pluginName,
526
+ hookName: "resolveName",
527
+ parameters: [params.name]
528
+ });
529
+ }
530
+ return this.hookFirstSync({
531
+ hookName: "resolveName",
532
+ parameters: [params.name]
533
+ });
485
534
  };
486
535
  load = async (id) => {
487
- return this.hookFirst("load", [id]);
536
+ return this.hookFirst({
537
+ hookName: "load",
538
+ parameters: [id]
539
+ });
488
540
  };
489
- // run only hook for a specific plugin name
490
- hookForPlugin(pluginName, hookName, parameters, skipped) {
541
+ /**
542
+ *
543
+ * Run only hook for a specific plugin name
544
+ */
545
+ hookForPlugin({
546
+ pluginName,
547
+ hookName,
548
+ parameters
549
+ }) {
550
+ const plugin = this.getPlugin(hookName, pluginName);
551
+ return this.run({
552
+ strategy: "hookFirst",
553
+ hookName,
554
+ parameters,
555
+ plugin
556
+ });
557
+ }
558
+ hookForPluginSync({
559
+ pluginName,
560
+ hookName,
561
+ parameters
562
+ }) {
563
+ const plugin = this.getPlugin(hookName, pluginName);
564
+ return this.runSync({
565
+ strategy: "hookFirst",
566
+ hookName,
567
+ parameters,
568
+ plugin
569
+ });
570
+ }
571
+ /**
572
+ *
573
+ * Chains, first non-null result stops and returns
574
+ */
575
+ hookFirst({
576
+ hookName,
577
+ parameters,
578
+ skipped
579
+ }) {
491
580
  let promise = Promise.resolve(null);
492
- for (const plugin of this.getSortedPlugins(hookName, pluginName)) {
581
+ for (const plugin of this.getSortedPlugins(hookName)) {
493
582
  if (skipped && skipped.has(plugin))
494
583
  continue;
495
584
  promise = promise.then((result) => {
496
585
  if (result != null)
497
586
  return result;
498
- return this.run("hookFirst", hookName, parameters, plugin);
587
+ return this.run({
588
+ strategy: "hookFirst",
589
+ hookName,
590
+ parameters,
591
+ plugin
592
+ });
499
593
  });
500
594
  }
501
595
  return promise;
502
596
  }
503
- // chains, first non-null result stops and returns
504
- hookFirst(hookName, parameters, skipped) {
505
- let promise = Promise.resolve(null);
597
+ /**
598
+ *
599
+ * Chains, first non-null result stops and returns
600
+ */
601
+ hookFirstSync({
602
+ hookName,
603
+ parameters,
604
+ skipped
605
+ }) {
606
+ let result = null;
506
607
  for (const plugin of this.getSortedPlugins(hookName)) {
507
608
  if (skipped && skipped.has(plugin))
508
609
  continue;
509
- promise = promise.then((result) => {
510
- if (result != null)
511
- return result;
512
- return this.run("hookFirst", hookName, parameters, plugin);
610
+ result = this.runSync({
611
+ strategy: "hookFirst",
612
+ hookName,
613
+ parameters,
614
+ plugin
513
615
  });
616
+ if (result != null) {
617
+ break;
618
+ }
514
619
  }
515
- return promise;
620
+ return result;
516
621
  }
517
622
  // parallel
518
- async hookParallel(hookName, parameters) {
623
+ async hookParallel({
624
+ hookName,
625
+ parameters
626
+ }) {
519
627
  const parallelPromises = [];
520
628
  for (const plugin of this.getSortedPlugins(hookName)) {
521
629
  if (plugin[hookName]?.sequential) {
522
630
  await Promise.all(parallelPromises);
523
631
  parallelPromises.length = 0;
524
- await this.run("hookParallel", hookName, parameters, plugin);
632
+ await this.run({
633
+ strategy: "hookParallel",
634
+ hookName,
635
+ parameters,
636
+ plugin
637
+ });
525
638
  } else {
526
- const promise = this.run("hookParallel", hookName, parameters, plugin);
639
+ const promise = this.run({ strategy: "hookParallel", hookName, parameters, plugin });
527
640
  parallelPromises.push(promise);
528
641
  }
529
642
  }
530
643
  return Promise.all(parallelPromises);
531
644
  }
532
645
  // chains, reduces returned value, handling the reduced value as the first hook argument
533
- hookReduceArg0(hookName, [argument0, ...rest], reduce) {
646
+ hookReduceArg0({
647
+ hookName,
648
+ parameters,
649
+ reduce
650
+ }) {
651
+ const [argument0, ...rest] = parameters;
534
652
  let promise = Promise.resolve(argument0);
535
653
  for (const plugin of this.getSortedPlugins(hookName)) {
536
654
  promise = promise.then(
537
- (argument02) => this.run("hookReduceArg0", hookName, [argument02, ...rest], plugin).then(
538
- (result) => reduce.call(this.core.api, argument02, result, plugin)
539
- )
655
+ (argument02) => this.run({
656
+ strategy: "hookReduceArg0",
657
+ hookName,
658
+ parameters: [argument02, ...rest],
659
+ plugin
660
+ }).then((result) => reduce.call(this.core.api, argument02, result, plugin))
540
661
  );
541
662
  }
542
663
  return promise;
543
664
  }
544
665
  // chains
545
- hookSeq(hookName, parameters) {
666
+ hookSeq({ hookName, parameters }) {
546
667
  let promise = Promise.resolve();
547
668
  for (const plugin of this.getSortedPlugins(hookName)) {
548
- promise = promise.then(() => this.run("hookSeq", hookName, parameters, plugin));
669
+ promise = promise.then(
670
+ () => this.run({
671
+ strategy: "hookSeq",
672
+ hookName,
673
+ parameters,
674
+ plugin
675
+ })
676
+ );
549
677
  }
550
678
  return promise.then(noReturn);
551
679
  }
552
- getSortedPlugins(hookName, pluginName) {
680
+ getSortedPlugins(_hookName) {
553
681
  const plugins = [...this.plugins];
554
- if (pluginName) {
555
- const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName]);
556
- if (pluginsByPluginName.length === 0) {
557
- if (this.config.logLevel === "warn" && this.logger?.spinner) {
558
- this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`);
559
- }
560
- return [this.core];
682
+ return plugins;
683
+ }
684
+ getPlugin(hookName, pluginName) {
685
+ const plugins = [...this.plugins];
686
+ const pluginByPluginName = plugins.find((item) => item.name === pluginName && item[hookName]);
687
+ if (!pluginByPluginName) {
688
+ if (this.config.logLevel === "warn" && this.logger?.spinner) {
689
+ this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`);
561
690
  }
562
- return pluginsByPluginName;
691
+ return this.core;
563
692
  }
564
- return plugins;
693
+ return pluginByPluginName;
565
694
  }
566
695
  /**
567
696
  * Run an async plugin hook and return the result.
@@ -570,7 +699,12 @@ var PluginManager = class {
570
699
  * @param plugin The actual pluginObject to run.
571
700
  */
572
701
  // Implementation signature
573
- run(strategy, hookName, parameters, plugin) {
702
+ run({
703
+ strategy,
704
+ hookName,
705
+ parameters,
706
+ plugin
707
+ }) {
574
708
  const hook = plugin[hookName];
575
709
  return Promise.resolve().then(() => {
576
710
  if (typeof hook !== "function") {
@@ -606,12 +740,21 @@ var PluginManager = class {
606
740
  * @param plugin The acutal plugin
607
741
  * @param replaceContext When passed, the plugin context can be overridden.
608
742
  */
609
- runSync(hookName, parameters, plugin) {
743
+ runSync({
744
+ strategy,
745
+ hookName,
746
+ parameters,
747
+ plugin
748
+ }) {
610
749
  const hook = plugin[hookName];
611
750
  try {
751
+ if (typeof hook !== "function") {
752
+ return hook;
753
+ }
612
754
  return hook.apply(this.core.api, parameters);
613
- } catch (error) {
614
- return error;
755
+ } catch (e) {
756
+ this.catcher(e, plugin, hookName);
757
+ return null;
615
758
  }
616
759
  }
617
760
  catcher(e, plugin, hookName) {
@@ -649,43 +792,60 @@ async function transformReducer(_previousCode, result, _plugin) {
649
792
  }
650
793
  return result;
651
794
  }
652
- async function buildImplementation(options, done) {
795
+ async function buildImplementation(options) {
653
796
  const { config, logger } = options;
654
797
  if (config.output.clean) {
655
798
  await clean(config.output.path);
656
799
  }
657
800
  const queueTask = async (id, file) => {
658
801
  const { path } = file;
659
- let code = fileManager.getSource(file);
660
- const loadedResult = await pluginManager.hookFirst("load", [path]);
802
+ let code = getFileSource(file);
803
+ const loadedResult = await pluginManager.hookFirst({
804
+ hookName: "load",
805
+ parameters: [path]
806
+ });
661
807
  if (loadedResult) {
662
808
  code = loadedResult;
663
809
  }
664
810
  if (code) {
665
- const transformedCode = await pluginManager.hookReduceArg0("transform", [code, path], transformReducer);
811
+ const transformedCode = await pluginManager.hookReduceArg0({
812
+ hookName: "transform",
813
+ parameters: [code, path],
814
+ reduce: transformReducer
815
+ });
666
816
  if (config.output.write || config.output.write === void 0) {
667
- await pluginManager.hookParallel("writeFile", [transformedCode, path]);
817
+ await pluginManager.hookParallel({
818
+ hookName: "writeFile",
819
+ parameters: [transformedCode, path]
820
+ });
668
821
  }
669
822
  }
670
823
  };
671
824
  const pluginManager = new PluginManager(config, { logger, task: queueTask });
672
825
  const { plugins, fileManager } = pluginManager;
673
- await pluginManager.hookParallel("validate", [plugins]);
674
- await pluginManager.hookParallel("buildStart", [config]);
675
- await pluginManager.hookParallel("buildEnd");
676
- setTimeout(() => {
677
- done({ files: fileManager.files.map((file) => ({ ...file, source: fileManager.getSource(file) })) });
678
- }, 500);
826
+ await pluginManager.hookParallel({
827
+ hookName: "validate",
828
+ parameters: [plugins]
829
+ });
830
+ await pluginManager.hookParallel({
831
+ hookName: "buildStart",
832
+ parameters: [config]
833
+ });
679
834
  pluginManager.fileManager.add({
680
835
  path: isURL(config.input.path) ? config.input.path : pathParser2.resolve(config.root, config.input.path),
681
836
  fileName: isURL(config.input.path) ? "input" : config.input.path,
682
837
  source: isURL(config.input.path) ? config.input.path : await read(pathParser2.resolve(config.root, config.input.path))
683
838
  });
839
+ await pluginManager.hookParallel({ hookName: "buildEnd" });
840
+ return { files: fileManager.files.map((file) => ({ ...file, source: getFileSource(file) })) };
684
841
  }
685
842
  function build(options) {
686
843
  return new Promise(async (resolve, reject) => {
687
844
  try {
688
- await buildImplementation(options, resolve);
845
+ const output = await buildImplementation(options);
846
+ setTimeout(() => {
847
+ resolve(output);
848
+ }, 500);
689
849
  } catch (e) {
690
850
  reject(e);
691
851
  }
@@ -719,6 +879,6 @@ var SchemaGenerator = class extends Generator {
719
879
  // src/index.ts
720
880
  var src_default = build;
721
881
 
722
- export { FileManager, Generator, PluginManager, Queue, SchemaGenerator, TreeNode, ValidationPluginError, build, clean, createJSDocBlockText, createPlugin, createPluginCache, src_default as default, defineConfig, getPathMode, getRelativePath, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, timeout, validatePlugins, write };
882
+ export { FileManager, Generator, PluginManager, Queue, SchemaGenerator, TreeNode, ValidationPluginError, build, clean, combineFiles, createJSDocBlockText, createPlugin, createPluginCache, src_default as default, defineConfig, getEncodedText, getFileSource, getPathMode, getRelativePath, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, renderTemplate, timeout, validatePlugins, write };
723
883
  //# sourceMappingURL=out.js.map
724
884
  //# sourceMappingURL=index.js.map