@akala/pm 14.4.42 → 14.5.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.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "pm": "dist/esm/cli.js",
5
5
  "pm-fork": "dist/esm/fork.js"
6
6
  },
7
- "version": "14.4.42",
7
+ "version": "14.5.1",
8
8
  "scripts": {
9
9
  "test": "echo 1",
10
10
  "generate": "ac generate dist/esm/commands commands.json --name pm && ac generate dist/esm/cli-commands cli-commands.json --name pm",
@@ -29,9 +29,9 @@
29
29
  "src/fork.ts"
30
30
  ],
31
31
  "dependencies": {
32
- "@akala/cli": "^5.5.32",
33
- "@akala/commands": "^13.0.2",
34
- "@akala/config": "^6.0.56",
32
+ "@akala/cli": "^5.6.0",
33
+ "@akala/commands": "^13.0.4",
34
+ "@akala/config": "^6.0.58",
35
35
  "@akala/core": "^39.0.0",
36
36
  "@akala/json-rpc-ws": "^11.0.75",
37
37
  "reflect-metadata": "^0.2.2",
package/src/akala.mts CHANGED
@@ -1,15 +1,16 @@
1
1
  import * as path from 'path'
2
- import { Processors, Metadata, Container, ICommandProcessor, Triggers, Cli, connect } from '@akala/commands';
2
+ import { Processors, Metadata, Container, ICommandProcessor, Triggers, Cli, connect, registerCommands } from '@akala/commands';
3
3
  import { platform, homedir } from 'os';
4
- import start from './commands/start.js'
5
4
  import { Readable } from 'stream';
6
5
 
7
6
  import { spawnAsync } from '@akala/cli/cli-helper';
8
- import State, { StateConfiguration } from './state.js';
7
+ import { StateConfiguration } from './state.js';
9
8
  import { CliContext, ErrorMessage, InteractError, NamespaceMiddleware, unparse } from '@akala/cli';
10
9
  import { eachAsync, logger, LogLevels, NotHandled, ObservableObject, Parser } from '@akala/core';
11
10
  import module from 'module'
12
11
  import commands from './container.js';
12
+ import cliCommands from './cli-container.js';
13
+ import Configuration from '@akala/config';
13
14
 
14
15
  const log = logger('akala:pm');
15
16
 
@@ -37,23 +38,26 @@ const truncate = '…';
37
38
  type CliOptions = { output: string, verbose: number, pmSock: string | number, tls: boolean, help: boolean };
38
39
  export default async function (_config, program: NamespaceMiddleware<{ configFile: string, verbose: number }>)
39
40
  {
41
+
42
+
40
43
  const cli = program.command('pm').state<{ pm?: StateConfiguration }>().options<CliOptions>({
41
44
  output: { aliases: ['o'], needsValue: true, doc: 'output as `table` if array otherwise falls back to standard node output' },
42
45
  verbose: { aliases: ['v'] }, tls: { doc: "enables tls connection to the `pmSock`" },
43
46
  pmSock: { aliases: ['pm-sock'], needsValue: true, doc: "path to the unix socket or destination in the form host:port" },
44
47
  help: { doc: "displays this help message" }
45
48
  });
46
- cli.command('start pm')
47
- .option<boolean>()('inspect', { doc: "starts the process with --inspect-brk parameter to help debugging" })
48
- .option<boolean>()('keepAttached', { doc: "keeps the process attached" })
49
- .action(c =>
50
- {
51
- c.options.configFile += '#pm';
52
- return start.call({ config: c.state.pm } as unknown as State, null, 'pm', { name: 'pm', ...c.options }, c);
53
- });
54
49
 
55
- const metaContainer = commands.meta;
50
+ const pm = new Container('pm-cli', {});
51
+
52
+ const fs = new Processors.FileSystem();
53
+
54
+ registerCommands(cliCommands.meta.commands, fs, pm);
55
+
56
+ await pm.attach(Triggers.cli, cli);
57
+
56
58
  let container: Container<unknown>;
59
+ const metaContainer = commands.meta;
60
+
57
61
  cli.preAction(async c =>
58
62
  {
59
63
  process.stdin.pause();
@@ -73,8 +77,12 @@ export default async function (_config, program: NamespaceMiddleware<{ configFil
73
77
  container = await connect(new URL('jsonrpc+unix://\\\\?\\pipe\\pm'), c.abort.signal, metaContainer);
74
78
  else
75
79
  {
76
- if (c.state?.pm?.mapping.pm?.connect)
77
- await eachAsync(c.state.pm.mapping.pm.connect, async (config, connectionString) =>
80
+ let connectMapping = c.state?.pm?.mapping.pm?.connect;
81
+ if (connectMapping)
82
+ if (connectMapping instanceof Configuration)
83
+ connectMapping = connectMapping.extract();
84
+ if (connectMapping)
85
+ await eachAsync(connectMapping, async (config, connectionString) =>
78
86
  {
79
87
  if (container)
80
88
  return;
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://raw.githubusercontent.com/npenin/akala/main/packages/commands/command-schema.json",
3
3
  "cli": {
4
4
  "inject": [
5
- "options.pmSock"
5
+ "context"
6
6
  ],
7
7
  "options": {
8
8
  "pmSock": {
@@ -13,4 +13,4 @@
13
13
  }
14
14
  }
15
15
  }
16
- }
16
+ }
@@ -4,7 +4,8 @@ import { connect, Container } from "@akala/commands";
4
4
  import { platform } from "os";
5
5
  import { Triggers } from "@akala/commands";
6
6
  import { ProxyConfiguration } from "@akala/config";
7
- import { ErrorWithStatus, HttpStatusCode } from "@akala/core";
7
+ import { eachAsync } from "@akala/core";
8
+ import commands from "../container.js";
8
9
 
9
10
  type CliOptions = { pmSock: string | number, tls: boolean };
10
11
 
@@ -25,13 +26,34 @@ export default async function (c: CliContext<CliOptions, ProxyConfiguration<{ pm
25
26
  container = await connect('unix://\\\\?\\pipe\\pm', c.abort.signal)
26
27
  else
27
28
  {
28
- const connectOptions = c.state?.pm?.mapping?.pm?.connect?.extract();
29
- if (connectOptions)
30
- container = await connect(Object.keys(connectOptions)[0], c.abort.signal);
29
+ const connectMapping = c.state?.pm?.mapping.pm?.connect;
30
+ await eachAsync(connectMapping.extract(), async (config, connectionString) =>
31
+ {
32
+ if (container)
33
+ return;
34
+ try
35
+ {
36
+ c.logger.verbose('trying to connect to ' + connectionString);
37
+ const url = new URL(connectionString);
38
+ if (url.hostname == '0.0.0.0')
39
+ url.hostname = 'localhost';
40
+ container = await connect(url, c.abort.signal, commands.meta);
41
+ }
42
+ catch (e)
43
+ {
44
+ c.logger.silly('failed to connect to ' + connectionString);
45
+ c.logger.silly(e)
46
+ if (e.code == 'ENOENT' || e.code == 'ECONNREFUSED')
47
+ return;
48
+ c.logger.error(e);
49
+ throw e;
50
+ }
51
+
52
+ })
31
53
  }
32
54
 
33
- if (!container)
34
- throw new ErrorWithStatus(HttpStatusCode.BadGateway, 'no connection option specified');
55
+ if (container)
56
+ await container.attach(Triggers.cli, program.command('pm'));
57
+ // throw new ErrorWithStatus(HttpStatusCode.BadGateway, 'no connection option specified');
35
58
 
36
- await container.attach(Triggers.cli, program.command('pm'));
37
- }
59
+ }
@@ -2,7 +2,6 @@
2
2
  "$schema": "https://raw.githubusercontent.com/npenin/akala/main/packages/commands/command-schema.json",
3
3
  "": {
4
4
  "inject": [
5
- "$container",
6
5
  "param.0",
7
6
  "param.1"
8
7
  ]
@@ -34,6 +33,13 @@
34
33
  "help": {
35
34
  "doc": "displays this help message"
36
35
  },
36
+ "keepAttached": {
37
+ "aliases": [
38
+ "keep-attached"
39
+ ],
40
+ "needsValue": false,
41
+ "doc": "keeps the process attached to the current terminal"
42
+ },
37
43
  "wait": {
38
44
  "aliases": [
39
45
  "w"
@@ -57,10 +63,9 @@
57
63
  }
58
64
  },
59
65
  "inject": [
60
- "$container",
61
66
  "options.program",
62
67
  "context"
63
68
  ],
64
69
  "usage": "start pm"
65
70
  }
66
- }
71
+ }
@@ -1,51 +1,19 @@
1
- import { Container } from "@akala/commands";
2
1
  import State, { } from '../state.js';
3
- import { spawn, ChildProcess, StdioOptions } from "child_process";
4
- import pmContainer from '../container.js';
2
+ import { StdioOptions } from "child_process";
5
3
  import { CliContext, unparseOptions } from "@akala/cli";
6
- import { ErrorWithStatus } from "@akala/core";
7
- import getRandomName from "../commands/name.js";
8
- import path from 'path'
9
- import { fileURLToPath } from 'url'
4
+ import ChildProcess from '../runtimes/child_process.js'
10
5
 
11
- //eslint-disable-next-line @typescript-eslint/ban-ts-comment
12
- //@ts-ignore
13
- const _dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url))
14
-
15
- export default async function start(this: State, pm: pmContainer.container & Container<State>, name: string, context?: CliContext<{ new?: boolean, name: string, keepAttached?: boolean, inspect?: boolean, verbose?: number, wait?: boolean }>): Promise<void | { execPath: string, args: string[], cwd: string, stdio: StdioOptions, shell: boolean, windowsHide: boolean }>
6
+ export default async function start(this: State, name: string, context?: CliContext<{ configFile: string, new?: boolean, name: string, keepAttached?: boolean, inspect?: boolean, verbose?: number, wait?: boolean }>): Promise<void | { execPath: string, args: string[], cwd: string, stdio: StdioOptions, shell: boolean, windowsHide: boolean }>
16
7
  {
17
- let args: string[];
18
-
19
- if (!context.options.name && context.options.new)
20
- context.options.name = getRandomName();
21
- else if (!context.options.name)
22
- context.options.name = name;
23
-
24
- if (this.isDaemon)
25
- throw new ErrorWithStatus(40, 'pm is already running');
26
- else
27
- {
28
- if (name != 'pm')
29
- throw new ErrorWithStatus(40, 'this command needs to run through daemon process');
30
-
31
- args = [...context.args, ...unparseOptions({ ...context.options, inspect: undefined })];
32
- }
33
-
34
- args.unshift(path.resolve(_dirname, '../fork.js'))
35
-
36
- if (context.options && context.options.inspect)
37
- args.unshift('--inspect-brk');
38
-
39
- args.unshift(...process.execArgv);
40
-
41
- if (context.options && context.options.verbose)
42
- args.push('-v')
43
-
44
- let cp: ChildProcess;
45
- if (context.options.keepAttached)
46
- cp = spawn(process.execPath, args, { cwd: process.cwd(), stdio: ['inherit', 'inherit', 'inherit', 'ipc'] });
47
- else
48
- cp = spawn(process.execPath, args, { cwd: process.cwd(), detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
8
+ const args = [...context.args, ...unparseOptions({
9
+ ...context.options,
10
+ configFile: context.options.configFile + '#pm',
11
+ name: 'pm',
12
+ program: new URL('../../../commands.json', import.meta.url).toString(),
13
+ inspect: undefined, new: undefined, wait: undefined
14
+ })];
15
+
16
+ const cp = ChildProcess.build(args, { ...context.options, inheritStdio: context.options.keepAttached }, context.abort.signal);
49
17
  cp.on('exit', function (...args: unknown[])
50
18
  {
51
19
  console.log(args);
@@ -53,8 +21,8 @@ export default async function start(this: State, pm: pmContainer.container & Con
53
21
  cp.on('message', function (message)
54
22
  {
55
23
  console.log(message);
56
- // cp.disconnect();
57
24
  });
25
+
58
26
  return new Promise<void>((resolve) =>
59
27
  {
60
28
  cp.on('disconnect', function ()
@@ -66,7 +34,7 @@ export default async function start(this: State, pm: pmContainer.container & Con
66
34
  }
67
35
  resolve();
68
36
  })
69
- })
37
+ });
70
38
  }
71
39
 
72
40
  start.$inject = ['$container', 'param.0', 'options']
package/src/cli.ts CHANGED
@@ -41,7 +41,7 @@ cli.command('start pm')
41
41
  c.options['name'] = 'pm'
42
42
  c.options['program'] = new URL('../../commands.json', import.meta.url).toString();
43
43
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
- return start.call({} as unknown as State, null, 'pm', c as any);
44
+ return start.call({} as unknown as State, null, c as any);
45
45
  });
46
46
 
47
47
  let socket: Socket;
@@ -23,8 +23,19 @@
23
23
  ]
24
24
  },
25
25
  "keepAttached": {
26
- "needsValue": true
26
+ "aliases": [
27
+ "keep-attached"
28
+ ],
29
+ "needsValue": false,
30
+ "doc": "keeps the process attached to the current terminal"
31
+ },
32
+ "wait": {
33
+ "aliases": [
34
+ "w"
35
+ ],
36
+ "needsValue": false,
37
+ "doc": "waits for the program to be started before returning, otherwise, returns after the start command is sent to the pm daemon"
27
38
  }
28
39
  }
29
40
  }
