@adonisjs/assembler 6.1.3-1 → 6.1.3-11

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/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # The MIT License
2
2
 
3
- Copyright (c) 2023 AdonisJS Framework
3
+ Copyright (c) 2023 Harminder Virk
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
6
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <br />
4
4
 
5
- [![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![synk-image]][synk-url]
5
+ [![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url] [![snyk-image]][snyk-url]
6
6
 
7
7
  ## Introduction
8
8
  Assembler exports the API for starting the **AdonisJS development server**, **building project for production** and **running tests** in watch mode. Assembler must be used during development only.
@@ -32,5 +32,5 @@ AdonisJS Assembler is open-sourced software licensed under the [MIT license](LIC
32
32
  [license-url]: LICENSE.md
33
33
  [license-image]: https://img.shields.io/github/license/adonisjs/ace?style=for-the-badge
34
34
 
35
- [synk-image]: https://img.shields.io/snyk/vulnerabilities/github/adonisjs/assembler?label=Synk%20Vulnerabilities&style=for-the-badge
36
- [synk-url]: https://snyk.io/test/github/adonisjs/assembler?targetFile=package.json "synk"
35
+ [snyk-image]: https://img.shields.io/snyk/vulnerabilities/github/adonisjs/assembler?label=snyk%20Vulnerabilities&style=for-the-badge
36
+ [snyk-url]: https://snyk.io/test/github/adonisjs/assembler?targetFile=package.json "snyk"
package/build/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { Bundler } from './src/bundler.js';
2
2
  export { DevServer } from './src/dev_server.js';
3
+ export { TestRunner } from './src/test_runner.js';
package/build/index.js CHANGED
@@ -1,2 +1,11 @@
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
+ */
1
9
  export { Bundler } from './src/bundler.js';
2
10
  export { DevServer } from './src/dev_server.js';
11
+ export { TestRunner } from './src/test_runner.js';
@@ -0,0 +1,32 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { type Logger } from '@poppinss/cliui';
3
+ import type { AssetsBundlerOptions } from './types.js';
4
+ /**
5
+ * Exposes the API to start the development server for processing assets during
6
+ * development.
7
+ *
8
+ * - Here we are running the assets dev server in a child process.
9
+ * - Piping the output from the child process and reformatting it before writing it to
10
+ * process streams.
11
+ *
12
+ * AssetsDevServer is agnostic and can run any assets dev server. Be it Vite or Encore or
13
+ * even Webpack directly.
14
+ */
15
+ export declare class AssetsDevServer {
16
+ #private;
17
+ constructor(cwd: URL, options?: AssetsBundlerOptions);
18
+ /**
19
+ * Set a custom CLI UI logger
20
+ */
21
+ setLogger(logger: Logger): this;
22
+ /**
23
+ * Starts the assets bundler server. The assets bundler server process is
24
+ * considered as the secondary process and therefore we do not perform
25
+ * any cleanup if it dies.
26
+ */
27
+ start(): void;
28
+ /**
29
+ * Stop the dev server
30
+ */
31
+ stop(): void;
32
+ }
@@ -0,0 +1,158 @@
1
+ /*
2
+ * @adonisjs/core
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 { cliui } from '@poppinss/cliui';
10
+ import { run } from './helpers.js';
11
+ /**
12
+ * Instance of CLIUI
13
+ */
14
+ const ui = cliui();
15
+ /**
16
+ * Exposes the API to start the development server for processing assets during
17
+ * development.
18
+ *
19
+ * - Here we are running the assets dev server in a child process.
20
+ * - Piping the output from the child process and reformatting it before writing it to
21
+ * process streams.
22
+ *
23
+ * AssetsDevServer is agnostic and can run any assets dev server. Be it Vite or Encore or
24
+ * even Webpack directly.
25
+ */
26
+ export class AssetsDevServer {
27
+ #cwd;
28
+ #logger = ui.logger;
29
+ #options;
30
+ #devServer;
31
+ /**
32
+ * Getting reference to colors library from logger
33
+ */
34
+ get #colors() {
35
+ return this.#logger.getColors();
36
+ }
37
+ constructor(cwd, options) {
38
+ this.#cwd = cwd;
39
+ this.#options = options;
40
+ }
41
+ /**
42
+ * Logs messages from vite dev server stdout and stderr
43
+ */
44
+ #logViteDevServerMessage(data) {
45
+ const dataString = data.toString();
46
+ const lines = dataString.split('\n');
47
+ /**
48
+ * Logging VITE ready in message with proper
49
+ * spaces and newlines
50
+ */
51
+ if (dataString.includes('ready in')) {
52
+ console.log('');
53
+ console.log(dataString.trim());
54
+ return;
55
+ }
56
+ /**
57
+ * Put a wrapper around vite network address log
58
+ */
59
+ if (dataString.includes('Local') && dataString.includes('Network')) {
60
+ const sticker = ui.sticker().useColors(this.#colors).useRenderer(this.#logger.getRenderer());
61
+ lines.forEach((line) => {
62
+ if (line.trim()) {
63
+ sticker.add(line);
64
+ }
65
+ });
66
+ sticker.render();
67
+ return;
68
+ }
69
+ /**
70
+ * Log rest of the lines
71
+ */
72
+ lines.forEach((line) => {
73
+ if (line.trim()) {
74
+ console.log(line);
75
+ }
76
+ });
77
+ }
78
+ /**
79
+ * Logs messages from assets dev server stdout and stderr
80
+ */
81
+ #logAssetsDevServerMessage(data) {
82
+ const dataString = data.toString();
83
+ const lines = dataString.split('\n');
84
+ lines.forEach((line) => {
85
+ if (line.trim()) {
86
+ console.log(line);
87
+ }
88
+ });
89
+ }
90
+ /**
91
+ * Set a custom CLI UI logger
92
+ */
93
+ setLogger(logger) {
94
+ this.#logger = logger;
95
+ return this;
96
+ }
97
+ /**
98
+ * Starts the assets bundler server. The assets bundler server process is
99
+ * considered as the secondary process and therefore we do not perform
100
+ * any cleanup if it dies.
101
+ */
102
+ start() {
103
+ if (!this.#options?.serve) {
104
+ return;
105
+ }
106
+ this.#logger.info(`starting "${this.#options.driver}" dev server...`);
107
+ /**
108
+ * Create child process
109
+ */
110
+ this.#devServer = run(this.#cwd, {
111
+ script: this.#options.cmd,
112
+ /**
113
+ * We do not inherit the stdio for vite and encore, because in
114
+ * inherit mode they own the stdin and interrupts the
115
+ * `Ctrl + C` command.
116
+ */
117
+ stdio: 'pipe',
118
+ scriptArgs: this.#options.args,
119
+ });
120
+ /**
121
+ * Log child process messages
122
+ */
123
+ this.#devServer.stdout?.on('data', (data) => {
124
+ if (this.#options.driver === 'vite') {
125
+ this.#logViteDevServerMessage(data);
126
+ }
127
+ else {
128
+ this.#logAssetsDevServerMessage(data);
129
+ }
130
+ });
131
+ this.#devServer.stderr?.on('data', (data) => {
132
+ if (this.#options.driver === 'vite') {
133
+ this.#logViteDevServerMessage(data);
134
+ }
135
+ else {
136
+ this.#logAssetsDevServerMessage(data);
137
+ }
138
+ });
139
+ this.#devServer
140
+ .then((result) => {
141
+ this.#logger.warning(`"${this.#options.driver}" dev server closed with status code "${result.exitCode}"`);
142
+ })
143
+ .catch((error) => {
144
+ this.#logger.warning(`unable to connect to "${this.#options.driver}" dev server`);
145
+ this.#logger.fatal(error);
146
+ });
147
+ }
148
+ /**
149
+ * Stop the dev server
150
+ */
151
+ stop() {
152
+ if (this.#devServer) {
153
+ this.#devServer.removeAllListeners();
154
+ this.#devServer.kill('SIGKILL');
155
+ this.#devServer = undefined;
156
+ }
157
+ }
158
+ }
@@ -2,9 +2,18 @@
2
2
  import type tsStatic from 'typescript';
