@kubb/core 1.14.0 → 1.14.1

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,19 +2,19 @@ import mod, { createRequire } from 'module';
2
2
  import pc3 from 'picocolors';
3
3
  export { default as pc } from 'picocolors';
4
4
  import crypto from 'crypto';
5
- import pathParser2 from 'path';
6
- import fs, { remove } from 'fs-extra';
7
- import { switcher } from 'js-runtime';
8
- import { performance } from 'perf_hooks';
9
- import dirTree from 'directory-tree';
10
- import os from 'os';
11
- import { pathToFileURL } from 'url';
12
- import seedrandom from 'seedrandom';
5
+ import fs2, { remove } from 'fs-extra';
13
6
  import { camelCase, camelCaseTransformMerge } from 'change-case';
14
7
  import { orderBy } from 'natural-orderby';
8
+ import { performance } from 'perf_hooks';
9
+ import seedrandom from 'seedrandom';
10
+ import pathParser from 'path';
11
+ import { switcher } from 'js-runtime';
12
+ import dirTree from 'directory-tree';
15
13
  import { createImportDeclaration, print, createExportDeclaration } from '@kubb/parser';
16
14
  import isEqual from 'lodash.isequal';
17
15
  import { EventEmitter as EventEmitter$1 } from 'events';
16
+ import os from 'os';
17
+ import { pathToFileURL } from 'url';
18
18
  import { findUp, findUpSync } from 'find-up';
19
19
  import { coerce, satisfies } from 'semver';
20
20
 
@@ -28,49 +28,6 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
28
28
  throw Error('Dynamic require of "' + x + '" is not supported');
29
29
  });
30
30
 
31
- // src/utils/isPromise.ts
32
- function isPromise(result) {
33
- return typeof result?.then === "function";
34
- }
35
- function isPromiseFulfilledResult(result) {
36
- return result.status === "fulfilled";
37
- }
38
- function isPromiseRejectedResult(result) {
39
- return result.status === "rejected";
40
- }
41
- async function saveCreateDirectory(path) {
42
- const passedPath = pathParser2.dirname(pathParser2.resolve(path));
43
- await fs.mkdir(passedPath, { recursive: true });
44
- }
45
- var writer = switcher(
46
- {
47
- node: async (path, data) => {
48
- try {
49
- await fs.stat(path);
50
- const oldContent = await fs.readFile(path, { encoding: "utf-8" });
51
- if (oldContent?.toString() === data) {
52
- return;
53
- }
54
- } catch (_err) {
55
- }
56
- await saveCreateDirectory(path);
57
- return fs.writeFile(pathParser2.resolve(path), data, { encoding: "utf-8" });
58
- },
59
- bun: async (path, data) => {
60
- try {
61
- await saveCreateDirectory(path);
62
- await Bun.write(pathParser2.resolve(path), data);
63
- } catch (e) {
64
- console.log(e, pathParser2.resolve(path));
65
- }
66
- }
67
- },
68
- "node"
69
- );
70
- async function write(data, path) {
71
- return writer(path, data);
72
- }
73
-
74
31
  // src/utils/cache.ts
75
32
  function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
76
33
  return {
@@ -98,6 +55,211 @@ function createPluginCache(Store = /* @__PURE__ */ Object.create(null)) {
98
55
  }
99
56
  };
100
57
  }
