@kubb/core 3.0.0-alpha.5 → 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-tzl0YsYE.d.ts → FileManager-Ceski1W9.d.ts} +46 -33
  2. package/dist/{FileManager-jZpqETKU.d.cts → FileManager-wyXRkgIk.d.cts} +46 -33
  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-Z5CHJQJB.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-FWU62YO5.cjs → chunk-DCZQYCCO.cjs} +216 -326
  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-RBP2ASUX.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 +80 -69
  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 +67 -58
  24. package/dist/index.js.map +1 -1
  25. package/dist/{logger-BnWJh6Yq.d.cts → logger-BWFeedRk.d.cts} +15 -5
  26. package/dist/{logger-BnWJh6Yq.d.ts → logger-BWFeedRk.d.ts} +15 -5
  27. package/dist/logger.cjs +2 -2
  28. package/dist/logger.d.cts +1 -2
  29. package/dist/logger.d.ts +1 -2
  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 +3 -5
  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 +24 -99
  50. package/src/FileManager.ts +156 -281
  51. package/src/PackageManager.ts +1 -1
  52. package/src/PluginManager.ts +89 -57
  53. package/src/build.ts +6 -19
  54. package/src/logger.ts +6 -8
  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-CEWT73XF.js +0 -637
  64. package/dist/chunk-CEWT73XF.js.map +0 -1
  65. package/dist/chunk-FWU62YO5.cjs.map +0 -1
  66. package/dist/chunk-JKZG2IJR.js +0 -283
  67. package/dist/chunk-JKZG2IJR.js.map +0 -1
  68. package/dist/chunk-PZT4CTBV.cjs +0 -299
  69. package/dist/chunk-PZT4CTBV.cjs.map +0 -1
  70. package/dist/chunk-RBP2ASUX.cjs.map +0 -1
  71. package/dist/chunk-YTSNYMHW.cjs.map +0 -1
  72. package/dist/chunk-Z5CHJQJB.js.map +0 -1
  73. package/src/utils/getParser.ts +0 -17