3
3
  import { type Logger } from '@poppinss/cliui';
4
4
  import type { BundlerOptions } from './types.js';
5
+ /**
6
+ * The bundler class exposes the API to build an AdonisJS project.
7
+ */
5
8
  export declare class Bundler {
6
9
  #private;
7
10
  constructor(cwd: URL, ts: typeof tsStatic, options: BundlerOptions);
11
+ /**
12
+ * Set a custom CLI UI logger
13
+ */
8
14
  setLogger(logger: Logger): this;
15
+ /**
16
+ * Bundles the application to be run in production
17
+ */
9
18
  bundle(stopOnError?: boolean, client?: 'npm' | 'yarn' | 'pnpm'): Promise<boolean>;
10
19
  }
@@ -1,18 +1,34 @@
1
- import fs from 'fs-extra';
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
+ */
2
9
  import slash from 'slash';
3
10
  import copyfiles from 'cpy';
11
+ import fs from 'node:fs/promises';
4
12
  import { fileURLToPath } from 'node:url';
5
13
  import { join, relative } from 'node:path';
6
14
  import { cliui } from '@poppinss/cliui';
7
- import { run } from './run.js';
8
- import { parseConfig } from './parse_config.js';
15
+ import { run, parseConfig } from './helpers.js';
16
+ /**
17
+ * Instance of CLIUI
18
+ */
9
19
  const ui = cliui();