58
+ async function clean(path) {
59
+ return remove(path);
60
+ }
61
+ var FunctionParams = class {
62
+ type;
63
+ items = [];
64
+ constructor(type) {
65
+ this.type = type;
66
+ return this;
67
+ }
68
+ add(item) {
69
+ if (!item) {
70
+ return this;
71
+ }
72
+ if (Array.isArray(item)) {
73
+ item.filter(Boolean).forEach((it) => this.items.push(it));
74
+ return this;
75
+ }
76
+ this.items.push(item);
77
+ return this;
78
+ }
79
+ toString() {
80
+ const sortedData = orderBy(this.items.filter(Boolean), [(v) => !v.default, (v) => v.required ?? true], ["desc", "desc"]);
81
+ return sortedData.filter(({ enabled = true }) => enabled).reduce((acc, { name, type, required = true, ...rest }) => {
82
+ if (!name) {
83
+ acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
84
+ return acc;
85
+ }
86
+ const parameterName = name.startsWith("{") ? name : camelCase(name, { delimiter: "", transform: camelCaseTransformMerge });
87
+ if (type) {
88
+ if (required) {
89
+ acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
90
+ } else {
91
+ acc.push(`${parameterName}?: ${type}`);
92
+ }
93
+ } else {
94
+ acc.push(`${parameterName}`);
95
+ }
96
+ return acc;
97
+ }, []).join(", ");
98
+ }
99
+ };
100
+
101
+ // src/utils/getUniqueName.ts
102
+ function getUniqueName(originalName, data) {
103
+ let used = data[originalName] || 0;
104
+ if (used) {
105
+ data[originalName] = ++used;
106
+ originalName += used;
107
+ }
108
+ data[originalName] = 1;
109
+ return originalName;
110
+ }
111
+
112
+ // src/utils/isPromise.ts
113
+ function isPromise(result) {
114
+ return typeof result?.then === "function";
115
+ }
116
+ function isPromiseFulfilledResult(result) {
117
+ return result.status === "fulfilled";
118
+ }
119
+ function isPromiseRejectedResult(result) {
120
+ return result.status === "rejected";
121
+ }
122
+
123
+ // src/utils/jsdoc.ts
124
+ function createJSDocBlockText({ comments }) {
125
+ const filteredComments = comments.filter(Boolean);
126
+ if (!filteredComments.length) {
127
+ return "";
128
+ }
129
+ return `/**
130
+ * ${filteredComments.join("\n * ")}
131
+ */`;
132
+ }
133
+ function createLogger(spinner) {
134
+ const logs = [];
135
+ const log = (message) => {
136
+ if (message && spinner) {
137
+ spinner.text = message;
138
+ logs.push(message);
139
+ }
140
+ };
141
+ const error = (message) => {
142
+ if (message) {
143
+ throw new Error(message || "Something went wrong");
144
+ }
145
+ };
146
+ const warn = (message) => {
147
+ if (message && spinner) {
148
+ spinner.warn(pc3.yellow(message));
149
+ logs.push(message);
150
+ }
151
+ };
152
+ const info = (message) => {
153
+ if (message && spinner) {
154
+ spinner.info(message);
155
+ logs.push(message);
156
+ }
157
+ };
158
+ const logger = {
159
+ log,
160
+ error,
161
+ warn,
162
+ info,
163
+ spinner,
164
+ logs
165
+ };
166
+ return logger;
167
+ }
168
+
169
+ // src/utils/nameSorter.ts
170
+ function nameSorter(a, b) {
171
+ if (a.name < b.name) {
172
+ return -1;
173
+ }
174
+ if (a.name > b.name) {
175
+ return 1;
176
+ }
177
+ return 0;
178
+ }
179
+ var Queue = class {
180
+ #queue = [];
181
+ #workerCount = 0;
182
+ #maxParallel;
183
+ #debug = false;
184
+ constructor(maxParallel, debug = false) {
185
+ this.#maxParallel = maxParallel;
186
+ this.#debug = debug;
187
+ }
188
+ run(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
189
+ return new Promise((resolve, reject) => {
190
+ const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
191
+ options.controller?.signal.addEventListener("abort", () => {
192
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
193
+ reject("Aborted");
194
+ });
195
+ this.#queue.push(item);
196
+ this.#work();
197
+ });
198
+ }
199
+ runSync(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
200
+ new Promise((resolve, reject) => {
201
+ const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
202
+ options.controller?.signal.addEventListener("abort", () => {
203
+ this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
204
+ });
205
+ this.#queue.push(item);
206
+ this.#work();
207
+ });
208
+ }
209
+ get hasJobs() {
210
+ return this.#workerCount > 0 || this.#queue.length > 0;
211
+ }
212
+ get count() {
213
+ return this.#workerCount;
214
+ }
215
+ #work() {
216
+ if (this.#workerCount >= this.#maxParallel) {
217
+ return;
218
+ }
219
+ this.#workerCount++;
220
+ let entry;
221
+ while (entry = this.#queue.shift()) {
222
+ const { reject, resolve, job, name, description } = entry;
223
+ if (this.#debug) {
224
+ performance.mark(name + "_start");
225
+ }
226
+ job().then((result) => {
227
+ resolve(result);
228
+ if (this.#debug) {
229
+ performance.mark(name + "_stop");
230
+ performance.measure(description, name + "_start", name + "_stop");
231
+ }
232
+ }).catch((err) => reject(err));
233
+ }
234
+ this.#workerCount--;
235
+ }
236
+ };
237
+ var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
238
+ function randomColour(text, colours = defaultColours) {
239
+ if (!text) {
240
+ return "white";
241
+ }
242
+ const random = seedrandom(text);
243
+ const colour = colours.at(Math.floor(random() * colours.length)) || "white";
244
+ return colour;
245
+ }
246
+ function randomPicoColour(text, colors = defaultColours) {
247
+ const colours = pc3.createColors(true);
248
+ if (!text) {
249
+ return colours.white(text);
250
+ }
251
+ const colour = randomColour(text, colors);
252
+ const isDark = colour.includes("dark");
253
+ const key = colour.replace("dark", "").toLowerCase();
254
+ const formatter = colours[key];
255
+ if (isDark) {
256
+ return pc3.bold(formatter(text));
257
+ }
258
+ if (typeof formatter !== "function") {
259
+ throw new Error("Formatter for picoColor is not of type function/Formatter");
260
+ }
261
+ return formatter(text);
262
+ }
101
263
  function slash(path, platform = "linux") {
102
264
  const isWindowsPath = /^\\\\\?\\/.test(path);
103
265
  if (["linux", "mac"].includes(platform) && !isWindowsPath) {
@@ -109,23 +271,23 @@ function getRelativePath(rootDir, filePath, platform = "linux") {
109
271
  if (!rootDir || !filePath) {
110
272
  throw new Error(`Root and file should be filled in when retrieving the relativePath, ${rootDir || ""} ${filePath || ""}`);
111
273
  }
112
- const relativePath = pathParser2.relative(rootDir, filePath);
274
+ const relativePath = pathParser.relative(rootDir, filePath);
113
275
  const path = slash(relativePath, platform);
114
276
  if (path.startsWith("../")) {
115
- return path.replace(pathParser2.basename(path), pathParser2.basename(path, pathParser2.extname(filePath)));
277
+ return path.replace(pathParser.basename(path), pathParser.basename(path, pathParser.extname(filePath)));
116
278
  }
117
- return `./${path.replace(pathParser2.basename(path), pathParser2.basename(path, pathParser2.extname(filePath)))}`;
279
+ return `./${path.replace(pathParser.basename(path), pathParser.basename(path, pathParser.extname(filePath)))}`;
118
280
  }
119
281
  function getPathMode(path) {
120
282
  if (!path) {
121
283
  return "directory";
122
284
  }
123
- return pathParser2.extname(path) ? "file" : "directory";
285
+ return pathParser.extname(path) ? "file" : "directory";
124
286
  }
125
287
  var reader = switcher(
126
288
  {
127
289
  node: async (path) => {
128
- return fs.readFile(path, { encoding: "utf8" });
290
+ return fs2.readFile(path, { encoding: "utf8" });
129
291
  },
130
292
  bun: async (path) => {
131
293
  const file = Bun.file(path);
@@ -137,7 +299,7 @@ var reader = switcher(
137
299
  var syncReader = switcher(
138
300
  {
139
301
  node: (path) => {
140
- return fs.readFileSync(path, { encoding: "utf8" });
302
+ return fs2.readFileSync(path, { encoding: "utf8" });
141
303
  },
142
304
  bun: () => {
143
305
  throw new Error("Bun cannot read sync");
@@ -152,38 +314,66 @@ function readSync(path) {
152
314
  return syncReader(path);
153
315
  }
154
316
 
155
- // src/utils/nameSorter.ts
156
- function nameSorter(a, b) {
157
- if (a.name < b.name) {
158
- return -1;
159
- }
160
- if (a.name > b.name) {
161
- return 1;
317
+ // src/utils/renderTemplate.ts
318
+ function renderTemplate(template, data = void 0) {
319
+ if (!data || !Object.keys(data).length) {
320
+ return template.replace(/{{(.*?)}}/g, "");
162
321
  }
163
- return 0;
322
+ const matches = template.match(/{{(.*?)}}/g);
323
+ return matches?.reduce((prev, curr) => {
324
+ const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
325
+ if (index === void 0) {
326
+ return prev;
327
+ }
328
+ const value = data[index];
329
+ if (value === void 0) {
330
+ return prev;
331
+ }
332
+ return prev.replace(curr, () => {
333
+ if (typeof value === "boolean") {
334
+ return `${value.toString()}` || "false";
335
+ }
336
+ return value || "";
337
+ }).trim();
338
+ }, template) || "";
164
339
  }
165
340
 
166
- // src/utils/jsdoc.ts
167
- function createJSDocBlockText({ comments }) {
168
- const filteredComments = comments.filter(Boolean);
169
- if (!filteredComments.length) {
170
- return "";
341
+ // src/utils/SummaryError.ts
342
+ var SummaryError = class extends Error {
343
+ summary;
344
+ constructor(message, options) {
345
+ super(message, { cause: options.cause });
346
+ this.name = "SummaryError";
347
+ this.summary = options.summary || [];
171
348
  }
172
- return `/**
173
- * ${filteredComments.join("\n * ")}
174
- */`;
175
- }
349
+ };
176
350
 
177
- // src/utils/getUniqueName.ts
178
- function getUniqueName(originalName, data) {
179
- let used = data[originalName] || 0;
180
- if (used) {
181
- data[originalName] = ++used;
182
- originalName += used;
183
- }
184
- data[originalName] = 1;
185
- return originalName;
186
- }
351
+ // src/utils/throttle.ts
352
+ var throttle = (fn, delay) => {
353
+ let wait = false;
354
+ let timeout2;
355
+ let cancelled = false;
356
+ return [
357
+ (...args) => {
358
+ if (cancelled) {
359
+ return void 0;
360
+ }
361
+ if (wait) {
362
+ return void 0;
363
+ }
364
+ const val = fn(...args);
365
+ wait = true;
366
+ timeout2 = setTimeout(() => {
367
+ wait = false;
368
+ }, delay);
369
+ return val;
370
+ },
371
+ () => {
372
+ cancelled = true;
373
+ clearTimeout(timeout2);
374
+ }
375
+ ];
376
+ };
187
377
 
188
378
  // src/utils/timeout.ts
189
379
  async function timeout(ms) {
@@ -193,64 +383,11 @@ async function timeout(ms) {
193
383
  }, ms);
194
384
  });
195
385
  }
196
- var Queue = class {
197
- #queue = [];
198
- #workerCount = 0;
199
- #maxParallel;
200
- #debug = false;
201
- constructor(maxParallel, debug = false) {
202
- this.#maxParallel = maxParallel;
203
- this.#debug = debug;
204
- }
205
- run(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
206
- return new Promise((resolve, reject) => {
207
- const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
208
- options.controller?.signal.addEventListener("abort", () => {
209
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
210
- reject("Aborted");
211
- });
212
- this.#queue.push(item);
213
- this.#work();
214
- });
215
- }
216
- runSync(job, options = { controller: new AbortController(), name: crypto.randomUUID(), description: "" }) {
217
- new Promise((resolve, reject) => {
218
- const item = { reject, resolve, job, name: options.name, description: options.description || options.name };
219
- options.controller?.signal.addEventListener("abort", () => {
220
- this.#queue = this.#queue.filter((queueItem) => queueItem.name === item.name);
221
- });
222
- this.#queue.push(item);
223
- this.#work();
224
- });
225
- }
226
- get hasJobs() {
227
- return this.#workerCount > 0 || this.#queue.length > 0;
228
- }
229
- get count() {
230
- return this.#workerCount;
231
- }
232
- #work() {
233
- if (this.#workerCount >= this.#maxParallel) {
234
- return;
235
- }
236
- this.#workerCount++;
237
- let entry;
238
- while (entry = this.#queue.shift()) {
239
- const { reject, resolve, job, name, description } = entry;
240
- if (this.#debug) {
241
- performance.mark(name + "_start");
242
- }
243
- job().then((result) => {
244
- resolve(result);
245
- if (this.#debug) {
246
- performance.mark(name + "_stop");
247
- performance.measure(description, name + "_start", name + "_stop");
248
- }
249
- }).catch((err) => reject(err));
250
- }
251
- this.#workerCount--;
252
- }
253
- };
386
+
387
+ // src/utils/transformers/combineCodes.ts
388
+ function combineCodes(codes) {
389
+ return codes.join("\n");
390
+ }
254
391
 
255
392
  // src/utils/transformers/escape.ts
256
393
  function escape(text) {
@@ -369,38 +506,6 @@ function transformReservedWord(word) {
369
506
  }
370
507
  return word;
371
508
  }
372
-
373
- // src/utils/transformers/combineCodes.ts
374
- function combineCodes(codes) {
375
- return codes.join("\n");
376
- }
377
-
378
- // src/utils/renderTemplate.ts
379
- function renderTemplate(template, data = void 0) {
380
- if (!data || !Object.keys(data).length) {
381
- return template.replace(/{{(.*?)}}/g, "");
382
- }
383
- const matches = template.match(/{{(.*?)}}/g);
384
- return matches?.reduce((prev, curr) => {
385
- const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
386
- if (index === void 0) {
387
- return prev;
388
- }
389
- const value = data[index];
390
- if (value === void 0) {
391
- return prev;
392
- }
393
- return prev.replace(curr, () => {
394
- if (typeof value === "boolean") {
395
- return `${value.toString()}` || "false";
396
- }
397
- return value || "";
398
- }).trim();
399
- }, template) || "";
400
- }
401
- async function clean(path) {
402
- return remove(path);
403
- }
404
509
  var TreeNode = class _TreeNode {
405
510
  data;
406
511
  parent;
@@ -491,144 +596,11 @@ var TreeNode = class _TreeNode {
491
596
 
492
597
  // src/utils/uniqueIdFactory.ts
493
598
  var uniqueIdFactory = (counter) => (str = "") => `${str}${++counter}`;
494
- var SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
495
- function normalizeDirectory(directory) {
496
- if (!SLASHES.has(directory[directory.length - 1])) {
497
- return `${directory}/`;
498
- }
499
- return directory;
500
- }
501
- function getLocation(path, cwd) {
502
- let location = path;
503
- if (cwd) {
504
- const require2 = mod.createRequire(normalizeDirectory(cwd));
505
- location = require2.resolve(path);
506
- }
507
- return location;
508
- }
509
- async function importModule(path, cwd) {
510
- try {
511
- let location = getLocation(path, cwd);
512
- if (os.platform() == "win32") {
513
- location = pathToFileURL(location).href;
514
- }
515
- const module = await import(location);
516
- return module?.default ?? module;
517
- } catch (e) {
518
- console.log(e);
519
- return void 0;
520
- }
521
- }
522
-
523
- // src/utils/throttle.ts
524
- var throttle = (fn, delay) => {
525
- let wait = false;
526
- let timeout2;
527
- let cancelled = false;
528
- return [
529
- (...args) => {
530
- if (cancelled) {
531
- return void 0;
532
- }
533
- if (wait) {
534
- return void 0;
535
- }
536
- const val = fn(...args);
537
- wait = true;
538
- timeout2 = setTimeout(() => {
539
- wait = false;
540
- }, delay);
541
- return val;
542
- },
543
- () => {
544
- cancelled = true;
545
- clearTimeout(timeout2);
546
- }
547
- ];
548
- };
549
-
550
- // src/utils/SummaryError.ts
551
- var SummaryError = class extends Error {
552
- summary;
553
- constructor(message, options) {
554
- super(message, { cause: options.cause });
555
- this.name = "SummaryError";
556
- this.summary = options.summary || [];
557
- }
558
- };
559
-
560
- // src/utils/Warning.ts
561
- var Warning = class extends Error {
562
- constructor(message, options) {
563
- super(message, { cause: options?.cause });
564
- this.name = "Warning";
565
- }
566
- };
567
- function createLogger(spinner) {
568
- const logs = [];
569
- const log = (message) => {
570
- if (message && spinner) {
571
- spinner.text = message;
572
- logs.push(message);
573
- }
574
- };
575
- const error = (message) => {
576
- if (message) {
577
- throw new Error(message || "Something went wrong");
578
- }
579
- };
580
- const warn = (message) => {
581
- if (message && spinner) {
582
- spinner.warn(pc3.yellow(message));
583
- logs.push(message);
584
- }
585
- };
586
- const info = (message) => {
587
- if (message && spinner) {
588
- spinner.info(message);
589
- logs.push(message);
590
- }
591
- };
592
- const logger = {
593
- log,
594
- error,
595
- warn,
596
- info,
597
- spinner,
598
- logs
599
- };
600
- return logger;
601
- }
602
- var defaultColours = ["black", "blue", "darkBlue", "cyan", "gray", "green", "darkGreen", "magenta", "red", "darkRed", "yellow", "darkYellow"];
603
- function randomColour(text, colours = defaultColours) {
604
- if (!text) {
605
- return "white";
606
- }
607
- const random = seedrandom(text);
608
- const colour = colours.at(Math.floor(random() * colours.length)) || "white";
609
- return colour;
610
- }
611
- function randomPicoColour(text, colors = defaultColours) {
612
- const colours = pc3.createColors(true);
613
- if (!text) {
614
- return colours.white(text);
615
- }
616
- const colour = randomColour(text, colors);
617
- const isDark = colour.includes("dark");
618
- const key = colour.replace("dark", "").toLowerCase();
619
- const formatter = colours[key];
620
- if (isDark) {
621
- return pc3.bold(formatter(text));
622
- }
623
- if (typeof formatter !== "function") {
624
- throw new Error("Formatter for picoColor is not of type function/Formatter");
625
- }
626
- return formatter(text);
627
- }
628
- var URLPath = class _URLPath {
599
+ var URLPath = class {
629
600
  path;
630
601
  constructor(path) {
631
602
  this.path = path;
603
+ return this;
632
604
  }
633
605
  /**
634
606
  * Convert Swagger path to URLPath(syntax of Express)
@@ -637,8 +609,16 @@ var URLPath = class _URLPath {
637
609
  get URL() {
638
610
  return this.toURLPath();
639
611
  }
640
- get isUrl() {
641
- return _URLPath.isURL(this.path);
612
+ get isURL() {
613
+ try {
614
+ const url = new URL(this.path);
615
+ if (url?.href) {
616
+ return true;
617
+ }
618
+ } catch (error) {
619
+ return false;
620
+ }
621
+ return false;
642
622
  }
643
623
  /**
644
624
  * Convert Swagger path to template literals/ template strings(camelcase)
@@ -655,17 +635,18 @@ var URLPath = class _URLPath {
655
635
  get params() {
656
636
  return this.getParams();
657
637
  }
658
- toObject(options = {}) {
659
- return _URLPath.toObject(this.path, options);
660
- }
661
- /**
662
- * Convert Swagger path to template literals/ template strings(camelcase)
663
- * @example /pet/{petId} => `/pet/${petId}`
664
- * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
665
- * @example /account/userID => `/account/${userId}`
666
- */
667
- toTemplateString(replacer) {
668
- return _URLPath.toTemplateString(this.path, replacer);
638
+ toObject({ type = "path", replacer, stringify } = {}) {
639
+ const object = {
640
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
641
+ params: this.getParams()
642
+ };
643
+ if (stringify) {
644
+ if (type !== "template") {
645
+ throw new Error("Type should be `template` when using stringiyf");
646
+ }
647
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
648
+ }
649
+ return object;
669
650
  }
670
651
  /**
671
652
  * Convert Swagger path to template literals/ template strings(camelcase)
@@ -673,25 +654,22 @@ var URLPath = class _URLPath {
673
654
  * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
674
655
  * @example /account/userID => `/account/${userId}`
675
656
  */
676
- static toTemplateString(path, replacer) {
657
+ toTemplateString(replacer) {
677
658
  const regex = /{(\w|-)*}/g;
678
- const found = path.match(regex);
679
- let newPath = path.replaceAll("{", "${");
659
+ const found = this.path.match(regex);
660
+ let newPath = this.path.replaceAll("{", "${");
680
661
  if (found) {
681
662
  newPath = found.reduce((prev, curr) => {
682
663
  const pathParam = replacer ? replacer(camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(curr, { delimiter: "", transform: camelCaseTransformMerge });
683
664
  const replacement = `\${${pathParam}}`;
684
665
  return prev.replace(curr, replacement);
685
- }, path);
666
+ }, this.path);
686
667
  }
687
668
  return `\`${newPath}\``;
688
669
  }
689
670
  getParams(replacer) {
690
- return _URLPath.getParams(this.path, replacer);
691
- }
692
- static getParams(path, replacer) {
693
671
  const regex = /{(\w|-)*}/g;
694
- const found = path.match(regex);
672
+ const found = this.path.match(regex);
695
673
  if (!found) {
696
674
  return void 0;
697
675
  }
@@ -700,7 +678,7 @@ var URLPath = class _URLPath {
700
678
  item = item.replaceAll("{", "").replaceAll("}", "");
701
679
  const pathParam = replacer ? replacer(camelCase(item, { delimiter: "", transform: camelCaseTransformMerge })) : camelCase(item, { delimiter: "", transform: camelCaseTransformMerge });
702
680
  params[pathParam] = pathParam;
703
- }, path);
681
+ }, this.path);
704
682
  return params;
705
683
  }
706
684
  /**
@@ -708,77 +686,61 @@ var URLPath = class _URLPath {
708
686
  * @example /pet/{petId} => /pet/:petId
709
687
  */
710
688
  toURLPath() {
711
- return _URLPath.toURLPath(this.path);
689
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
712
690
  }
713
- static toURLPath(path) {
714
- return path.replaceAll("{", ":").replaceAll("}", "");
691
+ };
692
+
693
+ // src/utils/Warning.ts
694
+ var Warning = class extends Error {
695
+ constructor(message, options) {
696
+ super(message, { cause: options?.cause });
697
+ this.name = "Warning";
715
698
  }
716
- static toObject(path, { type = "path", replacer, stringify } = {}) {
717
- const object = {
718
- url: type === "path" ? _URLPath.toURLPath(path) : _URLPath.toTemplateString(path, replacer),
719
- params: _URLPath.getParams(path)
720
- };
721
- if (stringify) {
722
- if (type !== "template") {
723
- throw new Error("Type should be `template` when using stringiyf");
699
+ };
700
+ async function saveCreateDirectory(path) {
701
+ const passedPath = pathParser.dirname(pathParser.resolve(path));
702
+ await fs2.mkdir(passedPath, { recursive: true });
703
+ }
704
+ var writer = switcher(
705
+ {
706
+ node: async (path, data) => {
707
+ try {
708
+ await fs2.stat(path);
709
+ const oldContent = await fs2.readFile(path, { encoding: "utf-8" });
710
+ if (oldContent?.toString() === data) {
711
+ return;
712
+ }
713
+ } catch (_err) {
724
714
  }
725
- return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
726
- }
727
- return object;
728
- }
729
- static isURL(path) {
730
- try {
731
- const url = new URL(path);
732
- if (url?.href) {
733
- return true;
715
+ await saveCreateDirectory(path);
716
+ return fs2.writeFile(pathParser.resolve(path), data, { encoding: "utf-8" });
717
+ },
718
+ bun: async (path, data) => {
719
+ try {
720
+ await saveCreateDirectory(path);
721
+ await Bun.write(pathParser.resolve(path), data);
722
+ } catch (e) {
723
+ console.log(e, pathParser.resolve(path));
734
724
  }
735
- } catch (error) {
736
- return false;
737
- }
738
- return false;
739
- }
740
- };
741
- var FunctionParams = class {
742
- type;
743
- items = [];
744
- constructor(type) {
745
- this.type = type;
746
- return this;
747
- }
748
- add(item) {
749
- if (!item) {
750
- return this;
751
725
  }
752
- if (Array.isArray(item)) {
753
- item.filter(Boolean).forEach((it) => this.items.push(it));
754
- return this;
726
+ },
727
+ "node"
728
+ );
729
+ async function write(data, path) {
730
+ return writer(path, data);
731
+ }
732
+ function getIndexes(root, extName, options = {}) {
733
+ const extMapper = {
734
+ ".ts": {
735
+ extensions: /\.ts/,
736
+ exclude: [/schemas/, /json/]
737
+ },
738
+ ".json": {
739
+ extensions: /\.json/,
740
+ exclude: []
755
741
  }
756
- this.items.push(item);
757
- return this;
758
- }
759
- toString() {
760
- const sortedData = orderBy(this.items.filter(Boolean), [(v) => !v.default, (v) => v.required ?? true], ["desc", "desc"]);
761
- return sortedData.filter(({ enabled = true }) => enabled).reduce((acc, { name, type, required = true, ...rest }) => {
762
- if (!name) {
763
- acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
764
- return acc;
765
- }
766
- const parameterName = name.startsWith("{") ? name : camelCase(name, { delimiter: "", transform: camelCaseTransformMerge });
767
- if (type) {
768
- if (required) {
769
- acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
770
- } else {
771
- acc.push(`${parameterName}?: ${type}`);
772
- }
773
- } else {
774
- acc.push(`${parameterName}`);
775
- }
776
- return acc;
777
- }, []).join(", ");
778
- }
779
- };
780
- function getIndexes(root, options = {}) {
781
- const tree = TreeNode.build(root, { extensions: /\.ts/, ...options });
742
+ };
743
+ const tree = TreeNode.build(root, { ...extMapper[extName] || {}, ...options });
782
744
  if (!tree) {
783
745
  return null;
784
746
  }
@@ -787,7 +749,7 @@ function getIndexes(root, options = {}) {
787
749
  return [];
788
750
  }
789
751
  if (currentTree.children?.length > 1) {
790
- const path = pathParser2.resolve(currentTree.data.path, "index.ts");
752
+ const path = pathParser.resolve(currentTree.data.path, "index.ts");
791
753
  const exports = currentTree.children.map((file) => {
792
754
  if (!file) {
793
755
  return void 0;
@@ -806,7 +768,7 @@ function getIndexes(root, options = {}) {
806
768
  });
807
769
  } else {
808
770
  currentTree.children?.forEach((child) => {
809
- const path = pathParser2.resolve(currentTree.data.path, "index.ts");
771
+ const path = pathParser.resolve(currentTree.data.path, "index.ts");
810
772
  const importPath = child.data.type === "directory" ? `./${child.data.name}` : `./${child.data.name.replace(/\.[^.]*$/, "")}`;
811
773
  files2.push({
812
774
  path,
@@ -979,6 +941,7 @@ var FileManager = class {
979
941
  this.#task = options.task;
980
942
  this.#queue = options.queue;
981
943
  }
944
+ return this;
982
945
  }
983
946
  get extensions() {
984
947
  return extensions;
@@ -1011,7 +974,7 @@ var FileManager = class {
1011
974
  }
1012
975
  return resolvedFile;
1013
976
  }
1014
- addOrAppend(file) {
977
+ async addOrAppend(file) {
1015
978
  const previousCaches = this.#cache.get(file.path);
1016
979
  const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : void 0;
1017
980
  if (previousCache) {
@@ -1027,6 +990,20 @@ ${file.source}` : "",
1027
990
  }
1028
991
  return this.add(file);
1029
992
  }
993
+ async addIndexes(root, extName = ".ts", options = {}) {
994
+ const files = await getIndexes(root, extName, options);
995
+ if (!files) {
996
+ return void 0;
997
+ }
998
+ return Promise.all(
999
+ files.map((file) => {
1000
+ if (file.override) {
1001
+ return this.add(file);
1002
+ }
1003
+ return this.addOrAppend(file);
1004
+ })
1005
+ );
1006
+ }
1030
1007
  #append(path, file) {
1031
1008
  const previousFiles = this.#cache.get(path) || [];
1032
1009
  this.#cache.set(path, [...previousFiles, file]);
@@ -1065,6 +1042,44 @@ ${file.source}` : "",
1065
1042
  return read(...params);
1066
1043
  }
1067
1044
  };
1045
+
1046
+ // src/managers/pluginManager/ParallelPluginError.ts
1047
+ var ParallelPluginError = class extends Error {
1048
+ errors = [];
1049
+ pluginManager;
1050
+ constructor(message, options) {
1051
+ super(message, { cause: options.cause });
1052
+ this.name = "ParallelPluginError";
1053
+ this.errors = options.errors;
1054
+ this.pluginManager = options.pluginManager;
1055
+ }
1056
+ findError(searchError) {
1057
+ if (!searchError) {
1058
+ return void 0;
1059
+ }
1060
+ return this.errors.find((error) => {
1061
+ if (error.cause) {
1062
+ if (error.cause.name == searchError.name) {
1063
+ return true;
1064
+ }
1065
+ return !!this.findError(error.cause);
1066
+ }
1067
+ return error.name === searchError.name;
1068
+ })?.cause;
1069
+ }
1070
+ };
1071
+
1072
+ // src/managers/pluginManager/PluginError.ts
1073
+ var PluginError = class extends Error {
1074
+ pluginManager;
1075
+ cause;
1076
+ constructor(message, options) {
1077
+ super(message, { cause: options.cause });
1078
+ this.name = "PluginError";
1079
+ this.cause = options.cause;
1080
+ this.pluginManager = options.pluginManager;
1081
+ }
1082
+ };
1068
1083
  function createPlugin(factory) {
1069
1084
  return (options) => {
1070
1085
  const plugin = factory(options);
@@ -1112,8 +1127,8 @@ var definePlugin = createPlugin((options) => {
1112
1127
  };
1113
1128
  },
1114
1129
  resolvePath(baseName) {
1115
- const root = pathParser2.resolve(this.config.root, this.config.output.path);
1116
- return pathParser2.resolve(root, baseName);
1130
+ const root = pathParser.resolve(this.config.root, this.config.output.path);
1131
+ return pathParser.resolve(root, baseName);
1117
1132
  },
1118
1133
  resolveName(name) {
1119
1134
  return name;
@@ -1139,54 +1154,22 @@ var EventEmitter = class {
1139
1154
  }
1140
1155
  };
1141
1156
 
1142
- // src/managers/pluginManager/ParallelPluginError.ts
1143
- var ParallelPluginError = class extends Error {
1144
- errors = [];
1145
- pluginManager;
1146
- constructor(message, options) {
1147
- super(message, { cause: options.cause });
1148
- this.name = "ParallelPluginError";
1149
- this.errors = options.errors;
1150
- this.pluginManager = options.pluginManager;
1151
- }
1152
- findError(searchError) {
1153
- if (!searchError) {
1154
- return void 0;
1155
- }
1156
- return this.errors.find((error) => {
1157
- if (error.cause) {
1158
- if (error.cause.name == searchError.name) {
1159
- return true;
1160
- }
1161
- return !!this.findError(error.cause);
1162
- }
1163
- return error.name === searchError.name;
1164
- })?.cause;
1165
- }
1166
- };
1167
-
1168
- // src/managers/pluginManager/PluginError.ts
1169
- var PluginError = class extends Error {
1170
- pluginManager;
1171
- cause;
1172
- constructor(message, options) {
1173
- super(message, { cause: options.cause });
1174
- this.name = "PluginError";
1175
- this.cause = options.cause;
1176
- this.pluginManager = options.pluginManager;
1177
- }
1178
- };
1179
-
1180
1157
  // src/managers/pluginManager/pluginParser.ts
1158
+ var usedPluginNames = {};
1181
1159
  function pluginParser(plugin, context) {
1160
+ const key = [plugin.kind, plugin.name, getUniqueName(plugin.name, usedPluginNames).split(plugin.name).at(1)];
1182
1161
  if (plugin.api && typeof plugin.api === "function") {
1183
1162
  const api = plugin.api.call(context);
1184
1163
  return {
1185
1164
  ...plugin,
1165
+ key,
1186
1166
  api
1187
1167
  };
1188
1168
  }
1189
- return null;
1169
+ return {
1170
+ ...plugin,
1171
+ key
1172
+ };
1190
1173
  }
1191
1174
 
1192
1175
  // src/managers/pluginManager/PluginManager.ts
@@ -1220,16 +1203,15 @@ var PluginManager = class {
1220
1203
  fileManager: this.fileManager,
1221
1204
  resolvePath: this.resolvePath.bind(this),
1222
1205
  resolveName: this.resolveName.bind(this),
1223
- getPlugins: this.#getSortedPlugins.bind(this)
1206
+ getPlugins: this.#getSortedPlugins.bind(this),
1207
+ plugin: void 0
1224
1208
  });
1225
1209
  this.#core = pluginParser(core, core.api.call(null));
1226
1210
  this.plugins = [this.#core, ...config.plugins || []].reduce((prev, plugin) => {
1227
1211
  const convertedApi = pluginParser(plugin, this.#core?.api);
1228
- if (convertedApi) {
1229
- return [...prev, convertedApi];
1230
- }
1231
- return [...prev, plugin];
1212
+ return [...prev, convertedApi];
1232
1213
  }, []);
1214
+ return this;
1233
1215
  }
1234
1216
  resolvePath = (params) => {
1235
1217
  if (params.pluginName) {
@@ -1250,8 +1232,8 @@ var PluginManager = class {
1250
1232
  pluginName: params.pluginName,
1251
1233
  hookName: "resolveName",
1252
1234
  parameters: [params.name, params.type]
1253
- }) || params.name;
1254
- return transformReservedWord(name2);
1235
+ });
1236
+ return transformReservedWord(name2 || params.name);
1255
1237
  }
1256
1238
  const name = this.hookFirstSync({
1257
1239
  hookName: "resolveName",
@@ -1263,7 +1245,6 @@ var PluginManager = class {
1263
1245
  this.eventEmitter.on(eventName, handler);
1264
1246
  }
1265
1247
  /**
1266
- *
1267
1248
  * Run only hook for a specific plugin name
1268
1249
  */
1269
1250
  hookForPlugin({
@@ -1293,7 +1274,6 @@ var PluginManager = class {
1293
1274
  });
1294
1275
  }
1295
1276
  /**
1296
- *
1297
1277
  * Chains, first non-null result stops and returns
1298
1278
  */
1299
1279
  hookFirst({
@@ -1316,16 +1296,17 @@ var PluginManager = class {
1316
1296
  parameters,
1317
1297
  plugin
1318
1298
  });
1319
- return Promise.resolve({
1320
- plugin,
1321
- result: value
1322
- });
1299
+ return Promise.resolve(
1300
+ {
1301
+ plugin,
1302
+ result: value
1303
+ }
1304
+ );
1323
1305
  });
1324
1306
  }
1325
1307
  return promise;
1326
1308
  }
1327
1309
  /**
1328
- *
1329
1310
  * Chains, first non-null result stops and returns
1330
1311
  */
1331
1312
  hookFirstSync({
@@ -1354,7 +1335,6 @@ var PluginManager = class {
1354
1335
  return parseResult;
1355
1336
  }
1356
1337
  /**
1357
- *
1358
1338
  * Parallel, runs all plugins
1359
1339
  */
1360
1340
  async hookParallel({
@@ -1381,7 +1361,6 @@ var PluginManager = class {
1381
1361
  return results.filter((result) => result.status === "fulfilled").map((result) => result.value);
1382
1362
  }
1383
1363
  /**
1384
- *
1385
1364
  * Chains, reduces returned value, handling the reduced value as the first hook argument
1386
1365
  */
1387
1366
  hookReduceArg0({
@@ -1410,14 +1389,14 @@ var PluginManager = class {
1410
1389
  hookSeq({ hookName, parameters }) {
1411
1390
  let promise = Promise.resolve();
1412
1391
  for (const plugin of this.#getSortedPlugins()) {
1413
- promise = promise.then(
1414
- () => this.#execute({
1392
+ promise = promise.then(() => {
1393
+ this.#execute({
1415
1394
  strategy: "hookSeq",
1416
1395
  hookName,
1417
1396
  parameters,
1418
1397
  plugin
1419
- })
1420
- );
1398
+ });
1399
+ });
1421
1400
  }
1422
1401
  return promise.then(noReturn);
1423
1402
  }
@@ -1463,7 +1442,7 @@ var PluginManager = class {
1463
1442
  this.eventEmitter.emit("execute", { strategy, hookName, parameters, plugin });
1464
1443
  const task = Promise.resolve().then(() => {
1465
1444
  if (typeof hook === "function") {
1466
- const possiblePromiseResult = hook.apply(this.#core.api, parameters);
1445
+ const possiblePromiseResult = hook.apply({ ...this.#core.api, plugin }, parameters);
1467
1446
  if (isPromise(possiblePromiseResult)) {
1468
1447
  return Promise.resolve(possiblePromiseResult);
1469
1448
  }
@@ -1571,7 +1550,7 @@ async function transformReducer(_previousCode, result, _plugin) {
1571
1550
  async function build(options) {
1572
1551
  const { config, logLevel, logger = createLogger() } = options;
1573
1552
  try {
1574
- if ("path" in config.input && !URLPath.isURL(config.input.path)) {
1553
+ if ("path" in config.input && !new URLPath(config.input.path).isURL) {
1575
1554
  await read(config.input.path);
1576
1555
  }
1577
1556
  } catch (e) {
@@ -1651,12 +1630,76 @@ async function build(options) {
1651
1630
  function defineConfig(options) {
1652
1631
  return options;
1653
1632
  }
1633
+
1634
+ // src/generators/Generator.ts
1635
+ var Generator = class {
1636
+ #options = {};
1637
+ #context = {};
1638
+ constructor(options, context) {
1639
+ if (context) {
1640
+ this.#context = context;
1641
+ }
1642
+ if (options) {
1643
+ this.#options = options;
1644
+ }
1645
+ return this;
1646
+ }
1647
+ get options() {
1648
+ return this.#options;
1649
+ }
1650
+ get context() {
1651
+ return this.#context;
1652
+ }
1653
+ set options(options) {
1654
+ this.#options = { ...this.#options, ...options };
1655
+ }
1656
+ };
1657
+
1658
+ // src/generators/SchemaGenerator.ts
1659
+ var SchemaGenerator = class extends Generator {
1660
+ };
1654
1661
  var PackageManager = class {
1655
1662
  #cwd;
1656
- constructor(workspace = process.cwd()) {
1657
- this.#cwd = workspace;
1663
+ #SLASHES = /* @__PURE__ */ new Set(["/", "\\"]);
1664
+ constructor(workspace) {
1665
+ if (workspace) {
1666
+ this.#cwd = workspace;
1667
+ }
1658
1668
  return this;
1659
1669
  }
1670
+ set workspace(workspace) {
1671
+ this.#cwd = workspace;
1672
+ }
1673
+ get workspace() {
1674
+ return this.#cwd;
1675
+ }
1676
+ normalizeDirectory(directory) {
1677
+ if (!this.#SLASHES.has(directory[directory.length - 1])) {
1678
+ return `${directory}/`;
1679
+ }
1680
+ return directory;
1681
+ }
1682
+ getLocation(path) {
1683
+ let location = path;
1684
+ if (this.#cwd) {
1685
+ const require2 = mod.createRequire(this.normalizeDirectory(this.#cwd));
1686
+ location = require2.resolve(path);
1687
+ }
1688
+ return location;
1689
+ }
1690
+ async import(path) {
1691
+ try {
1692
+ let location = this.getLocation(path);
1693
+ if (os.platform() == "win32") {
1694
+ location = pathToFileURL(location).href;
1695
+ }
1696
+ const module = await import(location);
1697
+ return module?.default ?? module;
1698
+ } catch (e) {
1699
+ console.log(e);
1700
+ return void 0;
1701
+ }
1702
+ }
1660
1703
  async getPackageJSON() {
1661
1704
  const pkgPath = await findUp(["package.json"], {
1662
1705
  cwd: this.#cwd
@@ -1713,37 +1756,9 @@ var PackageManager = class {
1713
1756
  }
1714
1757
  };
1715
1758
 
1716
- // src/generators/Generator.ts
1717
- var Generator = class {
1718
- #options = {};
1719
- #context = {};
1720
- constructor(options, context) {
1721
- if (context) {
1722
- this.#context = context;
1723
- }
1724
- if (options) {
1725
- this.#options = options;
1726
- }
1727
- return this;
1728
- }
1729
- get options() {
1730
- return this.#options;
1731
- }
1732
- get context() {
1733
- return this.#context;
1734
- }
1735
- set options(options) {
1736
- this.#options = { ...this.#options, ...options };
1737
- }
1738
- };
1739
-
1740
- // src/generators/SchemaGenerator.ts
1741
- var SchemaGenerator = class extends Generator {
1742
- };
1743
-
1744
1759
  // src/index.ts
1745
1760
  var src_default = build;
1746
1761
 
1747
- export { FileManager, FunctionParams, Generator, LogLevel, PackageManager, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, clean, combineCodes, combineExports, combineFiles, combineImports, createFileSource, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defaultColours, defineConfig, escape, extensions, getDependedPlugins, getIndexes, getLocation, getPathMode, getRelativePath, getUniqueName, hooks, importModule, isExtensionAllowed, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, jsStringEscape, pluginName as name, nameSorter, normalizeDirectory, pluginName, randomColour, randomPicoColour, read, readSync, renderTemplate, throttle, timeout, transformReservedWord, uniqueIdFactory, write };
1762
+ export { FileManager, FunctionParams, Generator, LogLevel, PackageManager, ParallelPluginError, PluginError, PluginManager, Queue, SchemaGenerator, SummaryError, TreeNode, URLPath, ValidationPluginError, Warning, build, clean, combineCodes, combineExports, combineFiles, combineImports, createFileSource, createJSDocBlockText, createLogger, createPlugin, createPluginCache, src_default as default, defaultColours, defineConfig, escape, extensions, getDependedPlugins, getIndexes, getPathMode, getRelativePath, getUniqueName, hooks, isExtensionAllowed, isPromise, isPromiseFulfilledResult, isPromiseRejectedResult, jsStringEscape, pluginName as name, nameSorter, pluginName, randomColour, randomPicoColour, read, readSync, renderTemplate, throttle, timeout, transformReservedWord, uniqueIdFactory, write };
1748
1763
  //# sourceMappingURL=out.js.map
1749
1764
  //# sourceMappingURL=index.js.map