@adonisjs/assembler 8.0.0-next.4 → 8.0.0-next.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 (35) hide show
  1. package/README.md +87 -59
  2. package/build/chunk-F4RAGKQN.js +387 -0
  3. package/build/chunk-MC3FJR62.js +411 -0
  4. package/build/chunk-TIKQQRMX.js +116 -0
  5. package/build/index.d.ts +1 -0
  6. package/build/index.js +606 -410
  7. package/build/src/bundler.d.ts +40 -3
  8. package/build/src/code_scanners/routes_scanner/main.d.ts +49 -9
  9. package/build/src/code_scanners/routes_scanner/main.js +445 -0
  10. package/build/src/code_scanners/routes_scanner/validator_extractor.d.ts +12 -4
  11. package/build/src/code_transformer/main.d.ts +44 -43
  12. package/build/src/code_transformer/main.js +123 -101
  13. package/build/src/code_transformer/rc_file_transformer.d.ts +56 -4
  14. package/build/src/debug.d.ts +12 -0
  15. package/build/src/dev_server.d.ts +40 -30
  16. package/build/src/file_buffer.d.ts +67 -0
  17. package/build/src/file_system.d.ts +45 -7
  18. package/build/src/helpers.d.ts +79 -4
  19. package/build/src/helpers.js +16 -0
  20. package/build/src/index_generator/main.d.ts +73 -0
  21. package/build/src/index_generator/main.js +7 -0
  22. package/build/src/index_generator/source.d.ts +66 -0
  23. package/build/src/paths_resolver.d.ts +27 -2
  24. package/build/src/shortcuts_manager.d.ts +42 -4
  25. package/build/src/test_runner.d.ts +58 -31
  26. package/build/src/types/code_scanners.d.ts +138 -24
  27. package/build/src/types/code_transformer.d.ts +61 -19
  28. package/build/src/types/common.d.ts +199 -55
  29. package/build/src/types/hooks.d.ts +173 -17
  30. package/build/src/types/main.d.ts +13 -0
  31. package/build/src/utils.d.ts +88 -10
  32. package/build/src/virtual_file_system.d.ts +112 -0
  33. package/package.json +9 -3
  34. package/build/chunk-RR4HCA4M.js +0 -7
  35. package/build/src/ast_file_system.d.ts +0 -17
package/README.md CHANGED
@@ -420,83 +420,111 @@ export const policies = {
420
420
  }
421
421
  ```
422
422
 
423
- ### makeEntityIndex
424
- The method is used to create an index file for a collection of entities discovered from one or more root folders. We use this method to create an index file for controllers or generate types for Inertia pages.
423
+ ## Index generator
424
+
425
+ The `IndexGenerator` is a core concept in Assembler that is used to watch the filesystem and create barrel files or types from a source directory.
426
+
427
+ For example, the core of the framework uses the following config to generate controllers, events, and listeners barrel file.
425
428
 
426
429
  ```ts