30
- }
41
+ }
@@ -150,8 +150,13 @@ export default async function (this: State, container: RunningContainer & pmCont
150
150
  if (!context.options.keepAttached)
151
151
  {
152
152
  if (process.send)
153
- process.send('disconnecting daemon');
153
+ await new Promise<void>((resolve, reject) => process.send('disconnecting daemon', err => err ? reject(err) : resolve()));
154
154
  process.disconnect();
155
155
  }
156
156
  }
157
+
158
+ context.abort.signal.addEventListener('abort', async () =>
159
+ {
160
+ await container.dispatch('stop', { param: ['pm'] });
161
+ });
157
162
  }
@@ -69,12 +69,6 @@ export default async function start(this: State, pm: pmContainer.container & Con
69
69
  args = [new URL('../../../commands.json', import.meta.url).toString(), ...(context?.args || []), ...unparseOptions({ ...options, inspect: undefined })];
70
70
  }
71
71
 
72
- if (!def?.type || def.type == 'nodejs')
73
- {
74
-
75
- args.unshift(path.resolve(_dirname, '../fork.js'))
76
- }
77
-
78
72
  if (options?.inspect)
79
73
  args.unshift('--inspect-brk');
80
74
 
package/src/fork.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import sms from 'source-map-support'
3
3
  sms.install();
