@kubb/core 3.0.0-alpha.6 → 3.0.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/{FileManager-wyXRkgIk.d.cts → FileManager-B0GJlthB.d.cts} +30 -16
  2. package/dist/{FileManager-Ceski1W9.d.ts → FileManager-BFycBDqG.d.ts} +30 -16
  3. package/dist/chunk-27CPVXAT.js +945 -0
  4. package/dist/chunk-27CPVXAT.js.map +1 -0
  5. package/dist/{chunk-34BPAXR2.cjs → chunk-5E2I6KH4.cjs} +7 -7
  6. package/dist/{chunk-34BPAXR2.cjs.map → chunk-5E2I6KH4.cjs.map} +1 -1
  7. package/dist/chunk-5IGANEGE.cjs +1564 -0
  8. package/dist/chunk-5IGANEGE.cjs.map +1 -0
  9. package/dist/{chunk-67C6RBGQ.cjs → chunk-A6PCLWEY.cjs} +5 -5
  10. package/dist/{chunk-67C6RBGQ.cjs.map → chunk-A6PCLWEY.cjs.map} +1 -1
  11. package/dist/{chunk-5HN4LW3R.cjs → chunk-DID47EQD.cjs} +3 -3
  12. package/dist/{chunk-5HN4LW3R.cjs.map → chunk-DID47EQD.cjs.map} +1 -1
  13. package/dist/{chunk-25NKJ3DV.js → chunk-HBQM723K.js} +6 -6
  14. package/dist/{chunk-LOLEBOMW.cjs → chunk-IPZQXBA2.cjs} +16 -21
  15. package/dist/chunk-IPZQXBA2.cjs.map +1 -0
  16. package/dist/{chunk-76UEJFFE.js → chunk-SCR3LUXT.js} +9 -16
  17. package/dist/{chunk-76UEJFFE.js.map → chunk-SCR3LUXT.js.map} +1 -1
  18. package/dist/{chunk-XCPFG6DO.cjs → chunk-SEH6NUCX.cjs} +4 -28
  19. package/dist/chunk-SEH6NUCX.cjs.map +1 -0
  20. package/dist/index.cjs +380 -378
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +325 -319
  25. package/dist/index.js.map +1 -1
  26. package/dist/logger.cjs +4 -4
  27. package/dist/logger.js +2 -3
  28. package/dist/mocks.cjs +20 -15
  29. package/dist/mocks.cjs.map +1 -1
  30. package/dist/mocks.d.cts +6 -5
  31. package/dist/mocks.d.ts +6 -5
  32. package/dist/mocks.js +15 -11
  33. package/dist/mocks.js.map +1 -1
  34. package/dist/{prompt-6FWP747F.cjs → prompt-DVQN7JTN.cjs} +61 -61
  35. package/dist/{prompt-6FWP747F.cjs.map → prompt-DVQN7JTN.cjs.map} +1 -1
  36. package/dist/{prompt-HK3MWREM.js → prompt-WQQUN22Z.js} +5 -6
  37. package/dist/{prompt-HK3MWREM.js.map → prompt-WQQUN22Z.js.map} +1 -1
  38. package/dist/transformers.cjs +19 -19
  39. package/dist/transformers.js +0 -1
  40. package/dist/transformers.js.map +1 -1
  41. package/dist/utils.cjs +8 -4
  42. package/dist/utils.cjs.map +1 -1
  43. package/dist/utils.d.cts +25 -24
  44. package/dist/utils.d.ts +25 -24
  45. package/dist/utils.js +5 -2
  46. package/package.json +7 -7
  47. package/src/BarrelManager.ts +90 -40
  48. package/src/FileManager.ts +89 -109
  49. package/src/PluginManager.ts +2 -1
  50. package/src/__snapshots__/barrel.json +91 -0
  51. package/src/__snapshots__/grouped.json +114 -0
  52. package/src/__snapshots__/ordered.json +62 -0
  53. package/src/build.ts +60 -23
  54. package/src/plugin.ts +2 -2
  55. package/src/types.ts +22 -2
  56. package/src/utils/TreeNode.ts +43 -1
  57. package/src/utils/index.ts +1 -1
  58. package/src/utils/parser.ts +128 -67
  59. package/dist/chunk-AWAZR3D5.js +0 -360
  60. package/dist/chunk-AWAZR3D5.js.map +0 -1
  61. package/dist/chunk-DCZQYCCO.cjs +0 -1155
  62. package/dist/chunk-DCZQYCCO.cjs.map +0 -1
  63. package/dist/chunk-HMLY7DHA.js +0 -16
  64. package/dist/chunk-HMLY7DHA.js.map +0 -1
  65. package/dist/chunk-L3JJLZ5Q.cjs +0 -371
  66. package/dist/chunk-L3JJLZ5Q.cjs.map +0 -1
  67. package/dist/chunk-LOLEBOMW.cjs.map +0 -1
  68. package/dist/chunk-RIEGCND2.js +0 -525
  69. package/dist/chunk-RIEGCND2.js.map +0 -1
  70. package/dist/chunk-XCPFG6DO.cjs.map +0 -1
  71. package/schema.json +0 -86
  72. /package/dist/{chunk-25NKJ3DV.js.map → chunk-HBQM723K.js.map} +0 -0
