@adonisjs/assembler 6.1.3-9 → 7.0.0-0
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.
- package/README.md +388 -11
- package/build/index.js +999 -11
- package/build/index.js.map +1 -0
- package/build/src/bundler.d.ts +3 -1
- package/build/src/code_transformer/main.d.ts +43 -0
- package/build/src/code_transformer/main.js +454 -0
- package/build/src/code_transformer/main.js.map +1 -0
- package/build/src/code_transformer/rc_file_transformer.d.ts +43 -0
- package/build/src/debug.d.ts +3 -0
- package/build/src/dev_server.d.ts +2 -2
- package/build/src/helpers.d.ts +7 -6
- package/build/src/test_runner.d.ts +8 -7
- package/build/src/types.d.ts +144 -20
- package/package.json +72 -46
- package/build/src/assets_dev_server.js +0 -158
- package/build/src/bundler.js +0 -223
- package/build/src/dev_server.js +0 -253
- package/build/src/helpers.js +0 -142
- package/build/src/test_runner.js +0 -287
- package/build/src/types.js +0 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bundler.ts","../src/helpers.ts","../src/debug.ts","../src/dev_server.ts","../src/assets_dev_server.ts","../src/test_runner.ts"],"sourcesContent":["/*\n * @adonisjs/assembler\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport slash from 'slash'\nimport fs from 'node:fs/promises'\nimport { relative } from 'node:path'\nimport type tsStatic from 'typescript'\nimport { fileURLToPath } from 'node:url'\nimport { cliui, type Logger } from '@poppinss/cliui'\nimport { detectPackageManager } from '@antfu/install-pkg'\n\nimport type { BundlerOptions } from './types.js'\nimport { run, parseConfig, copyFiles } from './helpers.js'\n\ntype SupportedPackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun'\n\n/**\n * List of package managers we support in order to\n * copy lockfiles\n */\nconst SUPPORT_PACKAGE_MANAGERS: {\n [K in SupportedPackageManager]: {\n lockFile: string\n installCommand: string\n }\n} = {\n npm: {\n lockFile: 'package-lock.json',\n installCommand: 'npm ci --omit=\"dev\"',\n },\n yarn: {\n lockFile: 'yarn.lock',\n installCommand: 'yarn install --production',\n },\n pnpm: {\n lockFile: 'pnpm-lock.yaml',\n installCommand: 'pnpm i --prod',\n },\n bun: {\n lockFile: 'bun.lockb',\n installCommand: 'bun install --production',\n },\n}\n\n/**\n * Instance of CLIUI\n */\nconst ui = cliui()\n\n/**\n * The bundler class exposes the API to build an AdonisJS project.\n */\nexport class Bundler {\n #cwd: URL\n #cwdPath: string\n #ts: typeof tsStatic\n #logger = ui.logger\n #options: BundlerOptions\n\n /**\n * Getting reference to colors library from logger\n */\n get #colors() {\n return this.#logger.getColors()\n }\n\n constructor(cwd: URL, ts: typeof tsStatic, options: BundlerOptions) {\n this.#cwd = cwd\n this.#cwdPath = fileURLToPath(this.#cwd)\n this.#ts = ts\n this.#options = options\n }\n\n /**\n * Returns the relative unix path for an absolute\n * file path\n */\n #getRelativeName(filePath: string) {\n return slash(relative(this.#cwdPath, filePath))\n }\n\n /**\n * Cleans up the build directory\n */\n async #cleanupBuildDirectory(outDir: string) {\n await fs.rm(outDir, { recursive: true, force: true, maxRetries: 5 })\n }\n\n /**\n * Runs assets bundler command to build assets\n */\n async #buildAssets(): Promise<boolean> {\n const assetsBundler = this.#options.assets\n if (!assetsBundler?.enabled) {\n return true\n }\n\n try {\n this.#logger.info('compiling frontend assets', { suffix: assetsBundler.cmd })\n await run(this.#cwd, {\n stdio: 'inherit',\n script: assetsBundler.cmd,\n scriptArgs: assetsBundler.args,\n })\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Runs tsc command to build the source.\n */\n async #runTsc(outDir: string): Promise<boolean> {\n try {\n await run(this.#cwd, {\n stdio: 'inherit',\n script: 'tsc',\n scriptArgs: ['--outDir', outDir],\n })\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Copy meta files to the output directory\n */\n async #copyMetaFiles(outDir: string, additionalFilesToCopy: string[]) {\n const metaFiles = (this.#options.metaFiles || [])\n .map((file) => file.pattern)\n .concat(additionalFilesToCopy)\n\n await copyFiles(metaFiles, this.#cwdPath, outDir)\n }\n\n /**\n * Detect the package manager used by the project\n * and return the lockfile name and install command\n * related to it.\n */\n async #getPackageManager(client?: SupportedPackageManager) {\n let pkgManager: string | null | undefined = client\n\n if (!pkgManager) {\n pkgManager = await detectPackageManager(this.#cwdPath)\n }\n if (!pkgManager) {\n pkgManager = 'npm'\n }\n\n if (!Object.keys(SUPPORT_PACKAGE_MANAGERS).includes(pkgManager)) {\n return null\n }\n\n return SUPPORT_PACKAGE_MANAGERS[pkgManager as SupportedPackageManager]\n }\n\n /**\n * Set a custom CLI UI logger\n */\n setLogger(logger: Logger) {\n this.#logger = logger\n return this\n }\n\n /**\n * Bundles the application to be run in production\n */\n async bundle(stopOnError: boolean = true, client?: SupportedPackageManager): Promise<boolean> {\n /**\n * Step 1: Parse config file to get the build output directory\n */\n const config = parseConfig(this.#cwd, this.#ts)\n if (!config) {\n return false\n }\n\n /**\n * Step 2: Cleanup existing build directory (if any)\n */\n const outDir = config.options.outDir || fileURLToPath(new URL('build/', this.#cwd))\n this.#logger.info('cleaning up output directory', { suffix: this.#getRelativeName(outDir) })\n await this.#cleanupBuildDirectory(outDir)\n\n /**\n * Step 3: Build frontend assets\n */\n if (!(await this.#buildAssets())) {\n return false\n }\n\n /**\n * Step 4: Build typescript source code\n */\n this.#logger.info('compiling typescript source', { suffix: 'tsc' })\n const buildCompleted = await this.#runTsc(outDir)\n await copyFiles(['ace.js'], this.#cwdPath, outDir)\n\n /**\n * Remove incomplete build directory when tsc build\n * failed and stopOnError is set to true.\n */\n if (!buildCompleted && stopOnError) {\n await this.#cleanupBuildDirectory(outDir)\n const instructions = ui\n .sticker()\n .fullScreen()\n .drawBorder((borderChar, colors) => colors.red(borderChar))\n\n instructions.add(\n this.#colors.red('Cannot complete the build process as there are TypeScript errors.')\n )\n instructions.add(\n this.#colors.red(\n 'Use \"--ignore-ts-errors\" flag to ignore TypeScript errors and continue the build.'\n )\n )\n\n this.#logger.logError(instructions.prepare())\n return false\n }\n\n /**\n * Step 5: Copy meta files to the build directory\n */\n const pkgManager = await this.#getPackageManager(client)\n const pkgFiles = pkgManager ? ['package.json', pkgManager.lockFile] : ['package.json']\n this.#logger.info('copying meta files to the output directory')\n await this.#copyMetaFiles(outDir, pkgFiles)\n\n this.#logger.success('build completed')\n this.#logger.log('')\n\n /**\n * Next steps\n */\n ui.instructions()\n .useRenderer(this.#logger.getRenderer())\n .heading('Run the following commands to start the server in production')\n .add(this.#colors.cyan(`cd ${this.#getRelativeName(outDir)}`))\n .add(\n this.#colors.cyan(\n pkgManager ? pkgManager.installCommand : 'Install production dependencies'\n )\n )\n .add(this.#colors.cyan('node bin/server.js'))\n .render()\n\n return true\n }\n}\n","/*\n * @adonisjs/assembler\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { isJunk } from 'junk'\nimport fastGlob from 'fast-glob'\nimport getRandomPort from 'get-port'\nimport { existsSync } from 'node:fs'\nimport type tsStatic from 'typescript'\nimport { fileURLToPath } from 'node:url'\nimport { execaNode, execa } from 'execa'\nimport { copyFile, mkdir } from 'node:fs/promises'\nimport { EnvLoader, EnvParser } from '@adonisjs/env'\nimport { ConfigParser, Watcher } from '@poppinss/chokidar-ts'\nimport { basename, dirname, isAbsolute, join, relative } from 'node:path'\n\nimport type { RunOptions, WatchOptions } from './types.js'\nimport debug from './debug.js'\n\n/**\n * Default set of args to pass in order to run TypeScript\n * source. Used by \"run\" and \"runNode\" scripts\n */\nconst DEFAULT_NODE_ARGS = [\n // Use ts-node/esm loader. The project must install it\n '--loader=ts-node/esm',\n // Disable annoying warnings\n '--no-warnings',\n // Enable expiremental meta resolve for cases where someone uses magic import string\n '--experimental-import-meta-resolve',\n // Enable source maps, since TSNode source maps are broken\n '--enable-source-maps',\n]\n\n/**\n * Parses tsconfig.json and prints errors using typescript compiler\n * host\n */\nexport function parseConfig(cwd: string | URL, ts: typeof tsStatic) {\n const { config, error } = new ConfigParser(cwd, 'tsconfig.json', ts).parse()\n if (error) {\n const compilerHost = ts.createCompilerHost({})\n console.log(ts.formatDiagnosticsWithColorAndContext([error], compilerHost))\n return\n }\n\n if (config!.errors.length) {\n const compilerHost = ts.createCompilerHost({})\n console.log(ts.formatDiagnosticsWithColorAndContext(config!.errors, compilerHost))\n return\n }\n\n return config\n}\n\n/**\n * Runs a Node.js script as a child process and inherits the stdio streams\n */\nexport function runNode(cwd: string | URL, options: RunOptions) {\n const childProcess = execaNode(options.script, options.scriptArgs, {\n nodeOptions: DEFAULT_NODE_ARGS.concat(options.nodeArgs),\n preferLocal: true,\n windowsHide: false,\n localDir: cwd,\n cwd,\n buffer: false,\n stdio: options.stdio || 'inherit',\n env: {\n ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),\n ...options.env,\n },\n })\n\n return childProcess\n}\n\n/**\n * Runs a script as a child process and inherits the stdio streams\n */\nexport function run(cwd: string | URL, options: Omit<RunOptions, 'nodeArgs'>) {\n const childProcess = execa(options.script, options.scriptArgs, {\n preferLocal: true,\n windowsHide: false,\n localDir: cwd,\n cwd,\n buffer: false,\n stdio: options.stdio || 'inherit',\n env: {\n ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),\n ...options.env,\n },\n })\n\n return childProcess\n}\n\n/**\n * Watches the file system using tsconfig file\n */\nexport function watch(cwd: string | URL, ts: typeof tsStatic, options: WatchOptions) {\n const config = parseConfig(cwd, ts)\n if (!config) {\n return\n }\n\n const watcher = new Watcher(typeof cwd === 'string' ? cwd : fileURLToPath(cwd), config!)\n const chokidar = watcher.watch(['.'], { usePolling: options.poll })\n return { watcher, chokidar }\n}\n\n/**\n * Check if file is an .env file\n */\nexport function isDotEnvFile(filePath: string) {\n if (filePath === '.env') {\n return true\n }\n\n return filePath.includes('.env.')\n}\n\n/**\n * Returns the port to use after inspect the dot-env files inside\n * a given directory.\n *\n * A random port is used when the specified port is in use. Following\n * is the logic for finding a specified port.\n *\n * - The \"process.env.PORT\" value is used if exists.\n * - The dot-env files are loaded using the \"EnvLoader\" and the PORT\n * value is used by iterating over all the loaded files. The\n * iteration stops after first find.\n */\nexport async function getPort(cwd: URL): Promise<number> {\n /**\n * Use existing port if exists\n */\n if (process.env.PORT) {\n return getRandomPort({ port: Number(process.env.PORT) })\n }\n\n /**\n * Loop over files and use the port from their contents. Stops\n * after first match\n */\n const files = await new EnvLoader(cwd).load()\n for (let file of files) {\n const envVariables = new EnvParser(file.contents).parse()\n if (envVariables.PORT) {\n return getRandomPort({ port: Number(envVariables.PORT) })\n }\n }\n\n /**\n * Use 3333 as the port\n */\n return getRandomPort({ port: 3333 })\n}\n\n/**\n * Helper function to copy files from relative paths or glob\n * patterns\n */\nexport async function copyFiles(files: string[], cwd: string, outDir: string) {\n /**\n * Looping over files and create a new collection with paths\n * and glob patterns\n */\n const { paths, patterns } = files.reduce<{ patterns: string[]; paths: string[] }>(\n (result, file) => {\n /**\n * If file is a glob pattern, then push it to patterns\n */\n if (fastGlob.isDynamicPattern(file)) {\n result.patterns.push(file)\n return result\n }\n\n /**\n * Otherwise, check if file exists and push it to paths to copy\n */\n if (existsSync(join(cwd, file))) {\n result.paths.push(file)\n }\n\n return result\n },\n { patterns: [], paths: [] }\n )\n\n debug('copyFiles inputs: %O, paths: %O, patterns: %O', files, paths, patterns)\n\n /**\n * Getting list of relative paths from glob patterns\n */\n const filePaths = paths.concat(await fastGlob(patterns, { cwd, dot: true })).filter((file) => {\n return !isJunk(basename(file))\n })\n\n /**\n * Finally copy files to the destination by keeping the same\n * directory structure and ignoring junk files\n */\n debug('copying files %O to destination \"%s\"', filePaths, outDir)\n const copyPromises = filePaths.map(async (file) => {\n const src = isAbsolute(file) ? file : join(cwd, file)\n const dest = join(outDir, relative(cwd, src))\n\n await mkdir(dirname(dest), { recursive: true })\n return copyFile(src, dest)\n })\n\n return await Promise.all(copyPromises)\n}\n","/*\n * @adonisjs/assembler\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport { debuglog } from 'node:util'\n\nexport default debuglog('adonisjs:assembler')\n","/*\n * @adonisjs/assembler\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport picomatch from 'picomatch'\nimport type tsStatic from 'typescript'\nimport prettyHrtime from 'pretty-hrtime'\nimport { type ExecaChildProcess } from 'execa'\nimport { cliui, type Logger } from '@poppinss/cliui'\nimport type { Watcher } from '@poppinss/chokidar-ts'\n\nimport type { DevServerOptions } from './types.js'\nimport { AssetsDevServer } from './assets_dev_server.js'\nimport { getPort, isDotEnvFile, runNode, watch } from './helpers.js'\n\n/**\n * Instance of CLIUI\n */\nconst ui = cliui()\n\n/**\n * Exposes the API to start the development. Optionally, the watch API can be\n * used to watch for file changes and restart the development server.\n *\n * The Dev server performs the following actions\n *\n * - Assigns a random PORT, when PORT inside .env file is in use.\n * - Uses tsconfig.json file to collect a list of files to watch.\n * - Uses metaFiles from adonisrc.ts file to collect a list of files to watch.\n * - Restart HTTP server on every file change.\n */\nexport class DevServer {\n #cwd: URL\n #logger = ui.logger\n #options: DevServerOptions\n\n /**\n * Flag to know if the dev server is running in watch\n * mode\n */\n #isWatching: boolean = false\n\n /**\n * Script file to start the development server\n */\n #scriptFile: string = 'bin/server.js'\n\n /**\n * Picomatch matcher function to know if a file path is a\n * meta file with reloadServer option enabled\n */\n #isMetaFileWithReloadsEnabled: picomatch.Matcher\n\n /**\n * Picomatch matcher function to know if a file path is a\n * meta file with reloadServer option disabled\n */\n #isMetaFileWithReloadsDisabled: picomatch.Matcher\n\n /**\n * External listeners that are invoked when child process\n * gets an error or closes\n */\n #onError?: (error: any) => any\n #onClose?: (exitCode: number) => any\n\n /**\n * Reference to the child process\n */\n #httpServer?: ExecaChildProcess<string>\n\n /**\n * Reference to the watcher\n */\n #watcher?: ReturnType<Watcher['watch']>\n\n /**\n * Reference to the assets server\n */\n #assetsServer?: AssetsDevServer\n\n /**\n * Getting reference to colors library from logger\n */\n get #colors() {\n return this.#logger.getColors()\n }\n\n constructor(cwd: URL, options: DevServerOptions) {\n this.#cwd = cwd\n this.#options = options\n\n this.#isMetaFileWithReloadsEnabled = picomatch(\n (this.#options.metaFiles || [])\n .filter(({ reloadServer }) => reloadServer === true)\n .map(({ pattern }) => pattern)\n )\n\n this.#isMetaFileWithReloadsDisabled = picomatch(\n (this.#options.metaFiles || [])\n .filter(({ reloadServer }) => reloadServer !== true)\n .map(({ pattern }) => pattern)\n )\n }\n\n /**\n * Inspect if child process message is from AdonisJS HTTP server\n */\n #isAdonisJSReadyMessage(message: unknown): message is {\n isAdonisJS: true\n environment: 'web'\n port: number\n host: string\n duration?: [number, number]\n } {\n return (\n message !== null &&\n typeof message === 'object' &&\n 'isAdonisJS' in message &&\n 'environment' in message &&\n message.environment === 'web'\n )\n }\n\n /**\n * Conditionally clear the terminal screen\n */\n #clearScreen() {\n if (this.#options.clearScreen) {\n process.stdout.write('\\u001Bc')\n }\n }\n\n /**\n * Starts the HTTP server\n */\n #startHTTPServer(port: string, mode: 'blocking' | 'nonblocking') {\n this.#httpServer = runNode(this.#cwd, {\n script: this.#scriptFile,\n env: { PORT: port, ...this.#options.env },\n nodeArgs: this.#options.nodeArgs,\n scriptArgs: this.#options.scriptArgs,\n })\n\n this.#httpServer.on('message', (message) => {\n if (this.#isAdonisJSReadyMessage(message)) {\n const host = message.host === '0.0.0.0' ? '127.0.0.1' : message.host\n\n const displayMessage = ui\n .sticker()\n .useColors(this.#colors)\n .useRenderer(this.#logger.getRenderer())\n .add(`Server address: ${this.#colors.cyan(`http://${host}:${message.port}`)}`)\n .add(\n `File system watcher: ${this.#colors.cyan(\n `${this.#isWatching ? 'enabled' : 'disabled'}`\n )}`\n )\n\n if (message.duration) {\n displayMessage.add(`Ready in: ${this.#colors.cyan(prettyHrtime(message.duration))}`)\n }\n\n displayMessage.render()\n }\n })\n\n this.#httpServer\n .then((result) => {\n if (mode === 'nonblocking') {\n this.#onClose?.(result.exitCode)\n this.#watcher?.close()\n this.#assetsServer?.stop()\n } else {\n this.#logger.info('Underlying HTTP server closed. Still watching for changes')\n }\n })\n .catch((error) => {\n if (mode === 'nonblocking') {\n this.#onError?.(error)\n this.#watcher?.close()\n this.#assetsServer?.stop()\n } else {\n this.#logger.info('Underlying HTTP server died. Still watching for changes')\n }\n })\n }\n\n /**\n * Starts the assets server\n */\n #startAssetsServer() {\n this.#assetsServer = new AssetsDevServer(this.#cwd, this.#options.assets)\n this.#assetsServer.setLogger(this.#logger)\n this.#assetsServer.start()\n }\n\n /**\n * Restarts the HTTP server in the watch mode. Do not call this\n * method when not in watch mode\n */\n #restartHTTPServer(port: string) {\n if (this.#httpServer) {\n this.#httpServer.removeAllListeners()\n this.#httpServer.kill('SIGKILL')\n }\n\n this.#startHTTPServer(port, 'blocking')\n }\n\n /**\n * Handles a non TypeScript file change\n */\n #handleFileChange(action: string, port: string, relativePath: string) {\n if (isDotEnvFile(relativePath)) {\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n this.#restartHTTPServer(port)\n return\n }\n\n if (this.#isMetaFileWithReloadsEnabled(relativePath)) {\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n this.#restartHTTPServer(port)\n return\n }\n\n if (this.#isMetaFileWithReloadsDisabled(relativePath)) {\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n }\n }\n\n /**\n * Handles TypeScript source file change\n */\n #handleSourceFileChange(action: string, port: string, relativePath: string) {\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n this.#restartHTTPServer(port)\n }\n\n /**\n * Set a custom CLI UI logger\n */\n setLogger(logger: Logger) {\n this.#logger = logger\n this.#assetsServer?.setLogger(logger)\n return this\n }\n\n /**\n * Add listener to get notified when dev server is\n * closed\n */\n onClose(callback: (exitCode: number) => any): this {\n this.#onClose = callback\n return this\n }\n\n /**\n * Add listener to get notified when dev server exists\n * with an error\n */\n onError(callback: (error: any) => any): this {\n this.#onError = callback\n return this\n }\n\n /**\n * Close watchers and running child processes\n */\n async close() {\n await this.#watcher?.close()\n this.#assetsServer?.stop()\n if (this.#httpServer) {\n this.#httpServer.removeAllListeners()\n this.#httpServer.kill('SIGKILL')\n }\n }\n\n /**\n * Start the development server\n */\n async start() {\n this.#clearScreen()\n this.#logger.info('starting HTTP server...')\n this.#startHTTPServer(String(await getPort(this.#cwd)), 'nonblocking')\n this.#startAssetsServer()\n }\n\n /**\n * Start the development server in watch mode\n */\n async startAndWatch(ts: typeof tsStatic, options?: { poll: boolean }) {\n const port = String(await getPort(this.#cwd))\n this.#isWatching = true\n\n this.#clearScreen()\n\n this.#logger.info('starting HTTP server...')\n this.#startHTTPServer(port, 'blocking')\n\n this.#startAssetsServer()\n\n /**\n * Create watcher using tsconfig.json file\n */\n const output = watch(this.#cwd, ts, options || {})\n if (!output) {\n this.#onClose?.(1)\n return\n }\n\n /**\n * Storing reference to watcher, so that we can close it\n * when HTTP server exists with error\n */\n this.#watcher = output.chokidar\n\n /**\n * Notify the watcher is ready\n */\n output.watcher.on('watcher:ready', () => {\n this.#logger.info('watching file system for changes...')\n })\n\n /**\n * Cleanup when watcher dies\n */\n output.chokidar.on('error', (error) => {\n this.#logger.warning('file system watcher failure')\n this.#logger.fatal(error)\n this.#onError?.(error)\n output.chokidar.close()\n })\n\n /**\n * Changes in TypeScript source file\n */\n output.watcher.on('source:add', ({ relativePath }) =>\n this.#handleSourceFileChange('add', port, relativePath)\n )\n output.watcher.on('source:change', ({ relativePath }) =>\n this.#handleSourceFileChange('update', port, relativePath)\n )\n output.watcher.on('source:unlink', ({ relativePath }) =>\n this.#handleSourceFileChange('delete', port, relativePath)\n )\n\n /**\n * Changes in non-TypeScript source files\n */\n output.watcher.on('add', ({ relativePath }) =>\n this.#handleFileChange('add', port, relativePath)\n )\n output.watcher.on('change', ({ relativePath }) =>\n this.#handleFileChange('update', port, relativePath)\n )\n output.watcher.on('unlink', ({ relativePath }) =>\n this.#handleFileChange('delete', port, relativePath)\n )\n }\n}\n","/*\n * @adonisjs/core\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport type { ExecaChildProcess } from 'execa'\nimport { type Logger, cliui } from '@poppinss/cliui'\n\nimport { run } from './helpers.js'\nimport type { AssetsBundlerOptions } from './types.js'\n\n/**\n * Instance of CLIUI\n */\nconst ui = cliui()\n\n/**\n * Exposes the API to start the development server for processing assets during\n * development.\n *\n * - Here we are running the assets dev server in a child process.\n * - Piping the output from the child process and reformatting it before writing it to\n * process streams.\n *\n * AssetsDevServer is agnostic and can run any assets dev server. Be it Vite or Encore or\n * even Webpack directly.\n */\nexport class AssetsDevServer {\n #cwd: URL\n #logger = ui.logger\n #options?: AssetsBundlerOptions\n #devServer?: ExecaChildProcess<string>\n\n /**\n * Getting reference to colors library from logger\n */\n get #colors() {\n return this.#logger.getColors()\n }\n\n constructor(cwd: URL, options?: AssetsBundlerOptions) {\n this.#cwd = cwd\n this.#options = options\n }\n\n /**\n * Logs messages from vite dev server stdout and stderr\n */\n #logViteDevServerMessage(data: Buffer) {\n const dataString = data.toString()\n const lines = dataString.split('\\n')\n\n /**\n * Put a wrapper around vite network address log\n */\n if (dataString.includes('Local') && dataString.includes('Network')) {\n const sticker = ui.sticker().useColors(this.#colors).useRenderer(this.#logger.getRenderer())\n\n lines.forEach((line: string) => {\n if (line.trim()) {\n sticker.add(line)\n }\n })\n\n sticker.render()\n return\n }\n\n /**\n * Logging VITE ready in message with proper\n * spaces and newlines\n */\n if (dataString.includes('ready in')) {\n console.log('')\n console.log(dataString.trim())\n return\n }\n\n /**\n * Log rest of the lines\n */\n lines.forEach((line: string) => {\n if (line.trim()) {\n console.log(line)\n }\n })\n }\n\n /**\n * Logs messages from assets dev server stdout and stderr\n */\n #logAssetsDevServerMessage(data: Buffer) {\n const dataString = data.toString()\n const lines = dataString.split('\\n')\n lines.forEach((line: string) => {\n if (line.trim()) {\n console.log(line)\n }\n })\n }\n\n /**\n * Set a custom CLI UI logger\n */\n setLogger(logger: Logger) {\n this.#logger = logger\n return this\n }\n\n /**\n * Starts the assets bundler server. The assets bundler server process is\n * considered as the secondary process and therefore we do not perform\n * any cleanup if it dies.\n */\n start() {\n if (!this.#options?.enabled) {\n return\n }\n\n this.#logger.info(`starting \"${this.#options.driver}\" dev server...`)\n\n /**\n * Create child process\n */\n this.#devServer = run(this.#cwd, {\n script: this.#options.cmd,\n\n /**\n * We do not inherit the stdio for vite and encore, because in\n * inherit mode they own the stdin and interrupts the\n * `Ctrl + C` command.\n */\n stdio: 'pipe',\n scriptArgs: this.#options.args,\n })\n\n /**\n * Log child process messages\n */\n this.#devServer.stdout?.on('data', (data) => {\n if (this.#options!.driver === 'vite') {\n this.#logViteDevServerMessage(data)\n } else {\n this.#logAssetsDevServerMessage(data)\n }\n })\n\n this.#devServer.stderr?.on('data', (data) => {\n if (this.#options!.driver === 'vite') {\n this.#logViteDevServerMessage(data)\n } else {\n this.#logAssetsDevServerMessage(data)\n }\n })\n\n this.#devServer\n .then((result) => {\n this.#logger.warning(\n `\"${this.#options!.driver}\" dev server closed with status code \"${result.exitCode}\"`\n )\n })\n .catch((error) => {\n this.#logger.warning(`unable to connect to \"${this.#options!.driver}\" dev server`)\n this.#logger.fatal(error)\n })\n }\n\n /**\n * Stop the dev server\n */\n stop() {\n if (this.#devServer) {\n this.#devServer.removeAllListeners()\n this.#devServer.kill('SIGKILL')\n this.#devServer = undefined\n }\n }\n}\n","/*\n * @adonisjs/assembler\n *\n * (c) AdonisJS\n *\n * For the full copyright and license information, please view the LICENSE\n * file that was distributed with this source code.\n */\n\nimport picomatch from 'picomatch'\nimport type tsStatic from 'typescript'\nimport { type ExecaChildProcess } from 'execa'\nimport { cliui, type Logger } from '@poppinss/cliui'\nimport type { Watcher } from '@poppinss/chokidar-ts'\n\nimport type { TestRunnerOptions } from './types.js'\nimport { AssetsDevServer } from './assets_dev_server.js'\nimport { getPort, isDotEnvFile, runNode, watch } from './helpers.js'\n\n/**\n * Instance of CLIUI\n */\nconst ui = cliui()\n\n/**\n * Exposes the API to run Japa tests and optionally watch for file\n * changes to re-run the tests.\n *\n * The watch mode functions as follows.\n *\n * - If the changed file is a test file, then only tests for that file\n * will be re-run.\n * - Otherwise, all tests will re-run with respect to the initial\n * filters applied when running the `node ace test` command.\n *\n */\nexport class TestRunner {\n #cwd: URL\n #logger = ui.logger\n #options: TestRunnerOptions\n\n /**\n * The script file to run as a child process\n */\n #scriptFile: string = 'bin/test.js'\n\n /**\n * Pico matcher function to check if the filepath is\n * part of the `metaFiles` glob patterns\n */\n #isMetaFile: picomatch.Matcher\n\n /**\n * Pico matcher function to check if the filepath is\n * part of a test file.\n */\n #isTestFile: picomatch.Matcher\n\n /**\n * Arguments to pass to the \"bin/test.js\" file.\n */\n #scriptArgs: string[]\n\n /**\n * Set of initial filters applied when running the test\n * command. In watch mode, we will append an additional\n * filter to run tests only for the file that has been\n * changed.\n */\n #initialFiltersArgs: string[]\n\n /**\n * In watch mode, after a file is changed, we wait for the current\n * set of tests to finish before triggering a re-run. Therefore,\n * we use this flag to know if we are already busy in running\n * tests and ignore file-changes.\n */\n #isBusy: boolean = false\n\n /**\n * External listeners that are invoked when child process\n * gets an error or closes\n */\n #onError?: (error: any) => any\n #onClose?: (exitCode: number) => any\n\n /**\n * Reference to the test script child process\n */\n #testScript?: ExecaChildProcess<string>\n\n /**\n * Reference to the watcher\n */\n #watcher?: ReturnType<Watcher['watch']>\n\n /**\n * Reference to the assets server\n */\n #assetsServer?: AssetsDevServer\n\n /**\n * Getting reference to colors library from logger\n */\n get #colors() {\n return this.#logger.getColors()\n }\n\n constructor(cwd: URL, options: TestRunnerOptions) {\n this.#cwd = cwd\n this.#options = options\n\n this.#isMetaFile = picomatch((this.#options.metaFiles || []).map(({ pattern }) => pattern))\n\n /**\n * Create a test file watch by collection all the globs\n * used by all the suites. However, if a suite filter\n * was used, then we only collect glob for the mentioned\n * suites.\n */\n this.#isTestFile = picomatch(\n this.#options.suites\n .filter((suite) => {\n if (this.#options.filters.suites) {\n return this.#options.filters.suites.includes(suite.name)\n }\n return true\n })\n .map((suite) => suite.files)\n .flat(1)\n )\n\n this.#scriptArgs = this.#convertOptionsToArgs().concat(this.#options.scriptArgs)\n this.#initialFiltersArgs = this.#convertFiltersToArgs(this.#options.filters)\n }\n\n /**\n * Convert test runner options to the CLI args\n */\n #convertOptionsToArgs() {\n const args: string[] = []\n\n if (this.#options.reporters) {\n args.push('--reporters')\n args.push(this.#options.reporters.join(','))\n }\n\n if (this.#options.timeout !== undefined) {\n args.push('--timeout')\n args.push(String(this.#options.timeout))\n }\n\n if (this.#options.failed) {\n args.push('--failed')\n }\n\n if (this.#options.retries !== undefined) {\n args.push('--retries')\n args.push(String(this.#options.retries))\n }\n\n return args\n }\n\n /**\n * Converts all known filters to CLI args.\n *\n * The following code snippet may seem like repetitive code. But, it\n * is done intentionally to have visibility around how each filter\n * is converted to an arg.\n */\n #convertFiltersToArgs(filters: TestRunnerOptions['filters']): string[] {\n const args: string[] = []\n\n if (filters.suites) {\n args.push(...filters.suites)\n }\n\n if (filters.files) {\n args.push('--files')\n args.push(filters.files.join(','))\n }\n\n if (filters.groups) {\n args.push('--groups')\n args.push(filters.groups.join(','))\n }\n\n if (filters.tags) {\n args.push('--tags')\n args.push(filters.tags.join(','))\n }\n\n if (filters.tests) {\n args.push('--tests')\n args.push(filters.tests.join(','))\n }\n\n return args\n }\n\n /**\n * Conditionally clear the terminal screen\n */\n #clearScreen() {\n if (this.#options.clearScreen) {\n process.stdout.write('\\u001Bc')\n }\n }\n\n /**\n * Runs tests\n */\n #runTests(\n port: string,\n mode: 'blocking' | 'nonblocking',\n filters?: TestRunnerOptions['filters']\n ) {\n this.#isBusy = true\n\n /**\n * If inline filters are defined, then we ignore the\n * initial filters\n */\n const scriptArgs = filters\n ? this.#convertFiltersToArgs(filters).concat(this.#scriptArgs)\n : this.#initialFiltersArgs.concat(this.#scriptArgs)\n\n this.#testScript = runNode(this.#cwd, {\n script: this.#scriptFile,\n env: { PORT: port, ...this.#options.env },\n nodeArgs: this.#options.nodeArgs,\n scriptArgs,\n })\n\n this.#testScript\n .then((result) => {\n if (mode === 'nonblocking') {\n this.#onClose?.(result.exitCode)\n this.close()\n }\n })\n .catch((error) => {\n if (mode === 'nonblocking') {\n this.#onError?.(error)\n this.close()\n }\n })\n .finally(() => {\n this.#isBusy = false\n })\n }\n\n /**\n * Re-run tests with additional inline filters. Should be\n * executed in watch mode only.\n */\n #rerunTests(port: string, filters?: TestRunnerOptions['filters']) {\n if (this.#testScript) {\n this.#testScript.removeAllListeners()\n this.#testScript.kill('SIGKILL')\n }\n\n this.#runTests(port, 'blocking', filters)\n }\n\n /**\n * Starts the assets server\n */\n #startAssetsServer() {\n this.#assetsServer = new AssetsDevServer(this.#cwd, this.#options.assets)\n this.#assetsServer.setLogger(this.#logger)\n this.#assetsServer.start()\n }\n\n /**\n * Handles a non TypeScript file change\n */\n #handleFileChange(action: string, port: string, relativePath: string) {\n if (this.#isBusy) {\n return\n }\n\n if (isDotEnvFile(relativePath) || this.#isMetaFile(relativePath)) {\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n this.#rerunTests(port)\n }\n }\n\n /**\n * Handles TypeScript source file change\n */\n #handleSourceFileChange(action: string, port: string, relativePath: string) {\n if (this.#isBusy) {\n return\n }\n\n this.#clearScreen()\n this.#logger.log(`${this.#colors.green(action)} ${relativePath}`)\n\n /**\n * If changed file is a test file after considering the initial filters,\n * then only run that file\n */\n if (this.#isTestFile(relativePath)) {\n this.#rerunTests(port, {\n ...this.#options.filters,\n files: [relativePath],\n })\n return\n }\n\n this.#rerunTests(port)\n }\n\n /**\n * Set a custom CLI UI logger\n */\n setLogger(logger: Logger) {\n this.#logger = logger\n this.#assetsServer?.setLogger(logger)\n return this\n }\n\n /**\n * Add listener to get notified when dev server is\n * closed\n */\n onClose(callback: (exitCode: number) => any): this {\n this.#onClose = callback\n return this\n }\n\n /**\n * Add listener to get notified when dev server exists\n * with an error\n */\n onError(callback: (error: any) => any): this {\n this.#onError = callback\n return this\n }\n\n /**\n * Close watchers and running child processes\n */\n async close() {\n await this.#watcher?.close()\n this.#assetsServer?.stop()\n if (this.#testScript) {\n this.#testScript.removeAllListeners()\n this.#testScript.kill('SIGKILL')\n }\n }\n\n /**\n * Runs tests\n */\n async run() {\n const port = String(await getPort(this.#cwd))\n\n this.#clearScreen()\n this.#startAssetsServer()\n\n this.#logger.info('booting application to run tests...')\n this.#runTests(port, 'nonblocking')\n }\n\n /**\n * Run tests in watch mode\n */\n async runAndWatch(ts: typeof tsStatic, options?: { poll: boolean }) {\n const port = String(await getPort(this.#cwd))\n\n this.#clearScreen()\n this.#startAssetsServer()\n\n this.#logger.info('booting application to run tests...')\n this.#runTests(port, 'blocking')\n\n /**\n * Create watcher using tsconfig.json file\n */\n const output = watch(this.#cwd, ts, options || {})\n if (!output) {\n this.#onClose?.(1)\n return\n }\n\n /**\n * Storing reference to watcher, so that we can close it\n * when HTTP server exists with error\n */\n this.#watcher = output.chokidar\n\n /**\n * Notify the watcher is ready\n */\n output.watcher.on('watcher:ready', () => {\n this.#logger.info('watching file system for changes...')\n })\n\n /**\n * Cleanup when watcher dies\n */\n output.chokidar.on('error', (error) => {\n this.#logger.warning('file system watcher failure')\n this.#logger.fatal(error)\n this.#onError?.(error)\n output.chokidar.close()\n })\n\n /**\n * Changes in TypeScript source file\n */\n output.watcher.on('source:add', ({ relativePath }) =>\n this.#handleSourceFileChange('add', port, relativePath)\n )\n output.watcher.on('source:change', ({ relativePath }) =>\n this.#handleSourceFileChange('update', port, relativePath)\n )\n output.watcher.on('source:unlink', ({ relativePath }) =>\n this.#handleSourceFileChange('delete', port, relativePath)\n )\n\n /**\n * Changes in non-TypeScript source files\n */\n output.watcher.on('add', ({ relativePath }) =>\n this.#handleFileChange('add', port, relativePath)\n )\n output.watcher.on('change', ({ relativePath }) =>\n this.#handleFileChange('update', port, relativePath)\n )\n output.watcher.on('unlink', ({ relativePath }) =>\n this.#handleFileChange('delete', port, relativePath)\n )\n }\n}\n"],"mappings":";AASA,OAAO,WAAW;AAClB,OAAO,QAAQ;AACf,SAAS,YAAAA,iBAAgB;AAEzB,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,aAA0B;AACnC,SAAS,4BAA4B;;;ACNrC,SAAS,cAAc;AACvB,OAAO,cAAc;AACrB,OAAO,mBAAmB;AAC1B,SAAS,kBAAkB;AAE3B,SAAS,qBAAqB;AAC9B,SAAS,WAAW,aAAa;AACjC,SAAS,UAAU,aAAa;AAChC,SAAS,WAAW,iBAAiB;AACrC,SAAS,cAAc,eAAe;AACtC,SAAS,UAAU,SAAS,YAAY,MAAM,gBAAgB;;;ACV9D,SAAS,gBAAgB;AAEzB,IAAO,gBAAQ,SAAS,oBAAoB;;;ADiB5C,IAAM,oBAAoB;AAAA;AAAA,EAExB;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AACF;AAMO,SAAS,YAAY,KAAmB,IAAqB;AAClE,QAAM,EAAE,QAAQ,MAAM,IAAI,IAAI,aAAa,KAAK,iBAAiB,EAAE,EAAE,MAAM;AAC3E,MAAI,OAAO;AACT,UAAM,eAAe,GAAG,mBAAmB,CAAC,CAAC;AAC7C,YAAQ,IAAI,GAAG,qCAAqC,CAAC,KAAK,GAAG,YAAY,CAAC;AAC1E;AAAA,EACF;AAEA,MAAI,OAAQ,OAAO,QAAQ;AACzB,UAAM,eAAe,GAAG,mBAAmB,CAAC,CAAC;AAC7C,YAAQ,IAAI,GAAG,qCAAqC,OAAQ,QAAQ,YAAY,CAAC;AACjF;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,QAAQ,KAAmB,SAAqB;AAC9D,QAAM,eAAe,UAAU,QAAQ,QAAQ,QAAQ,YAAY;AAAA,IACjE,aAAa,kBA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Q,MAAM,KAAK;AACxB,WAAK,WAAW,KAAK;AACrB,aAAO,SAAS,MAAM;AAAA,IACxB,CAAC;AAKD,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAc,CAAC,EAAE,aAAa,MAC9C,KAAK,wBAAwB,OAAO,MAAM,YAAY;AAAA,IACxD;AACA,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAiB,CAAC,EAAE,aAAa,MACjD,KAAK,wBAAwB,UAAU,MAAM,YAAY;AAAA,IAC3D;AACA,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAiB,CAAC,EAAE,aAAa,MACjD,KAAK,wBAAwB,UAAU,MAAM,YAAY;AAAA,IAC3D;AAKA,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAO,CAAC,EAAE,aAAa,MACvC,KAAK,kBAAkB,OAAO,MAAM,YAAY;AAAA,IAClD;AACA,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAU,CAAC,EAAE,aAAa,MAC1C,KAAK,kBAAkB,UAAU,MAAM,YAAY;AAAA,IACrD;AACA,WAAO,QAAQ;AAAA,MAAG;AAAA,MAAU,CAAC,EAAE,aAAa,MAC1C,KAAK,kBAAkB,UAAU,MAAM,YAAY;AAAA,IACrD;AAAA,EACF;AACF;","names":["relative","fileURLToPath","fileURLToPath","relative","cliui","cliui","ui","cliui","ui","cliui","picomatch","cliui","ui","cliui","picomatch"]}
|
package/build/src/bundler.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type tsStatic from 'typescript';
|
|
3
3
|
import { type Logger } from '@poppinss/cliui';
|
|
4
4
|
import type { BundlerOptions } from './types.js';
|
|
5
|
+
type SupportedPackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';
|
|
5
6
|
/**
|
|
6
7
|
* The bundler class exposes the API to build an AdonisJS project.
|
|
7
8
|
*/
|
|
@@ -15,5 +16,6 @@ export declare class Bundler {
|
|
|
15
16
|
/**
|
|
16
17
|
* Bundles the application to be run in production
|
|
17
18
|
*/
|
|
18
|
-
bundle(stopOnError?: boolean, client?:
|
|
19
|
+
bundle(stopOnError?: boolean, client?: SupportedPackageManager): Promise<boolean>;
|
|
19
20
|
}
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
import { installPackage, detectPackageManager } from '@antfu/install-pkg';
|
|
3
|
+
import { RcFileTransformer } from './rc_file_transformer.js';
|
|
4
|
+
import type { MiddlewareNode, EnvValidationNode } from '../types.js';
|
|
5
|
+
/**
|
|
6
|
+
* This class is responsible for updating
|
|
7
|
+
*/
|
|
8
|
+
export declare class CodeTransformer {
|
|
9
|
+
#private;
|
|
10
|
+
/**
|
|
11
|
+
* Exporting utilities to install package and detect
|
|
12
|
+
* the package manager
|
|
13
|
+
*/
|
|
14
|
+
installPackage: typeof installPackage;
|
|
15
|
+
detectPackageManager: typeof detectPackageManager;
|
|
16
|
+
constructor(cwd: URL);
|
|
17
|
+
/**
|
|
18
|
+
* Add new env variable validation in the
|
|
19
|
+
* `env.ts` file
|
|
20
|
+
*/
|
|
21
|
+
defineEnvValidations(definition: EnvValidationNode): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Define new middlewares inside the `start/kernel.ts`
|
|
24
|
+
* file
|
|
25
|
+
*
|
|
26
|
+
* This function is highly based on some assumptions
|
|
27
|
+
* and will not work if you significantly tweaked
|
|
28
|
+
* your `start/kernel.ts` file.
|
|
29
|
+
*/
|
|
30
|
+
addMiddlewareToStack(stack: 'server' | 'router' | 'named', middleware: MiddlewareNode[]): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Update the `adonisrc.ts` file
|
|
33
|
+
*/
|
|
34
|
+
updateRcFile(callback: (transformer: RcFileTransformer) => void): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Add a new Japa plugin in the `tests/bootstrap.ts` file
|
|
37
|
+
*/
|
|
38
|
+
addJapaPlugin(pluginCall: string, importDeclarations: {
|
|
39
|
+
isNamed: boolean;
|
|
40
|
+
module: string;
|
|
41
|
+
identifier: string;
|
|
42
|
+
}[]): Promise<void>;
|
|
43
|
+
}
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
// src/code_transformer/main.ts
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
4
|
+
import { installPackage, detectPackageManager } from "@antfu/install-pkg";
|
|
5
|
+
import {
|
|
6
|
+
Node as Node2,
|
|
7
|
+
Project as Project2,
|
|
8
|
+
QuoteKind,
|
|
9
|
+
SyntaxKind as SyntaxKind2
|
|
10
|
+
} from "ts-morph";
|
|
11
|
+
|
|
12
|
+
// src/code_transformer/rc_file_transformer.ts
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import {
|
|
15
|
+
Node,
|
|
16
|
+
SyntaxKind
|
|
17
|
+
} from "ts-morph";
|
|
18
|
+
var RcFileTransformer = class {
|
|
19
|
+
#cwd;
|
|
20
|
+
#project;
|
|
21
|
+
/**
|
|
22
|
+
* Settings to use when persisting files
|
|
23
|
+
*/
|
|
24
|
+
#editorSettings = {
|
|
25
|
+
indentSize: 2,
|
|
26
|
+
convertTabsToSpaces: true,
|
|
27
|
+
trimTrailingWhitespace: true,
|
|
28
|
+
ensureNewLineAtEndOfFile: true,
|
|
29
|
+
indentStyle: 2,
|
|
30
|
+
// @ts-expect-error SemicolonPreference doesn't seem to be re-exported from ts-morph
|
|
31
|
+
semicolons: "remove"
|
|
32
|
+
};
|
|
33
|
+
constructor(cwd, project) {
|
|
34
|
+
this.#cwd = cwd;
|
|
35
|
+
this.#project = project;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Get the `adonisrc.ts` source file
|
|
39
|
+
*/
|
|
40
|
+
#getRcFileOrThrow() {
|
|
41
|
+
const kernelUrl = fileURLToPath(new URL("./adonisrc.ts", this.#cwd));
|
|
42
|
+
return this.#project.getSourceFileOrThrow(kernelUrl);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Check if environments array has a subset of available environments
|
|
46
|
+
*/
|
|
47
|
+
#isInSpecificEnvironment(environments) {
|
|
48
|
+
if (!environments) {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
return !!["web", "console", "test", "repl"].find(
|
|
52
|
+
(env) => !environments.includes(env)
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Locate the `defineConfig` call inside the `adonisrc.ts` file
|
|
57
|
+
*/
|
|
58
|
+
#locateDefineConfigCallOrThrow(file) {
|
|
59
|
+
const call = file.getDescendantsOfKind(SyntaxKind.CallExpression).find((statement) => statement.getExpression().getText() === "defineConfig");
|
|
60
|
+
if (!call) {
|
|
61
|
+
throw new Error("Could not locate the defineConfig call.");
|
|
62
|
+
}
|
|
63
|
+
return call;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Return the ObjectLiteralExpression of the defineConfig call
|
|
67
|
+
*/
|
|
68
|
+
#getDefineConfigObjectOrThrow(defineConfigCall) {
|
|
69
|
+
const configObject = defineConfigCall.getArguments()[0].asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
|
|
70
|
+
return configObject;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Check if the defineConfig() call has the property assignment
|
|
74
|
+
* inside it or not. If not, it will create one and return it.
|
|
75
|
+
*/
|
|
76
|
+
#getPropertyAssignmentInDefineConfigCall(propertyName, initializer) {
|
|
77
|
+
const file = this.#getRcFileOrThrow();
|
|
78
|
+
const defineConfigCall = this.#locateDefineConfigCallOrThrow(file);
|
|
79
|
+
const configObject = this.#getDefineConfigObjectOrThrow(defineConfigCall);
|
|
80
|
+
let property = configObject.getProperty(propertyName);
|
|
81
|
+
if (!property) {
|
|
82
|
+
configObject.addPropertyAssignment({ name: propertyName, initializer });
|
|
83
|
+
property = configObject.getProperty(propertyName);
|
|
84
|
+
}
|
|
85
|
+
return property;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Extract list of imported modules from an ArrayLiteralExpression
|
|
89
|
+
*
|
|
90
|
+
* It assumes that the array can have two types of elements:
|
|
91
|
+
*
|
|
92
|
+
* - Simple lazy imported modules: [() => import('path/to/file')]
|
|
93
|
+
* - Or an object entry: [{ file: () => import('path/to/file'), environment: ['web', 'console'] }]
|
|
94
|
+
* where the `file` property is a lazy imported module.
|
|
95
|
+
*/
|
|
96
|
+
#extractModulesFromArray(array) {
|
|
97
|
+
const modules = array.getElements().map((element) => {
|
|
98
|
+
if (Node.isArrowFunction(element)) {
|
|
99
|
+
const importExp = element.getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression);
|
|
100
|
+
const literal = importExp.getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral);
|
|
101
|
+
return literal.getLiteralValue();
|
|
102
|
+
}
|
|
103
|
+
if (Node.isObjectLiteralExpression(element)) {
|
|
104
|
+
const fileProp = element.getPropertyOrThrow("file");
|
|
105
|
+
const arrowFn = fileProp.getFirstDescendantByKindOrThrow(SyntaxKind.ArrowFunction);
|
|
106
|
+
const importExp = arrowFn.getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression);
|
|
107
|
+
const literal = importExp.getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral);
|
|
108
|
+
return literal.getLiteralValue();
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
return modules.filter(Boolean);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Extract a specific property from an ArrayLiteralExpression
|
|
115
|
+
* that contains object entries.
|
|
116
|
+
*
|
|
117
|
+
* This function is mainly used for extractring the `pattern` property
|
|
118
|
+
* when adding a new meta files entry, or the `name` property when
|
|
119
|
+
* adding a new test suite.
|
|
120
|
+
*/
|
|
121
|
+
#extractPropertyFromArray(array, propertyName) {
|
|
122
|
+
const property = array.getElements().map((el) => {
|
|
123
|
+
if (!Node.isObjectLiteralExpression(el))
|
|
124
|
+
return;
|
|
125
|
+
const nameProp = el.getPropertyOrThrow(propertyName);
|
|
126
|
+
if (!Node.isPropertyAssignment(nameProp))
|
|
127
|
+
return;
|
|
128
|
+
const name = nameProp.getInitializerIfKindOrThrow(SyntaxKind.StringLiteral);
|
|
129
|
+
return name.getLiteralValue();
|
|
130
|
+
});
|
|
131
|
+
return property.filter(Boolean);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Build a new module entry for the preloads and providers array
|
|
135
|
+
* based upon the environments specified
|
|
136
|
+
*/
|
|
137
|
+
#buildNewModuleEntry(modulePath, environments) {
|
|
138
|
+
if (!this.#isInSpecificEnvironment(environments)) {
|
|
139
|
+
return `() => import('${modulePath}')`;
|
|
140
|
+
}
|
|
141
|
+
return `{
|
|
142
|
+
file: () => import('${modulePath}'),
|
|
143
|
+
environment: [${environments?.map((env) => `'${env}'`).join(", ")}],
|
|
144
|
+
}`;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Add a new command to the rcFile
|
|
148
|
+
*/
|
|
149
|
+
addCommand(commandPath) {
|
|
150
|
+
const commandsProperty = this.#getPropertyAssignmentInDefineConfigCall("commands", "[]");
|
|
151
|
+
const commandsArray = commandsProperty.getInitializerIfKindOrThrow(
|
|
152
|
+
SyntaxKind.ArrayLiteralExpression
|
|
153
|
+
);
|
|
154
|
+
const commandString = `() => import('${commandPath}')`;
|
|
155
|
+
if (commandsArray.getElements().some((el) => el.getText() === commandString)) {
|
|
156
|
+
return this;
|
|
157
|
+
}
|
|
158
|
+
commandsArray.addElement(commandString);
|
|
159
|
+
return this;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Add a new preloaded file to the rcFile
|
|
163
|
+
*/
|
|
164
|
+
addPreloadFile(modulePath, environments) {
|
|
165
|
+
const preloadsProperty = this.#getPropertyAssignmentInDefineConfigCall("preloads", "[]");
|
|
166
|
+
const preloadsArray = preloadsProperty.getInitializerIfKindOrThrow(
|
|
167
|
+
SyntaxKind.ArrayLiteralExpression
|
|
168
|
+
);
|
|
169
|
+
const existingPreloadedFiles = this.#extractModulesFromArray(preloadsArray);
|
|
170
|
+
const isDuplicate = existingPreloadedFiles.includes(modulePath);
|
|
171
|
+
if (isDuplicate) {
|
|
172
|
+
return this;
|
|
173
|
+
}
|
|
174
|
+
preloadsArray.addElement(this.#buildNewModuleEntry(modulePath, environments));
|
|
175
|
+
return this;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Add a new provider to the rcFile
|
|
179
|
+
*/
|
|
180
|
+
addProvider(providerPath, environments) {
|
|
181
|
+
const property = this.#getPropertyAssignmentInDefineConfigCall("providers", "[]");
|
|
182
|
+
const providersArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
|
|
183
|
+
const existingProviderPaths = this.#extractModulesFromArray(providersArray);
|
|
184
|
+
const isDuplicate = existingProviderPaths.includes(providerPath);
|
|
185
|
+
if (isDuplicate) {
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
providersArray.addElement(this.#buildNewModuleEntry(providerPath, environments));
|
|
189
|
+
return this;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Add a new meta file to the rcFile
|
|
193
|
+
*/
|
|
194
|
+
addMetaFile(globPattern, reloadServer = false) {
|
|
195
|
+
const property = this.#getPropertyAssignmentInDefineConfigCall("metaFiles", "[]");
|
|
196
|
+
const metaFilesArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
|
|
197
|
+
const alreadyDefinedPatterns = this.#extractPropertyFromArray(metaFilesArray, "pattern");
|
|
198
|
+
if (alreadyDefinedPatterns.includes(globPattern)) {
|
|
199
|
+
return this;
|
|
200
|
+
}
|
|
201
|
+
metaFilesArray.addElement(
|
|
202
|
+
`{
|
|
203
|
+
pattern: '${globPattern}',
|
|
204
|
+
reloadServer: ${reloadServer},
|
|
205
|
+
}`
|
|
206
|
+
);
|
|
207
|
+
return this;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Set directory name and path
|
|
211
|
+
*/
|
|
212
|
+
setDirectory(key, value) {
|
|
213
|
+
const property = this.#getPropertyAssignmentInDefineConfigCall("directories", "{}");
|
|
214
|
+
const directories = property.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
|
|
215
|
+
directories.addPropertyAssignment({ name: key, initializer: `'${value}'` });
|
|
216
|
+
return this;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Set command alias
|
|
220
|
+
*/
|
|
221
|
+
setCommandAlias(alias, command) {
|
|
222
|
+
const aliasProperty = this.#getPropertyAssignmentInDefineConfigCall("commandsAliases", "{}");
|
|
223
|
+
const aliases = aliasProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
|
|
224
|
+
aliases.addPropertyAssignment({ name: alias, initializer: `'${command}'` });
|
|
225
|
+
return this;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Add a new test suite to the rcFile
|
|
229
|
+
*/
|
|
230
|
+
addSuite(suiteName, files, timeout) {
|
|
231
|
+
const testProperty = this.#getPropertyAssignmentInDefineConfigCall(
|
|
232
|
+
"tests",
|
|
233
|
+
`{ suites: [], forceExit: true, timeout: 2000 }`
|
|
234
|
+
);
|
|
235
|
+
const property = testProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression).getPropertyOrThrow("suites");
|
|
236
|
+
const suitesArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
|
|
237
|
+
const existingSuitesNames = this.#extractPropertyFromArray(suitesArray, "name");
|
|
238
|
+
if (existingSuitesNames.includes(suiteName)) {
|
|
239
|
+
return this;
|
|
240
|
+
}
|
|
241
|
+
const filesArray = Array.isArray(files) ? files : [files];
|
|
242
|
+
suitesArray.addElement(
|
|
243
|
+
`{
|
|
244
|
+
name: '${suiteName}',
|
|
245
|
+
files: [${filesArray.map((file) => `'${file}'`).join(", ")}],
|
|
246
|
+
timeout: ${timeout ?? 2e3},
|
|
247
|
+
}`
|
|
248
|
+
);
|
|
249
|
+
return this;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Save the adonisrc.ts file
|
|
253
|
+
*/
|
|
254
|
+
save() {
|
|
255
|
+
const file = this.#getRcFileOrThrow();
|
|
256
|
+
file.formatText(this.#editorSettings);
|
|
257
|
+
return file.save();
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// src/code_transformer/main.ts
|
|
262
|
+
var CodeTransformer = class {
|
|
263
|
+
/**
|
|
264
|
+
* Exporting utilities to install package and detect
|
|
265
|
+
* the package manager
|
|
266
|
+
*/
|
|
267
|
+
installPackage = installPackage;
|
|
268
|
+
detectPackageManager = detectPackageManager;
|
|
269
|
+
/**
|
|
270
|
+
* Directory of the adonisjs project
|
|
271
|
+
*/
|
|
272
|
+
#cwd;
|
|
273
|
+
/**
|
|
274
|
+
* The TsMorph project
|
|
275
|
+
*/
|
|
276
|
+
#project;
|
|
277
|
+
/**
|
|
278
|
+
* Settings to use when persisting files
|
|
279
|
+
*/
|
|
280
|
+
#editorSettings = {
|
|
281
|
+
indentSize: 2,
|
|
282
|
+
convertTabsToSpaces: true,
|
|
283
|
+
trimTrailingWhitespace: true,
|
|
284
|
+
ensureNewLineAtEndOfFile: true,
|
|
285
|
+
indentStyle: 2,
|
|
286
|
+
// @ts-expect-error SemicolonPreference doesn't seem to be re-exported from ts-morph
|
|
287
|
+
semicolons: "remove"
|
|
288
|
+
};
|
|
289
|
+
constructor(cwd) {
|
|
290
|
+
this.#cwd = cwd;
|
|
291
|
+
this.#project = new Project2({
|
|
292
|
+
tsConfigFilePath: join(fileURLToPath2(this.#cwd), "tsconfig.json"),
|
|
293
|
+
manipulationSettings: { quoteKind: QuoteKind.Single }
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Add a new middleware to the middleware array of the
|
|
298
|
+
* given file
|
|
299
|
+
*/
|
|
300
|
+
#addToMiddlewareArray(file, target, middlewareEntry) {
|
|
301
|
+
const callExpressions = file.getDescendantsOfKind(SyntaxKind2.CallExpression).filter((statement) => statement.getExpression().getText() === target);
|
|
302
|
+
if (!callExpressions.length) {
|
|
303
|
+
throw new Error(`Cannot find ${target} statement in the file.`);
|
|
304
|
+
}
|
|
305
|
+
const arrayLiteralExpression = callExpressions[0].getArguments()[0];
|
|
306
|
+
if (!arrayLiteralExpression || !Node2.isArrayLiteralExpression(arrayLiteralExpression)) {
|
|
307
|
+
throw new Error(`Cannot find middleware array in ${target} statement.`);
|
|
308
|
+
}
|
|
309
|
+
const middleware = `() => import('${middlewareEntry.path}')`;
|
|
310
|
+
const existingMiddlewareIndex = arrayLiteralExpression.getElements().findIndex((element) => element.getText() === middleware);
|
|
311
|
+
if (existingMiddlewareIndex === -1) {
|
|
312
|
+
if (middlewareEntry.position === "before") {
|
|
313
|
+
arrayLiteralExpression.insertElement(0, middleware);
|
|
314
|
+
} else {
|
|
315
|
+
arrayLiteralExpression.addElement(middleware);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Add a new middleware to the named middleware of the given file
|
|
321
|
+
*/
|
|
322
|
+
#addToNamedMiddleware(file, middlewareEntry) {
|
|
323
|
+
if (!middlewareEntry.name) {
|
|
324
|
+
throw new Error("Named middleware requires a name.");
|
|
325
|
+
}
|
|
326
|
+
const callArguments = file.getVariableDeclarationOrThrow("middleware").getInitializerIfKindOrThrow(SyntaxKind2.CallExpression).getArguments();
|
|
327
|
+
if (callArguments.length === 0) {
|
|
328
|
+
throw new Error("Named middleware call has no arguments.");
|
|
329
|
+
}
|
|
330
|
+
const namedMiddlewareObject = callArguments[0];
|
|
331
|
+
if (!Node2.isObjectLiteralExpression(namedMiddlewareObject)) {
|
|
332
|
+
throw new Error("The argument of the named middleware call is not an object literal.");
|
|
333
|
+
}
|
|
334
|
+
const existingProperty = namedMiddlewareObject.getProperty(middlewareEntry.name);
|
|
335
|
+
if (!existingProperty) {
|
|
336
|
+
const middleware = `${middlewareEntry.name}: () => import('${middlewareEntry.path}')`;
|
|
337
|
+
namedMiddlewareObject.insertProperty(0, middleware);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Write a leading comment
|
|
342
|
+
*/
|
|
343
|
+
#addLeadingComment(writer, comment) {
|
|
344
|
+
if (!comment) {
|
|
345
|
+
return writer.blankLine();
|
|
346
|
+
}
|
|
347
|
+
return writer.blankLine().writeLine("/*").writeLine(`|----------------------------------------------------------`).writeLine(`| ${comment}`).writeLine(`|----------------------------------------------------------`).writeLine(`*/`);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Add new env variable validation in the
|
|
351
|
+
* `env.ts` file
|
|
352
|
+
*/
|
|
353
|
+
async defineEnvValidations(definition) {
|
|
354
|
+
const kernelUrl = fileURLToPath2(new URL("./start/env.ts", this.#cwd));
|
|
355
|
+
const file = this.#project.getSourceFileOrThrow(kernelUrl);
|
|
356
|
+
const callExpressions = file.getDescendantsOfKind(SyntaxKind2.CallExpression).filter((statement) => statement.getExpression().getText() === "Env.create");
|
|
357
|
+
if (!callExpressions.length) {
|
|
358
|
+
throw new Error(`Cannot find Env.create statement in the file.`);
|
|
359
|
+
}
|
|
360
|
+
const objectLiteralExpression = callExpressions[0].getArguments()[1];
|
|
361
|
+
if (!Node2.isObjectLiteralExpression(objectLiteralExpression)) {
|
|
362
|
+
throw new Error(`The second argument of Env.create is not an object literal.`);
|
|
363
|
+
}
|
|
364
|
+
let shouldAddComment = true;
|
|
365
|
+
for (const [variable, validation] of Object.entries(definition.variables)) {
|
|
366
|
+
const existingProperty = objectLiteralExpression.getProperty(variable);
|
|
367
|
+
if (existingProperty) {
|
|
368
|
+
shouldAddComment = false;
|
|
369
|
+
}
|
|
370
|
+
if (!existingProperty) {
|
|
371
|
+
objectLiteralExpression.addPropertyAssignment({
|
|
372
|
+
name: variable,
|
|
373
|
+
initializer: validation,
|
|
374
|
+
leadingTrivia: (writer) => {
|
|
375
|
+
if (!shouldAddComment) {
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
shouldAddComment = false;
|
|
379
|
+
return this.#addLeadingComment(writer, definition.leadingComment);
|
|
380
|
+
}
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
file.formatText(this.#editorSettings);
|
|
385
|
+
await file.save();
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Define new middlewares inside the `start/kernel.ts`
|
|
389
|
+
* file
|
|
390
|
+
*
|
|
391
|
+
* This function is highly based on some assumptions
|
|
392
|
+
* and will not work if you significantly tweaked
|
|
393
|
+
* your `start/kernel.ts` file.
|
|
394
|
+
*/
|
|
395
|
+
async addMiddlewareToStack(stack, middleware) {
|
|
396
|
+
const kernelUrl = fileURLToPath2(new URL("./start/kernel.ts", this.#cwd));
|
|
397
|
+
const file = this.#project.getSourceFileOrThrow(kernelUrl);
|
|
398
|
+
for (const middlewareEntry of middleware) {
|
|
399
|
+
if (stack === "named") {
|
|
400
|
+
this.#addToNamedMiddleware(file, middlewareEntry);
|
|
401
|
+
} else {
|
|
402
|
+
this.#addToMiddlewareArray(file, `${stack}.use`, middlewareEntry);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
file.formatText(this.#editorSettings);
|
|
406
|
+
await file.save();
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Update the `adonisrc.ts` file
|
|
410
|
+
*/
|
|
411
|
+
async updateRcFile(callback) {
|
|
412
|
+
const rcFileTransformer = new RcFileTransformer(this.#cwd, this.#project);
|
|
413
|
+
callback(rcFileTransformer);
|
|
414
|
+
await rcFileTransformer.save();
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Add a new Japa plugin in the `tests/bootstrap.ts` file
|
|
418
|
+
*/
|
|
419
|
+
async addJapaPlugin(pluginCall, importDeclarations) {
|
|
420
|
+
const testBootstrapUrl = fileURLToPath2(new URL("./tests/bootstrap.ts", this.#cwd));
|
|
421
|
+
const file = this.#project.getSourceFileOrThrow(testBootstrapUrl);
|
|
422
|
+
const existingImports = file.getImportDeclarations();
|
|
423
|
+
importDeclarations.forEach((importDeclaration) => {
|
|
424
|
+
const existingImport = existingImports.find(
|
|
425
|
+
(mod) => mod.getModuleSpecifierValue() === importDeclaration.module
|
|
426
|
+
);
|
|
427
|
+
if (existingImport && importDeclaration.isNamed) {
|
|
428
|
+
if (!existingImport.getNamedImports().find((namedImport) => namedImport.getName() === importDeclaration.identifier)) {
|
|
429
|
+
existingImport.addNamedImport(importDeclaration.identifier);
|
|
430
|
+
}
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (existingImport) {
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
file.addImportDeclaration({
|
|
437
|
+
...importDeclaration.isNamed ? { namedImports: [importDeclaration.identifier] } : { defaultImport: importDeclaration.identifier },
|
|
438
|
+
moduleSpecifier: importDeclaration.module
|
|
439
|
+
});
|
|
440
|
+
});
|
|
441
|
+
const pluginsArray = file.getVariableDeclaration("plugins")?.getInitializerIfKind(SyntaxKind2.ArrayLiteralExpression);
|
|
442
|
+
if (pluginsArray) {
|
|
443
|
+
if (!pluginsArray.getElements().find((element) => element.getText() === pluginCall)) {
|
|
444
|
+
pluginsArray.addElement(pluginCall);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
file.formatText(this.#editorSettings);
|
|
448
|
+
await file.save();
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
export {
|
|
452
|
+
CodeTransformer
|
|
453
|
+
};
|
|
454
|
+
//# sourceMappingURL=main.js.map
|