427
- const transformer = new CodeTransformer(appRoot)
430
+ import hooks from '@adonisjs/assembler/hooks'
431
+
432
+ export default hooks.init((type, parent, indexGenerator) => {
433
+ indexGenerator.add('controllers', {
434
+ source: './app/controllers',
435
+ importAlias: '#controllers',
436
+ as: 'barrelFile',
437
+ exportName: 'controllers',
438
+ removeSuffix: 'controllers',
439
+ output: './.adonisjs/server/controllers.ts',
440
+ })
428
441
 
429
- const output = await transformer.makeEntityIndex({
430
- source: 'app/controllers',
431
- importAlias: '#controllers'
432
- }, {
433
- destination: '.adonisjs/backend/controllers',
434
- exportName: 'controllers'
435
- })
442
+ indexGenerator.add('events', {
443
+ source: './app/events',
444
+ importAlias: '#events',
445
+ as: 'barrelFile',
446
+ exportName: 'events',
447
+ output: './.adonisjs/server/events.ts',
448
+ })
436
449
 
437
- /**
438
- export const controllers = {
439
- SignupController: () => import('#controllers/auth/signup_controller'),
440
- PostsController: () => import('#controllers/posts_controller'),
441
- HomePage: () => import('#controllers/public/home_page'),
442
- UserPostsController: () => import('#controllers/user/posts_controller'),
443
- }
444
- */
450
+ indexGenerator.add('listeners', {
451
+ source: './app/listeners',
452
+ importAlias: '#listeners',
453
+ as: 'barrelFile',
454
+ exportName: 'listeners',
455
+ removeSuffix: 'listener',
456
+ output: './.adonisjs/server/listeners.ts',
457
+ })
458
+ })
445
459
  ```
446
460
 
447
- If you would like to remove the `Controller` suffix from the key (which we do in our official generator), then you can specify the `removeNameSuffix` option.
461
+ Once the configurations have been registered with the `IndexGenerator`, it will scan the needed directories and generate the output files. Additionally, the file watchers will re-trigger the index generation when a file is added or removed from the source directory.
448
462
 
449
- ```ts
450
- const output = await transformer.makeEntityIndex({
451
- source: 'app/controllers',
452
- importAlias: '#controllers'
453
- }, {
454
- destination: '.adonisjs/backend/controllers',
455
- exportName: 'controllers',
456
- removeNameSuffix: 'controller'
457
- })
463
+ ### Barrel file generation
464
+
465
+ Barrel files provide a single entry point by exporting a collection of lazily imported entities, recursively gathered from a source directory. The `IndexGenerator` automates this process by scanning nested directories and generating import mappings that mirror the file structure.
466
+
467
+ For example, given the following `controllers` directory structure:
468
+
469
+ ```sh
470
+ app/controllers/
471
+ ├── auth/
472
+ │ ├── login_controller.ts
473
+ │ └── register_controller.ts
474
+ ├── blog/
475
+ │ ├── posts_controller.ts
476
+ │ └── post_comments_controller.ts
477
+ └── users_controller.ts
458
478
  ```
459
479
 
460
- For more advanced use-cases, you can specify the `computeBaseName` method to self compute the key name for the collection.
480
+ When processed with the controllers configuration, the `IndexGenerator` produces a barrel file that reflects the directory hierarchy as nested objects, using capitalized file names as property keys.
461
481
 
462
482
  ```ts
463
- import StringBuilder from '@poppinss/utils/string_builder'
464
-
465
- const output = await transformer.makeEntityIndex({
466
- source: 'app/controllers',
467
- importAlias: '#controllers'
468
- }, {
469
- destination: '.adonisjs/backend/controllers',
470
- exportName: 'controllers',
471
- computeBaseName(filePath, sourcePath) {
472
- const baseName = relative(sourcePath, filePath)
473
- return new StringBuilder(baseName).toUnixSlash().removeExtension().removeSuffix('Controller').toString()
483
+ export const controllers = {
484
+ auth: {
485
+ Login: () => import('#controllers/auth/login_controller'),
486
+ Register: () => import('#controllers/auth/register_controller'),
474
487
  },
475
- })
488
+ blog: {
489
+ Posts: () => import('#controllers/blog/posts_controller'),
490
+ PostComments: () => import('#controllers/blog/post_comments_controller'),
491
+ },
492
+ Users: () => import('#controllers/users_controller'),
493
+ }
476
494
  ```
477
495
 
478
- #### Controlling the output
479
- The output is an object with key-value pair in which the value is a lazily imported module. However, you can customize the output to generate a TypeScript type using the `computeOutput` method.
496
+ ### Types generation
497
+
498
+ To generate a types file, register a custom callback that takes an instance of the `VirtualFileSystem` and updates the output string via the `buffer` object.
499
+
500
+ The collection is represented as key–value pairs:
501
+
502
+ - **Key** — the relative path (without extension) from the root of the source directory.
503
+ - **Value** — an object containing the file's `importPath`, `relativePath`, and `absolutePath`.
480
504
 