4
- import * as path from 'path'
4
+ import path from 'path'
5
5
  import { lstat } from 'fs/promises';
6
6
  import pmDef from './container.js';
7
7
  import { IpcAdapter } from "./ipc-adapter.js";
@@ -23,14 +23,15 @@ let log: Logger;
23
23
  const logMiddleware = new NamespaceMiddleware<{ program: string, name: string, tls: boolean }>(null).option<string>()('verbose', { aliases: ['v',] });
24
24
  logMiddleware.preAction(async c =>
25
25
  {
26
+ const fs: Processors.FileSystem = new Processors.FileSystem(path.dirname(c.options.program));
26
27
  if (c.options.verbose)
27
- processor = new Processors.LogProcessor((_c, cmd, params) =>
28
+ processor = new Processors.LogEventProcessor(fs, c.abort.signal, (_c, cmd, params) =>
28
29
  {
29
30
  log.verbose({ cmd, params });
30
- return undefined;
31
31
  });
32
32
 
33
- await Processors.FileSystem.discoverCommands(c.options.program, cliContainer, { processor: processor, isDirectory: folderOrFile.isDirectory() });
33
+ const options: Processors.DiscoveryOptions = { processor: processor, isDirectory: folderOrFile.isDirectory() };
34
+ await Processors.FileSystem.discoverCommands(c.options.program, cliContainer, options);
34
35
  });
35
36
  let initMiddleware = new NamespaceMiddleware<{ program: string, name: string, tls: boolean }>(null);
36
37
  const controller = new AbortController();
@@ -39,6 +40,7 @@ program.option<string>()('program', { needsValue: true, normalize: true, positio
39
40
  option<string>()('name', { needsValue: true, positional: true, position: 1, optional: true }).
40
41
  option<boolean>()('tls', { needsValue: false }).
41
42
  option<string>()('configFile', { needsValue: false }).
43
+ option<number>()('verbose', { aliases: ['v'], needsValue: false }).
42
44
  options<{
43
45
  port?: number,
44
46
  tcpPort?: string,
@@ -175,7 +177,9 @@ program.option<string>()('program', { needsValue: true, normalize: true, positio
175
177
  const serveArgs = await pm.dispatch('connect', c.options.name);
176
178
  // console.log(serveArgs)
177
179
  // serveArgs.signal = controller.signal;
178
- await cliContainer.dispatch('$serve', serveArgs, controller.signal);
180
+ if (!serveArgs && (!('socketName' in c.options) || !c.options.socketName))
181
+ c.options['socketName'] = c.options.name;
182
+ await cliContainer.dispatch('$serve', serveArgs || c, controller.signal);
179
183
  }
180
184
  catch (e)
181
185
  {
@@ -22,10 +22,10 @@ export default class Runtime extends EventEmitter<ChildProcessRuntimeEventMap> i
22
22
  {
23
23
  private readonly cp: ChildProcess;
24
24
  public readonly adapter: IpcAdapter;
25
- constructor(args: string[], options: ChildProcessRuntimeOptions)
25
+ constructor(args: string[], options: ChildProcessRuntimeOptions, signal?: AbortSignal)
26
26
  {
27
27
  super();
28
- args.unshift(fileURLToPath(new URL('../fork', import.meta.url)));
28
+ args.unshift(fileURLToPath(new URL('../fork.js', import.meta.url)));
29
29
  if (options.inspect)
30
30
  args.unshift("--inspect-brk");
31
31
  this.cp = spawn(process.execPath, args, { cwd: process.cwd(), detached: !options.keepAttached, env: Object.assign({ DEBUG_COLORS: process.stdout.isTTY }, process.env), stdio: ['ignore', options.inheritStdio ? 'inherit' : 'pipe', options.inheritStdio ? 'inherit' : 'pipe', 'ipc'], shell: false, windowsHide: true });
@@ -36,15 +36,22 @@ export default class Runtime extends EventEmitter<ChildProcessRuntimeEventMap> i
36
36
  }
37
37
  this.adapter = new IpcAdapter(this.cp);
38
38
  this.cp.on('close', (code, signal) => { this.emit('close', code, signal); this.emit('exit') });
39
+ this.cp.on('message', (message, sendHandle) => this.emit('message', message, sendHandle));
39
40
 
41
+ this.cp.on('disconnect', () => { this.emit('disconnect'); });
40
42
  if (options.keepAttached)
41
- this.cp.on('disconnect', () => this.emit('exit'));
43
+ this.cp.on('disconnect', () => { this.emit('exit') });
44
+
45
+ signal?.addEventListener('abort', () =>
46
+ {
47
+ return this.stop(5000);
48
+ })
42
49
  }
43
50
  stop(timeoutInMs?: number): Promise<number>
44
51
  {
45
52
  return new Promise((resolve) =>
46
53
  {
47
- this.cp.on('exit', (code, signal) =>
54
+ this.cp.on('exit', (code) =>
48
55
  {
49
56
  clearTimeout(timeout);
50
57
  resolve(code);
@@ -54,9 +61,11 @@ export default class Runtime extends EventEmitter<ChildProcessRuntimeEventMap> i
54
61
  })
55
62
  }
56
63
 
57
- public static build(args: string[], options: ChildProcessRuntimeOptions)
64
+ public static build(args: string[], options: ChildProcessRuntimeOptions, signal?: AbortSignal)
58
65
  {
59
- return new Runtime(args, options) as Runtime & RuntimeInstance;
66
+ return new Runtime(args, options, signal) as Runtime & RuntimeInstance;
67
+
68
+
60
69
  }
61
70
 
62
71
  public unref()