@adonisjs/assembler 6.1.3-9 → 7.0.0-1

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.
@@ -1,223 +0,0 @@
1
- /*
2
- * @adonisjs/assembler
3
- *
4
- * (c) AdonisJS
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import slash from 'slash';
10
- import copyfiles from 'cpy';
11
- import fs from 'node:fs/promises';
12
- import { fileURLToPath } from 'node:url';
13
- import { join, relative } from 'node:path';
14
- import { cliui } from '@poppinss/cliui';
15
- import { run, parseConfig } from './helpers.js';
16
- /**
17
- * Instance of CLIUI
18
- */
19
- const ui = cliui();
20
- /**
21
- * The bundler class exposes the API to build an AdonisJS project.
22
- */
23
- export class Bundler {
24
- #cwd;
25
- #cwdPath;
26
- #ts;
27
- #logger = ui.logger;
28
- #options;
29
- /**
30
- * Getting reference to colors library from logger
31
- */
32
- get #colors() {
33
- return this.#logger.getColors();
34
- }
35
- constructor(cwd, ts, options) {
36
- this.#cwd = cwd;
37
- this.#cwdPath = fileURLToPath(this.#cwd);
38
- this.#ts = ts;
39
- this.#options = options;
40
- }
41
- #getRelativeName(filePath) {
42
- return slash(relative(this.#cwdPath, filePath));
43
- }
44
- /**
45
- * Cleans up the build directory
46
- */
47
- async #cleanupBuildDirectory(outDir) {
48
- await fs.rm(outDir, { recursive: true, force: true, maxRetries: 5 });
49
- }
50
- /**
51
- * Runs assets bundler command to build assets.
52
- */
53
- async #buildAssets() {
54
- const assetsBundler = this.#options.assets;
55
- if (!assetsBundler?.serve) {
56
- return true;
57
- }
58
- try {
59
- this.#logger.info('compiling frontend assets', { suffix: assetsBundler.cmd });
60
- await run(this.#cwd, {
61
- stdio: 'inherit',
62
- script: assetsBundler.cmd,
63
- scriptArgs: [],
64
- });
65
- return true;
66
- }
67
- catch {
68
- return false;
69
- }
70
- }
71
- /**
72
- * Runs tsc command to build the source.
73
- */
74
- async #runTsc(outDir) {
75
- try {
76
- await run(this.#cwd, {
77
- stdio: 'inherit',
78
- script: 'tsc',
79
- scriptArgs: ['--outDir', outDir],
80
- });
81
- return true;
82
- }
83
- catch {
84
- return false;
85
- }
86
- }
87
- /**
88
- * Copy files to destination directory
89
- */
90
- async #copyFiles(files, outDir) {
91
- try {
92
- await copyfiles(files, outDir, { parents: true, cwd: this.#cwdPath });
93
- }
94
- catch (error) {
95
- if (!error.message.includes("the file doesn't exist")) {
96
- throw error;
97
- }
98
- }
99
- }
100
- /**
101
- * Copy meta files to the output directory
102
- */
103
- async #copyMetaFiles(outDir, additionalFilesToCopy) {
104
- const metaFiles = (this.#options.metaFiles || [])
105
- .map((file) => file.pattern)
106
- .concat(additionalFilesToCopy);
107
- await this.#copyFiles(metaFiles, outDir);
108
- }
109
- /**
110
- * Copies .adonisrc.json file to the destination
111
- */
112
- async #copyAdonisRcFile(outDir) {
113
- const existingContents = JSON.parse(await fs.readFile(join(this.#cwdPath, '.adonisrc.json'), 'utf-8'));
114
- const compiledContents = Object.assign({}, existingContents, {
115
- typescript: false,
116
- lastCompiledAt: new Date().toISOString(),
117
- });
118
- await fs.mkdir(outDir, { recursive: true });
119
- await fs.writeFile(join(outDir, '.adonisrc.json'), JSON.stringify(compiledContents, null, 2) + '\n');
120
- }
121
- /**
122
- * Returns the lock file name for a given packages client
123
- */
124
- #getClientLockFile(client) {
125
- switch (client) {
126
- case 'npm':
127
- return 'package-lock.json';
128
- case 'yarn':
129
- return 'yarn.lock';
130
- case 'pnpm':
131
- return 'pnpm-lock.yaml';
132
- }
133
- }
134
- /**
135
- * Returns the installation command for a given packages client
136
- */
137
- #getClientInstallCommand(client) {
138
- switch (client) {
139
- case 'npm':
140
- return 'npm ci --omit="dev"';
141
- case 'yarn':
142
- return 'yarn install --production';
143
- case 'pnpm':
144
- return 'pnpm i --prod';
145
- }
146
- }
147
- /**
148
- * Set a custom CLI UI logger
149
- */
150
- setLogger(logger) {
151
- this.#logger = logger;
152
- return this;
153
- }
154
- /**
155
- * Bundles the application to be run in production
156
- */
157
- async bundle(stopOnError = true, client = 'npm') {
158
- /**
159
- * Step 1: Parse config file to get the build output directory
160
- */
161
- const config = parseConfig(this.#cwd, this.#ts);
162
- if (!config) {
163
- return false;
164
- }
165
- /**
166
- * Step 2: Cleanup existing build directory (if any)
167
- */
168
- const outDir = config.options.outDir || fileURLToPath(new URL('build/', this.#cwd));
169
- this.#logger.info('cleaning up output directory', { suffix: this.#getRelativeName(outDir) });
170
- await this.#cleanupBuildDirectory(outDir);
171
- /**
172
- * Step 3: Build frontend assets
173
- */
174
- if (!(await this.#buildAssets())) {
175
- return false;
176
- }
177
- /**
178
- * Step 4: Build typescript source code
179
- */
180
- this.#logger.info('compiling typescript source', { suffix: 'tsc' });
181
- const buildCompleted = await this.#runTsc(outDir);
182
- await this.#copyFiles(['ace.js'], outDir);
183
- /**
184
- * Remove incomplete build directory when tsc build
185
- * failed and stopOnError is set to true.
186
- */
187
- if (!buildCompleted && stopOnError) {
188
- await this.#cleanupBuildDirectory(outDir);
189
- const instructions = ui
190
- .sticker()
191
- .fullScreen()
192
- .drawBorder((borderChar, colors) => colors.red(borderChar));
193
- instructions.add(this.#colors.red('Cannot complete the build process as there are TypeScript errors.'));
194
- instructions.add(this.#colors.red('Use "--ignore-ts-errors" flag to ignore TypeScript errors and continue the build.'));
195
- this.#logger.logError(instructions.prepare());
196
- return false;
197
- }
198
- /**
199
- * Step 5: Copy meta files to the build directory
200
- */
201
- const pkgFiles = ['package.json', this.#getClientLockFile(client)];
202
- this.#logger.info('copying meta files to the output directory');
203
- await this.#copyMetaFiles(outDir, pkgFiles);
204
- /**
205
- * Step 6: Copy .adonisrc.json file to the build directory
206
- */
207
- this.#logger.info('copying .adonisrc.json file to the output directory');
208
- await this.#copyAdonisRcFile(outDir);
209
- this.#logger.success('build completed');
210
- this.#logger.log('');
211
- /**
212
- * Next steps
213
- */
214
- ui.instructions()
215
- .useRenderer(this.#logger.getRenderer())
216
- .heading('Run the following commands to start the server in production')
217
- .add(this.#colors.cyan(`cd ${this.#getRelativeName(outDir)}`))
218
- .add(this.#colors.cyan(this.#getClientInstallCommand(client)))
219
- .add(this.#colors.cyan('node bin/server.js'))
220
- .render();
221
- return true;
222
- }
223
- }
@@ -1,253 +0,0 @@
1
- /*
2
- * @adonisjs/assembler
3
- *
4
- * (c) AdonisJS
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import picomatch from 'picomatch';
10
- import { cliui } from '@poppinss/cliui';
11
- import { AssetsDevServer } from './assets_dev_server.js';
12
- import { getPort, isDotEnvFile, isRcFile, runNode, watch } from './helpers.js';
13
- /**
14
- * Instance of CLIUI
15
- */
16
- const ui = cliui();
17
- /**
18
- * Exposes the API to start the development. Optionally, the watch API can be
19
- * used to watch for file changes and restart the development server.
20
- *
21
- * The Dev server performs the following actions
22
- *
23
- * - Assigns a random PORT, when PORT inside .env file is in use
24
- * - Uses tsconfig.json file to collect a list of files to watch.
25
- * - Uses metaFiles from .adonisrc.json file to collect a list of files to watch.
26
- * - Restart HTTP server on every file change.
27
- */
28
- export class DevServer {
29
- #cwd;
30
- #logger = ui.logger;
31
- #options;
32
- #isWatching = false;
33
- #scriptFile = 'bin/server.js';
34
- #isMetaFileWithReloadsEnabled;
35
- #isMetaFileWithReloadsDisabled;
36
- #onError;
37
- #onClose;
38
- #httpServer;
39
- #watcher;
40
- #assetsServer;
41
- /**
42
- * Getting reference to colors library from logger
43
- */
44
- get #colors() {
45
- return this.#logger.getColors();
46
- }
47
- constructor(cwd, options) {
48
- this.#cwd = cwd;
49
- this.#options = options;
50
- this.#isMetaFileWithReloadsEnabled = picomatch((this.#options.metaFiles || [])
51
- .filter(({ reloadServer }) => reloadServer === true)
52
- .map(({ pattern }) => pattern));
53
- this.#isMetaFileWithReloadsDisabled = picomatch((this.#options.metaFiles || [])
54
- .filter(({ reloadServer }) => reloadServer !== true)
55
- .map(({ pattern }) => pattern));
56
- }
57
- /**
58
- * Inspect if child process message is from AdonisJS HTTP server
59
- */
60
- #isAdonisJSReadyMessage(message) {
61
- return (message !== null &&
62
- typeof message === 'object' &&
63
- 'isAdonisJS' in message &&
64
- 'environment' in message &&
65
- message.environment === 'web');
66
- }
67
- /**
68
- * Conditionally clear the terminal screen
69
- */
70
- #clearScreen() {
71
- if (this.#options.clearScreen) {
72
- process.stdout.write('\u001Bc');
73
- }
74
- }
75
- /**
76
- * Starts the HTTP server
77
- */
78
- #startHTTPServer(port, mode) {
79
- this.#httpServer = runNode(this.#cwd, {
80
- script: this.#scriptFile,
81
- env: { PORT: port, ...this.#options.env },
82
- nodeArgs: this.#options.nodeArgs,
83
- scriptArgs: this.#options.scriptArgs,
84
- });
85
- this.#httpServer.on('message', (message) => {
86
- if (this.#isAdonisJSReadyMessage(message)) {
87
- ui.sticker()
88
- .useColors(this.#colors)
89
- .useRenderer(this.#logger.getRenderer())
90
- .add(`Server address: ${this.#colors.cyan(`http://${message.host}:${message.port}`)}`)
91
- .add(`File system watcher: ${this.#colors.cyan(`${this.#isWatching ? 'enabled' : 'disabled'}`)}`)
92
- .render();
93
- }
94
- });
95
- this.#httpServer
96
- .then((result) => {
97
- if (mode === 'nonblocking') {
98
- this.#onClose?.(result.exitCode);
99
- this.#watcher?.close();
100
- this.#assetsServer?.stop();
101
- }
102
- })
103
- .catch((error) => {
104
- if (mode === 'nonblocking') {
105
- this.#onError?.(error);
106
- this.#watcher?.close();
107
- this.#assetsServer?.stop();
108
- }
109
- });
110
- }
111
- /**
112
- * Starts the assets server
113
- */
114
- #startAssetsServer() {
115
- this.#assetsServer = new AssetsDevServer(this.#cwd, this.#options.assets);
116
- this.#assetsServer.setLogger(this.#logger);
117
- this.#assetsServer.start();
118
- }
119
- /**
120
- * Restarts the HTTP server
121
- */
122
- #restartHTTPServer(port) {
123
- if (this.#httpServer) {
124
- this.#httpServer.removeAllListeners();
125
- this.#httpServer.kill('SIGKILL');
126
- }
127
- this.#startHTTPServer(port, 'blocking');
128
- }
129
- /**
130
- * Handles a non TypeScript file change
131
- */
132
- #handleFileChange(action, port, relativePath) {
133
- if (isDotEnvFile(relativePath) || isRcFile(relativePath)) {
134
- this.#clearScreen();
135
- this.#logger.log(`${this.#colors.green(action)} ${relativePath}`);
136
- this.#restartHTTPServer(port);
137
- return;
138
- }
139
- if (this.#isMetaFileWithReloadsEnabled(relativePath)) {
140
- this.#clearScreen();
141
- this.#logger.log(`${this.#colors.green(action)} ${relativePath}`);
142
- this.#restartHTTPServer(port);
143
- return;
144
- }
145
- if (this.#isMetaFileWithReloadsDisabled(relativePath)) {
146
- this.#clearScreen();
147
- this.#logger.log(`${this.#colors.green(action)} ${relativePath}`);
148
- }
149
- }
150
- /**
151
- * Handles TypeScript source file change
152
- */
153
- #handleSourceFileChange(action, port, relativePath) {
154
- this.#clearScreen();
155
- this.#logger.log(`${this.#colors.green(action)} ${relativePath}`);
156
- this.#restartHTTPServer(port);
157
- }
158
- /**
159
- * Set a custom CLI UI logger
160
- */
161
- setLogger(logger) {
162
- this.#logger = logger;
163
- this.#assetsServer?.setLogger(logger);
164
- return this;
165
- }
166
- /**
167
- * Add listener to get notified when dev server is
168
- * closed
169
- */
170
- onClose(callback) {
171
- this.#onClose = callback;
172
- return this;
173
- }
174
- /**
175
- * Add listener to get notified when dev server exists
176
- * with an error
177
- */
178
- onError(callback) {
179
- this.#onError = callback;
180
- return this;
181
- }
182
- /**
183
- * Close watchers and running child processes
184
- */
185
- async close() {
186
- await this.#watcher?.close();
187
- this.#assetsServer?.stop();
188
- if (this.#httpServer) {
189
- this.#httpServer.removeAllListeners();
190
- this.#httpServer.kill('SIGKILL');
191
- }
192
- }
193
- /**
194
- * Start the development server
195
- */
196
- async start() {
197
- this.#clearScreen();
198
- this.#logger.info('starting HTTP server...');
199
- this.#startHTTPServer(String(await getPort(this.#cwd)), 'nonblocking');
200
- this.#startAssetsServer();
201
- }
202
- /**
203
- * Start the development server in watch mode
204
- */
205
- async startAndWatch(ts, options) {
206
- const port = String(await getPort(this.#cwd));
207
- this.#isWatching = true;
208
- this.#clearScreen();
209
- this.#logger.info('starting HTTP server...');
210
- this.#startHTTPServer(port, 'blocking');
211
- this.#startAssetsServer();
212
- /**
213
- * Create watcher using tsconfig.json file
214
- */
215
- const output = watch(this.#cwd, ts, options || {});
216
- if (!output) {
217
- this.#onClose?.(1);
218
- return;
219
- }
220
- /**
221
- * Storing reference to watcher, so that we can close it
222
- * when HTTP server exists with error
223
- */
224
- this.#watcher = output.chokidar;
225
- /**
226
- * Notify the watcher is ready
227
- */
228
- output.watcher.on('watcher:ready', () => {
229
- this.#logger.info('watching file system for changes...');
230
- });
231
- /**
232
- * Cleanup when watcher dies
233
- */
234
- output.chokidar.on('error', (error) => {
235
- this.#logger.warning('file system watcher failure');
236
- this.#logger.fatal(error);
237
- this.#onError?.(error);
238
- output.chokidar.close();
239
- });
240
- /**
241
- * Changes in TypeScript source file
242
- */
243
- output.watcher.on('source:add', ({ relativePath }) => this.#handleSourceFileChange('add', port, relativePath));
244
- output.watcher.on('source:change', ({ relativePath }) => this.#handleSourceFileChange('update', port, relativePath));
245
- output.watcher.on('source:unlink', ({ relativePath }) => this.#handleSourceFileChange('delete', port, relativePath));
246
- /**
247
- * Changes in non-TypeScript source files
248
- */
249
- output.watcher.on('add', ({ relativePath }) => this.#handleFileChange('add', port, relativePath));
250
- output.watcher.on('change', ({ relativePath }) => this.#handleFileChange('update', port, relativePath));
251
- output.watcher.on('unlink', ({ relativePath }) => this.#handleFileChange('delete', port, relativePath));
252
- }
253
- }
@@ -1,142 +0,0 @@
1
- /*
2
- * @adonisjs/assembler
3
- *
4
- * (c) AdonisJS
5
- *
6
- * For the full copyright and license information, please view the LICENSE
7
- * file that was distributed with this source code.
8
- */
9
- import getRandomPort from 'get-port';
10
- import { fileURLToPath } from 'node:url';
11
- import { execaNode, execa } from 'execa';
12
- import { EnvLoader, EnvParser } from '@adonisjs/env';
13
- import { ConfigParser, Watcher } from '@poppinss/chokidar-ts';
14
- /**
15
- * Default set of args to pass in order to run TypeScript
16
- * source. Used by "run" and "runNode" scripts
17
- */
18
- const DEFAULT_NODE_ARGS = [
19
- // Use ts-node/esm loader. The project must install it
20
- '--loader=ts-node/esm',
21
- // Disable annonying warnings
22
- '--no-warnings',
23
- // Enable expiremental meta resolve for cases where someone uses magic import string
24
- '--experimental-import-meta-resolve',
25
- ];
26
- /**
27
- * Parses tsconfig.json and prints errors using typescript compiler
28
- * host
29
- */
30
- export function parseConfig(cwd, ts) {
31
- const { config, error } = new ConfigParser(cwd, 'tsconfig.json', ts).parse();
32
- if (error) {
33
- const compilerHost = ts.createCompilerHost({});
34
- console.log(ts.formatDiagnosticsWithColorAndContext([error], compilerHost));
35
- return;
36
- }
37
- if (config.errors.length) {
38
- const compilerHost = ts.createCompilerHost({});
39
- console.log(ts.formatDiagnosticsWithColorAndContext(config.errors, compilerHost));
40
- return;
41
- }
42
- return config;
43
- }
44
- /**
45
- * Runs a Node.js script as a child process and inherits the stdio streams
46
- */
47
- export function runNode(cwd, options) {
48
- const childProcess = execaNode(options.script, options.scriptArgs, {
49
- nodeOptions: DEFAULT_NODE_ARGS.concat(options.nodeArgs),
50
- preferLocal: true,
51
- windowsHide: false,
52
- localDir: cwd,
53
- cwd,
54
- buffer: false,
55
- stdio: options.stdio || 'inherit',
56
- env: {
57
- ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
58
- ...options.env,
59
- },
60
- });
61
- return childProcess;
62
- }
63
- /**
64
- * Runs a script as a child process and inherits the stdio streams
65
- */
66
- export function run(cwd, options) {
67
- const childProcess = execa(options.script, options.scriptArgs, {
68
- preferLocal: true,
69
- windowsHide: false,
70
- localDir: cwd,
71
- cwd,
72
- buffer: false,
73
- stdio: options.stdio || 'inherit',
74
- env: {
75
- ...(options.stdio === 'pipe' ? { FORCE_COLOR: 'true' } : {}),
76
- ...options.env,
77
- },
78
- });
79
- return childProcess;
80
- }
81
- /**
82
- * Watches the file system using tsconfig file
83
- */
84
- export function watch(cwd, ts, options) {
85
- const config = parseConfig(cwd, ts);
86
- if (!config) {
87
- return;
88
- }
89
- const watcher = new Watcher(typeof cwd === 'string' ? cwd : fileURLToPath(cwd), config);
90
- const chokidar = watcher.watch(['.'], { usePolling: options.poll });
91
- return { watcher, chokidar };
92
- }
93
- /**
94
- * Check if file is an .env file
95
- */
96
- export function isDotEnvFile(filePath) {
97
- if (filePath === '.env') {
98
- return true;
99
- }
100
- return filePath.includes('.env.');
101
- }
102
- /**
103
- * Check if file is .adonisrc.json file
104
- */
105
- export function isRcFile(filePath) {
106
- return filePath === '.adonisrc.json';
107
- }
108
- /**
109
- * Returns the port to use after inspect the dot-env files inside
110
- * a given directory.
111
- *
112
- * A random port is used when the specified port is in use. Following
113
- * is the logic for finding a specified port.
114
- *
115
- * - The "process.env.PORT" value is used if exists.
116
- * - The dot-env files are loaded using the "EnvLoader" and the PORT
117
- * value is by iterating over all the loaded files. The iteration
118
- * stops after first find.
119
- */
120
- export async function getPort(cwd) {
121
- /**
122
- * Use existing port if exists
123
- */
124
- if (process.env.PORT) {
125
- return getRandomPort({ port: Number(process.env.PORT) });
126
- }
127
- /**
128
- * Loop over files and use the port from their contents. Stops
129
- * after first match
130
- */
131
- const files = await new EnvLoader(cwd).load();
132
- for (let file of files) {
133
- const envVariables = new EnvParser(file.contents).parse();
134
- if (envVariables.PORT) {
135
- return getRandomPort({ port: Number(envVariables.PORT) });
136
- }
137
- }
138
- /**
139
- * Use 3333 as the port
140
- */
141
- return getRandomPort({ port: 3333 });
142
- }