481
505
  ```ts
482
- const output = await transformer.makeEntityIndex(
483
- { source: './inertia/pages', allowedExtensions: ['.tsx'] },
484
- {
485
- destination: outputPath,
486
- computeOutput(entries) {
487
- return entries
488
- .reduce<string[]>(
489
- (result, entry) => {
490
- result.push(`${entry.name}: typeof import('${entry.importPath}')`)
491
- return result
492
- },
493
- [`declare module '@adonisjs/inertia' {`, 'export interface Pages {']
506
+ import hooks from '@adonisjs/assembler/hooks'
507
+
508
+ export default hooks.init((type, parent, indexGenerator) => {
509
+ indexGenerator.add('inertiaPages', {
510
+ source: './inertia/pages',
511
+ as: (vfs, buffer) => {
512
+ buffer.write(`declare module '@adonisjs/inertia' {`).indent()
513
+ buffer.write(`export interface Pages {`).indent()
514
+
515
+ const files = vfs.asList()
516
+ Object.keys(files).forEach((filePath) => {
517
+ buffer.write(
518
+ `'${filePath}': InferPageProps<typeof import('${file.importPath}').default>`
494
519
  )
495
- .concat('}', '}')
496
- .join('\n')
520
+ })
521
+
522
+ buffer.dedent().write('}')
523
+ buffer.dedent().write('}')
497
524
  },
498
- }
499
- )
525
+ output: './.adonisjs/server/inertia_pages.d.ts',
526
+ })
527
+ })
500
528
  ```
501
529
 
502
530
  ## Contributing
@@ -0,0 +1,387 @@
1
+ // src/debug.ts
2
+ import { debuglog } from "util";
3
+ var debug_default = debuglog("adonisjs:assembler");
4
+
5
+ // src/virtual_file_system.ts
6
+ import { fdir } from "fdir";
7
+ import Cache2 from "tmp-cache";
8
+ import { relative as relative2 } from "path/posix";
9
+ import lodash from "@poppinss/utils/lodash";
10
+ import string from "@poppinss/utils/string";
11
+ import { readFile } from "fs/promises";
12
+ import { naturalSort } from "@poppinss/utils";
13
+ import { Lang, parse } from "@ast-grep/napi";
14
+ import picomatch from "picomatch";
15
+
16
+ // src/utils.ts
17
+ import Cache from "tmp-cache";
18
+ import { isJunk } from "junk";
19
+ import fastGlob from "fast-glob";
20
+ import Hooks from "@poppinss/hooks";
21
+ import { existsSync } from "fs";
22
+ import getRandomPort from "get-port";
23
+ import { fileURLToPath } from "url";
24
+ import { execaNode, execa } from "execa";
25
+ import { importDefault } from "@poppinss/utils";
26
+ import { copyFile, mkdir } from "fs/promises";
27
+ import { EnvLoader, EnvParser } from "@adonisjs/env";
28
+ import chokidar from "chokidar";
29
+ import { basename, dirname, isAbsolute, join, relative } from "path";
30
+ var DEFAULT_NODE_ARGS = ["--import=@poppinss/ts-exec", "--enable-source-maps"];
31
+ function parseConfig(cwd, ts) {
32
+ const cwdPath = typeof cwd === "string" ? cwd : fileURLToPath(cwd);
33
+ const configFile = join(cwdPath, "tsconfig.json");
34
+ debug_default('parsing config file "%s"', configFile);
35
+ let hardException = null;
36
+ const parsedConfig = ts.getParsedCommandLineOfConfigFile(
37
+ configFile,
38
+ {},
39
+ {
40
+ ...ts.sys,
41
+ useCaseSensitiveFileNames: true,
42
+ getCurrentDirectory: () => cwdPath,
43
+ onUnRecoverableConfigFileDiagnostic: (error) => hardException = error
44
+ }
45
+ );
46
+ if (hardException) {
47
+ const compilerHost = ts.createCompilerHost({});
48
+ console.log(ts.formatDiagnosticsWithColorAndContext([hardException], compilerHost));
49
+ return;
50
+ }
51
+ if (parsedConfig.errors.length) {
52
+ const compilerHost = ts.createCompilerHost({});
53
+ console.log(ts.formatDiagnosticsWithColorAndContext(parsedConfig.errors, compilerHost));
54
+ return;
55
+ }
56
+ return parsedConfig;
57
+ }
58
+ function runNode(cwd, options) {
59
+ const childProcess = execaNode(options.script, options.scriptArgs, {
60
+ nodeOptions: DEFAULT_NODE_ARGS.concat(options.nodeArgs),
61
+ preferLocal: true,
62
+ windowsHide: false,
63
+ localDir: cwd,
64
+ cwd,
65
+ reject: options.reject ?? false,
66
+ buffer: false,
67
+ stdio: options.stdio || "inherit",
68
+ env: {
69
+ ...options.stdio === "pipe" ? { FORCE_COLOR: "true" } : {},
70
+ ...options.env
71
+ }
72
+ });
73
+ return childProcess;
74
+ }
75
+ function run(cwd, options) {
76
+ const childProcess = execa(options.script, options.scriptArgs, {
77
+ preferLocal: true,
78
+ windowsHide: false,
79
+ localDir: cwd,
80
+ cwd,
81
+ buffer: false,
82
+ stdio: options.stdio || "inherit",
83
+ env: {
84
+ ...options.stdio === "pipe" ? { FORCE_COLOR: "true" } : {},
85
+ ...options.env
86
+ }
87
+ });
88
+ return childProcess;
89
+ }
90
+ function watch(options) {
91
+ return chokidar.watch(["."], options);
92
+ }
93
+ async function getPort(cwd) {
94
+ if (process.env.PORT) {
95
+ return getRandomPort({ port: Number(process.env.PORT) });
96
+ }
97
+ const files = await new EnvLoader(cwd).load();
98
+ for (let file of files) {
99
+ const envVariables = await new EnvParser(file.contents, cwd).parse();
100
+ if (envVariables.PORT) {
101
+ return getRandomPort({ port: Number(envVariables.PORT) });
102
+ }
103
+ }
104
+ return getRandomPort({ port: 3333 });
105
+ }
106
+ async function copyFiles(files, cwd, outDir) {
107
+ const { paths, patterns } = files.reduce(
108
+ (result, file) => {
109
+ if (fastGlob.isDynamicPattern(file)) {
110
+ result.patterns.push(file);
111
+ return result;
112
+ }
113
+ if (existsSync(join(cwd, file))) {
114
+ result.paths.push(file);
115
+ }
116
+ return result;
117
+ },
118
+ { patterns: [], paths: [] }
119
+ );
120
+ debug_default("copyFiles inputs: %O, paths: %O, patterns: %O", files, paths, patterns);
121
+ const filePaths = paths.concat(await fastGlob(patterns, { cwd, dot: true })).filter((file) => {
122
+ return !isJunk(basename(file));
123
+ });
124
+ debug_default('copying files %O to destination "%s"', filePaths, outDir);
125
+ const copyPromises = filePaths.map(async (file) => {
126
+ const src = isAbsolute(file) ? file : join(cwd, file);
127
+ const dest = join(outDir, relative(cwd, src));
128
+ await mkdir(dirname(dest), { recursive: true });
129
+ return copyFile(src, dest);
130
+ });
131
+ return await Promise.all(copyPromises);
132
+ }
133
+ function memoize(fn, maxKeys) {
134
+ const cache = new Cache({ max: maxKeys });
135
+ return (input, ...args) => {
136
+ if (cache.has(input)) {
137
+ return cache.get(input);
138
+ }
139
+ return fn(input, ...args);
140
+ };
141
+ }
142
+ function isRelative(pathValue) {
143
+ return pathValue.startsWith("./") || pathValue.startsWith("../");
144
+ }
145
+ async function loadHooks(rcFileHooks, names) {
146
+ const groups = names.map((name) => {
147
+ return {
148
+ group: name,
149
+ hooks: rcFileHooks?.[name] ?? []
150
+ };
151
+ });
152
+ const hooks = new Hooks();
153
+ for (const { group, hooks: collection } of groups) {
154
+ for (const item of collection) {
155
+ hooks.add(group, await importDefault(item));
156
+ }
157
+ }
158
+ return hooks;
159
+ }
160
+ function throttle(fn, name) {
161
+ name = name || "throttled";
162
+ let isBusy = false;
163
+ let hasQueuedCalls = false;
164
+ let lastCallArgs;
165
+ async function throttled(...args) {
166
+ if (isBusy) {
167
+ debug_default('ignoring "%s" invocation as current execution is in progress', name);
168
+ hasQueuedCalls = true;
169
+ lastCallArgs = args;
170
+ return;
171
+ }
172
+ isBusy = true;
173
+ debug_default('executing "%s" function', name);
174
+ await fn(...args);
175
+ isBusy = false;
176
+ if (hasQueuedCalls) {
177
+ hasQueuedCalls = false;
178
+ debug_default('resuming and running latest "%s" invocation', name);
179
+ await throttled(...lastCallArgs);
180
+ }
181
+ }
182
+ return throttled;
183
+ }
184
+ function removeExtension(filePath) {
185
+ return filePath.substring(0, filePath.lastIndexOf("."));
186
+ }
187
+
188
+ // src/virtual_file_system.ts
189
+ var BYPASS_FN = (input) => input;
190
+ var DEFAULT_GLOB = ["**/!(*.d).ts", "**/*.tsx", "**/*.js"];
191
+ var VirtualFileSystem = class {
192
+ /**
193
+ * Absolute path to the source directory from where to read the files.
194
+ * Additionally, a glob pattern or a filter could be specified to
195
+ * narrow down the scanned files list.
196
+ */
197
+ #source;
198
+ /**
199
+ * Filesystem options
200
+ */
201
+ #options;
202
+ /**
203
+ * Files collected from the initial scan with pre-computed relative paths
204
+ */
205
+ #files = /* @__PURE__ */ new Map();
206
+ /**
207
+ * LRU cache storing parsed AST nodes by file path with size limit
208
+ */
209
+ #astCache = new Cache2({ max: 60 });
210
+ /**
211
+ * Matcher is defined when glob is defined via the options
212
+ */
213
+ #matcher;
214
+ /**
215
+ * Picomatch options used for file pattern matching
216
+ */
217
+ #picoMatchOptions;
218
+ /**
219
+ * Create a new VirtualFileSystem instance
220
+ *
221
+ * @param source - Absolute path to the source directory
222
+ * @param options - Optional configuration for file filtering and processing
223
+ */
224
+ constructor(source, options) {
225
+ this.#source = source;
226
+ this.#options = options ?? {};
227
+ this.#picoMatchOptions = {
228
+ cwd: this.#source
229
+ };
230
+ this.#matcher = picomatch(this.#options.glob ?? DEFAULT_GLOB, this.#picoMatchOptions);
231
+ }
232
+ /**
233
+ * Scans the filesystem to collect the files. Newly files must
234
+ * be added via the ".add" method.
235
+ *
236
+ * This method performs an initial scan of the source directory using
237
+ * the configured glob patterns and populates the internal file list.
238
+ */
239
+ async scan() {
240
+ debug_default('fetching entities from source "%s"', this.#source);
241
+ const filesList = await new fdir().globWithOptions(this.#options.glob ?? DEFAULT_GLOB, this.#picoMatchOptions).withFullPaths().crawl(this.#source).withPromise();
242
+ debug_default("scanned files %O", filesList);
243
+ const sortedFiles = filesList.sort(naturalSort);
244
+ this.#files.clear();
245
+ for (let filePath of sortedFiles) {
246
+ filePath = string.toUnixSlash(filePath);
247
+ const relativePath = removeExtension(relative2(this.#source, filePath));
248
+ this.#files.set(filePath, relativePath);
249
+ }
250
+ }
251
+ /**
252
+ * Check if a given file is part of the virtual file system. The method
253
+ * checks for the scanned files as well as glob pattern matches.
254
+ *
255
+ * @param filePath - Absolute file path to check
256
+ * @returns True if the file is tracked or matches the configured patterns
257
+ */
258
+ has(filePath) {
259
+ if (this.#files.has(filePath)) {
260
+ return true;
261
+ }
262
+ if (!filePath.startsWith(this.#source)) {
263
+ return false;
264
+ }
265
+ return this.#matcher(filePath);
266
+ }
267
+ /**
268
+ * Returns the files as a flat list of key-value pairs
269
+ *
270
+ * Converts the tracked files into a flat object where keys are relative
271
+ * paths (without extensions) and values are absolute file paths.
272
+ *
273
+ * @param options - Optional transformation functions for keys and values
274
+ * @returns Object with file mappings
275
+ */
276
+ asList(options) {
277
+ const list = {};
278
+ const transformKey = options?.transformKey ?? BYPASS_FN;
279
+ const transformValue = options?.transformValue ?? BYPASS_FN;
280
+ for (const [filePath, relativePath] of this.#files) {
281
+ list[transformKey(relativePath)] = transformValue(filePath);
282
+ }
283
+ return list;
284
+ }
285
+ /**
286
+ * Returns the files as a nested tree structure
287
+ *
288
+ * Converts the tracked files into a hierarchical object structure that
289
+ * mirrors the directory structure of the source files.
290
+ *
291
+ * @param options - Optional transformation functions for keys and values
292
+ * @returns Nested object representing the file tree
293
+ */
294
+ asTree(options) {
295
+ const list = {};
296
+ const transformKey = options?.transformKey ?? BYPASS_FN;
297
+ const transformValue = options?.transformValue ?? BYPASS_FN;
298
+ for (const [filePath, relativePath] of this.#files) {
299
+ lodash.set(list, transformKey(relativePath).split("/"), transformValue(filePath));
300
+ }
301
+ return list;
302
+ }
303
+ /**
304
+ * Add a new file to the virtual file system. File is only added when it
305
+ * matches the pre-defined filters.
306
+ *
307
+ * @param filePath - Absolute path of the file to add
308
+ * @returns True if the file was added, false if it doesn't match filters
309
+ */
310
+ add(filePath) {
311
+ if (this.has(filePath)) {
312
+ debug_default('adding new "%s" file to the virtual file system', filePath);
313
+ const relativePath = removeExtension(relative2(this.#source, filePath));
314
+ this.#files.set(filePath, relativePath);
315
+ return true;
316
+ }
317
+ return false;
318
+ }
319
+ /**
320
+ * Remove a file from the virtual file system
321
+ *
322
+ * @param filePath - Absolute path of the file to remove
323
+ * @returns True if the file was removed, false if it wasn't tracked
324
+ */
325
+ remove(filePath) {
326
+ debug_default('removing "%s" file from virtual file system', filePath);
327
+ return this.#files.delete(filePath);
328
+ }
329
+ /**
330
+ * Returns the file contents as AST-grep node and caches it
331
+ * forever. Use the "invalidate" method to remove it from the cache.
332
+ *
333
+ * This method reads the file content, parses it into an AST using ast-grep,
334
+ * and caches the result for future requests to improve performance.
335
+ *
336
+ * @param filePath - The absolute path to the file to parse
337
+ * @returns Promise resolving to the AST-grep node
338
+ */
339
+ async get(filePath) {
340
+ const cached = this.#astCache.get(filePath);
341
+ if (cached) {
342
+ debug_default('returning AST nodes from cache "%s"', filePath);
343
+ return cached;
344
+ }
345
+ const fileContents = await readFile(filePath, "utf-8");
346
+ debug_default('parsing "%s" file to AST', filePath);
347
+ this.#astCache.set(filePath, parse(Lang.TypeScript, fileContents).root());
348
+ return this.#astCache.get(filePath);
349
+ }
350
+ /**
351
+ * Invalidates AST cache for a single file or all files
352
+ *
353
+ * Use this method when files have been modified to ensure fresh
354
+ * AST parsing on subsequent get() calls.
355
+ *
356
+ * @param filePath - Optional file path to clear. If omitted, clears entire cache
357
+ */
358
+ invalidate(filePath) {
359
+ debug_default('invalidate AST cache "%s"', filePath);
360
+ filePath ? this.#astCache.delete(filePath) : this.#astCache.clear();
361
+ }
362
+ /**
363
+ * Clear all scanned files from memory
364
+ *
365
+ * Removes all tracked files from the internal file list, effectively
366
+ * resetting the virtual file system.
367
+ */
368
+ clear() {
369
+ this.#files.clear();
370
+ }
371
+ };
372
+
373
+ export {
374
+ debug_default,
375
+ parseConfig,
376
+ runNode,
377
+ run,
378
+ watch,
379
+ getPort,
380
+ copyFiles,
381
+ memoize,
382
+ isRelative,
383
+ loadHooks,
384
+ throttle,
385
+ removeExtension,
386
+ VirtualFileSystem
387
+ };