@akala/pm 14.5.8 → 14.6.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/src/fork.ts CHANGED
@@ -1,208 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import sms from 'source-map-support'
3
- sms.install();
4
- import path from 'path'
5
- import pmDef from './container.js';
6
- import { IpcAdapter } from "./ipc-adapter.js";
7
- import { logger, Logger, module as coreModule, MiddlewareCompositeAsync } from '@akala/core';
8
- import { program, buildCliContextFromProcess, ErrorMessage, NamespaceMiddleware } from '@akala/cli';
9
- import { Processors, Triggers, ServeMetadata, Cli, registerCommands, SelfDefinedCommand, StructuredParameters, Container, CommandProcessor, serveMetadata, connectByPreference, Metadata, $metadata } from '@akala/commands';
10
- import { pathToFileURL } from 'url';
11
- import commands from './container.js';
12
- import Configuration from '@akala/config';
13
- import fsHandler, { Stats } from '@akala/fs';
2
+ import program, { buildCliContextFromProcess } from '@akala/cli';
14
3
 
15
- var isPm = false;
4
+ process.setSourceMapsEnabled(true);
16
5
 
17
- program.option('help')
18
- let folderOrFile: Stats;
19
- let cliContainer: Container<unknown>;
20
- let processor: CommandProcessor;
21
- let log: Logger;
22
- const logMiddleware = new NamespaceMiddleware<{ program: string, name: string, tls: boolean }>(null).option<string>()('verbose', { aliases: ['v',] });
23
- logMiddleware.preAction(async c =>
24
- {
25
- const fs: Processors.FileSystem = new Processors.FileSystem(new URL('./', c.options.program));
26
- if (c.options.verbose)
27
- processor = new Processors.LogEventProcessor(fs, c.abort.signal, (_c, cmd, params) =>
28
- {
29
- log.verbose({ cmd, params });
30
- });
31
-
32
- const options: Processors.DiscoveryOptions = { processor: processor, isDirectory: folderOrFile.isDirectory };
33
- await Processors.FileSystem.discoverCommands(c.options.program, cliContainer, options);
34
- });
35
- let initMiddleware = new NamespaceMiddleware<{ program: string, name: string, tls: boolean }>(null);
36
- const controller = new AbortController();
37
-
38
- program.option<string>()('program', { needsValue: true, normalize: true, positional: true, position: 0 }).
39
- option<string>()('name', { needsValue: true, positional: true, position: 1, optional: true }).
40
- option<boolean>()('tls', { needsValue: false }).
41
- option<string>()('configFile', { needsValue: false }).
42
- option<number>()('verbose', { aliases: ['v'], needsValue: false }).
43
- options<{
44
- port?: number,
45
- tcpPort?: string,
46
- cert?: string,
47
- key?: string,
48
- }>({
49
- port: { needsValue: true, doc: 'http/ws port\n(default: 80 if http, 443 is certificate and key are provided)', aliases: ['p'], optional: true, caseSensitive: false },
50
- tcpPort: { needsValue: true, doc: 'tcp port', aliases: ['tcp-port'], optional: true, caseSensitive: false },
51
- cert: { needsValue: true, doc: 'public certificate', aliases: ['certificate'], optional: true, caseSensitive: false },
52
- key: { needsValue: true, doc: 'private certificate key. Requires public certificate', aliases: ['certificate-key'], optional: true, caseSensitive: false }
53
- }).
54
- preAction(async c => //If pure js file
55
- {
56
- if (!URL.canParse(c.options.program))
57
- c.options.program = pathToFileURL(c.options.program).toString();
58
- const fs = await fsHandler.process(new URL('./', c.options.program));
59
- folderOrFile = await fs.stat(c.options.program);
60
- if (folderOrFile.isFile && path.extname(c.options.program) === '.js')
61
- return import(c.options.program);
62
-
63
- log = logger(c.options.name);
64
-
65
- if (c.options.configFile)
66
- c.state = await Configuration.load(c.options.configFile)
67
-
68
- cliContainer = new Container('cli', {});
69
-
70
- if (folderOrFile.isFile)
71
- processor = new Processors.FileSystem(new URL('./', c.options.program));
72
- else
73
- processor = new Processors.FileSystem(new URL(c.options.program));
74
- }).
75
- useMiddleware(null, MiddlewareCompositeAsync.new(logMiddleware,
76
- {
77
- handle: async c =>
78
- {
79
- cliContainer.name = c.options.name;
80
- isPm = c.options.name === 'pm' && c.options.program === new URL('../../commands.json', import.meta.url).toString();
81
- const init = cliContainer.resolve('$init');
82
- if (init && init.config && init.config.cli && init.config.cli.options)
83
- {
84
- if (init.config.cli.usage)
85
- {
86
- initMiddleware = initMiddleware.command(init.config.cli.usage, init.config?.doc?.description)
87
- c.args.unshift('$init');
88
- }
89
- Triggers.addCliOptions(init, initMiddleware);
90
- }
91
-
92
- process.on('unhandledRejection', (x) =>
93
- {
94
- controller.abort(x)
95
- return false;
96
- });
97
- process.on('uncaughtException', (x) =>
98
- {
99
- controller.abort(x)
100
- return false;
101
- });
102
- process.on('SIGINT', () => controller.abort(null));
6
+ import { cli } from '@akala/cli/cli'
7
+ import { logger, LogLevels } from '@akala/core';
103
8
 
104
- initMiddleware.option<string>()('pmSocket', { aliases: ['pm-socket', 'pm-sock'], needsValue: true }).action(async c =>
105
- {
106
- let pm: Container<unknown> & pmDef.container;
107
- let pmConnectInfo: ServeMetadata;
9
+ const context = buildCliContextFromProcess(logger('akala', LogLevels.help), { plugins: [] });
10
+ cli();
108
11
 
109
- if (!isPm)
110
- {
111
- //eslint-disable-next-line @typescript-eslint/no-var-requires
112
- const pmMeta = commands.meta;
113
- if (process.connected)
114
- {
115
- pm = new Container('pm', null, new Processors.JsonRpc(Processors.JsonRpc.getConnection(new IpcAdapter(process), cliContainer))) as Container<unknown> & pmDef.container;
116
- registerCommands(pmMeta.commands, null, pm);
117
- }
118
- else
119
- {
120
- if (c.options.pmSocket)
121
- pmConnectInfo = { [c.options.pmSocket]: {} };
122
- else
123
- pmConnectInfo = serveMetadata({ args: ['local'], options: { socketName: 'pm' } })
124
- const x = await connectByPreference(pmConnectInfo, { metadata: pmMeta, signal: controller.signal, container: cliContainer });
125
- // controller.signal.addEventListener('abort', () => x.processor)
126
- pm = x.container as Container<unknown> & pmDef.container;
127
- pm.processor.useMiddleware(20, x.processor);
128
- const connect = pm.resolve('connect');
129
- pm.unregister('connect');
130
- pm.register(new SelfDefinedCommand((name: string, param: StructuredParameters<unknown[]>) =>
131
- {
132
- if (name == 'pm')
133
- return pmConnectInfo;
134
- return x.processor.handle(pm, connect, param).then(e => { throw e }, r => r);
135
- }, 'connect', [
136
- "param.0",
137
- "$param"
138
- ]));
139
- }
140
- // eslint-disable-next-line @typescript-eslint/no-var-requires
141
- pm.unregister(Cli.Metadata.name);
142
- pm.register(Metadata.extractCommandMetadata(Cli.Metadata));
143
- }
144
- else
145
- pm = cliContainer as pmDef.container & Container<unknown>;
146
-
147
- coreModule('@akala/pm').register('container', pm);
148
-
149
- cliContainer.register(new SelfDefinedCommand(async (connectionId: string) =>
150
- {
151
- if (!pmConnectInfo)
152
- pmConnectInfo = await pm.dispatch('connect', 'pm');
153
- var pm2 = await connectByPreference(pmConnectInfo, { metadata: await cliContainer.dispatch('$metadata'), container: cliContainer });
154
- pm2.container.processor.useMiddleware(20, pm2.processor);
155
- pm2.container.unregister($metadata.name);
156
- pm2.container.register($metadata);
157
- pm2.container.register(Metadata.extractCommandMetadata(pm.resolve('bridge')));
158
- if (!await pm2.container.dispatch('bridge', connectionId))
159
- throw new Error('connection could not be established');
160
- }, '$bridge', ['param.0']));
161
-
162
- if (init)
163
- {
164
- await cliContainer.dispatch(init, { options: c.options, param: c.args, _trigger: 'cli', pm: pm, context: c, signal: controller.signal });
165
- }
166
-
167
-
168
- try
169
- {
170
- const serveArgs = await pm.dispatch('connect', c.options.name);
171
- // console.log(serveArgs)
172
- // serveArgs.signal = controller.signal;
173
- if (!serveArgs && (!('socketName' in c.options) || !c.options.socketName))
174
- c.options['socketName'] = c.options.name;
175
- await cliContainer.dispatch('$serve', serveArgs || c, controller.signal);
176
- }
177
- catch (e)
178
- {
179
- if (!e || e.statusCode !== 404)
180
- throw e;
181
- console.warn(e.message);
182
- }
183
-
184
- if (pm !== cliContainer)
185
- await pm.dispatch('ready')
186
- });
187
-
188
- return undefined;
189
- }
190
- },
191
- initMiddleware));
192
-
193
- controller.signal.addEventListener('abort', function ()
194
- {
195
- if (this.reason)
196
- {
197
- process.exitCode = 1;
198
- if (this.reason instanceof ErrorMessage)
199
- console.error(this.reason.message);
200
- else
201
- console.error(this.reason);
202
- }
203
- })
12
+ process.on('SIGINT', () => context.abort.abort('SIGINT'));
13
+ process.on('SIGTERM', () => context.abort.abort('SIGTERM'));
204
14
 
205
- program.process(buildCliContextFromProcess()).catch(e =>
15
+ program.process(context).catch(e =>
206
16
  {
207
- setImmediate(() => controller.abort(e));
17
+ setImmediate(() => context.abort.abort(e));
208
18
  });
@@ -25,7 +25,7 @@ export default class Runtime extends EventEmitter<ChildProcessRuntimeEventMap> i
25
25
  constructor(args: string[], options: ChildProcessRuntimeOptions, signal?: AbortSignal)
26
26
  {
27
27
  super();
28
- args.unshift(fileURLToPath(new URL('../fork.js', import.meta.url)));
28
+ args.unshift(fileURLToPath(new URL('../fork.js', import.meta.url)), 'pm', 'run');
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 });