@kubb/core 1.1.13 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,6 +5,10 @@ import pathParser2 from 'node:path';
5
5
  import { camelCase, camelCaseTransformMerge } from 'change-case';
6
6
  import { rimraf } from 'rimraf';
7
7
  import dirTree from 'directory-tree';
8
+ import mod from 'node:module';
9
+ import { pathToFileURL } from 'node:url';
10
+ import pc from 'picocolors';
11
+ export { default as pc } from 'picocolors';
8
12
  import { createImportDeclaration, print, createExportDeclaration } from '@kubb/ts-codegen';
9
13
 
10
14
  createRequire(import.meta.url);
@@ -13,6 +17,12 @@ createRequire(import.meta.url);
13
17
  function isPromise(result) {
14
18
  return typeof result?.then === "function";
15
19
  }
20
+ function isPromiseFulfilledResult(result) {
21
+ return result.status === "fulfilled";
22
+ }
23
+ function isPromiseRejectedResult(result) {
24
+ return result.status === "rejected";
25
+ }
16
26
  async function safeWriteFileToPath(path, data) {
17
27
  const passedPath = pathParser2.dirname(pathParser2.resolve(path));
18
28
  await fs.mkdir(passedPath, { recursive: true });
@@ -402,6 +412,31 @@ function getStackTrace(belowFn) {
402
412
 
403
413
  // src/utils/uniqueId.ts
404
414
  var uniqueId = ((counter) => (str = "") => `${str}${++counter}`)(0);
415
+ var SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
416
+ function normalizeDirectory(directory) {
417
+ if (!SLASHES.has(directory[directory.length - 1])) {
418
+ return `${directory}/`;
419
+ }
420
+ return directory;
421
+ }
422
+ function getLocation(path, cwd) {
423
+ let location = path;
424
+ if (cwd) {
425
+ const require2 = mod.createRequire(normalizeDirectory(cwd));
426
+ location = require2.resolve(path);
427
+ }
428
+ return location;
429
+ }
430
+ async function importModule(path, cwd) {
431
+ try {
432
+ const location = getLocation(path, cwd);
433
+ const module = await import(pathToFileURL(location).href);
434
+ return module?.default ?? module;
435
+ } catch (e) {
436
+ console.log(e);
437
+ return void 0;
438
+ }
439
+ }
405
440
 
406
441
  // src/utils/throttle.ts
407
442
  var throttle = (fn, delay) => {
@@ -430,108 +465,53 @@ var throttle = (fn, delay) => {
430
465
  ];
431
466
  };
432
467
 
433
- // src/managers/fileManager/FileManager.ts
434
- var FileManager = class {
435
- cache = /* @__PURE__ */ new Map();
436
- task;
437
- queue;
438
- constructor(options) {
439
- if (options) {
440
- this.task = options.task;
441
- this.queue = options.queue;
442
- }
443
- }
444
- getCache(id) {
445
- return this.cache.get(id);
446
- }
447
- getCacheByPath(path) {
448
- let cache;
449
- this.cache.forEach((item) => {
450
- if (item.file.path === path) {
451
- cache = item;
452
- }
453
- });
454
- return cache;
455
- }
456
- get files() {
457
- const files = [];
458
- this.cache.forEach((item) => {
459
- files.push(item.file);
460
- });
461
- return files;
462
- }
463
- get cachedFiles() {
464
- const files = [];
465
- this.cache.forEach((item) => {
466
- files.push(item);
467
- });
468
- return files;
469
- }
470
- async add(file) {
471
- const cacheItem = { id: crypto.randomUUID(), file, status: "new" };
472
- this.cache.set(cacheItem.id, cacheItem);
473
- if (this.queue) {
474
- await this.queue.run(async () => {
475
- await this.task?.(cacheItem.id, file);
476
- });
477
- }
478
- return file;
468
+ // src/utils/SummaryError.ts
469
+ var SummaryError = class extends Error {
470
+ summary;
471
+ constructor(message, options) {
472
+ super(message, { cause: options.cause });
473
+ this.name = "SummaryError";
474
+ this.summary = options.summary || [];
479
475
  }
480
- addOrAppend(file) {
481
- if (!file.path.endsWith(file.fileName)) ;
482
- const previousCache = this.getCacheByPath(file.path);
483
- if (previousCache) {
484
- const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
485
- if (sourceAlreadyExists) {
486
- return Promise.resolve(file);
487
- }
488
- this.cache.delete(previousCache.id);
489
- return this.add({
490
- ...file,
491
- source: `${previousCache.file.source}
492
- ${file.source}`,
493
- imports: [...previousCache.file.imports || [], ...file.imports || []],
494
- exports: [...previousCache.file.exports || [], ...file.exports || []]
495
- });
496
- }
497
- return this.add(file);
476
+ };
477
+
478
+ // src/utils/Warning.ts
479
+ var Warning = class extends Error {
480
+ constructor(message, options) {
481
+ super(message, { cause: options?.cause });
482
+ this.name = "Warning";
498
483
  }
499
- setStatus(id, status) {
500
- const cacheItem = this.getCache(id);
501
- if (!cacheItem) {
502
- return;
484
+ };
485
+ function createLogger(spinner) {
486
+ const [log] = throttle((message) => {
487
+ if (message && spinner) {
488
+ spinner.text = message;
503
489
  }
504
- cacheItem.status = status;
505
- this.cache.set(id, cacheItem);
506
- }
507
- get(id) {
508
- const cacheItem = this.getCache(id);
509
- return cacheItem?.file;
510
- }
511
- remove(id) {
512
- const cacheItem = this.getCache(id);
513
- if (!cacheItem) {
514
- return;
490
+ }, 100);
491
+ const [error] = throttle((message) => {
492
+ if (message) {
493
+ throw new Error(message || "Something went wrong");
515
494
  }
516
- this.setStatus(id, "removed");
517
- }
518
- async write(...params) {
519
- if (this.queue) {
520
- return this.queue.run(async () => {
521
- return write(...params);
522
- });
495
+ }, 100);
496
+ const [warn] = throttle((message) => {
497
+ if (message && spinner) {
498
+ spinner.warn(pc.yellow(message));
523
499
  }
524
- return write(...params);
525
- }
526
- async read(...params) {
527
- if (this.queue) {
528
- return this.queue.run(async () => {
529
- return read(...params);
530
- });
500
+ }, 100);
501
+ const [info] = throttle((message) => {
502
+ if (message && spinner) {
503
+ spinner.text = message;
531
504
  }
532
- return read(...params);
533
- }
534
- };
505
+ }, 100);
506
+ const logger = {
507
+ log,
508
+ error,
509
+ warn,
510
+ info,
511
+ spinner
512
+ };
513
+ return logger;
514
+ }
535
515
  function writeIndexes(root, options = {}) {
536
516
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
537
517
  if (!tree) {
@@ -589,7 +569,8 @@ function combineFiles(files) {
589
569
  source: prev.source && curr.source ? `${prev.source}
590
570
  ${curr.source}` : "'",
591
571
  imports: [...prev.imports || [], ...curr.imports || []],
592
- exports: [...prev.exports || [], ...curr.exports || []]
572
+ exports: [...prev.exports || [], ...curr.exports || []],
573
+ env: { ...prev.env || {}, ...curr.env || {} }
593
574
  };
594
575
  } else {
595
576
  acc.push(curr);
@@ -597,9 +578,10 @@ ${curr.source}` : "'",
597
578
  return acc;
598
579
  }, []);
599
580
  }
581
+ var extensions = [".js", ".ts"];
600
582
  function getFileSource(file) {
601
583
  let { source } = file;
602
- if (!file.fileName.endsWith(".ts")) {
584
+ if (!extensions.some((extension) => file.fileName.endsWith(extension))) {
603
585
  return file.source;
604
586
  }
605
587
  const imports = [];
@@ -646,6 +628,7 @@ function getFileSource(file) {
646
628
  return [...prev, createExportDeclaration({ name: curr.name, path: curr.path, isTypeOnly: curr.isTypeOnly, asAlias: curr.asAlias })];
647
629
  }, []);
648
630
  const exportSource = print(exportNodes);
631
+ source = getEnvSource(source, file.env);
649
632
  if (importSource) {
650
633
  source = `${importSource}
651
634
  ${source}`;
@@ -656,6 +639,149 @@ ${source}`;
656
639
  }
657
640
  return source;
658
641
  }
642
+ function searchAndReplace(options) {
643
+ const { text, replaceBy, prefix = "", key } = options;
644
+ const searchValues = options.searchValues?.(prefix, key) || [
645
+ `${prefix}["${key}"]`,
646
+ `${prefix}['${key}']`,
647
+ `${prefix}[\`${key}\`]`,
648
+ `${prefix}"${key}"`,
649
+ `${prefix}'${key}'`,
650
+ `${prefix}\`${key}\``,
651
+ new RegExp(`${prefix}${key}`, "g")
652
+ ];
653
+ return searchValues.reduce((prev, searchValue) => {
654
+ return prev.toString().replaceAll(searchValue, replaceBy);
655
+ }, text);
656
+ }
657
+ function getEnvSource(source, env) {
658
+ if (!env) {
659
+ return source;
660
+ }
661
+ const keys = Object.keys(env);
662
+ if (!keys.length) {
663
+ return source;
664
+ }
665
+ return keys.reduce((prev, key) => {
666
+ const environmentValue = env[key];
667
+ const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', "")?.replaceAll("'", "")}'` : "undefined";
668
+ if (key.toUpperCase() !== key) {
669
+ throw new TypeError(`Environment should be in upperCase for ${key}`);
670
+ }
671
+ if (typeof replaceBy === "string") {
672
+ prev = searchAndReplace({ text: prev.replaceAll(`process.env.${key}`, replaceBy), replaceBy, prefix: "process.env", key });
673
+ prev = searchAndReplace({ text: prev.replaceAll(new RegExp(`(declare const).*
674
+ `, "ig"), ""), replaceBy, key });
675
+ }
676
+ return prev;
677
+ }, source);
678
+ }
679
+
680
+ // src/managers/fileManager/FileManager.ts
681
+ var FileManager = class {
682
+ cache = /* @__PURE__ */ new Map();
683
+ task;
684
+ queue;
685
+ constructor(options) {
686
+ if (options) {
687
+ this.task = options.task;
688
+ this.queue = options.queue;
689
+ }
690
+ }
691
+ getCache(id) {
692
+ return this.cache.get(id);
693
+ }
694
+ get extensions() {
695
+ return extensions;
696
+ }
697
+ getCacheByPath(path) {
698
+ let cache;
699
+ this.cache.forEach((item) => {
700
+ if (item.file.path === path) {
701
+ cache = item;
702
+ }
703
+ });
704
+ return cache;
705
+ }
706
+ get files() {
707
+ const files = [];
708
+ this.cache.forEach((item) => {
709
+ files.push(item.file);
710
+ });
711
+ return files;
712
+ }
713
+ get cachedFiles() {
714
+ const files = [];
715
+ this.cache.forEach((item) => {
716
+ files.push(item);
717
+ });
718
+ return files;
719
+ }
720
+ async add(file) {
721
+ const cacheItem = { id: crypto.randomUUID(), file, status: "new" };
722
+ this.cache.set(cacheItem.id, cacheItem);
723
+ if (this.queue) {
724
+ await this.queue.run(async () => {
725
+ await this.task?.(cacheItem.id, file);
726
+ });
727
+ }
728
+ return file;
729
+ }
730
+ addOrAppend(file) {
731
+ if (!file.path.endsWith(file.fileName)) ;
732
+ const previousCache = this.getCacheByPath(file.path);
733
+ if (previousCache) {
734
+ const sourceAlreadyExists = file.source && previousCache.file.source.includes(file.source);
735
+ if (sourceAlreadyExists) {
736
+ return Promise.resolve(file);
737
+ }
738
+ this.cache.delete(previousCache.id);
739
+ return this.add({
740
+ ...file,
741
+ source: `${previousCache.file.source}
742
+ ${file.source}`,
743
+ imports: [...previousCache.file.imports || [], ...file.imports || []],
744
+ exports: [...previousCache.file.exports || [], ...file.exports || []]
745
+ });
746
+ }
747
+ return this.add(file);
748
+ }
749
+ setStatus(id, status) {
750
+ const cacheItem = this.getCache(id);
751
+ if (!cacheItem) {
752
+ return;
753
+ }
754
+ cacheItem.status = status;
755
+ this.cache.set(id, cacheItem);
756
+ }
757
+ get(id) {
758
+ const cacheItem = this.getCache(id);
759
+ return cacheItem?.file;
760
+ }
761
+ remove(id) {
762
+ const cacheItem = this.getCache(id);
763
+ if (!cacheItem) {
764
+ return;
765
+ }
766
+ this.setStatus(id, "removed");
767
+ }
768
+ async write(...params) {
769
+ if (this.queue) {
770
+ return this.queue.run(async () => {
771
+ return write(...params);
772
+ });
773
+ }
774
+ return write(...params);
775
+ }
776
+ async read(...params) {
777
+ if (this.queue) {
778
+ return this.queue.run(async () => {
779
+ return read(...params);
780
+ });
781
+ }
782
+ return read(...params);
783
+ }
784
+ };
659
785
  function createPlugin(factory) {
660
786
  return (options) => {
661
787
  const plugin = factory(options);
@@ -670,9 +796,9 @@ function createPlugin(factory) {
670
796
  return plugin;
671
797
  };
672
798
  }
673
- var name = "core";
799
+ var pluginName = "core";
674
800
  var definePlugin = createPlugin((options) => {
675
- const { fileManager, resolvePath, resolveName, load } = options;
801
+ const { fileManager, resolvePath, resolveName, load, logger } = options;
676
802
  const api = {
677
803
  get config() {
678
804
  return options.config;
@@ -689,14 +815,14 @@ var definePlugin = createPlugin((options) => {
689
815
  }
690
816
  return 0;
691
817
  });
692
- const pluginName = plugins?.[0]?.name;
818
+ const pluginName2 = plugins?.[0]?.name;
693
819
  return Promise.all(
694
820
  files.map((file) => {
695
821
  const fileWithMeta = {
696
822
  ...file,
697
823
  meta: {
698
824
  ...file.meta || {},
699
- pluginName
825
+ pluginName: pluginName2
700
826
  }
701
827
  };
702
828
  if (file.override) {
@@ -708,29 +834,30 @@ var definePlugin = createPlugin((options) => {
708
834
  },
709
835
  resolvePath,
710
836
  resolveName: (params) => {
711
- const name2 = resolveName(params);
712
- return transformReservedWord(name2);
837
+ const name = resolveName(params);
838
+ return transformReservedWord(name);
713
839
  },
714
840
  load,
841
+ logger,
715
842
  cache: createPluginCache(/* @__PURE__ */ Object.create(null))
716
843
  };
717
844
  return {
718
- name,
845
+ name: pluginName,
719
846
  options,
720
847
  api,
721
848
  resolvePath(fileName) {
722
849
  const root = pathParser2.resolve(this.config.root, this.config.output.path);
723
850
  return pathParser2.resolve(root, fileName);
724
851
  },
725
- resolveName(name2) {
726
- return name2;
852
+ resolveName(name) {
853
+ return name;
727
854
  }
728
855
  };
729
856
  });
730
857
 
731
858
  // src/managers/pluginManager/ParallelPluginError.ts
732
859
  var ParallelPluginError = class extends Error {
733
- errors;
860
+ errors = [];
734
861
  pluginManager;
735
862
  constructor(message, options) {
736
863
  super(message, { cause: options.cause });
@@ -738,14 +865,27 @@ var ParallelPluginError = class extends Error {
738
865
  this.errors = options.errors;
739
866
  this.pluginManager = options.pluginManager;
740
867
  }
868
+ findError(searchError) {
869
+ return this.errors.find((error) => {
870
+ if (error.cause) {
871
+ if (error.cause.name == searchError.name) {
872
+ return true;
873
+ }
874
+ return !!this.findError(error.cause);
875
+ }
876
+ return error.name === searchError.name;
877
+ })?.cause;
878
+ }
741
879
  };
742
880
 
743
881
  // src/managers/pluginManager/PluginError.ts
744
882
  var PluginError = class extends Error {
745
883
  pluginManager;
884
+ cause;
746
885
  constructor(message, options) {
747
886
  super(message, { cause: options.cause });
748
887
  this.name = "PluginError";
888
+ this.cause = options.cause;
749
889
  this.pluginManager = options.pluginManager;
750
890
  }
751
891
  };
@@ -770,12 +910,15 @@ var PluginManager = class {
770
910
  queue;
771
911
  executer;
772
912
  executed = [];
913
+ logger;
773
914
  constructor(config, options) {
774
915
  this.onExecute = options.onExecute?.bind(this);
916
+ this.logger = options.logger;
775
917
  this.queue = new Queue(10);
776
918
  this.fileManager = new FileManager({ task: options.task, queue: this.queue });
777
919
  this.core = definePlugin({
778
920
  config,
921
+ logger: this.logger,
779
922
  fileManager: this.fileManager,
780
923
  load: this.load,
781
924
  resolvePath: this.resolvePath,
@@ -824,11 +967,11 @@ var PluginManager = class {
824
967
  * Run only hook for a specific plugin name
825
968
  */
826
969
  hookForPlugin({
827
- pluginName,
970
+ pluginName: pluginName2,
828
971
  hookName,
829
972
  parameters
830
973
  }) {
831
- const plugin = this.getPlugin(hookName, pluginName);
974
+ const plugin = this.getPlugin(hookName, pluginName2);
832
975
  return this.execute({
833
976
  strategy: "hookFirst",
834
977
  hookName,
@@ -837,11 +980,11 @@ var PluginManager = class {
837
980
  });
838
981
  }
839
982
  hookForPluginSync({
840
- pluginName,
983
+ pluginName: pluginName2,
841
984
  hookName,
842
985
  parameters
843
986
  }) {
844
- const plugin = this.getPlugin(hookName, pluginName);
987
+ const plugin = this.getPlugin(hookName, pluginName2);
845
988
  return this.executeSync({
846
989
  strategy: "hookFirst",
847
990
  hookName,
@@ -926,7 +1069,12 @@ var PluginManager = class {
926
1069
  }
927
1070
  }
928
1071
  const results = await Promise.allSettled(parallelPromises);
929
- const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
1072
+ const errors = results.map((result) => {
1073
+ if (isPromiseRejectedResult(result) && result.reason instanceof PluginError) {
1074
+ return result.reason;
1075
+ }
1076
+ return void 0;
1077
+ }).filter(Boolean);
930
1078
  if (errors.length) {
931
1079
  throw new ParallelPluginError("Error", { errors, pluginManager: this });
932
1080
  }
@@ -977,9 +1125,9 @@ var PluginManager = class {
977
1125
  const plugins = [...this.plugins].filter((plugin) => plugin.name !== "core");
978
1126
  return plugins;
979
1127
  }
980
- getPlugin(hookName, pluginName) {
1128
+ getPlugin(hookName, pluginName2) {
981
1129
  const plugins = [...this.plugins];
982
- const pluginByPluginName = plugins.find((item) => item.name === pluginName && item[hookName]);
1130
+ const pluginByPluginName = plugins.find((item) => item.name === pluginName2 && item[hookName]);
983
1131
  if (!pluginByPluginName) {
984
1132
  return this.core;
985
1133
  }
@@ -1036,6 +1184,7 @@ var PluginManager = class {
1036
1184
  return hook;
1037
1185
  }).catch((e) => {
1038
1186
  this.catcher(e, plugin, hookName);
1187
+ return null;
1039
1188
  });
1040
1189
  }
1041
1190
  /**
@@ -1100,31 +1249,21 @@ function validatePlugins(plugins, dependedPluginNames) {
1100
1249
  } else {
1101
1250
  pluginNames = dependedPluginNames;
1102
1251
  }
1103
- pluginNames.forEach((pluginName) => {
1104
- const exists = plugins.some((plugin) => plugin.name === pluginName);
1252
+ pluginNames.forEach((pluginName2) => {
1253
+ const exists = plugins.some((plugin) => plugin.name === pluginName2);
1105
1254
  if (!exists) {
1106
- throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
1255
+ throw new ValidationPluginError(`This plugin depends on the ${pluginName2} plugin.`);
1107
1256
  }
1108
1257
  });
1109
1258
  return true;
1110
1259
  }
1111
1260
 
1112
- // src/managers/pluginManager/SummaryError.ts
1113
- var SummaryError = class extends Error {
1114
- summary;
1115
- constructor(message, options) {
1116
- super(message, { cause: options.cause });
1117
- this.name = "SummaryError";
1118
- this.summary = options.summary || [];
1119
- }
1120
- };
1121
-
1122
1261
  // src/build.ts
1123
1262
  async function transformReducer(_previousCode, result, _plugin) {
1124
1263
  return result;
1125
1264
  }
1126
1265
  async function build(options) {
1127
- const { config, logger } = options;
1266
+ const { config, logger = createLogger() } = options;
1128
1267
  try {
1129
1268
  if (!isURL(config.input.path)) {
1130
1269
  await read(config.input.path);
@@ -1167,11 +1306,12 @@ async function build(options) {
1167
1306
  return;
1168
1307
  }
1169
1308
  const { hookName, plugin } = executer;
1170
- if (config.logLevel === "info" && logger) {
1171
- logger.log(null, { logLevel: config.logLevel, params: { hookName, pluginName: plugin.name } });
1309
+ if (config.logLevel === "info") {
1310
+ const messsage = `\u{1FA82} Executing ${hookName || "unknown"}(${pc.yellow(plugin.name || "unknown")})`;
1311
+ logger.log(messsage);
1172
1312
  }
1173
1313
  };
1174
- const pluginManager = new PluginManager(config, { task: queueTask, onExecute });
1314
+ const pluginManager = new PluginManager(config, { logger, task: queueTask, onExecute });
1175
1315
  const { plugins, fileManager } = pluginManager;
1176
1316
  await pluginManager.hookParallel({
1177
1317
  hookName: "validate",
@@ -1212,6 +1352,6 @@ var SchemaGenerator = class extends Generator {
1212
1352
  // src/index.ts
1213
1353
  var src_default = build;
1214
1354
 
1215
- export { FileManager, Generator, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, ValidationPluginError, build, clean, combineFiles, createJSDocBlockText, createPlugin, createPluginCache, src_default as default, defineConfig, getEncodedText, getFileSource, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1355
+ export { FileManager, Generator, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, ValidationPluginError, Warning, build, clean, combineFiles, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defineConfig, extensions, getEncodedText, getFileSource, getLocation, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, importModule, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, isURL, pluginName as name, nameSorter, normalizeDirectory, objectToParameters, pluginName, read, renderTemplate, throttle, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };
1216
1356
  //# sourceMappingURL=out.js.map
1217
1357
  //# sourceMappingURL=index.js.map