@kubb/core 3.0.0-alpha.0 → 3.0.0-alpha.10

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 (99) hide show
  1. package/dist/FileManager-BbUCeEyv.d.cts +469 -0
  2. package/dist/FileManager-CpuFz6eH.d.ts +469 -0
  3. package/dist/chunk-2EU7DMPM.js +97 -0
  4. package/dist/chunk-2EU7DMPM.js.map +1 -0
  5. package/dist/chunk-5E2I6KH4.cjs +1071 -0
  6. package/dist/chunk-5E2I6KH4.cjs.map +1 -0
  7. package/dist/{chunk-XRC6KXC3.cjs → chunk-A6PCLWEY.cjs} +5 -5
  8. package/dist/{chunk-XRC6KXC3.cjs.map → chunk-A6PCLWEY.cjs.map} +1 -1
  9. package/dist/chunk-DID47EQD.cjs +102 -0
  10. package/dist/chunk-DID47EQD.cjs.map +1 -0
  11. package/dist/chunk-HBQM723K.js +1063 -0
  12. package/dist/chunk-HBQM723K.js.map +1 -0
  13. package/dist/chunk-L6YLVCKM.js +929 -0
  14. package/dist/chunk-L6YLVCKM.js.map +1 -0
  15. package/dist/{chunk-XRUOSVKX.cjs → chunk-M7NLNCSM.cjs} +71 -38
  16. package/dist/chunk-M7NLNCSM.cjs.map +1 -0
  17. package/dist/{chunk-3OXCZ5DJ.js → chunk-MU3CBCQT.js} +59 -35
  18. package/dist/chunk-MU3CBCQT.js.map +1 -0
  19. package/dist/chunk-NB4JMN75.cjs +1548 -0
  20. package/dist/chunk-NB4JMN75.cjs.map +1 -0
  21. package/dist/chunk-SEH6NUCX.cjs +42 -0
  22. package/dist/chunk-SEH6NUCX.cjs.map +1 -0
  23. package/dist/index.cjs +496 -552
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +9 -477
  26. package/dist/index.d.ts +9 -477
  27. package/dist/index.js +438 -492
  28. package/dist/index.js.map +1 -1
  29. package/dist/{logger-DChjnJMn.d.cts → logger-DvbHXjIO.d.cts} +29 -19
  30. package/dist/{logger-DChjnJMn.d.ts → logger-DvbHXjIO.d.ts} +29 -19
  31. package/dist/logger.cjs +4 -5
  32. package/dist/logger.cjs.map +1 -1
  33. package/dist/logger.d.cts +1 -2
  34. package/dist/logger.d.ts +1 -2
  35. package/dist/logger.js +2 -4
  36. package/dist/mocks.cjs +25 -19
  37. package/dist/mocks.cjs.map +1 -1
  38. package/dist/mocks.d.cts +6 -9
  39. package/dist/mocks.d.ts +6 -9
  40. package/dist/mocks.js +21 -16
  41. package/dist/mocks.js.map +1 -1
  42. package/dist/prompt-DVQN7JTN.cjs +760 -0
  43. package/dist/prompt-DVQN7JTN.cjs.map +1 -0
  44. package/dist/prompt-WQQUN22Z.js +754 -0
  45. package/dist/prompt-WQQUN22Z.js.map +1 -0
  46. package/dist/transformers.cjs +198 -42
  47. package/dist/transformers.cjs.map +1 -1
  48. package/dist/transformers.d.cts +1 -3
  49. package/dist/transformers.d.ts +1 -3
  50. package/dist/transformers.js +155 -14
  51. package/dist/transformers.js.map +1 -1
  52. package/dist/utils.cjs +12 -4
  53. package/dist/utils.cjs.map +1 -1
  54. package/dist/utils.d.cts +31 -3
  55. package/dist/utils.d.ts +31 -3
  56. package/dist/utils.js +11 -4
  57. package/package.json +11 -14
  58. package/src/BarrelManager.ts +93 -107
  59. package/src/{Generator.ts → BaseGenerator.ts} +1 -1
  60. package/src/FileManager.ts +198 -297
  61. package/src/PackageManager.ts +1 -1
  62. package/src/PluginManager.ts +152 -101
  63. package/src/__snapshots__/barrel.json +91 -0
  64. package/src/__snapshots__/grouped.json +114 -0
  65. package/src/__snapshots__/ordered.json +62 -0
  66. package/src/build.ts +86 -171
  67. package/src/errors.ts +0 -11
  68. package/src/index.ts +1 -5
  69. package/src/logger.ts +76 -34
  70. package/src/plugin.ts +3 -3
  71. package/src/transformers/index.ts +2 -3
  72. package/src/transformers/trim.ts +0 -4
  73. package/src/types.ts +35 -40
  74. package/src/utils/TreeNode.ts +132 -50
  75. package/src/utils/executeStrategies.ts +1 -1
  76. package/src/utils/index.ts +2 -1
  77. package/src/utils/parser.ts +157 -0
  78. package/dist/chunk-3OXCZ5DJ.js.map +0 -1
  79. package/dist/chunk-5JZNFPUP.js +0 -309
  80. package/dist/chunk-5JZNFPUP.js.map +0 -1
  81. package/dist/chunk-DKW7IBJV.cjs +0 -299
  82. package/dist/chunk-DKW7IBJV.cjs.map +0 -1
  83. package/dist/chunk-HMLY7DHA.js +0 -16
  84. package/dist/chunk-HMLY7DHA.js.map +0 -1
  85. package/dist/chunk-JKZG2IJR.js +0 -283
  86. package/dist/chunk-JKZG2IJR.js.map +0 -1
  87. package/dist/chunk-LKXUCYWU.cjs +0 -66
  88. package/dist/chunk-LKXUCYWU.cjs.map +0 -1
  89. package/dist/chunk-OPOT6TCT.cjs +0 -320
  90. package/dist/chunk-OPOT6TCT.cjs.map +0 -1
  91. package/dist/chunk-SA2GZKXS.js +0 -596
  92. package/dist/chunk-SA2GZKXS.js.map +0 -1
  93. package/dist/chunk-XRUOSVKX.cjs.map +0 -1
  94. package/dist/chunk-Y3LLJA4H.cjs +0 -1227
  95. package/dist/chunk-Y3LLJA4H.cjs.map +0 -1
  96. package/globals.d.ts +0 -49
  97. package/schema.json +0 -86
  98. package/src/kubb.ts +0 -11
  99. package/src/utils/getParser.ts +0 -17
