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

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 (73) hide show
  1. package/dist/{FileManager-CaejIVBd.d.ts → FileManager-Ceski1W9.d.ts} +47 -47
  2. package/dist/{FileManager--scIq4y4.d.cts → FileManager-wyXRkgIk.d.cts} +47 -47
  3. package/dist/chunk-2EU7DMPM.js +97 -0
  4. package/dist/chunk-2EU7DMPM.js.map +1 -0
  5. package/dist/chunk-5HN4LW3R.cjs +102 -0
  6. package/dist/chunk-5HN4LW3R.cjs.map +1 -0
  7. package/dist/{chunk-EFQPHF4E.js → chunk-76UEJFFE.js} +1 -4
  8. package/dist/chunk-76UEJFFE.js.map +1 -0
  9. package/dist/{chunk-5JZNFPUP.js → chunk-AWAZR3D5.js} +61 -10
  10. package/dist/chunk-AWAZR3D5.js.map +1 -0
  11. package/dist/{chunk-V5THHXXQ.cjs → chunk-DCZQYCCO.cjs} +218 -299
  12. package/dist/chunk-DCZQYCCO.cjs.map +1 -0
  13. package/dist/{chunk-YTSNYMHW.cjs → chunk-L3JJLZ5Q.cjs} +62 -11
  14. package/dist/chunk-L3JJLZ5Q.cjs.map +1 -0
  15. package/dist/{chunk-QRIDQ4RG.cjs → chunk-LOLEBOMW.cjs} +1 -4
  16. package/dist/chunk-LOLEBOMW.cjs.map +1 -0
  17. package/dist/chunk-RIEGCND2.js +525 -0
  18. package/dist/chunk-RIEGCND2.js.map +1 -0
  19. package/dist/index.cjs +81 -75
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +4 -6
  22. package/dist/index.d.ts +4 -6
  23. package/dist/index.js +68 -64
  24. package/dist/index.js.map +1 -1
  25. package/dist/{logger-dzAcLeAA.d.cts → logger-BWFeedRk.d.cts} +17 -2
  26. package/dist/{logger-dzAcLeAA.d.ts → logger-BWFeedRk.d.ts} +17 -2
  27. package/dist/logger.cjs +2 -2
  28. package/dist/logger.d.cts +1 -1
  29. package/dist/logger.d.ts +1 -1
  30. package/dist/logger.js +1 -1
  31. package/dist/mocks.cjs +4 -6
  32. package/dist/mocks.cjs.map +1 -1
  33. package/dist/mocks.d.cts +3 -5
  34. package/dist/mocks.d.ts +3 -5
  35. package/dist/mocks.js +5 -7
  36. package/dist/mocks.js.map +1 -1
  37. package/dist/transformers.cjs +189 -33
  38. package/dist/transformers.cjs.map +1 -1
  39. package/dist/transformers.d.cts +1 -3
  40. package/dist/transformers.d.ts +1 -3
  41. package/dist/transformers.js +156 -14
  42. package/dist/transformers.js.map +1 -1
  43. package/dist/utils.cjs +6 -2
  44. package/dist/utils.cjs.map +1 -1
  45. package/dist/utils.d.cts +30 -3
  46. package/dist/utils.d.ts +30 -3
  47. package/dist/utils.js +7 -3
  48. package/package.json +9 -8
  49. package/src/BarrelManager.ts +27 -93
  50. package/src/FileManager.ts +165 -266
  51. package/src/PackageManager.ts +1 -1
  52. package/src/PluginManager.ts +89 -57
  53. package/src/build.ts +7 -26
  54. package/src/logger.ts +6 -7
  55. package/src/transformers/index.ts +2 -3
  56. package/src/transformers/trim.ts +0 -4
  57. package/src/types.ts +1 -1
  58. package/src/utils/TreeNode.ts +91 -26
  59. package/src/utils/executeStrategies.ts +1 -1
  60. package/src/utils/index.ts +2 -1
  61. package/src/utils/parser.ts +96 -0
  62. package/dist/chunk-5JZNFPUP.js.map +0 -1
  63. package/dist/chunk-EFQPHF4E.js.map +0 -1
  64. package/dist/chunk-JKZG2IJR.js +0 -283
  65. package/dist/chunk-JKZG2IJR.js.map +0 -1
  66. package/dist/chunk-PZT4CTBV.cjs +0 -299
  67. package/dist/chunk-PZT4CTBV.cjs.map +0 -1
  68. package/dist/chunk-QRIDQ4RG.cjs.map +0 -1
  69. package/dist/chunk-UUBPTMRW.js +0 -608
  70. package/dist/chunk-UUBPTMRW.js.map +0 -1
  71. package/dist/chunk-V5THHXXQ.cjs.map +0 -1
  72. package/dist/chunk-YTSNYMHW.cjs.map +0 -1
  73. package/src/utils/getParser.ts +0 -17