20
+ /**
21
+ * The bundler class exposes the API to build an AdonisJS project.
22
+ */
10
23
  export class Bundler {
11
24
  #cwd;
12
25
  #cwdPath;
13
26
  #ts;
14
27
  #logger = ui.logger;
15
28
  #options;
29
+ /**
30
+ * Getting reference to colors library from logger
31
+ */
16
32
  get #colors() {
17
33
  return this.#logger.getColors();
18
34
  }
@@ -25,9 +41,15 @@ export class Bundler {
25
41
  #getRelativeName(filePath) {
26
42
  return slash(relative(this.#cwdPath, filePath));
27
43
  }
44
+ /**
45
+ * Cleans up the build directory
46
+ */
28
47
  async #cleanupBuildDirectory(outDir) {
29
- await fs.remove(outDir);
48
+ await fs.rm(outDir, { recursive: true, force: true, maxRetries: 5 });
30
49
  }
50
+ /**
51
+ * Runs assets bundler command to build assets.
52
+ */
31
53
  async #buildAssets() {
32
54
  const assetsBundler = this.#options.assets;
33
55
  if (!assetsBundler?.serve) {
@@ -46,6 +68,9 @@ export class Bundler {
46
68
  return false;
47
69
  }
48
70
  }
71
+ /**
72
+ * Runs tsc command to build the source.
73
+ */
49
74
  async #runTsc(outDir) {
50
75
  try {
51
76
  await run(this.#cwd, {
@@ -59,9 +84,12 @@ export class Bundler {
59
84
  return false;
60
85
  }
61
86
  }
87
+ /**
88
+ * Copy files to destination directory
89
+ */
62
90
  async #copyFiles(files, outDir) {
63
91
  try {
64
- await copyfiles(files, outDir, { cwd: this.#cwdPath });
92
+ await copyfiles(files, outDir, { parents: true, cwd: this.#cwdPath });
65
93
  }
66
94
  catch (error) {
67
95
  if (!error.message.includes("the file doesn't exist")) {
@@ -69,20 +97,30 @@ export class Bundler {
69
97
  }
70
98
  }
71
99
  }
100
+ /**
101
+ * Copy meta files to the output directory
102
+ */
72
103
  async #copyMetaFiles(outDir, additionalFilesToCopy) {
73
104
  const metaFiles = (this.#options.metaFiles || [])
74
105
  .map((file) => file.pattern)
75
106
  .concat(additionalFilesToCopy);
76
107
  await this.#copyFiles(metaFiles, outDir);
77
108
  }
109
+ /**
110
+ * Copies .adonisrc.json file to the destination
111
+ */
78
112
  async #copyAdonisRcFile(outDir) {
79
- const existingContents = await fs.readJSON(join(this.#cwdPath, '.adonisrc.json'));
113
+ const existingContents = JSON.parse(await fs.readFile(join(this.#cwdPath, '.adonisrc.json'), 'utf-8'));
80
114
  const compiledContents = Object.assign({}, existingContents, {
81
115
  typescript: false,
82
116
  lastCompiledAt: new Date().toISOString(),
83
117
  });
84
- await fs.outputJSON(join(outDir, '.adonisrc.json'), compiledContents, { spaces: 2 });
118
+ await fs.mkdir(outDir, { recursive: true });
119
+ await fs.writeFile(join(outDir, '.adonisrc.json'), JSON.stringify(compiledContents, null, 2) + '\n');
85
120
  }
121
+ /**
122
+ * Returns the lock file name for a given packages client
123
+ */
86
124
  #getClientLockFile(client) {
87
125
  switch (client) {
88
126
  case 'npm':
@@ -93,6 +131,9 @@ export class Bundler {
93
131
  return 'pnpm-lock.yaml';
94
132
  }
95
133
  }
134
+ /**
135
+ * Returns the installation command for a given packages client
136
+ */
96
137
  #getClientInstallCommand(client) {
97
138
  switch (client) {
98
139
  case 'npm':
@@ -103,24 +144,46 @@ export class Bundler {
103
144
  return 'pnpm i --prod';
104
145
  }
105
146
  }
147
+ /**
148
+ * Set a custom CLI UI logger
149
+ */
106
150
  setLogger(logger) {
107
151
  this.#logger = logger;
108
152
  return this;
109
153
  }
154
+ /**
155
+ * Bundles the application to be run in production
156
+ */
110
157
  async bundle(stopOnError = true, client = 'npm') {
158
+ /**
159
+ * Step 1: Parse config file to get the build output directory
160
+ */
111
161
  const config = parseConfig(this.#cwd, this.#ts);
112
162
  if (!config) {
113
163
  return false;
114
164
  }
165
+ /**
166
+ * Step 2: Cleanup existing build directory (if any)
167
+ */
115
168
  const outDir = config.options.outDir || fileURLToPath(new URL('build/', this.#cwd));
116
169
  this.#logger.info('cleaning up output directory', { suffix: this.#getRelativeName(outDir) });
117
170
  await this.#cleanupBuildDirectory(outDir);
171
+ /**
172
+ * Step 3: Build frontend assets
173
+ */
118
174
  if (!(await this.#buildAssets())) {
119
175
  return false;
120
176
  }
177
+ /**
178
+ * Step 4: Build typescript source code
179
+ */
121
180
  this.#logger.info('compiling typescript source', { suffix: 'tsc' });
122
181
  const buildCompleted = await this.#runTsc(outDir);
123
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
+ */
124
187
  if (!buildCompleted && stopOnError) {
125
188
  await this.#cleanupBuildDirectory(outDir);
126
189
  const instructions = ui
@@ -132,13 +195,22 @@ export class Bundler {
132
195
  this.#logger.logError(instructions.prepare());
133
196
  return false;
134
197
  }
198
+ /**
199
+ * Step 5: Copy meta files to the build directory
200
+ */
135
201
  const pkgFiles = ['package.json', this.#getClientLockFile(client)];
136
202
  this.#logger.info('copying meta files to the output directory');
137
203
  await this.#copyMetaFiles(outDir, pkgFiles);
204
+ /**
205
+ * Step 6: Copy .adonisrc.json file to the build directory
206
+ */
138
207
  this.#logger.info('copying .adonisrc.json file to the output directory');
139
208
  await this.#copyAdonisRcFile(outDir);
140
209
  this.#logger.success('build completed');
141
210
  this.#logger.log('');
211
+ /**
212
+ * Next steps
213
+ */
142
214
  ui.instructions()
143
215
  .useRenderer(this.#logger.getRenderer())
144
216
  .heading('Run the following commands to start the server in production')
@@ -2,13 +2,45 @@
2
2
  import type tsStatic from 'typescript';
3
3
  import { type Logger } from '@poppinss/cliui';
4
4
  import type { DevServerOptions } from './types.js';
5
+ /**
6
+ * Exposes the API to start the development. Optionally, the watch API can be
7
+ * used to watch for file changes and restart the development server.
8
+ *
9
+ * The Dev server performs the following actions
10
+ *
11
+ * - Assigns a random PORT, when PORT inside .env file is in use
12
+ * - Uses tsconfig.json file to collect a list of files to watch.
13
+ * - Uses metaFiles from .adonisrc.json file to collect a list of files to watch.
14
+ * - Restart HTTP server on every file change.
15
+ */
5
16
  export declare class DevServer {
6
17
  #private;
7
18
  constructor(cwd: URL, options: DevServerOptions);
19
+ /**
20
+ * Set a custom CLI UI logger
21
+ */
8
22
  setLogger(logger: Logger): this;
23
+ /**
24
+ * Add listener to get notified when dev server is
25
+ * closed
26
+ */
9
27
  onClose(callback: (exitCode: number) => any): this;
28
+ /**
29
+ * Add listener to get notified when dev server exists
30
+ * with an error
31
+ */
10
32
  onError(callback: (error: any) => any): this;
33
+ /**
34
+ * Close watchers and running child processes
35
+ */
36
+ close(): Promise<void>;
37
+ /**
38
+ * Start the development server
39
+ */
11
40
  start(): Promise<void>;
41
+ /**
42
+ * Start the development server in watch mode
43
+ */
12
44
  startAndWatch(ts: typeof tsStatic, options?: {
13
45
  poll: boolean;
14
46
  }): Promise<void>;