@kubb/core 3.0.0-alpha.2 → 3.0.0-alpha.21

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