@@ -1,49 +1,28 @@
1
- import crypto from 'node:crypto'
2
- import { extname, resolve } from 'node:path'
1
+ import { extname, relative, resolve } from 'node:path'
3
2
 
4
3
  import { orderBy } from 'natural-orderby'
5
4
  import { isDeepEqual } from 'remeda'
6
5
 
7
6
  import { getRelativePath, read, write } from '@kubb/fs'
8
7
  import { BarrelManager } from './BarrelManager.ts'
9
- import { searchAndReplace } from './transformers/searchAndReplace.ts'
10
- import { trimExtName } from './transformers/trim.ts'
11
8
 
12
9
  import type * as KubbFile from '@kubb/fs/types'
13
10
 
14
- import type { BaseName, File, UUID } from '@kubb/fs/src/types.ts'
11
+ import { trimExtName } from '@kubb/fs'
12
+ import type { ResolvedFile } from '@kubb/fs/types'
15
13
  import type { GreaterThan } from '@kubb/types'
14
+ import PQueue from 'p-queue'
16
15
  import type { BarrelManagerOptions } from './BarrelManager.ts'
17
16
  import type { Logger } from './logger.ts'
18
- import transformers from './transformers/index.ts'
19
- import type { Plugin } from './types.ts'
20
- import { getParser } from './utils'
21
- import PQueue from 'p-queue'
22
-
23
- export type ResolvedFile<TMeta extends FileMetaBase = FileMetaBase, TBaseName extends BaseName = BaseName> = File<TMeta, TBaseName> & {
24
- /**
25
- * @default crypto.randomUUID()
26
- */
27
- id: UUID
28
- /**
29
- * Contains the first part of the baseName, generated based on baseName
30
- * @link https://nodejs.org/api/path.html#pathformatpathobject
31
- */
32
-
33
- name: string
34
- }
17
+ import type { Config, Plugin } from './types.ts'
18
+ import { createFile, getFileParser } from './utils'
19
+ import { type DirectoryTree, TreeNode, buildDirectoryTree } from './utils/TreeNode.ts'
35
20
 
36
21
  export type FileMetaBase = {
37
22
  pluginKey?: Plugin['key']
38
23
  }
39
24
 
40
- type FileWithMeta<TMeta extends FileMetaBase = FileMetaBase> = KubbFile.File<TMeta>
41
-
42
- type CacheItem = ResolvedFile & {
43
- cancel?: () => void
44
- }
45
-
46
- type AddResult<T extends Array<FileWithMeta>> = Promise<Awaited<GreaterThan<T['length'], 1> extends true ? Promise<ResolvedFile[]> : Promise<ResolvedFile>>>
25
+ type AddResult<T extends Array<KubbFile.File>> = Promise<Awaited<GreaterThan<T['length'], 1> extends true ? Promise<ResolvedFile[]> : Promise<ResolvedFile>>>
47
26
 
