@kubb/core 1.1.7 → 1.1.9

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/README.md CHANGED
@@ -5,38 +5,45 @@
5
5
 
6
6
  <p>
7
7
  Core utils for other packages.
8
- </p>
8
+ </p>
9
+ <img src="https://raw.githubusercontent.com/kubb-project/kubb/main/assets/banner.png" alt="logo" height="auto" />
9
10
 
10
- <!-- Badges -->
11
- <p>
12
- <a href="https://www.npmjs.com/package/@kubb/core">
11
+ <!-- Badges -->
12
+ <p>
13
+ <a href="https://www.npmjs.com/package/@kubb/core" target="_blank">
13
14
  <img alt="npm version" src="https://img.shields.io/npm/v/@kubb/core?style=for-the-badge"/>
14
15
  </a>
15
- <a href="https://www.npmjs.com/package/@kubb/core">
16
- <img alt="npm downloads" src="https://img.shields.io/bundlephobia/min/@kubb/core?style=for-the-badge"/>
17
- </a>
18
- <a href="https://www.npmjs.com/package/@kubb/core">
16
+
17
+ <a href="https://www.npmjs.com/package/@kubb/core" target="_blank">
19
18
  <img alt="npm downloads" src="https://img.shields.io/npm/dm/@kubb/core?style=for-the-badge"/>
20
19
  </a>
21
- </p>
20
+ </p>
21
+
22
+ <p>
23
+ <a href="https://www.npmjs.com/package/@kubb/core" target="_blank">
24
+ <img alt="Minified size" src="https://img.shields.io/bundlephobia/min/@kubb/core?style=for-the-badge"/>
25
+ </a>
26
+
27
+ <a href="https://www.npmjs.com/package/@kubb/core" target="_blank">
28
+ <img alt="Coverage" src="https://img.shields.io/codecov/c/github/kubb-project/kubb?style=for-the-badge"/>
29
+ </a>
30
+
31
+ <a href="https://www.npmjs.com/package/@kubb/core" target="_blank">
32
+ <img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/kubb-project/kubb/ci.yaml?style=for-the-badge"/>
33
+ </a>
34
+
35
+
36
+ <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
37
+ <!-- ALL-CONTRIBUTORS-BADGE:END -->
38
+ </p>
22
39
 
23
- <h4>
24
- <a href="https://codesandbox.io/s/github/kubb-project/kubb/tree/main/examples/simple">View Demo</a>
25
- <span> · </span>
26
- <a href="https://kubb.dev/" target="_blank">Documentation</a>
27
- <span> · </span>
28
- <a href="https://github.com/kubb-project/kubb/issues/">Report Bug</a>
29
- <span> · </span>
30
- <a href="https://github.com/kubb-project/kubb/issues/">Request Feature</a>
40
+ <h4>
41
+ <a href="https://codesandbox.io/s/github/kubb-project/kubb/tree/main/examples/simple" target="_blank">View Demo</a>
42
+ <span> · </span>
43
+ <a href="https://kubb.dev/" target="_blank">Documentation</a>
44
+ <span> · </span>
45
+ <a href="https://github.com/kubb-project/kubb/issues/" target="_blank">Report Bug</a>
46
+ <span> · </span>
47
+ <a href="https://github.com/kubb-project/kubb/issues/" target="_blank">Request Feature</a>
31
48
  </h4>
32
49
  </div>
33
-
34
- <br />
35
-
36
- <!-- About the Project
37
- ## :star2: About the Project
38
-
39
- <div align="center">
40
- <img src="assets/screenshot.jpg" alt="screenshot" />
41
- </div>
42
- -->
package/dist/index.cjs CHANGED
@@ -2,9 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var module$1 = require('module');
6
5
  var crypto = require('crypto');
7
- var fs = require('fs');
6
+ var fs = require('fs-extra');
8
7
  var pathParser2 = require('path');