@@ -0,0 +1,929 @@
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
+ #cachedLeaves = void 0;
290
+ constructor(data, parent) {
291
+ this.data = data;
292
+ this.parent = parent;
293
+ return this;
294
+ }
295
+ addChild(data) {
296
+ const child = new _TreeNode(data, this);
297
+ if (!this.children) {
298
+ this.children = [];
299
+ }
300
+ this.children.push(child);
301
+ return child;
302
+ }
303
+ get root() {
304
+ if (!this.parent) {
305
+ return this;
306
+ }
307
+ return this.parent.root;
308
+ }
309
+ get leaves() {
310
+ if (!this.children || this.children.length === 0) {
311
+ return [this];
312
+ }
313
+ if (this.#cachedLeaves) {
314
+ return this.#cachedLeaves;
315
+ }
316
+ const leaves = [];
317
+ if (this.children) {
318
+ for (let i = 0, { length } = this.children; i < length; i++) {
319
+ leaves.push.apply(leaves, this.children[i].leaves);
320
+ }
321
+ }
322
+ this.#cachedLeaves = leaves;
323
+ return leaves;
324
+ }
325
+ forEach(callback) {
326
+ if (typeof callback !== "function") {
327
+ throw new TypeError("forEach() callback must be a function");
328
+ }
329
+ callback(this);
330
+ if (this.children) {
331
+ for (let i = 0, { length } = this.children; i < length; i++) {
332
+ this.children[i]?.forEach(callback);
333
+ }
334
+ }
335
+ return this;
336
+ }
337
+ findDeep(predicate) {
338
+ if (typeof predicate !== "function") {
339
+ throw new TypeError("find() predicate must be a function");
340
+ }
341
+ return this.leaves.find(predicate);
342
+ }
343
+ forEachDeep(callback) {
344
+ if (typeof callback !== "function") {
345
+ throw new TypeError("forEach() callback must be a function");
346
+ }
347
+ this.leaves.forEach(callback);
348
+ }
349
+ filterDeep(callback) {
350
+ if (typeof callback !== "function") {
351
+ throw new TypeError("filter() callback must be a function");
352
+ }
353
+ return this.leaves.filter(callback);
354
+ }
355
+ mapDeep(callback) {
356
+ if (typeof callback !== "function") {
357
+ throw new TypeError("map() callback must be a function");
358
+ }
359
+ return this.leaves.map(callback);
360
+ }
361
+ static build(files, root) {
362
+ try {
363
+ const filteredTree = buildDirectoryTree(files, root);
364
+ if (!filteredTree) {
365
+ return null;
366
+ }
367
+ const treeNode = new _TreeNode({
368
+ name: filteredTree.name,
369
+ path: filteredTree.path,
370
+ file: filteredTree.file,
371
+ type: FileManager.getMode(filteredTree.path)
372
+ });
373
+ const recurse = (node, item) => {
374
+ const subNode = node.addChild({
375
+ name: item.name,
376
+ path: item.path,
377
+ file: item.file,
378
+ type: FileManager.getMode(item.path)
379
+ });
380
+ if (item.children?.length) {
381
+ item.children?.forEach((child) => {
382
+ recurse(subNode, child);
383
+ });
384
+ }
385
+ };
386
+ filteredTree.children?.forEach((child) => recurse(treeNode, child));
387
+ return treeNode;
388
+ } catch (e) {
389
+ throw new Error("Something went wrong with creating barrel files with the TreeNode class", { cause: e });
390
+ }
391
+ }
392
+ };
393
+ function buildDirectoryTree(files, rootFolder = "") {
394
+ const rootPrefix = rootFolder.endsWith("/") ? rootFolder : `${rootFolder}/`;
395
+ const filteredFiles = files.filter((file) => rootFolder ? file.path.startsWith(rootPrefix) && !file.path.endsWith(".json") : !file.path.endsWith(".json"));
396
+ if (filteredFiles.length === 0) {
397
+ return null;
398
+ }
399
+ const root = {
400
+ name: rootFolder || "",
401
+ path: rootFolder || "",
402
+ children: []
403
+ };
404
+ filteredFiles.forEach((file) => {
405
+ const path = file.path.slice(rootFolder.length);
406
+ const parts = path.split("/");
407
+ let currentLevel = root.children;
408
+ let currentPath = rootFolder;
409
+ parts.forEach((part, index) => {
410
+ if (index !== 0) {
411
+ currentPath += `/${part}`;
412
+ } else {
413
+ currentPath += `${part}`;
414
+ }
415
+ let existingNode = currentLevel.find((node) => node.name === part);
416
+ if (!existingNode) {
417
+ if (index === parts.length - 1) {
418
+ existingNode = {
419
+ name: part,
420
+ file,
421
+ path: currentPath
422
+ };
423
+ } else {
424
+ existingNode = {
425
+ name: part,
426
+ path: currentPath,
427
+ children: []
428
+ };
429
+ }
430
+ currentLevel.push(existingNode);
431
+ }
432
+ if (!existingNode.file) {
433
+ currentLevel = existingNode.children;
434
+ }
435
+ });
436
+ });
437
+ return root;
438
+ }
439
+
440
+ // src/BarrelManager.ts
441
+ import { getRelativePath } from "@kubb/fs";
442
+ var BarrelManager = class {
443
+ #options;
444
+ constructor(options = {}) {
445
+ this.#options = options;
446
+ return this;
447
+ }
448
+ getFiles({ files: generatedFiles, root, meta }) {
449
+ const { logger } = this.#options;
450
+ const cachedFiles = /* @__PURE__ */ new Map();
451
+ logger?.emit("debug", { date: /* @__PURE__ */ new Date(), logs: [`Start barrel generation for pluginKey ${meta?.pluginKey?.join(".")} and root '${root}'`] });
452
+ TreeNode.build(generatedFiles, root)?.forEach((treeNode) => {
453
+ if (!treeNode || !treeNode.children || !treeNode.parent?.data.path) {
454
+ return void 0;
455
+ }
456
+ const barrelFile = {
457
+ path: join(treeNode.parent?.data.path, "index.ts"),
458
+ baseName: "index.ts",
459
+ exports: [],
460
+ sources: []
461
+ };
462
+ const previousBarrelFile = cachedFiles.get(barrelFile.path);
463
+ const leaves = treeNode.leaves;
464
+ leaves.forEach((item) => {
465
+ if (!item.data.name) {
466
+ return void 0;
467
+ }
468
+ const sources = item.data.file?.sources || [];
469
+ if (!sources.some((source) => source.isIndexable)) {
470
+ logger?.emit(
471
+ "warning",
472
+ `No isIndexable source found(source should have a name and isIndexable):
473
+ File: ${JSON.stringify(item.data.file, void 0, 2)}`
474
+ );
475
+ }
476
+ sources.forEach((source) => {
477
+ if (!item.data.file?.path || !source.isIndexable || !source.name) {
478
+ return void 0;
479
+ }
480
+ const alreadyContainInPreviousBarrelFile = previousBarrelFile?.sources.some((item2) => item2.name === source.name);
481
+ if (alreadyContainInPreviousBarrelFile) {
482
+ return void 0;
483
+ }
484
+ if (!barrelFile.exports) {
485
+ barrelFile.exports = [];
486
+ }
487
+ const isSubExport = !!treeNode.parent?.data.path?.split?.("/")?.length;
488
+ if (isSubExport) {
489
+ barrelFile.exports.push({
490
+ name: [source.name],
491
+ path: getRelativePath(treeNode.parent?.data.path, item.data.path),
492
+ isTypeOnly: source.isTypeOnly
493
+ });
494
+ } else {
495
+ barrelFile.exports.push({
496
+ name: [source.name],
497
+ path: `./${item.data.file.baseName}`,
498
+ isTypeOnly: source.isTypeOnly
499
+ });
500
+ }
501
+ barrelFile.sources.push({
502
+ name: source.name,
503
+ isTypeOnly: source.isTypeOnly,
504
+ //TODO use parser to generate import
505
+ value: "",
506
+ isExportable: false,
507
+ isIndexable: false
508
+ });
509
+ });
510
+ });
511
+ logger?.emit("debug", {
512
+ date: /* @__PURE__ */ new Date(),
513
+ logs: [
514
+ `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(", ")}'`
515
+ ]
516
+ });
517
+ logger?.emit("debug", {
518
+ date: /* @__PURE__ */ new Date(),
519
+ logs: [
520
+ `Generated barrelFile '${getRelativePath(root, barrelFile.path)}' for '${getRelativePath(root, treeNode.data?.path)}' with exports: '${cachedFiles.get(barrelFile.path)?.sources?.map((source) => source.name).join(", ")}'`
521
+ ]
522
+ });
523
+ if (previousBarrelFile) {
524
+ previousBarrelFile.sources.push(...barrelFile.sources);
525
+ previousBarrelFile.exports?.push(...barrelFile.exports || []);
526
+ } else {
527
+ cachedFiles.set(barrelFile.path, barrelFile);
528
+ }
529
+ });
530
+ return [...cachedFiles.values()];
531
+ }
532
+ };
533
+
534
+ // src/FileManager.ts
535
+ import { trimExtName } from "@kubb/fs";
536
+ import PQueue from "p-queue";
537
+ var FileManager = class {
538
+ #filesByPath = /* @__PURE__ */ new Map();
539
+ #files = /* @__PURE__ */ new Set();
540
+ constructor() {
541
+ return this;
542
+ }
543
+ get files() {
544
+ return Array.from(this.#files);
545
+ }
546
+ get orderedFiles() {
547
+ return orderBy(Array.from(this.#files), [
548
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
549
+ (v) => v.path.length,
550
+ (v) => trimExtName(v.path).endsWith("index"),
551
+ (v) => trimExtName(v.baseName),
552
+ (v) => v.path.split(".").pop()
553
+ ]);
554
+ }
555
+ get groupedFiles() {
556
+ return buildDirectoryTree(Array.from(this.#files));
557
+ }
558
+ get treeNode() {
559
+ return TreeNode.build(Array.from(this.#files));
560
+ }
561
+ async add(...files) {
562
+ const promises = files.map((file) => {
563
+ if (file.override) {
564
+ return this.#add(file);
565
+ }
566
+ return this.#addOrAppend(file);
567
+ });
568
+ const resolvedFiles = await Promise.all(promises);
569
+ if (files.length > 1) {
570
+ return resolvedFiles;
571
+ }
572
+ return resolvedFiles[0];
573
+ }
574
+ async #add(file) {
575
+ const resolvedFile = createFile(file);
576
+ this.#filesByPath.set(resolvedFile.path, resolvedFile);
577
+ this.#files.add(resolvedFile);
578
+ return resolvedFile;
579
+ }
580
+ clear() {
581
+ this.#filesByPath.clear();
582
+ this.#files.clear();
583
+ }
584
+ async #addOrAppend(file) {
585
+ const previousFile = this.#filesByPath.get(file.path);
586
+ if (previousFile) {
587
+ this.#filesByPath.delete(previousFile.path);
588
+ this.#files.delete(previousFile);
589
+ return this.#add(mergeFile(previousFile, file));
590
+ }
591
+ return this.#add(file);
592
+ }
593
+ getCacheById(id) {
594
+ let cache;
595
+ this.#files.forEach((file) => {
596
+ if (file.id === id) {
597
+ cache = file;
598
+ }
599
+ });
600
+ return cache;
601
+ }
602
+ getByPath(path) {
603
+ return this.#filesByPath.get(path);
604
+ }
605
+ deleteByPath(path) {
606
+ const cacheItem = this.getByPath(path);
607
+ if (!cacheItem) {
608
+ return;
609
+ }
610
+ this.#filesByPath.delete(path);
611
+ this.#files.delete(cacheItem);
612
+ }
613
+ async getBarrelFiles({ files, meta, root, output, logger }) {
614
+ const { exportType = "barrelNamed" } = output;
615
+ const barrelManager = new BarrelManager({ logger });
616
+ if (exportType === false) {
617
+ return [];
618
+ }
619
+ const pathToBuildFrom = join2(root, output.path);
620
+ if (trimExtName(pathToBuildFrom).endsWith("index")) {
621
+ logger?.emit("warning", "Output has the same fileName as the barrelFiles, please disable barrel generation");
622
+ return [];
623
+ }
624
+ const barrelFiles = barrelManager.getFiles({ files, root: pathToBuildFrom, meta });
625
+ if (exportType === "barrel") {
626
+ return barrelFiles.map((file) => {
627
+ return {
628
+ ...file,
629
+ exports: file.exports?.map((exportItem) => {
630
+ return {
631
+ ...exportItem,
632
+ name: void 0
633
+ };
634
+ })
635
+ };
636
+ });
637
+ }
638
+ return barrelFiles.map((indexFile) => {
639
+ return {
640
+ ...indexFile,
641
+ meta
642
+ };
643
+ });
644
+ }
645
+ async write(...params) {
646
+ return write(...params);
647
+ }
648
+ async read(...params) {
649
+ return read(...params);
650
+ }
651
+ // statics
652
+ static getMode(path) {
653
+ if (!path) {
654
+ return "split";
655
+ }
656
+ return extname(path) ? "single" : "split";
657
+ }
658
+ };
659
+ async function getSource(file, { logger } = {}) {
660
+ const parser = await getFileParser(file.extName);
661
+ return parser.print(file, { logger });
662
+ }
663
+ function mergeFile(a, b) {
664
+ return {
665
+ ...a,
666
+ sources: [...a.sources || [], ...b.sources || []],
667
+ imports: [...a.imports || [], ...b.imports || []],
668
+ exports: [...a.exports || [], ...b.exports || []]
669
+ };
670
+ }
671
+ function combineSources(sources) {
672
+ return sources.reduce(
673
+ (prev, curr) => {
674
+ const prevByName = prev.findLast((imp) => imp.name === curr.name);
675
+ const prevByPathAndIsExportable = prev.findLast((imp) => imp.name === curr.name && imp.isExportable);
676
+ if (prevByPathAndIsExportable) {
677
+ return [...prev, curr];
678
+ }
679
+ if (prevByName) {
680
+ prevByName.value = curr.value;
681
+ prevByName.isExportable = curr.isExportable;
682
+ prevByName.isTypeOnly = curr.isTypeOnly;
683
+ prevByName.isIndexable = curr.isIndexable;
684
+ return prev;
685
+ }
686
+ return [...prev, curr];
687
+ },
688
+ []
689
+ );
690
+ }
691
+ function combineExports(exports) {
692
+ const combinedExports = exports.reduce(
693
+ (prev, curr) => {
694
+ const name = curr.name;
695
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path);
696
+ const prevByPathAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
697
+ if (prevByPathAndIsTypeOnly) {
698
+ return prev;
699
+ }
700
+ const uniquePrev = prev.findLast(
701
+ (imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly && imp.asAlias === curr.asAlias
702
+ );
703
+ if (uniquePrev || Array.isArray(name) && !name.length || prevByPath?.asAlias && !curr.asAlias) {
704
+ return prev;
705
+ }
706
+ if (!prevByPath) {
707
+ return [
708
+ ...prev,
709
+ {
710
+ ...curr,
711
+ name: Array.isArray(name) ? [...new Set(name)] : name
712
+ }
713
+ ];
714
+ }
715
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(curr.name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
716
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...curr.name])];
717
+ return prev;
718
+ }
719
+ return [...prev, curr];
720
+ },
721
+ []
722
+ );
723
+ return orderBy(combinedExports, [
724
+ (v) => !!Array.isArray(v.name),
725
+ (v) => !v.isTypeOnly,
726
+ (v) => v.path,
727
+ (v) => !!v.name,
728
+ (v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
729
+ ]);
730
+ }
731
+ function combineImports(imports, exports, source) {
732
+ const combinedImports = imports.reduce(
733
+ (prev, curr) => {
734
+ let name = Array.isArray(curr.name) ? [...new Set(curr.name)] : curr.name;
735
+ const hasImportInSource = (importName) => {
736
+ if (!source) {
737
+ return true;
738
+ }
739
+ const checker = (name2) => name2 && !!source.includes(name2);
740
+ return checker(importName) || exports.some(({ name: name2 }) => Array.isArray(name2) ? name2.some(checker) : checker(name2));
741
+ };
742
+ if (curr.path === curr.root) {
743
+ return prev;
744
+ }
745
+ if (Array.isArray(name)) {
746
+ name = name.filter((item) => typeof item === "string" ? hasImportInSource(item) : hasImportInSource(item.propertyName));
747
+ }
748
+ const prevByPath = prev.findLast((imp) => imp.path === curr.path && imp.isTypeOnly === curr.isTypeOnly);
749
+ const uniquePrev = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly === curr.isTypeOnly);
750
+ const prevByPathNameAndIsTypeOnly = prev.findLast((imp) => imp.path === curr.path && isDeepEqual(imp.name, name) && imp.isTypeOnly);
751
+ if (prevByPathNameAndIsTypeOnly) {
752
+ return prev;
753
+ }
754
+ if (uniquePrev || Array.isArray(name) && !name.length) {
755
+ return prev;
756
+ }
757
+ if (!prevByPath) {
758
+ return [
759
+ ...prev,
760
+ {
761
+ ...curr,
762
+ name
763
+ }
764
+ ];
765
+ }
766
+ if (prevByPath && Array.isArray(prevByPath.name) && Array.isArray(name) && prevByPath.isTypeOnly === curr.isTypeOnly) {
767
+ prevByPath.name = [.../* @__PURE__ */ new Set([...prevByPath.name, ...name])];
768
+ return prev;
769
+ }
770
+ if (!Array.isArray(name) && name && !hasImportInSource(name)) {
771
+ return prev;
772
+ }
773
+ return [...prev, curr];
774
+ },
775
+ []
776
+ );
777
+ return orderBy(combinedImports, [
778
+ (v) => !!Array.isArray(v.name),
779
+ (v) => !v.isTypeOnly,
780
+ (v) => v.path,
781
+ (v) => !!v.name,
782
+ (v) => Array.isArray(v.name) ? orderBy(v.name) : v.name
783
+ ]);
784
+ }
785
+ var queue = new PQueue({ concurrency: 100 });
786
+ async function processFiles({ dryRun, config, logger, files }) {
787
+ const orderedFiles = orderBy(files, [
788
+ (v) => v?.meta && "pluginKey" in v.meta && !v.meta.pluginKey,
789
+ (v) => v.path.length,
790
+ (v) => trimExtName(v.path).endsWith("index")
791
+ ]);
792
+ logger.emit("debug", {
793
+ date: /* @__PURE__ */ new Date(),
794
+ logs: [JSON.stringify({ files: orderedFiles }, null, 2)],
795
+ fileName: "kubb-files.log"
796
+ });
797
+ if (!dryRun) {
798
+ const size = orderedFiles.length;
799
+ logger.emit("progress_start", { id: "files", size, message: "Writing files ..." });
800
+ const promises = orderedFiles.map(async (file) => {
801
+ await queue.add(async () => {
802
+ const message = file ? `Writing ${relative(config.root, file.path)}` : "";
803
+ const source = await getSource(file, { logger });
804
+ await write(file.path, source, { sanity: false });
805
+ logger.emit("progressed", { id: "files", message });
806
+ });
807
+ });
808
+ await Promise.all(promises);
809
+ logger.emit("progress_stop", { id: "files" });
810
+ }
811
+ return files;
812
+ }
813
+
814
+ // src/utils/parser.ts
815
+ function createFile(file) {
816
+ const extName = extname2(file.baseName);
817
+ if (!extName) {
818
+ throw new Error(`No extName found for ${file.baseName}`);
819
+ }
820
+ const source = file.sources.map((item) => item.value).join("\n\n");
821
+ const exports = file.exports ? combineExports(file.exports) : [];
822
+ const imports = file.imports && source ? combineImports(file.imports, exports, source) : [];
823
+ const sources = file.sources ? combineSources(file.sources) : [];
824
+ return {
825
+ ...file,
826
+ id: hash({ path: file.path }),
827
+ name: trimExtName2(file.baseName),
828
+ extName,
829
+ imports: imports.map((item) => createFileImport(item)),
830
+ exports: exports.map((item) => createFileExport(item)),
831
+ sources: sources.map((item) => createFileSource(item))
832
+ };
833
+ }
834
+ function createFileSource(source) {
835
+ return source;
836
+ }
837
+ function createFileImport(imp) {
838
+ const extName = extname2(imp.path);
839
+ return {
840
+ ...imp,
841
+ extName: imp.extName ? imp.extName : extName
842
+ };
843
+ }
844
+ function createFileExport(exp) {
845
+ const extName = extname2(exp.path);
846
+ return {
847
+ ...exp,
848
+ extName: exp.extName ? exp.extName : extName
849
+ };
850
+ }
851
+ function createFileParser(parser) {
852
+ return parser;
853
+ }
854
+ var typeScriptParser = createFileParser({
855
+ render() {
856
+ return void 0;
857
+ },
858
+ async print(file) {
859
+ const module = await import("@kubb/parser-ts");
860
+ const importNodes = file.imports.map((item) => {
861
+ const path = item.root ? getRelativePath2(item.root, item.path) : item.path;
862
+ return module.factory.createImportDeclaration({
863
+ name: item.name,
864
+ path,
865
+ isTypeOnly: item.isTypeOnly
866
+ });
867
+ }).filter(Boolean);
868
+ const exportNodes = file.exports.map((item) => {
869
+ return module.factory.createExportDeclaration({
870
+ name: item.name,
871
+ path: item.path,
872
+ isTypeOnly: item.isTypeOnly,
873
+ asAlias: item.asAlias
874
+ });
875
+ }).filter(Boolean);
876
+ const source = [module.print([...importNodes, ...exportNodes]), file.sources.map((item) => item.value).join("\n\n")].join("\n");
877
+ return module.print([], { source, noEmitHelpers: false });
878
+ }
879
+ });
880
+ var defaultParser = createFileParser({
881
+ render() {
882
+ return void 0;
883
+ },
884
+ async print(file, { logger }) {
885
+ return file.sources.map((item) => item.value).join("\n\n");
886
+ }
887
+ });
888
+ var parsers = {
889
+ ".ts": typeScriptParser,
890
+ ".js": typeScriptParser,
891
+ ".jsx": typeScriptParser,
892
+ ".tsx": typeScriptParser,
893
+ ".json": defaultParser
894
+ };
895
+ async function getFileParser(extName) {
896
+ if (!extName) {
897
+ return defaultParser;
898
+ }
899
+ const parser = parsers[extName];
900
+ if (!parser) {
901
+ console.warn(`[parser] No parser found for ${extName}, default parser will be used`);
902
+ }
903
+ return parser || defaultParser;
904
+ }
905
+ function trimExtName2(text) {
906
+ const extName = text.split(".").pop();
907
+ return text.replace(`.${extName}`, "");
908
+ }
909
+
910
+ export {
911
+ FunctionParams,
912
+ isPromise,
913
+ isPromiseFulfilledResult,
914
+ isPromiseRejectedResult,
915
+ renderTemplate,
916
+ timeout,
917
+ getUniqueName,
918
+ setUniqueName,
919
+ URLPath,
920
+ createFile,
921
+ createFileImport,
922
+ createFileExport,
923
+ createFileParser,
924
+ getFileParser,
925
+ FileManager,
926
+ getSource,
927
+ processFiles
928
+ };
929
+ //# sourceMappingURL=chunk-L6YLVCKM.js.map