48
27
  type AddIndexesProps = {
49
28
  /**
@@ -56,31 +35,49 @@ type AddIndexesProps = {
56
35
  output: {
57
36
  path: string
58
37
  exportAs?: string
59
- extName?: KubbFile.Extname
38
+ extName?: string
60
39
  exportType?: 'barrel' | 'barrelNamed' | false
61
40
  }
41
+ group?: {
42
+ output: string
43
+ exportAs: string
44
+ }
62
45
  logger: Logger
46
+ files: KubbFile.File[]
63
47
  options?: BarrelManagerOptions
64
- meta?: FileWithMeta['meta']
48
+ plugin: Plugin
65
49
  }
66
50
 
67
51
  export class FileManager {
68
- #cache: Map<KubbFile.Path, CacheItem[]> = new Map()
52
+ #filesByPath: Map<KubbFile.Path, KubbFile.ResolvedFile> = new Map()
53
+ #files: Set<KubbFile.ResolvedFile> = new Set()
69
54
  constructor() {
70
55
  return this
71
56
  }
72
57
 
73
- get files(): Array<FileWithMeta> {
74
- const files: Array<FileWithMeta> = []
75
- this.#cache.forEach((item) => {
76
- files.push(...item.flat(1))
77
- })
58
+ get files(): Array<KubbFile.ResolvedFile> {
59
+ return Array.from(this.#files)
60
+ }
78
61
 
79
- return files
62
+ get orderedFiles(): Array<KubbFile.ResolvedFile> {
63
+ return orderBy(Array.from(this.#files), [
64
+ (v) => v.path.length,
65
+ (v) => trimExtName(v.path).endsWith('index'),
66
+ (v) => trimExtName(v.baseName),
67
+ (v) => v.path.split('.').pop(),
68
+ ])
80
69
  }
81
70
 
82
- async add<T extends Array<FileWithMeta> = Array<FileWithMeta>>(...files: T): AddResult<T> {
83
- const promises = combineFiles(files).map((file) => {
71
+ get groupedFiles(): DirectoryTree | null {
72
+ return buildDirectoryTree(Array.from(this.#files))
73
+ }
74
+
75
+ get treeNode(): TreeNode | null {
76
+ return TreeNode.build(Array.from(this.#files))
77
+ }
78
+
79
+ async add<T extends Array<KubbFile.File> = Array<KubbFile.File>>(...files: T): AddResult<T> {
80
+ const promises = files.map((file) => {
84
81
  if (file.override) {
85
82
  return this.#add(file)
86
83
  }
@@ -97,94 +94,84 @@ export class FileManager {
97
94
  return resolvedFiles[0] as unknown as AddResult<T>
98
95
  }
99
96
 
100
- async #add(file: FileWithMeta): Promise<ResolvedFile> {
101
- const controller = new AbortController()
102
- const resolvedFile: ResolvedFile = {
103
- id: crypto.randomUUID(),
104
- name: trimExtName(file.baseName),
105
- ...file,
106
- }
107
-
108
- if (resolvedFile.exports?.length) {
109
- const folder = resolvedFile.path.replace(resolvedFile.baseName, '')
97
+ async #add(file: KubbFile.File): Promise<ResolvedFile> {
98
+ const resolvedFile = createFile(file)
110
99
 
111
- resolvedFile.exports = resolvedFile.exports.filter((exportItem) => {
112
- const exportedFile = this.files.find((file) => file.path.includes(resolve(folder, exportItem.path)))
113
-
114
- if (exportedFile) {
115
- return exportedFile.exportable
116
- }
117
-
118
- return true
119
- })
120
- }
121
-
122
- this.#cache.set(resolvedFile.path, [{ cancel: () => controller.abort(), ...resolvedFile }])
100
+ this.#filesByPath.set(resolvedFile.path, resolvedFile)
101
+ this.#files.add(resolvedFile)
123
102
 
124
103
  return resolvedFile
125
104
  }
126
105
 
127
- async #addOrAppend(file: FileWithMeta): Promise<ResolvedFile> {
128
- const previousCaches = this.#cache.get(file.path)
129
- const previousCache = previousCaches ? previousCaches.at(previousCaches.length - 1) : undefined
106
+ async #addOrAppend(file: KubbFile.File): Promise<ResolvedFile> {
107
+ const previousFile = this.#filesByPath.get(file.path)
130
108
 
131
- if (previousCache) {
132
- this.#cache.delete(previousCache.path)
109
+ if (previousFile) {
110
+ this.#filesByPath.delete(previousFile.path)
111
+ this.#files.delete(previousFile)
133
112
 
134
113
  return this.#add({
135
114
  ...file,
136
- source: previousCache.source && file.source ? `${previousCache.source}\n${file.source}` : '',
137
- imports: [...(previousCache.imports || []), ...(file.imports || [])],
138
- exports: [...(previousCache.exports || []), ...(file.exports || [])],
139
- env: { ...(previousCache.env || {}), ...(file.env || {}) },
115
+ sources: [...(previousFile.sources || []), ...(file.sources || [])],
116
+ imports: [...(previousFile.imports || []), ...(file.imports || [])],
117
+ exports: [...(previousFile.exports || []), ...(file.exports || [])],
140
118
  })
141
119
  }
142
120
  return this.#add(file)
143
121
  }
144
122
 
145
- async getIndexFiles({ root, output, meta, logger, options = {} }: AddIndexesProps): Promise<ResolvedFile[]> {
123
+ getCacheById(id: string): KubbFile.File | undefined {
124
+ let cache: KubbFile.File | undefined
125
+
126
+ this.#files.forEach((file) => {
127
+ if (file.id === id) {
128
+ cache = file
129
+ }
130
+ })
131
+ return cache
132
+ }
133
+
134
+ getByPath(path: KubbFile.Path): KubbFile.ResolvedFile | undefined {
135
+ return this.#filesByPath.get(path)
136
+ }
137
+
138
+ deleteByPath(path: KubbFile.Path): void {
139
+ const cacheItem = this.getByPath(path)
140
+ if (!cacheItem) {
141
+ return
142
+ }
143
+
144
+ this.#filesByPath.delete(path)
145
+ this.#files.delete(cacheItem)
146
+ }
147
+
148
+ async getIndexFiles({ files, plugin, root, output, logger, options = {} }: AddIndexesProps): Promise<KubbFile.File[]> {
146
149
  const { exportType = 'barrel' } = output
147
- // ^?
148
150
  if (exportType === false) {
149
151
  return []
150
152
  }
151
153
 
152
154
  const pathToBuildFrom = resolve(root, output.path)
153
155
 
154
- if (transformers.trimExtName(pathToBuildFrom).endsWith('index')) {
156
+ if (trimExtName(pathToBuildFrom).endsWith('index')) {
155
157
  logger.emit('warning', 'Output has the same fileName as the barrelFiles, please disable barrel generation')
156
158
  return []
157
159
  }
158
160
 
159
- const exportPath = output.path.startsWith('./') ? trimExtName(output.path) : `./${trimExtName(output.path)}`
161
+ const exportPath = output.path.startsWith('./') ? output.path : `./${output.path}`
160
162
  const mode = FileManager.getMode(output.path)
161
- const barrelManager = new BarrelManager({
162
- extName: output.extName,
163
- ...options,
164
- })
165
- let files = barrelManager.getIndexes(pathToBuildFrom)
163
+ const barrelManager = new BarrelManager({ ...options, extName: output.extName })
166
164
 
167
- if (!files) {
168
- return []
169
- }
165
+ let indexFiles = barrelManager.getIndexes(files, pathToBuildFrom)
170
166
 
171
- if (exportType === 'barrelNamed') {
172
- files = files.map((file) => {
173
- if (file.exports) {
174
- return {
175
- ...file,
176
- exports: barrelManager.getNamedExports(pathToBuildFrom, file.exports),
177
- }
178
- }
179
- return file
180
- })
167
+ if (!indexFiles) {
168
+ return []
181
169
  }
182
170
 
183
171
  const rootPath = mode === 'split' ? `${exportPath}/index${output.extName || ''}` : `${exportPath}${output.extName || ''}`
184
- const rootFile: FileWithMeta = {
172
+ const rootFile: KubbFile.File = {
185
173
  path: resolve(root, 'index.ts'),
186
174
  baseName: 'index.ts',
187
- source: '',
188
175
  exports: [
189
176
  output.exportAs
190
177
  ? {
@@ -198,51 +185,46 @@ export class FileManager {
198
185
  isTypeOnly: options.isTypeOnly,
199
186
  },
200
187
  ],
201
- exportable: true,
188
+ sources: [],
189
+ meta: {
190
+ pluginKey: plugin.key,
191
+ },
202
192
  }
203
193
 
204
- if (exportType === 'barrelNamed' && !output.exportAs && rootFile.exports?.[0]) {
205
- rootFile.exports = barrelManager.getNamedExport(root, rootFile.exports[0])
194
+ if (exportType === 'barrel') {
195
+ indexFiles = indexFiles.map((file) => {
196
+ return {
197
+ ...file,
198
+ exports: file.exports?.map((exportItem) => {
199
+ return {
200
+ ...exportItem,
201
+ name: undefined,
202
+ }
203
+ }),
204
+ }
205
+ })
206
+
207
+ rootFile.exports = rootFile.exports?.map((item) => {
208
+ return {
209
+ ...item,
210
+ name: undefined,
211
+ }
212
+ })
206
213
  }
207
214
 
208
215
  return [
209
- ...(await Promise.all(
210
- files.map((file) => {
211
- return this.#addOrAppend({
212
- ...file,
213
- meta: meta ? meta : file.meta,
214
- })
215
- }),
216
- )),
217
- await this.#addOrAppend({
218
- ...rootFile,
219
- meta: meta ? meta : rootFile.meta,
216
+ ...indexFiles.map((indexFile) => {
217
+ return {
218
+ ...indexFile,
219
+ meta: {
220
+ pluginKey: plugin.key,
221
+ },
222
+ }
220
223
  }),
224
+ rootFile,
221
225
  ]
222
226
  }
223
227
 
224
- getCacheByUUID(UUID: KubbFile.UUID): FileWithMeta | undefined {
225
- let cache: FileWithMeta | undefined
226
-
227
- this.#cache.forEach((files) => {
228
- cache = files.find((item) => item.id === UUID)
229
- })
230
- return cache
231
- }
232
-
233
- get(path: KubbFile.Path): Array<FileWithMeta> | undefined {
234
- return this.#cache.get(path)
235
- }
236
-
237
- remove(path: KubbFile.Path): void {
238
- const cacheItem = this.get(path)
239
- if (!cacheItem) {
240
- return
241
- }
242
-
243
- this.#cache.delete(path)
244
- }
245
-
246
228
  async write(...params: Parameters<typeof write>): ReturnType<typeof write> {
247
229
  return write(...params)
248
230
  }
@@ -250,83 +232,23 @@ export class FileManager {
250
232
  async read(...params: Parameters<typeof read>): ReturnType<typeof read> {
251
233
  return read(...params)
252
234
  }
253
- async processFiles(...params: Parameters<typeof processFiles>): ReturnType<typeof processFiles> {
254
- return processFiles(...params)
255
- }
256
235
 
257
236
  // statics
258
-
259
- static async getSource<TMeta extends FileMetaBase = FileMetaBase>(file: FileWithMeta<TMeta>): Promise<string> {
260
- return getSource<TMeta>(file)
261
- }
262
-
263
- static combineFiles<TMeta extends FileMetaBase = FileMetaBase>(files: Array<FileWithMeta<TMeta> | null>): Array<FileWithMeta<TMeta>> {
264
- return combineFiles<TMeta>(files)
265
- }
266
237
  static getMode(path: string | undefined | null): KubbFile.Mode {
267
238
  if (!path) {
268
239
  return 'split'
269
240
  }
270
241
  return extname(path) ? 'single' : 'split'
271
242
  }
272
-
273
- static get extensions(): Array<KubbFile.Extname> {
274
- return ['.js', '.ts', '.tsx']
275
- }
276
-
277
- static isJavascript(baseName: string): boolean {
278
- return FileManager.extensions.some((extension) => baseName.endsWith(extension))
279
- }
280
243
  }
281
244
 
282
- function combineFiles<TMeta extends FileMetaBase = FileMetaBase>(files: Array<FileWithMeta<TMeta> | null>): Array<FileWithMeta<TMeta>> {
283
- return files.filter(Boolean).reduce(
284
- (acc, file: FileWithMeta<TMeta>) => {
285
- const prevIndex = acc.findIndex((item) => item.path === file.path)
286
-
287
- if (prevIndex === -1) {
288
- return [...acc, file]
289
- }
290
-
291
- const prev = acc[prevIndex]
292
-
293
- if (prev && file.override) {
294
- acc[prevIndex] = {
295
- imports: [],
296
- exports: [],
297
- ...file,
298
- }
299
- return acc
300
- }
301
-
302
- if (prev) {
303
- acc[prevIndex] = {
304
- ...file,
305
- source: prev.source && file.source ? `${prev.source}\n${file.source}` : '',
306
- imports: [...(prev.imports || []), ...(file.imports || [])],
307
- exports: [...(prev.exports || []), ...(file.exports || [])],
308
- env: { ...(prev.env || {}), ...(file.env || {}) },
309
- }
310
- }
311
-
312
- return acc
313
- },
314
- [] as Array<FileWithMeta<TMeta>>,
315
- )
316
- }
317
-
318
- export async function getSource<TMeta extends FileMetaBase = FileMetaBase>(file: FileWithMeta<TMeta>): Promise<string> {
319
- // only use .js, .ts or .tsx files for ESM imports
320
-
321
- if (file.language ? !['typescript', 'javascript'].includes(file.language) : !FileManager.isJavascript(file.baseName)) {
322
- return file.source
323
- }
324
-
325
- const parser = await getParser(file.language)
245
+ export async function getSource<TMeta extends FileMetaBase = FileMetaBase>(file: KubbFile.File<TMeta> | ResolvedFile<TMeta>): Promise<string> {
246
+ const parser = await getFileParser(file.extName)
326
247
 
248
+ const source = file.sources.map((item) => item.value).join('\n\n')
327
249
  const exports = file.exports ? combineExports(file.exports) : []
328
250
  // imports should be defined and source should contain code or we have imports without them being used
329
- const imports = file.imports && file.source ? combineImports(file.imports, exports, file.source) : []
251
+ const imports = file.imports && source ? combineImports(file.imports, exports, source) : []
330
252
 
331
253
  const importNodes = imports
332
254
  .filter((item) => {
@@ -337,25 +259,30 @@ export async function getSource<TMeta extends FileMetaBase = FileMetaBase>(file:
337
259
  .map((item) => {
338
260
  const path = item.root ? getRelativePath(item.root, item.path) : item.path
339
261
 
340
- return parser.factory.createImportDeclaration({
262
+ return parser.createImport({
341
263
  name: item.name,
342
264
  path: item.extName ? `${path}${item.extName}` : path,
343
265
  isTypeOnly: item.isTypeOnly,
344
266
  })
345
267
  })
346
- const exportNodes = exports.map((item) =>
347
- parser.factory.createExportDeclaration({
348
- name: item.name,
349
- path: item.extName ? `${item.path}${item.extName}` : item.path,
350
- isTypeOnly: item.isTypeOnly,
351
- asAlias: item.asAlias,
352
- }),
353
- )
354
-
355
- const source = [parser.print([...importNodes, ...exportNodes]), getEnvSource(file.source, file.env)].join('\n')
268
+ const exportNodes = exports
269
+ .map((item) => {
270
+ if (item.path) {
271
+ return parser.createExport({
272
+ name: item.name,
273
+ path: item.extName ? `${item.path}${item.extName}` : item.path,
274
+ isTypeOnly: item.isTypeOnly,
275
+ asAlias: item.asAlias,
276
+ })
277
+ }
278
+ })
279
+ .filter(Boolean)
356
280
 
357
- // do some basic linting with the ts compiler
358
- return parser.print([], { source, noEmitHelpers: false })
281
+ return parser.print({
282
+ imports: importNodes,
283
+ exports: exportNodes,
284
+ source,
285
+ })
359
286
  }
360
287
 
361
288
  export function combineExports(exports: Array<KubbFile.Export>): Array<KubbFile.Export> {
@@ -399,7 +326,7 @@ export function combineExports(exports: Array<KubbFile.Export>): Array<KubbFile.
399
326
  [] as Array<KubbFile.Export>,
400
327
  )
401
328
 
402
- return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias], ['desc', 'desc'])
329
+ return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias])
403
330
  }
404
331
 
405
332
  export function combineImports(imports: Array<KubbFile.Import>, exports: Array<KubbFile.Export>, source?: string): Array<KubbFile.Import> {
@@ -464,79 +391,51 @@ export function combineImports(imports: Array<KubbFile.Import>, exports: Array<K
464
391
  [] as Array<KubbFile.Import>,
465
392
  )
466
393
 
467
- return orderBy(combinedImports, [(v) => !v.isTypeOnly], ['desc'])
468
- }
469
-
470
- function getEnvSource(source: string, env: NodeJS.ProcessEnv | undefined): string {
471
- if (!env) {
472
- return source
473
- }
474
-
475
- const keys = Object.keys(env)
476
-
477
- if (!keys.length) {
478
- return source
479
- }
480
-
481
- return keys.reduce((prev, key: string) => {
482
- const environmentValue = env[key]
483
- const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', '')?.replaceAll("'", '')}'` : 'undefined'
484
-
485
- if (key.toUpperCase() !== key) {
486
- throw new TypeError(`Environment should be in upperCase for ${key}`)
487
- }
488
-
489
- if (typeof replaceBy === 'string') {
490
- prev = searchAndReplace({
491
- text: prev.replaceAll(`process.env.${key}`, replaceBy),
492
- replaceBy,
493
- prefix: 'process.env',
494
- key,
495
- })
496
- // removes `declare const ...`
497
- prev = searchAndReplace({
498
- text: prev.replaceAll(/(declare const).*\n/gi, ''),
499
- replaceBy,
500
- key,
501
- })
502
- }
503
-
504
- return prev
505
- }, source)
394
+ return orderBy(combinedImports, [(v) => !v.isTypeOnly])
506
395
  }
507
396
 
508
397
  type WriteFilesProps = {
509
- files: KubbFile.File[]
398
+ config: Config
399
+ files: Array<KubbFile.ResolvedFile>
510
400
  logger: Logger
511
401
  dryRun?: boolean
512
402
  }
513
403
  /**
514
404
  * Global queue
515
405
  */
516
- const queue = new PQueue({ concurrency: 1 })
517
-
518
- export async function processFiles({ dryRun, logger, files }: WriteFilesProps) {
519
- const mergedFiles = await Promise.all(
520
- files.map(async (file) => ({
521
- ...file,
522
- source: await FileManager.getSource(file),
523
- })),
524
- )
406
+ const queue = new PQueue({ concurrency: 100 })
407
+
408
+ export async function processFiles({ dryRun, config, logger, files }: WriteFilesProps) {
409
+ const orderedFiles = orderBy(files, [
410
+ (v) => v?.meta && 'pluginKey' in v.meta && !v.meta.pluginKey,
411
+ (v) => v.path.length,
412
+ (v) => trimExtName(v.path).endsWith('index'),
413
+ ])
414
+
415
+ logger.emit('debug', {
416
+ logs: [JSON.stringify({ files: orderedFiles }, null, 2)],
417
+ fileName: 'kubb-files.json',
418
+ override: true,
419
+ })
525
420
 
526
421
  if (!dryRun) {
527
- logger.consola?.pauseLogs()
422
+ const size = orderedFiles.length
423
+
424
+ logger.emit('progress_start', { id: 'files', size })
425
+ const promises = orderedFiles.map(async (file) => {
426
+ await queue.add(async () => {
427
+ const source = await getSource(file)
428
+
429
+ await write(file.path, source, { sanity: false })
528
430
 
529
- const filePromises = mergedFiles.map(async (file, index) => {
530
- await queue.add(() => {
531
- logger.emit('progress', index, mergedFiles.length)
532
- return write(file.path, file.source, { sanity: false })
431
+ logger.emit('progress', { id: 'files', data: file ? relative(config.root, file.path) : '' })
533
432
  })
534
433
  })
535
434
 
536
- await Promise.all(filePromises)
435
+ await Promise.all(promises)
537
436
 
538
- logger.consola?.resumeLogs()
437
+ logger.emit('progress_stop', { id: 'files' })
539
438
  }
540
439
 
541
- return mergedFiles
440
+ return files
542
441
  }
@@ -68,7 +68,7 @@ export class PackageManager {
68
68
 
69
69
  return module?.default ?? module
70
70
  } catch (e) {
71
- console.log(e)
71
+ console.error(e)
72
72
  return undefined
73
73
  }
74
74
  }