9
8
  var changeCase = require('change-case');
10
9
  var rimraf = require('rimraf');
@@ -14,10 +13,11 @@ var tsCodegen = require('@kubb/ts-codegen');
14
13
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
15
14
 
16
15
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
16
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
17
17
  var pathParser2__default = /*#__PURE__*/_interopDefault(pathParser2);
18
18
  var dirTree__default = /*#__PURE__*/_interopDefault(dirTree);
19
19
 
20
- module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('out.js', document.baseURI).href)));
20
+ // src/managers/fileManager/FileManager.ts
21
21
 
22
22
  // src/utils/isPromise.ts
23
23
  function isPromise(result) {
@@ -25,13 +25,13 @@ function isPromise(result) {
25
25
  }
26
26
  async function safeWriteFileToPath(path, data) {
27
27
  const passedPath = pathParser2__default.default.dirname(pathParser2__default.default.resolve(path));
28
- await fs.promises.mkdir(passedPath, { recursive: true });
29
- return fs.promises.writeFile(pathParser2__default.default.resolve(path), data, { encoding: "utf-8" });
28
+ await fs__default.default.mkdir(passedPath, { recursive: true });
29
+ return fs__default.default.writeFile(pathParser2__default.default.resolve(path), data, { encoding: "utf-8" });
30
30
  }
31
31
  async function write(data, path) {
32
32
  try {
33
- await fs.promises.stat(path);
34
- const oldContent = await fs.promises.readFile(path, { encoding: "utf-8" });
33
+ await fs__default.default.stat(path);
34
+ const oldContent = await fs__default.default.readFile(path, { encoding: "utf-8" });
35
35
  if (oldContent?.toString() === data) {
36
36
  return;
37
37
  }
@@ -49,15 +49,17 @@ function createPluginCache(cache) {
49
49
  },
50
50
  get(id) {
51
51
  const item = cache[id];
52
- if (!item)
52
+ if (!item) {
53
53
  return null;
54
+ }
54
55
  item[0] = 0;
55
56
  return item[1];
56
57
  },
57
58
  has(id) {
58
59
  const item = cache[id];
59
- if (!item)
60
+ if (!item) {
60
61
  return false;
62
+ }
61
63
  item[0] = 0;
62
64
  return true;
63
65
  },
@@ -66,19 +68,19 @@ function createPluginCache(cache) {
66
68
  }
67
69
  };
68
70
  }
69
- function slash(path) {
70
- const isExtendedLengthPath = /^\\\\\?\\/.test(path);
71
- if (isExtendedLengthPath) {
72
- return path;
71
+ function slash(path, platform = "linux") {
72
+ const isWindowsPath = /^\\\\\?\\/.test(path);
73
+ if (["linux", "mac"].includes(platform) && !isWindowsPath) {
74
+ return path.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
73
75
  }
74
- return path.replace(/\\/g, "/");
76
+ return path.replaceAll(/\\/g, "/").replace("../", "").trimEnd();
75
77
  }
76
- function getRelativePath(rootDir, filePath) {
78
+ function getRelativePath(rootDir, filePath, platform = "linux") {
77
79
  if (!rootDir || !filePath) {
78
- throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir} ${filePath}`);
80
+ throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
79
81
  }
80
82
  const relativePath = pathParser2__default.default.relative(rootDir, filePath);
81
- const path = slash(relativePath).replace("../", "").trimEnd();
83
+ const path = slash(relativePath, platform);
82
84
  if (path.startsWith("../")) {
83
85
  return path.replace(pathParser2__default.default.basename(path), pathParser2__default.default.basename(path, pathParser2__default.default.extname(filePath)));
84
86
  }
@@ -91,12 +93,7 @@ function getPathMode(path) {
91
93
  return pathParser2__default.default.extname(path) ? "file" : "directory";
92
94
  }
93
95
  async function read(path) {
94
- try {
95
- return fs.promises.readFile(path, { encoding: "utf8" });
96
- } catch (err) {
97
- console.error(err);
98
- throw err;
99
- }
96
+ return fs__default.default.readFile(path, { encoding: "utf8" });
100
97
  }
101
98
 
102
99
  // src/utils/isURL.ts
@@ -184,9 +181,10 @@ var Queue = class {
184
181
  this.work();
185
182
  });
186
183
  }
187
- async work() {
188
- if (this.workerCount >= this.maxParallel)
184
+ work() {
185
+ if (this.workerCount >= this.maxParallel) {
189
186
  return;
187
+ }
190
188
  this.workerCount++;
191
189
  let entry;
192
190
  while (entry = this.queue.shift()) {
@@ -233,10 +231,13 @@ var TreeNode = class {
233
231
  return child;
234
232
  }
235
233
  find(data) {
234
+ if (!data) {
235
+ return null;
236
+ }
236
237
  if (data === this.data) {
237
238
  return this;
238
239
  }
239
- if (this.children) {
240
+ if (this.children?.length) {
240
241
  for (let i = 0, { length } = this.children, target = null; i < length; i++) {
241
242
  target = this.children[i].find(data);
242
243
  if (target) {
@@ -246,23 +247,23 @@ var TreeNode = class {
246
247
  }
247
248
  return null;
248
249
  }
249
- leaves() {
250
+ get leaves() {
250
251
  if (!this.children || this.children.length === 0) {
251
252
  return [this];
252
253
  }
253
254
  const leaves = [];
254
255
  if (this.children) {
255
256
  for (let i = 0, { length } = this.children; i < length; i++) {
256
- leaves.push.apply(leaves, this.children[i].leaves());
257
+ leaves.push.apply(leaves, this.children[i].leaves);
257
258
  }
258
259
  }
259
260
  return leaves;
260
261
  }
261
- root() {
262
+ get root() {
262
263
  if (!this.parent) {
263
264
  return this;
264
265
  }
265
- return this.parent.root();
266
+ return this.parent.root;
266
267
  }
267
268
  forEach(callback) {
268
269
  if (typeof callback !== "function") {
@@ -277,21 +278,26 @@ var TreeNode = class {
277
278
  return this;
278
279
  }
279
280
  static build(path, options = {}) {
280
- const filteredTree = dirTree__default.default(path, { extensions: options?.extensions, exclude: options.exclude });
281
- if (!filteredTree) {
282
- return null;
283
- }
284
- const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
285
- const recurse = (node, item) => {
286
- const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
287
- if (item.children?.length) {
288
- item.children?.forEach((child) => {
289
- recurse(subNode, child);
290
- });
281
+ try {
282
+ const exclude = Array.isArray(options.exclude) ? options.exclude : [options.exclude].filter(Boolean);
283
+ const filteredTree = dirTree__default.default(path, { extensions: options.extensions, exclude: [/node_modules/, ...exclude] });
284
+ if (!filteredTree) {
285
+ return null;
291
286
  }
292
- };
293
- filteredTree.children?.forEach((child) => recurse(treeNode, child));
294
- return treeNode;
287
+ const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type || getPathMode(filteredTree.path) });
288
+ const recurse = (node, item) => {
289
+ const subNode = node.addChild({ name: item.name, path: item.path, type: item.type || getPathMode(item.path) });
290
+ if (item.children?.length) {
291
+ item.children?.forEach((child) => {
292
+ recurse(subNode, child);
293
+ });
294
+ }
295
+ };
296
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
297
+ return treeNode;
298
+ } catch (e) {
299
+ throw new Error("Something went wrong with creating index files with the TreehNode class", { cause: e });
300
+ }
295
301
  }
296
302
  };
297
303
 
@@ -404,6 +410,9 @@ function getStackTrace(belowFn) {
404
410
  return v8StackTrace;
405
411
  }
406
412
 
413
+ // src/utils/uniqueId.ts
414
+ var uniqueId = ((counter) => (str = "") => `${str}${++counter}`)(0);
415
+
407
416
  // src/managers/fileManager/FileManager.ts
408
417
  var FileManager = class {
409
418
  cache = /* @__PURE__ */ new Map();
@@ -496,18 +505,18 @@ ${file.source}`,
496
505
  return read(...params);
497
506
  }
498
507
  };
499
- function writeIndexes(root, options) {
508
+ function writeIndexes(root, options = {}) {
500
509
  const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
501
510
  if (!tree) {
502
- return void 0;
511
+ return null;
503
512
  }
504
- const fileReducer = (files2, item) => {
505
- if (!item.children) {
513
+ const fileReducer = (files2, currentTree) => {
514
+ if (!currentTree.children) {
506
515
  return [];
507
516
  }
508
- if (item.children?.length > 1) {
509
- const path = pathParser2__default.default.resolve(item.data.path, "index.ts");
510
- const exports = item.children.map((file) => {
517
+ if (currentTree.children?.length > 1) {
518
+ const path = pathParser2__default.default.resolve(currentTree.data.path, "index.ts");
519
+ const exports = currentTree.children.map((file) => {
511
520
  if (!file) {
512
521
  return void 0;
513
522
  }
@@ -524,8 +533,8 @@ function writeIndexes(root, options) {
524
533
  exports
525
534
  });
526
535
  } else {
527
- item.children?.forEach((child) => {
528
- const path = pathParser2__default.default.resolve(item.data.path, "index.ts");
536
+ currentTree.children?.forEach((child) => {
537
+ const path = pathParser2__default.default.resolve(currentTree.data.path, "index.ts");
529
538
  const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
530
539
  files2.push({
531
540
  path,
@@ -535,7 +544,7 @@ function writeIndexes(root, options) {
535
544
  });
536
545
  });
537
546
  }
538
- item.children.forEach((childItem) => {
547
+ currentTree.children.forEach((childItem) => {
539
548
  fileReducer(files2, childItem);
540
549
  });
541
550
  return files2;
@@ -545,9 +554,6 @@ function writeIndexes(root, options) {
545
554
  }
546
555
  function combineFiles(files) {
547
556
  return files.filter(Boolean).reduce((acc, curr) => {
548
- if (!curr) {
549
- return acc;
550
- }
551
557
  const prevIndex = acc.findIndex((item) => item.path === curr.path);
552
558
  if (prevIndex !== -1) {
553
559
  const prev = acc[prevIndex];
@@ -572,19 +578,19 @@ function getFileSource(file) {
572
578
  const imports = [];
573
579
  const exports = [];
574
580
  file.imports?.forEach((curr) => {
575
- const exists = imports.find((imp) => imp.path === curr.path);
576
- if (!exists) {
581
+ const existingImport = imports.find((imp) => imp.path === curr.path);
582
+ if (!existingImport) {
577
583
  imports.push({
578
584
  ...curr,
579
585
  name: Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name
580
586
  });
581
587
  }
582
- if (exists && !Array.isArray(exists.name) && exists.name !== curr.name) {
588
+ if (existingImport && !Array.isArray(existingImport.name) && existingImport.name !== curr.name) {
583
589
  imports.push(curr);
584
590
  }
585
- if (exists && Array.isArray(exists.name)) {
591
+ if (existingImport && Array.isArray(existingImport.name)) {
586
592
  if (Array.isArray(curr.name)) {
587
- exists.name = [.../* @__PURE__ */ new Set([...exists.name, ...curr.name])];
593
+ existingImport.name = [.../* @__PURE__ */ new Set([...existingImport.name, ...curr.name])];
588
594
  }
589
595
  }
590
596
  });
@@ -610,7 +616,7 @@ function getFileSource(file) {
610
616
  }, []);
611
617
  const importSource = tsCodegen.print(importNodes);
612
618
  const exportNodes = exports.reduce((prev, curr) => {
613
- return [...prev, tsCodegen.createExportDeclaration({ name: curr.name, path: curr.path, asAlias: curr.asAlias })];
619
+ return [...prev, tsCodegen.createExportDeclaration({ name: curr.name, path: curr.path, isTypeOnly: curr.isTypeOnly, asAlias: curr.asAlias })];
614
620
  }, []);
615
621
  const exportSource = tsCodegen.print(exportNodes);
616
622
  if (importSource) {
@@ -648,10 +654,12 @@ var definePlugin = createPlugin((options) => {
648
654
  async addFile(...files) {
649
655
  const trace = getStackTrace();
650
656
  const plugins = options.config.plugins?.filter((plugin) => trace[1].getFileName()?.includes(plugin.name)).sort((a, b) => {
651
- if (a.name.length < b.name.length)
657
+ if (a.name.length < b.name.length) {
652
658
  return 1;
653
- if (a.name.length > b.name.length)
659
+ }
660
+ if (a.name.length > b.name.length) {
654
661
  return -1;
662
+ }
655
663
  return 0;
656
664
  });
657
665
  const pluginName = plugins?.[0].name;
@@ -823,8 +831,9 @@ var PluginManager = class {
823
831
  }) {
824
832
  let promise = Promise.resolve(null);
825
833
  for (const plugin of this.getSortedPlugins(hookName)) {
826
- if (skipped && skipped.has(plugin))
834
+ if (skipped && skipped.has(plugin)) {
827
835
  continue;
836
+ }
828
837
  promise = promise.then(async (parseResult) => {
829
838
  if (parseResult?.result != null) {
830
839
  return parseResult;
@@ -854,8 +863,9 @@ var PluginManager = class {
854
863
  }) {
855
864
  let parseResult = null;
856
865
  for (const plugin of this.getSortedPlugins(hookName)) {
857
- if (skipped && skipped.has(plugin))
866
+ if (skipped && skipped.has(plugin)) {
858
867
  continue;
868
+ }
859
869
  parseResult = {
860
870
  result: this.executeSync({
861
871
  strategy: "hookFirst",
@@ -1081,7 +1091,7 @@ async function build(options) {
1081
1091
  await read(config.input.path);
1082
1092
  }
1083
1093
  } catch (e) {
1084
- throw new Error("Cannot read file defined in `input.path` or set with --input in the CLI of your Kubb config", { cause: e });
1094
+ throw new Error("Cannot read file/URL defined in `input.path` or set with --input in the CLI of your Kubb config", { cause: e });
1085
1095
  }
1086
1096
  if (config.output.clean) {
1087
1097
  await clean(config.output.path);
@@ -1197,6 +1207,7 @@ exports.read = read;
1197
1207
  exports.renderTemplate = renderTemplate;
1198
1208
  exports.timeout = timeout;
1199
1209
  exports.transformReservedWord = transformReservedWord;
1210
+ exports.uniqueId = uniqueId;
1200
1211
  exports.validatePlugins = validatePlugins;
1201
1212
  exports.write = write;
1202
1213
  exports.writeIndexes = writeIndexes;
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ interface Cache<T extends object = object> {
13
13
  }
14
14
  declare function createPluginCache<T extends Record<string, [number, unknown]>>(cache: T): Cache<T>;
15
15
 
16
- declare function getRelativePath(rootDir?: string | null, filePath?: string | null): string;
16
+ declare function getRelativePath(rootDir?: string | null, filePath?: string | null, platform?: 'windows' | 'mac' | 'linux'): string;
17
17
  type PathMode = 'file' | 'directory';
18
18
  declare function getPathMode(path: string | undefined | null): PathMode;
19
19
  declare function read(path: string): Promise<string>;
@@ -67,9 +67,9 @@ declare class TreeNode<T = unknown> {
67
67
  children: Array<TreeNode<T>>;
68
68
  constructor(data: T, parent?: TreeNode<T>);
69
69
  addChild(data: T): TreeNode<T>;
70
- find(data: T): {} | null;
71
- leaves(): TreeNode<T>[];
72
- root(): TreeNode<T>;
70
+ find(data?: T): TreeNode<T> | null;
71
+ get leaves(): TreeNode<T>[];
72
+ get root(): TreeNode<T>;
73
73
  forEach(callback: (treeNode: TreeNode<T>) => void): this;
74
74
  static build<T = unknown>(path: string, options?: TreeNodeOptions): TreeNode<T> | null;
75
75
  }
@@ -78,6 +78,8 @@ declare function transformReservedWord(word?: string | null): string | null | un
78
78
 
79
79
  declare function getStackTrace(belowFn?: Function): NodeJS.CallSite[];
80
80
 
81
+ declare const uniqueId: (str?: string) => string;
82
+
81
83
  type Import = {
82
84
  name: string | string[];
83
85
  path: string;
@@ -139,7 +141,7 @@ declare class FileManager {
139
141
  read(...params: Parameters<typeof read>): Promise<string>;
140
142
  }
141
143
 
142
- declare function writeIndexes(root: string, options: TreeNodeOptions): File[] | undefined;
144
+ declare function writeIndexes(root: string, options?: TreeNodeOptions): File[] | null;
143
145
  declare function combineFiles(files: Array<File | null>): File[];
144
146
  declare function getFileSource(file: File): string;
145
147
 
@@ -553,4 +555,4 @@ declare abstract class SchemaGenerator<TOptions extends object, TInput, TOutput>
553
555
  abstract build(schema: TInput, name: string, description?: string): TOutput;
554
556
  }
555
557
 
556
- export { Argument0, BuildOutput, CLIOptions, Cache, CacheStore, CorePluginOptions, Executer, File, FileManager, FileName, Generator, KubbConfig, KubbJSONPlugin, KubbObjectPlugin, KubbPlugin, KubbPluginKind, KubbUserConfig, LogLevel, Logger, MaybePromise, OnExecute, OptionalPath, ParallelPluginError, ParseResult, Path, PathMode, PluginContext, PluginError, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, Queue, QueueTask, Register, ResolveNameParams, ResolvePathParams, SafeParseResult, SchemaGenerator, Status, Strategy, TransformResult, TreeNode, TreeNodeOptions, UUID, ValidationPluginError, build, clean, combineFiles, createJSDocBlockText, createPlugin, createPluginCache, build as default, defineConfig, getEncodedText, getFileSource, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, renderTemplate, timeout, transformReservedWord, validatePlugins, write, writeIndexes };
558
+ export { Argument0, BuildOutput, CLIOptions, Cache, CacheStore, CorePluginOptions, Executer, File, FileManager, FileName, Generator, KubbConfig, KubbJSONPlugin, KubbObjectPlugin, KubbPlugin, KubbPluginKind, KubbUserConfig, LogLevel, Logger, MaybePromise, OnExecute, OptionalPath, ParallelPluginError, ParseResult, Path, PathMode, PluginContext, PluginError, PluginFactoryOptions, PluginLifecycle, PluginLifecycleHooks, PluginManager, Queue, QueueTask, Register, ResolveNameParams, ResolvePathParams, SafeParseResult, SchemaGenerator, Status, Strategy, TransformResult, TreeNode, TreeNodeOptions, UUID, ValidationPluginError, build, clean, combineFiles, createJSDocBlockText, createPlugin, createPluginCache, build as default, defineConfig, getEncodedText, getFileSource, getPathMode, getRelativePath, getStackTrace, getUniqueName, hooks, isPromise, isURL, name, nameSorter, objectToParameters, read, renderTemplate, timeout, transformReservedWord, uniqueId, validatePlugins, write, writeIndexes };