@@ -1,49 +1,28 @@
1
- import crypto from 'node:crypto'
2
- import path, { 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
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,52 +94,58 @@ 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, '')
110
-
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
- }
97
+ async #add(file: KubbFile.File): Promise<ResolvedFile> {
98
+ const resolvedFile = createFile(file)
121
99
 
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({ plugin, root, output, 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
150
  if (exportType === false) {
148
151
  return []
@@ -150,28 +153,25 @@ export class FileManager {
150
153
 
151
154
  const pathToBuildFrom = resolve(root, output.path)
152
155
 
153
- if (transformers.trimExtName(pathToBuildFrom).endsWith('index')) {
156
+ if (trimExtName(pathToBuildFrom).endsWith('index')) {
154
157
  logger.emit('warning', 'Output has the same fileName as the barrelFiles, please disable barrel generation')
155
158
  return []
156
159
  }
157
160
 
158
- const exportPath = output.path.startsWith('./') ? trimExtName(output.path) : `./${trimExtName(output.path)}`
161
+ const exportPath = output.path.startsWith('./') ? output.path : `./${output.path}`
159
162
  const mode = FileManager.getMode(output.path)
160
- const barrelManager = new BarrelManager({
161
- extName: output.extName,
162
- ...options,
163
- })
164
- let files = barrelManager.getIndexes(pathToBuildFrom)
163
+ const barrelManager = new BarrelManager({ ...options, extName: output.extName })
164
+
165
+ let indexFiles = barrelManager.getIndexes(files, pathToBuildFrom)
165
166
 
166
- if (!files) {
167
+ if (!indexFiles) {
167
168
  return []
168
169
  }
169
170
 
170
171
  const rootPath = mode === 'split' ? `${exportPath}/index${output.extName || ''}` : `${exportPath}${output.extName || ''}`
171
- const rootFile: FileWithMeta = {
172
+ const rootFile: KubbFile.File = {
172
173
  path: resolve(root, 'index.ts'),
173
174
  baseName: 'index.ts',
174
- source: '',
175
175
  exports: [
176
176
  output.exportAs
177
177
  ? {
@@ -185,80 +185,46 @@ export class FileManager {
185
185
  isTypeOnly: options.isTypeOnly,
186
186
  },
187
187
  ],
188
- exportable: true,
188
+ sources: [],
189
+ meta: {
190
+ pluginKey: plugin.key,
191
+ },
189
192
  }
190
193
 
191
- if (exportType === 'barrelNamed') {
192
- files = files.map((file) => {
193
- if (file.exports) {
194
- return {
195
- ...file,
196
- exports: barrelManager.getNamedExports(pathToBuildFrom, file.exports),
197
- }
198
- }
199
- return file
200
- })
201
-
202
- const barrelExportRoot = rootFile.exports?.[0]
203
-
204
- if (!output.exportAs && barrelExportRoot) {
205
- const exportFile = files.find((file) => {
206
- return trimExtName(file.path) === path.resolve(root, barrelExportRoot.path)
207
- })
208
-
209
- if (exportFile?.exports) {
210
- rootFile.exports = exportFile.exports.map((exportItem) => {
194
+ if (exportType === 'barrel') {
195
+ indexFiles = indexFiles.map((file) => {
196
+ return {
197
+ ...file,
198
+ exports: file.exports?.map((exportItem) => {
211
199
  return {
212
200
  ...exportItem,
213
- path: getRelativePath(rootFile.path, exportFile.path),
201
+ name: undefined,
214
202
  }
215
- })
203
+ }),
216
204
  }
217
- }
205
+ })
206
+
207
+ rootFile.exports = rootFile.exports?.map((item) => {
208
+ return {
209
+ ...item,
210
+ name: undefined,
211
+ }
212
+ })
218
213
  }
219
214
 
220
215
  return [
221
- ...(await Promise.all(
222
- files.map((file) => {
223
- return this.#addOrAppend({
224
- ...file,
225
- meta: {
226
- pluginKey: plugin.key,
227
- },
228
- })
229
- }),
230
- )),
231
- await this.#addOrAppend({
232
- ...rootFile,
233
- meta: {
234
- pluginKey: plugin.key,
235
- },
216
+ ...indexFiles.map((indexFile) => {
217
+ return {
218
+ ...indexFile,
219
+ meta: {
220
+ pluginKey: plugin.key,
221
+ },
222
+ }
236
223
  }),
224
+ rootFile,
237
225
  ]
238
226
  }
239
227
 
240
- getCacheByUUID(UUID: KubbFile.UUID): FileWithMeta | undefined {
241
- let cache: FileWithMeta | undefined
242
-
243
- this.#cache.forEach((files) => {
244
- cache = files.find((item) => item.id === UUID)
245
- })
246
- return cache
247
- }
248
-
249
- get(path: KubbFile.Path): Array<FileWithMeta> | undefined {
250
- return this.#cache.get(path)
251
- }
252
-
253
- remove(path: KubbFile.Path): void {
254
- const cacheItem = this.get(path)
255
- if (!cacheItem) {
256
- return
257
- }
258
-
259
- this.#cache.delete(path)
260
- }
261
-
262
228
  async write(...params: Parameters<typeof write>): ReturnType<typeof write> {
263
229
  return write(...params)
264
230
  }
@@ -267,79 +233,22 @@ export class FileManager {
267
233
  return read(...params)
268
234
  }
269
235
 
270
- async processFiles(...params: Parameters<typeof processFiles>): ReturnType<typeof processFiles> {
271
- return processFiles(...params)
272
- }
273
-
274
236
  // statics
275
-
276
- static combineFiles<TMeta extends FileMetaBase = FileMetaBase>(files: Array<FileWithMeta<TMeta> | null>): Array<FileWithMeta<TMeta>> {
277
- return combineFiles<TMeta>(files)
278
- }
279
237
  static getMode(path: string | undefined | null): KubbFile.Mode {
280
238
  if (!path) {
281
239
  return 'split'
282
240
  }
283
241
  return extname(path) ? 'single' : 'split'
284
242
  }
285
-
286
- static get extensions(): Array<KubbFile.Extname> {
287
- return ['.js', '.ts', '.tsx']
288
- }
289
-
290
- static isJavascript(baseName: string): boolean {
291
- return FileManager.extensions.some((extension) => baseName.endsWith(extension))
292
- }
293
243
  }
294
244
 
295
- function combineFiles<TMeta extends FileMetaBase = FileMetaBase>(files: Array<FileWithMeta<TMeta> | null>): Array<FileWithMeta<TMeta>> {
296
- return files.filter(Boolean).reduce(
297
- (acc, file: FileWithMeta<TMeta>) => {
298
- const prevIndex = acc.findIndex((item) => item.path === file.path)
299
-
300
- if (prevIndex === -1) {
301
- return [...acc, file]
302
- }
303
-
304
- const prev = acc[prevIndex]
305
-
306
- if (prev && file.override) {
307
- acc[prevIndex] = {
308
- imports: [],
309
- exports: [],
310
- ...file,
311
- }
312
- return acc
313
- }
314
-
315
- if (prev) {
316
- acc[prevIndex] = {
317
- ...file,
318
- source: prev.source && file.source ? `${prev.source}\n${file.source}` : '',
319
- imports: [...(prev.imports || []), ...(file.imports || [])],
320
- exports: [...(prev.exports || []), ...(file.exports || [])],
321
- env: { ...(prev.env || {}), ...(file.env || {}) },
322
- }
323
- }
324
-
325
- return acc
326
- },
327
- [] as Array<FileWithMeta<TMeta>>,
328
- )
329
- }
330
-
331
- export async function getSource<TMeta extends FileMetaBase = FileMetaBase>(file: FileWithMeta<TMeta>): Promise<string> {
332
- // only use .js, .ts or .tsx files for ESM imports
333
-
334
- if (file.language ? !['typescript', 'javascript'].includes(file.language) : !FileManager.isJavascript(file.baseName)) {
335
- return file.source
336
- }
337
-
338
- 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)
339
247
 
248
+ const source = file.sources.map((item) => item.value).join('\n\n')
340
249
  const exports = file.exports ? combineExports(file.exports) : []
341
250
  // imports should be defined and source should contain code or we have imports without them being used
342
- const imports = file.imports && file.source ? combineImports(file.imports, exports, file.source) : []
251
+ const imports = file.imports && source ? combineImports(file.imports, exports, source) : []
343
252
 
344
253
  const importNodes = imports
345
254
  .filter((item) => {
@@ -350,25 +259,30 @@ export async function getSource<TMeta extends FileMetaBase = FileMetaBase>(file:
350
259
  .map((item) => {
351
260
  const path = item.root ? getRelativePath(item.root, item.path) : item.path
352
261
 
353
- return parser.factory.createImportDeclaration({
262
+ return parser.createImport({
354
263
  name: item.name,
355
264
  path: item.extName ? `${path}${item.extName}` : path,
356
265
  isTypeOnly: item.isTypeOnly,
357
266
  })
358
267
  })
359
- const exportNodes = exports.map((item) =>
360
- parser.factory.createExportDeclaration({
361
- name: item.name,
362
- path: item.extName ? `${item.path}${item.extName}` : item.path,
363
- isTypeOnly: item.isTypeOnly,
364
- asAlias: item.asAlias,
365
- }),
366
- )
367
-
368
- 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)
369
280
 
370
- // do some basic linting with the ts compiler
371
- return parser.print([], { source, noEmitHelpers: false })
281
+ return parser.print({
282
+ imports: importNodes,
283
+ exports: exportNodes,
284
+ source,
285
+ })
372
286
  }
373
287
 
374
288
  export function combineExports(exports: Array<KubbFile.Export>): Array<KubbFile.Export> {
@@ -412,7 +326,7 @@ export function combineExports(exports: Array<KubbFile.Export>): Array<KubbFile.
412
326
  [] as Array<KubbFile.Export>,
413
327
  )
414
328
 
415
- return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias], ['desc', 'desc'])
329
+ return orderBy(combinedExports, [(v) => !v.isTypeOnly, (v) => v.asAlias])
416
330
  }
417
331
 
418
332
  export function combineImports(imports: Array<KubbFile.Import>, exports: Array<KubbFile.Export>, source?: string): Array<KubbFile.Import> {
@@ -477,90 +391,51 @@ export function combineImports(imports: Array<KubbFile.Import>, exports: Array<K
477
391
  [] as Array<KubbFile.Import>,
478
392
  )
479
393
 
480
- return orderBy(combinedImports, [(v) => !v.isTypeOnly], ['desc'])
481
- }
482
-
483
- function getEnvSource(source: string, env: NodeJS.ProcessEnv | undefined): string {
484
- if (!env) {
485
- return source
486
- }
487
-
488
- const keys = Object.keys(env)
489
-
490
- if (!keys.length) {
491
- return source
492
- }
493
-
494
- return keys.reduce((prev, key: string) => {
495
- const environmentValue = env[key]
496
- const replaceBy = environmentValue ? `'${environmentValue.replaceAll('"', '')?.replaceAll("'", '')}'` : 'undefined'
497
-
498
- if (key.toUpperCase() !== key) {
499
- throw new TypeError(`Environment should be in upperCase for ${key}`)
500
- }
501
-
502
- if (typeof replaceBy === 'string') {
503
- prev = searchAndReplace({
504
- text: prev.replaceAll(`process.env.${key}`, replaceBy),
505
- replaceBy,
506
- prefix: 'process.env',
507
- key,
508
- })
509
- // removes `declare const ...`
510
- prev = searchAndReplace({
511
- text: prev.replaceAll(/(declare const).*\n/gi, ''),
512
- replaceBy,
513
- key,
514
- })
515
- }
516
-
517
- return prev
518
- }, source)
394
+ return orderBy(combinedImports, [(v) => !v.isTypeOnly])
519
395
  }
520
396
 
521
397
  type WriteFilesProps = {
522
- files: KubbFile.File[]
398
+ config: Config
399
+ files: Array<KubbFile.ResolvedFile>
523
400
  logger: Logger
524
401
  dryRun?: boolean
525
402
  }
526
403
  /**
527
404
  * Global queue
528
405
  */
529
- const queue = new PQueue({ concurrency: 10 })
530
-
531
- export async function processFiles({ dryRun, logger, files }: WriteFilesProps) {
532
- const mergedFiles: Array<KubbFile.File<FileMetaBase>> = await Promise.all(
533
- files.map(async (file) => ({
534
- ...file,
535
- source: await getSource(file),
536
- })),
537
- )
538
- const orderedFiles = orderBy(mergedFiles, [(v) => !v.meta?.pluginKey, (v) => v.path.length, (v) => trimExtName(v.path).endsWith('index')], ['desc', 'desc'])
406
+ const queue = new PQueue({ concurrency: 100 })
539
407
 
540
- logger.emit(
541
- 'debug',
542
- orderedFiles.map((item) => `[${item.meta?.pluginKey || 'unknown'}]${item.path}: \n${item.source}`),
543
- )
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
+ })
544
420
 
545
421
  if (!dryRun) {
546
- logger.consola?.pauseLogs()
547
422
  const size = orderedFiles.length
548
423
 
549
- const promises = orderedFiles.map(async (file, index) => {
424
+ logger.emit('progress_start', { id: 'files', size })
425
+ const promises = orderedFiles.map(async (file) => {
550
426
  await queue.add(async () => {
551
- logger.emit('progress', { count: index, size, file })
552
- await write(file.path, file.source, { sanity: false })
553
- await new Promise((resolve) => {
554
- setTimeout(resolve, 0)
555
- })
556
- logger.emit('progress', { count: index + 1, size, file })
427
+ const source = await getSource(file)
428
+
429
+ await write(file.path, source, { sanity: false })
430
+
431
+ logger.emit('progress', { id: 'files', data: file ? relative(config.root, file.path) : '' })
557
432
  })
558
433
  })
559
434
 
560
435
  await Promise.all(promises)
561
436
 
562
- logger.consola?.resumeLogs()
437
+ logger.emit('progress_stop', { id: 'files' })
563
438
  }
564
439
 
565
- return mergedFiles
440
+ return files
566
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
  }