@@ -0,0 +1,945 @@
1
+ import {
2
+ camelCase,
3
+ orderBy
4
+ } from "./chunk-4X5FFJPJ.js";
5
+
6
+ // src/utils/FunctionParams.ts
7
+ var FunctionParams = class _FunctionParams {
8
+ #items = [];
9
+ constructor() {
10
+ return this;
11
+ }
12
+ get items() {
13
+ return this.#items.flat();
14
+ }
15
+ add(item) {
16
+ if (!item) {
17
+ return this;
18
+ }
19
+ if (Array.isArray(item)) {
20
+ item.filter(Boolean).forEach((it) => this.#items.push(it));
21
+ return this;
22
+ }
23
+ this.#items.push(item);
24
+ return this;
25
+ }
26
+ static #orderItems(items) {
27
+ return orderBy(
28
+ items.filter(Boolean),
29
+ [
30
+ (v) => {
31
+ if (Array.isArray(v)) {
32
+ return void 0;
33
+ }
34
+ return !v.default;
35
+ },
36
+ (v) => {
37
+ if (Array.isArray(v)) {
38
+ return void 0;
39
+ }
40
+ return v.required ?? true;
41
+ }
42
+ ],
43
+ ["desc", "desc"]
44
+ );
45
+ }
46
+ static #addParams(acc, item) {
47
+ const { enabled = true, name, type, required = true, ...rest } = item;
48
+ if (!enabled) {
49
+ return acc;
50
+ }
51
+ if (!name) {
52
+ acc.push(`${type}${rest.default ? ` = ${rest.default}` : ""}`);
53
+ return acc;
54
+ }
55
+ const parameterName = name.startsWith("{") ? name : camelCase(name);
56
+ if (type) {
57
+ if (required) {
58
+ acc.push(`${parameterName}: ${type}${rest.default ? ` = ${rest.default}` : ""}`);
59
+ } else {
60
+ acc.push(`${parameterName}?: ${type}`);
61
+ }
62
+ } else {
63
+ acc.push(`${parameterName}`);
64
+ }
65
+ return acc;
66
+ }
67
+ static toObject(items) {
68
+ let type = [];
69
+ let name = [];
70
+ const enabled = items.every((item) => item.enabled) ? items.at(0)?.enabled : true;
71
+ const required = items.every((item) => item.required) ?? true;
72
+ items.forEach((item) => {
73
+ name = _FunctionParams.#addParams(name, { ...item, type: void 0 });
74
+ if (items.some((item2) => item2.type)) {
75
+ type = _FunctionParams.#addParams(type, item);
76
+ }
77
+ });
78
+ return {
79
+ name: `{ ${name.join(", ")} }`,
80
+ type: type.length ? `{ ${type.join("; ")} }` : void 0,
81
+ enabled,
82
+ required
83
+ };
84
+ }
85
+ static toString(items) {
86
+ const sortedData = _FunctionParams.#orderItems(items);
87
+ return sortedData.reduce((acc, item) => {
88
+ if (Array.isArray(item)) {
89
+ if (item.length <= 0) {
90
+ return acc;
91
+ }
92
+ const subItems = _FunctionParams.#orderItems(item);
93
+ const objectItem = _FunctionParams.toObject(subItems);
94
+ return _FunctionParams.#addParams(acc, objectItem);
95
+ }
96
+ return _FunctionParams.#addParams(acc, item);
97
+ }, []).join(", ");
98
+ }
99
+ toObject() {
100
+ const items = _FunctionParams.#orderItems(this.#items).flat();
101
+ return _FunctionParams.toObject(items);
102
+ }
103
+ toString() {
104
+ const items = _FunctionParams.#orderItems(this.#items);
105
+ return _FunctionParams.toString(items);
106
+ }
107
+ };
108
+
109
+ // src/utils/promise.ts
110
+ function isPromise(result) {
111
+ return !!result && typeof result?.then === "function";
112
+ }
113
+ function isPromiseFulfilledResult(result) {
114
+ return result.status === "fulfilled";
115
+ }
116
+ function isPromiseRejectedResult(result) {
117
+ return result.status === "rejected";
118
+ }
119
+
120
+ // src/utils/renderTemplate.ts
121
+ function renderTemplate(template, data = void 0) {
122
+ if (!data || !Object.keys(data).length) {
123
+ return template.replace(/{{(.*?)}}/g, "");
124
+ }
125
+ const matches = template.match(/{{(.*?)}}/g);
126
+ return matches?.reduce((prev, curr) => {
127
+ const index = curr.split(/{{|}}/).filter(Boolean)[0]?.trim();
128
+ if (index === void 0) {
129
+ return prev;
130
+ }
131
+ const value = data[index];
132
+ if (value === void 0) {
133
+ return prev;
134
+ }
135
+ return prev.replace(curr, () => {
136
+ if (typeof value === "boolean") {
137
+ return `${value.toString()}` || "false";
138
+ }
139
+ return value || "";
140
+ }).trim();
141
+ }, template) || "";
142
+ }
143
+
144
+ // src/utils/timeout.ts
145
+ async function timeout(ms) {
146
+ return new Promise((resolve) => {
147
+ setTimeout(() => {
148
+ resolve(true);
149
+ }, ms);
150
+ });
151
+ }
152
+
153
+ // src/utils/uniqueName.ts
154
+ function getUniqueName(originalName, data) {
155
+ let used = data[originalName] || 0;
156
+ if (used) {
157
+ data[originalName] = ++used;
158
+ originalName += used;
159
+ }
160
+ data[originalName] = 1;
161
+ return originalName;
162
+ }
163
+ function setUniqueName(originalName, data) {
164
+ let used = data[originalName] || 0;
165
+ if (used) {
166
+ data[originalName] = ++used;
167
+ return originalName;
168
+ }
169
+ data[originalName] = 1;
170
+ return originalName;
171
+ }
172
+
173
+ // src/utils/URLPath.ts
174
+ var URLPath = class {
175
+ path;
176
+ constructor(path) {
177
+ this.path = path;
178
+ return this;
179
+ }
180
+ /**
181
+ * Convert Swagger path to URLPath(syntax of Express)
182
+ * @example /pet/{petId} => /pet/:petId
183
+ */
184
+ get URL() {
185
+ return this.toURLPath();
186
+ }
187
+ get isURL() {
188
+ try {
189
+ const url = new URL(this.path);
190
+ if (url?.href) {
191
+ return true;
192
+ }
193
+ } catch (error) {
194
+ return false;
195
+ }
196
+ return false;
197
+ }
198
+ /**
199
+ * Convert Swagger path to template literals/ template strings(camelcase)
200
+ * @example /pet/{petId} => `/pet/${petId}`
201
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
202
+ * @example /account/userID => `/account/${userId}`
203
+ */
204
+ get template() {
205
+ return this.toTemplateString();
206
+ }
207
+ get object() {
208
+ return this.toObject();
209
+ }
210
+ get params() {
211
+ return this.getParams();
212
+ }
213
+ toObject({ type = "path", replacer, stringify } = {}) {
214
+ const object = {
215
+ url: type === "path" ? this.toURLPath() : this.toTemplateString(replacer),
216
+ params: this.getParams()
217
+ };
218
+ if (stringify) {
219
+ if (type === "template") {
220
+ return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
221
+ }
222
+ if (object.params) {
223
+ return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
224
+ }
225
+ return `{ url: '${object.url}' }`;
226
+ }
227
+ return object;
228
+ }
229
+ /**
230
+ * Convert Swagger path to template literals/ template strings(camelcase)
231
+ * @example /pet/{petId} => `/pet/${petId}`
232
+ * @example /account/monetary-accountID => `/account/${monetaryAccountId}`
233
+ * @example /account/userID => `/account/${userId}`
234
+ */
235
+ toTemplateString(replacer) {
236
+ const regex = /{(\w|-)*}/g;
237
+ const found = this.path.match(regex);
238
+ let newPath = this.path.replaceAll("{", "${");
239
+ if (found) {
240
+ newPath = found.reduce((prev, curr) => {
241
+ const pathParam = replacer ? replacer(camelCase(curr)) : camelCase(curr);
242
+ const replacement = `\${${pathParam}}`;
243
+ return prev.replace(curr, replacement);
244
+ }, this.path);
245
+ }
246
+ return `\`${newPath}\``;
247
+ }
248
+ getParams(replacer) {
249
+ const regex = /{(\w|-)*}/g;
250
+ const found = this.path.match(regex);
251
+ if (!found) {
252
+ return void 0;
253
+ }
254
+ const params = {};
255
+ found.forEach((item) => {
256
+ item = item.replaceAll("{", "").replaceAll("}", "");
257
+ const pathParam = replacer ? replacer(camelCase(item)) : camelCase(item);
258
+ params[pathParam] = pathParam;
259
+ }, this.path);
260
+ return params;
261
+ }
262
+ /**
263
+ * Convert Swagger path to URLPath(syntax of Express)
264
+ * @example /pet/{petId} => /pet/:petId
265
+ */
266
+ toURLPath() {
267
+ return this.path.replaceAll("{", ":").replaceAll("}", "");
268
+ }
269
+ };
270
+
271
+ // src/utils/parser.ts
272
+ import { extname as extname2 } from "node:path";
273
+ import { getRelativePath as getRelativePath2 } from "@kubb/fs";
274
+ import hash from "object-hash";
275
+
276
+ // src/FileManager.ts
277
+ import { extname, join as join2, relative } from "node:path";
278
+ import { isDeepEqual } from "remeda";
279
+ import { read, write } from "@kubb/fs";
280
+
281
+ // src/BarrelManager.ts
282
+ import { join } from "node:path";
283
+
284
+ // src/utils/TreeNode.ts
285
+ var TreeNode = class _TreeNode {
286
+ data;
287
+ parent;
288
+ children = [];
289
+ constructor(data, parent) {
290
+ this.data = data;
291
+ this.parent = parent;
292
+ return this;
293
+ }
294
+ addChild(data) {
295
+ const child = new _TreeNode(data, this);
296
+ if (!this.children) {
297
+ this.children = [];
298
+ }
299
+ this.children.push(child);
300
+ return child;
301
+ }
302
+ find(data) {
303
+ if (!data) {
304
+ return null;
305
+ }
306
+ if (data === this.data) {
307
+ return this;
308
+ }
309
+ if (this.children?.length) {
310
+ for (let i = 0, { length } = this.children, target = null; i < length; i++) {
311
+ target = this.children[i].find(data);
312
+ if (target) {
313
+ return target;
314
+ }
315
+ }
316
+ }
317
+ return null;
318
+ }
319
+ get leaves() {
320
+ if (!this.children || this.children.length === 0) {
321
+ return [this];
322
+ }
323
+ const leaves = [];
324
+ if (this.children) {
325
+ for (let i = 0, { length } = this.children; i < length; i++) {
326
+ leaves.push.apply(leaves, this.children[i].leaves);
327
+ }
328
+ }
329
+ return leaves;
330
+ }
331
+ get root() {
332
+ if (!this.parent) {
333
+ return this;
334
+ }
335
+ return this.parent.root;
336
+ }
337
+ forEach(callback) {
338
+ if (typeof callback !== "function") {
339
+ throw new TypeError("forEach() callback must be a function");
340
+ }
341
+ callback(this);
342
+ if (this.children) {
343
+ for (let i = 0, { length } = this.children; i < length; i++) {
344
+ this.children[i]?.forEach(callback);
345
+ }
346
+ }
347
+ return this;
348
+ }
349
+ filter(callback) {
350
+ let data = [];
351
+ if (typeof callback !== "function") {
352
+ throw new TypeError("forEach() callback must be a function");
353
+ }
354
+ if (callback(this)) {
355
+ data.push(this);
356
+ }
357
+ if (this.children) {
358
+ for (let i = 0, { length } = this.children; i < length; i++) {
359
+ const childData = this.children[i]?.filter(callback).filter(Boolean) || [];
360
+ data = [.../* @__PURE__ */ new Set([...data, ...childData])];
361
+ }
362
+ }
363
+ return data;
364
+ }
365
+ map(callback) {
366
+ let data = [];
367
+ if (typeof callback !== "function") {
368
+ throw new TypeError("forEach() callback must be a function");
369
+ }
370
+ data.push(callback(this));
371
+ if (this.children) {
372
+ for (let i = 0, { length } = this.children; i < length; i++) {
373
+ const childData = this.children[i]?.map(callback).filter(Boolean) || [];
374
+ data = [.../* @__PURE__ */ new Set([...data, ...childData])];
375
+ }
376
+ }
377
+ return data;
378
+ }
379
+ static build(files, root) {
380
+ try {
381
+ const filteredTree = buildDirectoryTree(files, root);
382
+ if (!filteredTree) {
383
+ return null;
384
+ }
385
+ const treeNode = new _TreeNode({
386
+ name: filteredTree.name,
387
+ path: filteredTree.path,
388
+ file: filteredTree.file,
389
+ type: FileManager.getMode(filteredTree.path)
390
+ });
391
+ const recurse = (node, item) => {
392
+ const subNode = node.addChild({
393
+ name: item.name,
394
+ path: item.path,
395
+ file: item.file,
396
+ type: FileManager.getMode(item.path)
397
+ });
398
+ if (item.children?.length) {
399
+ item.children?.forEach((child) => {
400
+ recurse(subNode, child);
401
+ });
402
+ }
403
+ };
404
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
405
+ return treeNode;
406
+ } catch (e) {
407
+ throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: e });
408
+ }
409
+ }
410
+ };
411
+ function buildDirectoryTree(files, rootFolder = "") {
412
+ const rootPrefix = rootFolder.endsWith("/") ? rootFolder : `${rootFolder}/`;
413
+ const filteredFiles = files.filter((file) => rootFolder ? file.path.startsWith(rootPrefix) && !file.path.endsWith(".json") : !file.path.endsWith(".json"));
414
+ if (filteredFiles.length === 0) {
415
+ return null;
416
+ }
417
+ const root = {
418
+ name: rootFolder || "",
419
+ path: rootFolder || "",
420
+ children: []
421
+ };
422
+ filteredFiles.forEach((file) => {
423
+ const path = file.path.slice(rootFolder.length);
424
+ const parts = path.split("/");
425
+ let currentLevel = root.children;
426
+ let currentPath = rootFolder;
427
+ parts.forEach((part, index) => {
428
+ if (index !== 0) {
429
+ currentPath += `/${part}`;
430
+ } else {
431
+ currentPath += `${part}`;
432
+ }
433
+ let existingNode = currentLevel.find((node) => node.name === part);
434
+ if (!existingNode) {
435
+ if (index === parts.length - 1) {
436
+ existingNode = {
437
+ name: part,
438
+ file,
439
+ path: currentPath
440
+ };
441
+ } else {
442
+ existingNode = {
443
+ name: part,
444
+ path: currentPath,
445
+ children: []
446
+ };
447
+ }
448
+ currentLevel.push(existingNode);
449
+ }
450
+ if (!existingNode.file) {
451
+ currentLevel = existingNode.children;
452
+ }
453
+ });
454
+ });
455
+ return root;
456
+ }
457
+
458
+ // src/BarrelManager.ts
459
+ import { getRelativePath } from "@kubb/fs";
460
+ var BarrelManager = class {
461
+ #options;
462
+ constructor(options = {}) {
463
+ this.#options = options;
464
+ return this;
465
+ }
466
+ getFiles(generatedFiles, root) {
467
+ const { logger } = this.#options;
468
+ const files = /* @__PURE__ */ new Map();
469
+ TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
470
+ if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {
471
+ return void 0;
472
+ }
473
+ const barrelPath = join(treeNode.parent?.data.path, "index.ts");
474
+ const leaves = treeNode.leaves;
475
+ const exports = leaves.map((item) => {
476
+ if (!item.data.name) {
477
+ return void 0;
478
+ }
479
+ const sources = item.data.file?.sources || [];
480
+ if (!sources.some((source) => source.isIndexable)) {
481
+ logger?.emit(
482
+ "warning",
483
+ `No isIndexable source found(source should have a name and isIndexable):
484
+ File: ${JSON.stringify(item.data.file, void 0, 2)}`
485
+ );
486
+ }
487
+ return sources.map((source) => {
488
+ if (!item.data.file?.path || !source.isIndexable) {
489
+ return void 0;
490
+ }
491
+ const isSubExport = !!treeNode.parent?.data.path?.split?.("/")?.length;
492
+ if (isSubExport) {
493
+ return {
494
+ name: [source.name],
495
+ path: getRelativePath(treeNode.parent?.data.path, item.data.path),
496
+ isTypeOnly: source.isTypeOnly
497
+ };
498
+ }
499
+ return {
500
+ name: [source.name],
501
+ path: `./${item.data.file.baseName}`,
502
+ isTypeOnly: source.isTypeOnly
503
+ };
504
+ });
505
+ }).flat().filter(Boolean);
506
+ const barrelFile = {
507
+ path: barrelPath,
508
+ baseName: "index.ts",
509
+ exports,
510
+ sources: exports.flatMap((item) => {
511
+ if (Array.isArray(item.name)) {
512
+ return item.name.map((name) => {
513
+ return {
514
+ name,
515
+ isTypeOnly: item.isTypeOnly,
516
+ //TODO use parser to generate import
517
+ value: "",
518
+ isExportable: false,
519
+ isIndexable: false
520
+ };
521
+ });
522
+ }
523
+ return [
524
+ {
525
+ name: item.name,
526
+ isTypeOnly: item.isTypeOnly,
527
+ //TODO use parser to generate import
528
+ value: "",
529
+ isExportable: false,
530
+ isIndexable: false
531
+ }
532
+ ];
533
+ })
534
+ };
535
+ const previousBarrelFile = files.get(barrelFile.path);
536
+ if (previousBarrelFile) {
537
+ files.set(barrelFile.path, {
538
+ ...previousBarrelFile,
539
+ ...barrelFile,
540
+ exports: combineExports([...previousBarrelFile.exports || [], ...barrelFile.exports || []]),
541
+ sources: combineSources([...previousBarrelFile.sources || [], ...barrelFile.sources || []])
542
+ });
543
+ } else {
544
+ files.set(barrelFile.path, barrelFile);
545
+ }
546
+ });
547
+ return [...files.values()];
548
+ }
549
+ };
550
+
551
+ // src/FileManager.ts
552
+ import { trimExtName } from "@kubb/fs";
553
+ import PQueue from "p-queue";
554
+ var FileManager = class {
555
+ #filesByPath = /* @__PURE__ */ new Map();
556
+ #files = /* @__PURE__ */ new Set();
557
+ constructor() {
558
+ return this;
559
+ }
560
+ get files() {
561
+ return Array.from(this.#files);
562
+ }
563
+ get orderedFiles() {
564
+ return orderBy(Array.from(this.#files), [
565
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
566
+ (v) => v.path.length,
567
+ (v) => trimExtName(v.path).endsWith("index"),
568
+ (v) => trimExtName(v.baseName),
569
+ (v) => v.path.split(".").pop()
570
+ ]);
571
+ }
572
+ get groupedFiles() {
573
+ return buildDirectoryTree(Array.from(this.#files));
574
+ }
575
+ get treeNode() {
576
+ return TreeNode.build(Array.from(this.#files));
577
+ }
578
+ async add(...files) {
579
+ const promises = files.map((file) => {
580
+ if (file.override) {
581
+ return this.#add(file);
582
+ }
583
+ return this.#addOrAppend(file);
584
+ });
585
+ const resolvedFiles = await Promise.all(promises);
586
+ if (files.length > 1) {
587
+ return resolvedFiles;
588
+ }
589
+ return resolvedFiles[0];
590
+ }
591
+ async #add(file) {
592
+ const resolvedFile = createFile(file);
593
+ this.#filesByPath.set(resolvedFile.path, resolvedFile);
594
+ this.#files.add(resolvedFile);
595
+ return resolvedFile;
596
+ }
597
+ clear() {
598
+ this.#filesByPath.clear();
599
+ this.#files.clear();
600
+ }
601
+ async #addOrAppend(file) {
602
+ const previousFile = this.#filesByPath.get(file.path);
603
+ if (previousFile) {
604
+ this.#filesByPath.delete(previousFile.path);
605
+ this.#files.delete(previousFile);
606
+ return this.#add(mergeFile(previousFile, file));
607
+ }
608
+ return this.#add(file);
609
+ }
610
+ getCacheById(id) {
611
+ let cache;
612
+ this.#files.forEach((file) => {
613
+ if (file.id === id) {
614
+ cache = file;
615
+ }
616
+ });
617
+ return cache;
618
+ }
619
+ getByPath(path) {
620
+ return this.#filesByPath.get(path);
621
+ }
622
+ deleteByPath(path) {
623
+ const cacheItem = this.getByPath(path);
624
+ if (!cacheItem) {
625
+ return;
626
+ }
627
+ this.#filesByPath.delete(path);
628
+ this.#files.delete(cacheItem);
629
+ }
630
+ async getBarrelFiles({ files, meta, root, output, logger }) {
631
+ const { exportType = "barrelNamed" } = output;
632
+ const barrelManager = new BarrelManager({ logger });
633
+ if (exportType === false) {
634
+ return [];
635
+ }
636
+ const pathToBuildFrom = join2(root, output.path);
637
+ if (trimExtName(pathToBuildFrom).endsWith("index")) {
638
+ logger?.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
639
+ return [];
640
+ }
641
+ const barrelFiles = barrelManager.getFiles(files, pathToBuildFrom);
642
+ if (exportType === "barrel") {
643
+ return barrelFiles.map((file) => {
644
+ return {
645
+ ...file,
646
+ exports: file.exports?.map((exportItem) => {
647
+ return {
648
+ ...exportItem,
649
+ name: void 0
650
+ };
651
+ })
652
+ };
653
+ });
654
+ }
655
+ return barrelFiles.map((indexFile) => {
656
+ return {
657
+ ...indexFile,
658
+ meta
659
+ };
660
+ });
661
+ }
662
+ async write(...params) {
663
+ return write(...params);
664
+ }
665
+ async read(...params) {
666
+ return read(...params);
667
+ }
668
+ // statics
669
+ static getMode(path) {
670
+ if (!path) {
671
+ return "split";
672
+ }
673
+ return extname(path) ? "single" : "split";
674
+ }
675
+ };
676
+ async function getSource(file, { logger } = {}) {
677
+ const parser = await getFileParser(file.extName);
678
+ return parser.print(file, { logger });
679
+ }
680
+ function mergeFile(a, b) {
681
+ return {
682
+ ...a,
683
+ sources: [...a.sources || [], ...b.sources || []],
684
+ imports: [...a.imports || [], ...b.imports || []],
685
+ exports: [...a.exports || [], ...b.exports || []]
686
+ };
687
+ }
688
+ function combineSources(sources) {
689
+ return sources.reduce(
690
+ (prev, curr) => {
691
+ const prevByName = prev.findLast((imp) => imp.name === curr.name);
692
+ const prevByPathAndIsExportable = prev.findLast((imp) => imp.name === curr.name && imp.isExportable);
693
+ if (prevByPathAndIsExportable) {
694
+ return [...prev, curr];
695
+ }
696
+ if (prevByName) {
697
+ prevByName.value = curr.value;
698
+ prevByName.isExportable = curr.isExportable;
699
+ prevByName.isTypeOnly = curr.isTypeOnly;
700
+ prevByName.isIndexable = curr.isIndexable;
701
+ return prev;
702
+ }
703
+ return [...prev, curr];
704
+ },
705
+ []
706
+ );
707
+ }
708
+ function combineExports(exports) {
709
+ const combinedExports = exports.reduce(
710
+ (prev, curr) => {
711
+ const name = curr.name;
712
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path);
713
+ const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
714
+ if (prevByPathAndIsTypeOnly) {
715
+ return prev;
716
+ }
717
+ const uniquePrev = prev.findLast(
718
+ (imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
719
+ );
720
+ if (uniquePrev || Array.isArray(name) && !name.length || prevByPath?.asAlias && !curr.asAlias) {
721
+ return prev;
722
+ }
723
+ if (!prevByPath) {
724
+ return [
725
+ ...prev,
726
+ {
727
+ ...curr,
728
+ name: Array.isArray(name) ? [...new Set(name)] : name
729
+ }
730
+ ];
731
+ }
732
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
733
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...curr.name])];
734
+ return prev;
735
+ }
736
+ return [...prev, curr];
737
+ },
738
+ []
739
+ );
740
+ return orderBy(combinedExports, [
741
+ (v) => !!Array.isArray(v.name),
742
+ (v) => !v.isTypeOnly,
743
+ (v) => v.path,
744
+ (v) => !!v.name,
745
+ (v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
746
+ ]);
747
+ }
748
+ function combineImports(imports, exports, source) {
749
+ const combinedImports = imports.reduce(
750
+ (prev, curr) => {
751
+ let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
752
+ const hasImportInSource = (importName) => {
753
+ if (!source) {
754
+ return true;
755
+ }
756
+ const checker = (name2) => name2 && !!source.includes(name2);
757
+ return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
758
+ };
759
+ if (curr.path === curr.root) {
760
+ return prev;
761
+ }
762
+ if (Array.isArray(name)) {
763
+ name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
764
+ }
765
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
766
+ const uniquePrev = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
767
+ const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
768
+ if (prevByPathNameAndIsTypeOnly) {
769
+ return prev;
770
+ }
771
+ if (uniquePrev || Array.isArray(name) && !name.length) {
772
+ return prev;
773
+ }
774
+ if (!prevByPath) {
775
+ return [
776
+ ...prev,
777
+ {
778
+ ...curr,
779
+ name
780
+ }
781
+ ];
782
+ }
783
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
784
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...name])];
785
+ return prev;
786
+ }
787
+ if (!Array.isArray(name) && name && !hasImportInSource(name)) {
788
+ return prev;
789
+ }
790
+ return [...prev, curr];
791
+ },
792
+ []
793
+ );
794
+ return orderBy(combinedImports, [
795
+ (v) => !!Array.isArray(v.name),
796
+ (v) => !v.isTypeOnly,
797
+ (v) => v.path,
798
+ (v) => !!v.name,
799
+ (v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
800
+ ]);
801
+ }
802
+ var queue = new PQueue({ concurrency: 100 });
803
+ async function processFiles({ dryRun, config, logger, files }) {
804
+ const orderedFiles = orderBy(files, [
805
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
806
+ (v) => v.path.length,
807
+ (v) => trimExtName(v.path).endsWith("index")
808
+ ]);
809
+ logger.emit("debug", {
810
+ logs: [JSON.stringify({ files: orderedFiles }, null, 2)],
811
+ fileName: "kubb-files.json",
812
+ override: true
813
+ });
814
+ if (!dryRun) {
815
+ const size = orderedFiles.length;
816
+ logger.emit("progress_start", { id: "files", size });
817
+ const promises = orderedFiles.map(async (file) => {
818
+ await queue.add(async () => {
819
+ const source = await getSource(file, { logger });
820
+ await write(file.path, source, { sanity: false });
821
+ logger.emit("progress", { id: "files", data: file ? relative(config.root, file.path) : "" });
822
+ });
823
+ });
824
+ await Promise.all(promises);
825
+ logger.emit("progress_stop", { id: "files" });
826
+ }
827
+ return files;
828
+ }
829
+
830
+ // src/utils/parser.ts
831
+ function createFile(file) {
832
+ const extName = extname2(file.baseName);
833
+ if (!extName) {
834
+ throw new Error(`No extName found for ${file.baseName}`);
835
+ }
836
+ const source = file.sources.map((item) => item.value).join("\n\n");
837
+ const exports = file.exports ? combineExports(file.exports) : [];
838
+ const imports = file.imports && source ? combineImports(file.imports, exports, source) : [];
839
+ const sources = file.sources ? combineSources(file.sources) : [];
840
+ return {
841
+ ...file,
842
+ id: hash({ path: file.path }),
843
+ name: trimExtName2(file.baseName),
844
+ extName,
845
+ imports: imports.map((item) => createFileImport(item)),
846
+ exports: exports.map((item) => createFileExport(item)),
847
+ sources: sources.map((item) => createFileSource(item))
848
+ };
849
+ }
850
+ function createFileSource(source) {
851
+ return source;
852
+ }
853
+ function createFileImport(imp) {
854
+ const extName = extname2(imp.path);
855
+ return {
856
+ ...imp,
857
+ extName: imp.extName ? imp.extName : extName
858
+ };
859
+ }
860
+ function createFileExport(exp) {
861
+ const extName = extname2(exp.path);
862
+ return {
863
+ ...exp,
864
+ extName: exp.extName ? exp.extName : extName
865
+ };
866
+ }
867
+ function createFileParser(parser) {
868
+ return parser;
869
+ }
870
+ var typeScriptParser = createFileParser({
871
+ render() {
872
+ return void 0;
873
+ },
874
+ async print(file) {
875
+ const module = await import("@kubb/parser-ts");
876
+ const importNodes = file.imports.map((item) => {
877
+ const path = item.root ? getRelativePath2(item.root, item.path) : item.path;
878
+ return module.factory.createImportDeclaration({
879
+ name: item.name,
880
+ path,
881
+ isTypeOnly: item.isTypeOnly
882
+ });
883
+ }).filter(Boolean);
884
+ const exportNodes = file.exports.map((item) => {
885
+ return module.factory.createExportDeclaration({
886
+ name: item.name,
887
+ path: item.path,
888
+ isTypeOnly: item.isTypeOnly,
889
+ asAlias: item.asAlias
890
+ });
891
+ }).filter(Boolean);
892
+ const source = [module.print([...importNodes, ...exportNodes]), file.sources.map((item) => item.value).join("\n\n")].join("\n");
893
+ return module.print([], { source, noEmitHelpers: false });
894
+ }
895
+ });
896
+ var defaultParser = createFileParser({
897
+ render() {
898
+ return void 0;
899
+ },
900
+ async print(file, { logger }) {
901
+ return file.sources.map((item) => item.value).join("\n\n");
902
+ }
903
+ });
904
+ var parsers = {
905
+ ".ts": typeScriptParser,
906
+ ".js": typeScriptParser,
907
+ ".jsx": typeScriptParser,
908
+ ".tsx": typeScriptParser,
909
+ ".json": defaultParser
910
+ };
911
+ async function getFileParser(extName) {
912
+ if (!extName) {
913
+ return defaultParser;
914
+ }
915
+ const parser = parsers[extName];
916
+ if (!parser) {
917
+ console.warn(`[parser] No parser found for ${extName}, default parser will be used`);
918
+ }
919
+ return parser || defaultParser;
920
+ }
921
+ function trimExtName2(text) {
922
+ const extName = text.split(".").pop();
923
+ return text.replace(`.${extName}`, "");
924
+ }
925
+
926
+ export {
927
+ FunctionParams,
928
+ isPromise,
929
+ isPromiseFulfilledResult,
930
+ isPromiseRejectedResult,
931
+ renderTemplate,
932
+ timeout,
933
+ getUniqueName,
934
+ setUniqueName,
935
+ URLPath,
936
+ createFile,
937
+ createFileImport,
938
+ createFileExport,
939
+ createFileParser,
940
+ getFileParser,
941
+ FileManager,
942
+ getSource,
943
+ processFiles
944
+ };
945
+ //# sourceMappingURL=chunk-27CPVXAT.js.map