@wtf/platform 1.0.0 → 2.1.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 CHANGED
@@ -29,7 +29,8 @@ from `@wtf/platform-browser`, one in memory from `@wtf/platform-memory`, and a t
29
29
  | `./dirs` | `Dirs`, `PlatformFacts` (`cwd` too), `AppDirs` | `dirsOf({ facts, env })`; `testDirs(facts)` |
30
30
  | `./terminal` | `Terminal` | `colorDepthOf(stream, env)`; `testTerminal({ input })` |
31
31
  | `./open` | `Open` | `printOpen({ console })`; `memoryOpen()` |
32
- | `./process` | `Spawn`, `ChildProcess`, `ProcessStatus`, `SpawnOptions` | `exec(spawn, command, args, { cwd, env, input, signal })` |
32
+ | `./module` | `LoadModule` | types only |
33
+ | `./process` | `Spawn`, `ChildProcess`, `ProcessStatus`, `ProcessSignal`, … | `exec(spawn, command, args, { cwd, env, input, signal })` |
33
34
  | `./runtime` | `Program`, `Interrupts`, `Exit`, `ExitCode` | `runMain(program, { platform, interrupts, exit })`; `manualInterrupts()` |
34
35
  | `./errors` | `PlatformError` | `BadArgument`, `SystemError` with a `reason`, `isPlatformError` |
35
36
  | `./test` | `TestPlatform`, `TestPlatformOptions` | `testPlatform({ directory, ...members })`, every double |
@@ -71,7 +72,8 @@ No web standard starts a process, so `./process` builds one from standard parts,
71
72
  `Command` does. A `Spawn` starts a command with its arguments, with no shell, and gives you a
72
73
  `ChildProcess`: its `stdin` is a `WritableStream` of bytes, its `stdout` and `stderr` are
73
74
  `ReadableStream`s of bytes, and its `status` is a promise of how it ended, `{ code, signal? }`. An
74
- `AbortSignal` you pass ends it. `exec` runs one to its end and gives you its output as text:
75
+ `AbortSignal` you pass ends it with `SIGTERM`, and `kill(signal)` sends it a signal, as Deno's
76
+ `ChildProcess` does. `exec` runs one to its end and gives you its output as text:
75
77
 
76
78
  ```ts
77
79
  import type { ProcessPlatform } from '@wtf/platform'
@@ -90,9 +92,29 @@ const head = async (platform: Pick<ProcessPlatform, 'spawn' | 'dirs'>) => {
90
92
  process gets the `env` you give it, whole, or else the platform's, and works in the `cwd` you give
91
93
  it, or else the platform's working folder. A command that is not there rejects its `status`, and
92
94
  `exec`, with a `SystemError` whose `reason` is `NotFound`. A non-zero exit code is not an error:
93
- `exec` gives it to you to decide. A platform's own `spawn` builds on `signalled(signal)`, the status
94
- of a process a signal ended, and `notStarted(command, reason)`, the error of one that could not
95
- start.
95
+ `exec` gives it to you to decide. `spawn` itself never throws: a process that could not start, for
96
+ any reason, rejects its `status`. Its `stdin` takes bytes alone: a chunk that is no `Uint8Array`
97
+ rejects with a `TypeError`, and the process sees its input end.
98
+
99
+ A process may catch or ignore `SIGTERM`. To be sure it ends, send it `SIGKILL` after a grace of
100
+ your own, by the platform's timers:
101
+
102
+ ```ts
103
+ import type { ProcessPlatform } from '@wtf/platform'
104
+
105
+ declare const platform: ProcessPlatform
106
+
107
+ const child = platform.spawn('server', [])
108
+ // …
109
+ const grace = platform.setTimeout(() => child.kill('SIGKILL'), 2000)
110
+ child.kill() // SIGTERM
111
+ const { code, signal } = await child.status.finally(() => platform.clearTimeout(grace))
112
+ ```
113
+
114
+ `kill` sends nothing to a process that has ended, and throws a `BadArgument` of a name that is no
115
+ `ProcessSignal`. A platform's own `spawn` builds on `signalled(signal)`, the status of a process a
116
+ signal ended, `sendable(signal)`, the signal a `kill` sends, checked, and
117
+ `notStarted(command, reason)`, the error of one that could not start.
96
118
 
97
119
  ## The file system
98
120
 
@@ -100,11 +122,11 @@ start.
100
122
  `FileSystemDirectoryHandle` typed by `./fs`, the File System Standard's types. That is a page's
101
123
  origin private file system, the folder Node's entry point passes in, or the folder a test gives
102
124
  `testPlatform({ directory })`. To reach a path, resolve it against `dirs.cwd` with `path`, and
103
- walk down from the root, one folder at a time. Without a `directory`, `testPlatform()` has no file
125
+ walk down from the root, as `at` from `@wtf/platform-fs/path` does. Without a `directory`, `testPlatform()` has no file
104
126
  system: `getDirectory()` rejects with a `SecurityError`, as the Storage Standard says a page
105
127
  without storage does.
106
128
 
107
129
  The types follow a web standard where one exists, and are defined here otherwise. The doubles are
108
130
  real exports. The only dependency is `@standard-schema/spec`, for the types of `parse`. The file
109
131
  system types are this package's own, in `./fs`, so any file system that keeps to the standard fits
110
- them, and fails with this package's `PlatformError`s.
132
+ them; `@wtf/platform-fs` builds on them, and its errors are this package's `PlatformError`s.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Loading a module a program is told of as it runs: {@link LoadModule}, what loads the module a
3
+ * name or a path names, and gives the object of its exports, as a configuration names a plugin of
4
+ * a tool. JavaScript's `import()` loads a module of a specifier, but no web standard says where a
5
+ * name is looked for, of which folder, nor what a path is relative to, so the loader is our own.
6
+ * Node's is `nodeLoadModule` of `@wtf/platform-node/module`, which looks from the root of a
7
+ * project. Types only, with no code.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ /**
12
+ * Loads the module `module` names, a path or the name of a package, as the loader that was made
13
+ * resolves it, and gives the object of its exports, as `import()` does. A module that cannot be
14
+ * found or loaded rejects: a test passes a function of its own, of the modules it means.
15
+ */
16
+ export type LoadModule = (module: string) => Promise<unknown>;
package/dist/module.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Loading a module a program is told of as it runs: {@link LoadModule}, what loads the module a
3
+ * name or a path names, and gives the object of its exports, as a configuration names a plugin of
4
+ * a tool. JavaScript's `import()` loads a module of a specifier, but no web standard says where a
5
+ * name is looked for, of which folder, nor what a path is relative to, so the loader is our own.
6
+ * Node's is `nodeLoadModule` of `@wtf/platform-node/module`, which looks from the root of a
7
+ * project. Types only, with no code.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ export {};
12
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../src/module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG","sourcesContent":["/**\n * Loading a module a program is told of as it runs: {@link LoadModule}, what loads the module a\n * name or a path names, and gives the object of its exports, as a configuration names a plugin of\n * a tool. JavaScript's `import()` loads a module of a specifier, but no web standard says where a\n * name is looked for, of which folder, nor what a path is relative to, so the loader is our own.\n * Node's is `nodeLoadModule` of `@wtf/platform-node/module`, which looks from the root of a\n * project. Types only, with no code.\n *\n * @packageDocumentation\n */\n\n/**\n * Loads the module `module` names, a path or the name of a package, as the loader that was made\n * resolves it, and gives the object of its exports, as `import()` does. A module that cannot be\n * found or loaded rejects: a test passes a function of its own, of the modules it means.\n */\nexport type LoadModule = (module: string) => Promise<unknown>\n"]}
package/dist/process.d.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * of its {@link ProcessStatus}; and {@link exec}, which runs one to its end and gives its output as
5
5
  * text. No web standard starts a process, so the shape is made of standard parts, as Deno's
6
6
  * `Command` is: a `WritableStream` of its stdin, a `ReadableStream` of each of its stdout and
7
- * stderr, and an `AbortSignal` that ends it. A platform that starts processes is a
7
+ * stderr, an `AbortSignal` that ends it, and `kill`, which sends it a signal, as Deno's
8
+ * `ChildProcess` does. A platform that starts processes is a
8
9
  * `ProcessPlatform` of the root; a browser starts none. `nodeSpawn` of
9
10
  * `@wtf/platform-node/process` starts one of Node, and `memorySpawn` of
10
11
  * `@wtf/platform-memory/process` answers each by a script, for a test or a dry run.
@@ -37,17 +38,38 @@ export type ProcessStatus = {
37
38
  readonly code: number;
38
39
  readonly signal?: string;
39
40
  };
41
+ /**
42
+ * A signal a process may be sent, by its name, as POSIX has them: `SIGTERM` asks it to end, which
43
+ * it may catch or ignore, and `SIGKILL` ends it, which it cannot.
44
+ */
45
+ export type ProcessSignal = 'SIGHUP' | 'SIGINT' | 'SIGQUIT' | 'SIGKILL' | 'SIGTERM';
40
46
  /**
41
47
  * A process started: what it reads, `stdin`, which it sees end when the stream is closed; what it
42
48
  * writes, `stdout` and `stderr`; and how it ended, `status`. Read or cancel both of its outputs,
43
- * or it may wait on a full pipe. A process that could not start ends its outputs, and rejects its
44
- * `status` with a `SystemError`, `NotFound` of a command not there.
49
+ * or it may wait on a full pipe. Its stdin takes bytes alone: a chunk that is no `Uint8Array`
50
+ * rejects its write with a `TypeError`, errors the stream, and ends the process's input. A process
51
+ * that could not start ends its outputs, and rejects its `status` with a `SystemError`, `NotFound`
52
+ * of a command not there; `spawn` itself never throws.
45
53
  */
46
54
  export type ChildProcess = {
47
55
  readonly stdin: WritableStream<Uint8Array>;
48
56
  readonly stdout: ReadableStream<Uint8Array>;
49
57
  readonly stderr: ReadableStream<Uint8Array>;
50
58
  readonly status: Promise<ProcessStatus>;
59
+ /**
60
+ * Sends the process `signal`, `SIGTERM` by default, as `kill()` of Deno's `ChildProcess` does,
61
+ * and its `status` says the signal that ended it. A process that has ended, or never started,
62
+ * is sent nothing. A name of no {@link ProcessSignal} throws a `BadArgument`. So a caller ends a
63
+ * process that ignores `SIGTERM` by `SIGKILL`, after a grace of its own timers:
64
+ *
65
+ * ```ts
66
+ * const child = platform.spawn('server', [])
67
+ * const grace = platform.setTimeout(() => child.kill('SIGKILL'), 2000)
68
+ * child.kill()
69
+ * await child.status.finally(() => platform.clearTimeout(grace))
70
+ * ```
71
+ */
72
+ kill(signal?: ProcessSignal): void;
51
73
  };
52
74
  /**
53
75
  * Starts `command` with its arguments `args`, each given to it as it is, with no shell between: a
@@ -78,6 +100,11 @@ export type ExecResult = {
78
100
  * ```
79
101
  */
80
102
  export declare const exec: (spawn: Spawn, command: string, args: readonly string[], { input, ...options }?: ExecOptions) => Promise<ExecResult>;
103
+ /**
104
+ * The signal `signal`, as a `kill` of a {@link ChildProcess} sends it: a name of no
105
+ * {@link ProcessSignal} is a `BadArgument`.
106
+ */
107
+ export declare const sendable: (signal: unknown) => ProcessSignal;
81
108
  /**
82
109
  * The status of a process a signal ended, its code 128 and the signal's number, as a shell gives
83
110
  * it: `SIGTERM` by default, as an aborted signal ends a process.
package/dist/process.js CHANGED
@@ -4,7 +4,8 @@
4
4
  * of its {@link ProcessStatus}; and {@link exec}, which runs one to its end and gives its output as
5
5
  * text. No web standard starts a process, so the shape is made of standard parts, as Deno's
6
6
  * `Command` is: a `WritableStream` of its stdin, a `ReadableStream` of each of its stdout and
7
- * stderr, and an `AbortSignal` that ends it. A platform that starts processes is a
7
+ * stderr, an `AbortSignal` that ends it, and `kill`, which sends it a signal, as Deno's
8
+ * `ChildProcess` does. A platform that starts processes is a
8
9
  * `ProcessPlatform` of the root; a browser starts none. `nodeSpawn` of
9
10
  * `@wtf/platform-node/process` starts one of Node, and `memorySpawn` of
10
11
  * `@wtf/platform-memory/process` answers each by a script, for a test or a dry run.
@@ -17,7 +18,7 @@
17
18
  *
18
19
  * @packageDocumentation
19
20
  */
20
- import { SystemError } from "./errors.js";
21
+ import { BadArgument, SystemError } from "./errors.js";
21
22
  /** The text of a stream of bytes, decoded as UTF-8, to its end. */
22
23
  const textOf = async (stream) => {
23
24
  const reader = stream.getReader();
@@ -78,6 +79,19 @@ const SIGNALS = {
78
79
  SIGKILL: 9,
79
80
  SIGTERM: 15
80
81
  };
82
+ /**
83
+ * The signal `signal`, as a `kill` of a {@link ChildProcess} sends it: a name of no
84
+ * {@link ProcessSignal} is a `BadArgument`.
85
+ */
86
+ export const sendable = (signal) => {
87
+ if (typeof signal === 'string' && Object.hasOwn(SIGNALS, signal))
88
+ return signal;
89
+ throw new BadArgument({
90
+ module: 'Process',
91
+ method: 'kill',
92
+ description: `${String(signal)} is no signal a process may be sent.`
93
+ });
94
+ };
81
95
  /**
82
96
  * The status of a process a signal ended, its code 128 and the signal's number, as a shell gives
83
97
  * it: `SIGTERM` by default, as an aborted signal ends a process.
@@ -1 +1 @@
1
- {"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAqDzC,mEAAmE;AACnE,MAAM,MAAM,GAAG,KAAK,EAAE,MAAkC,EAAmB,EAAE;IAC3E,MAAM,MAAM,GAAG,MAAM,CAAC,SAA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AAC,EAAE,KAAK,EAAE,CAAC;CAC1C,CAAC,CAAA","sourcesContent":["/**\n * Processes: {@link Spawn}, what starts a program as a process of its own, and {@link ChildProcess},\n * the process it gives, whose input and output are Web Streams of bytes and whose end is a promise\n * of its {@link ProcessStatus}; and {@link exec}, which runs one to its end and gives its output as\n * text. No web standard starts a process, so the shape is made of standard parts, as Deno's\n * `Command` is: a `WritableStream` of its stdin, a `ReadableStream` of each of its stdout and\n * stderr, and an `AbortSignal` that ends it. A platform that starts processes is a\n * `ProcessPlatform` of the root; a browser starts none. `nodeSpawn` of\n * `@wtf/platform-node/process` starts one of Node, and `memorySpawn` of\n * `@wtf/platform-memory/process` answers each by a script, for a test or a dry run.\n *\n * ```ts\n * const { stdout, code } = await exec(platform.spawn, 'git', ['rev-parse', 'HEAD'], {\n * cwd: platform.dirs.cwd\n * })\n * ```\n *\n * @packageDocumentation\n */\nimport { SystemError } from './errors.ts'\n\n/**\n * Where and how a process runs: the folder it works in, `cwd`; its whole environment, `env`, which\n * takes the place of the platform's, not added to it; and the `signal` that ends it, aborted.\n * Without `cwd`, it works in the platform's working folder; without `env`, it has the platform's\n * environment.\n */\nexport type SpawnOptions = {\n readonly cwd?: string\n readonly env?: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n}\n\n/**\n * How a process ended: its exit `code`, and the `signal` that ended it, if one did, by its name, as\n * `SIGTERM`. A process a signal ended has the code a shell gives it, 128 and the signal's number.\n */\nexport type ProcessStatus = { readonly code: number; readonly signal?: string }\n\n/**\n * A process started: what it reads, `stdin`, which it sees end when the stream is closed; what it\n * writes, `stdout` and `stderr`; and how it ended, `status`. Read or cancel both of its outputs,\n * or it may wait on a full pipe. A process that could not start ends its outputs, and rejects its\n * `status` with a `SystemError`, `NotFound` of a command not there.\n */\nexport type ChildProcess = {\n readonly stdin: WritableStream<Uint8Array>\n readonly stdout: ReadableStream<Uint8Array>\n readonly stderr: ReadableStream<Uint8Array>\n readonly status: Promise<ProcessStatus>\n}\n\n/**\n * Starts `command` with its arguments `args`, each given to it as it is, with no shell between: a\n * process of the platform, or what a double makes of it. Where no web standard defines one, the\n * shape is the platform's own.\n */\nexport type Spawn = (\n command: string,\n args: readonly string[],\n options?: SpawnOptions\n) => ChildProcess\n\n/** What {@link exec} runs a process with: the {@link SpawnOptions}, and the text of its stdin. */\nexport type ExecOptions = SpawnOptions & {\n /** What the process reads, as text or bytes, before its stdin ends: none by default. */\n readonly input?: string | Uint8Array\n}\n\n/** What a process {@link exec} ran wrote, as text, and the code it exited with. */\nexport type ExecResult = { readonly stdout: string; readonly stderr: string; readonly code: number }\n\n/** The text of a stream of bytes, decoded as UTF-8, to its end. */\nconst textOf = async (stream: ReadableStream<Uint8Array>): Promise<string> => {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let text = ''\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- a stream is read one chunk at a time\n const { done, value } = await reader.read()\n if (done) return text + decoder.decode()\n text += decoder.decode(value, { stream: true })\n }\n}\n\n/** Writes `input` to `stdin`, and closes it: what the process did not read, it ended before. */\nconst feed = async (stdin: WritableStream<Uint8Array>, input?: string | Uint8Array) => {\n const writer = stdin.getWriter()\n try {\n if (input !== undefined && input.length > 0)\n await writer.write(typeof input === 'string' ? new TextEncoder().encode(input) : input)\n await writer.close()\n } catch {\n // The process ended before it read all of its input: its status says how.\n } finally {\n writer.releaseLock()\n }\n}\n\n/**\n * Runs `command` by `spawn` to its end, as `execFile` of Node and Deno's `output()` do: writes\n * `input` to its stdin, and ends it, and gives what it wrote to its stdout and stderr, as text, and\n * the code it exited with. A process that exits with a code but 0 resolves, with its code: the\n * caller decides what a code means. One that could not start rejects with the `SystemError` of its\n * `status`; one whose `signal` is aborted is ended, and rejects with the signal's reason.\n *\n * ```ts\n * const { stdout } = await exec(platform.spawn, 'git', ['status', '--porcelain'])\n * ```\n */\nexport const exec = async (\n spawn: Spawn,\n command: string,\n args: readonly string[],\n { input, ...options }: ExecOptions = {}\n): Promise<ExecResult> => {\n const { signal } = options\n signal?.throwIfAborted()\n const child = spawn(command, args, options)\n const [stdout, stderr, status] = await Promise.all([\n textOf(child.stdout),\n textOf(child.stderr),\n child.status,\n feed(child.stdin, input)\n ])\n signal?.throwIfAborted()\n return { stdout, stderr, code: status.code }\n}\n\n/** The number of each signal a process may end by, as POSIX has them, which its code is 128 and. */\nconst SIGNALS: Readonly<Record<string, number>> = {\n SIGHUP: 1,\n SIGINT: 2,\n SIGQUIT: 3,\n SIGKILL: 9,\n SIGTERM: 15\n}\n\n/**\n * The status of a process a signal ended, its code 128 and the signal's number, as a shell gives\n * it: `SIGTERM` by default, as an aborted signal ends a process.\n */\nexport const signalled = (signal = 'SIGTERM'): ProcessStatus => ({\n code: 128 + (SIGNALS[signal] ?? 0),\n signal\n})\n\n/** The `SystemError` of a command that could not be started, by its reason. */\nexport const notStarted = (\n command: string,\n reason: 'NotFound' | 'PermissionDenied' | 'Unknown',\n cause?: unknown\n): SystemError =>\n new SystemError({\n reason,\n module: 'Process',\n method: 'spawn',\n pathOrDescriptor: command,\n description:\n reason === 'NotFound' ? `${command} is not there.` : `${command} could not be started.`,\n ...(cause === undefined ? {} : { cause })\n })\n"]}
1
+ {"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AA2EtD,mEAAmE;AACnE,MAAM,MAAM,GAAG,KAAK,EAAE,MAAkC,EAAmB,EAAE;IAC3E,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,CAAA;IACjC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;IACjC,IAAI,IAAI,GAAG,EAAE,CAAA;IACb,SAAS,CAAC;QACR,oFAAoF;QACpF,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAA;QAC3C,IAAI,IAA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AAG,OAAO,gBAAgB,CAAC,CAAC,CAAC,GAAG,OAAO,wBAAwB;IACzF,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;CAC1C,CAAC,CAAA","sourcesContent":["/**\n * Processes: {@link Spawn}, what starts a program as a process of its own, and {@link ChildProcess},\n * the process it gives, whose input and output are Web Streams of bytes and whose end is a promise\n * of its {@link ProcessStatus}; and {@link exec}, which runs one to its end and gives its output as\n * text. No web standard starts a process, so the shape is made of standard parts, as Deno's\n * `Command` is: a `WritableStream` of its stdin, a `ReadableStream` of each of its stdout and\n * stderr, an `AbortSignal` that ends it, and `kill`, which sends it a signal, as Deno's\n * `ChildProcess` does. A platform that starts processes is a\n * `ProcessPlatform` of the root; a browser starts none. `nodeSpawn` of\n * `@wtf/platform-node/process` starts one of Node, and `memorySpawn` of\n * `@wtf/platform-memory/process` answers each by a script, for a test or a dry run.\n *\n * ```ts\n * const { stdout, code } = await exec(platform.spawn, 'git', ['rev-parse', 'HEAD'], {\n * cwd: platform.dirs.cwd\n * })\n * ```\n *\n * @packageDocumentation\n */\nimport { BadArgument, SystemError } from './errors.ts'\n\n/**\n * Where and how a process runs: the folder it works in, `cwd`; its whole environment, `env`, which\n * takes the place of the platform's, not added to it; and the `signal` that ends it, aborted.\n * Without `cwd`, it works in the platform's working folder; without `env`, it has the platform's\n * environment.\n */\nexport type SpawnOptions = {\n readonly cwd?: string\n readonly env?: Readonly<Record<string, string>>\n readonly signal?: AbortSignal\n}\n\n/**\n * How a process ended: its exit `code`, and the `signal` that ended it, if one did, by its name, as\n * `SIGTERM`. A process a signal ended has the code a shell gives it, 128 and the signal's number.\n */\nexport type ProcessStatus = { readonly code: number; readonly signal?: string }\n\n/**\n * A signal a process may be sent, by its name, as POSIX has them: `SIGTERM` asks it to end, which\n * it may catch or ignore, and `SIGKILL` ends it, which it cannot.\n */\nexport type ProcessSignal = 'SIGHUP' | 'SIGINT' | 'SIGQUIT' | 'SIGKILL' | 'SIGTERM'\n\n/**\n * A process started: what it reads, `stdin`, which it sees end when the stream is closed; what it\n * writes, `stdout` and `stderr`; and how it ended, `status`. Read or cancel both of its outputs,\n * or it may wait on a full pipe. Its stdin takes bytes alone: a chunk that is no `Uint8Array`\n * rejects its write with a `TypeError`, errors the stream, and ends the process's input. A process\n * that could not start ends its outputs, and rejects its `status` with a `SystemError`, `NotFound`\n * of a command not there; `spawn` itself never throws.\n */\nexport type ChildProcess = {\n readonly stdin: WritableStream<Uint8Array>\n readonly stdout: ReadableStream<Uint8Array>\n readonly stderr: ReadableStream<Uint8Array>\n readonly status: Promise<ProcessStatus>\n /**\n * Sends the process `signal`, `SIGTERM` by default, as `kill()` of Deno's `ChildProcess` does,\n * and its `status` says the signal that ended it. A process that has ended, or never started,\n * is sent nothing. A name of no {@link ProcessSignal} throws a `BadArgument`. So a caller ends a\n * process that ignores `SIGTERM` by `SIGKILL`, after a grace of its own timers:\n *\n * ```ts\n * const child = platform.spawn('server', [])\n * const grace = platform.setTimeout(() => child.kill('SIGKILL'), 2000)\n * child.kill()\n * await child.status.finally(() => platform.clearTimeout(grace))\n * ```\n */\n kill(signal?: ProcessSignal): void\n}\n\n/**\n * Starts `command` with its arguments `args`, each given to it as it is, with no shell between: a\n * process of the platform, or what a double makes of it. Where no web standard defines one, the\n * shape is the platform's own.\n */\nexport type Spawn = (\n command: string,\n args: readonly string[],\n options?: SpawnOptions\n) => ChildProcess\n\n/** What {@link exec} runs a process with: the {@link SpawnOptions}, and the text of its stdin. */\nexport type ExecOptions = SpawnOptions & {\n /** What the process reads, as text or bytes, before its stdin ends: none by default. */\n readonly input?: string | Uint8Array\n}\n\n/** What a process {@link exec} ran wrote, as text, and the code it exited with. */\nexport type ExecResult = { readonly stdout: string; readonly stderr: string; readonly code: number }\n\n/** The text of a stream of bytes, decoded as UTF-8, to its end. */\nconst textOf = async (stream: ReadableStream<Uint8Array>): Promise<string> => {\n const reader = stream.getReader()\n const decoder = new TextDecoder()\n let text = ''\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- a stream is read one chunk at a time\n const { done, value } = await reader.read()\n if (done) return text + decoder.decode()\n text += decoder.decode(value, { stream: true })\n }\n}\n\n/** Writes `input` to `stdin`, and closes it: what the process did not read, it ended before. */\nconst feed = async (stdin: WritableStream<Uint8Array>, input?: string | Uint8Array) => {\n const writer = stdin.getWriter()\n try {\n if (input !== undefined && input.length > 0)\n await writer.write(typeof input === 'string' ? new TextEncoder().encode(input) : input)\n await writer.close()\n } catch {\n // The process ended before it read all of its input: its status says how.\n } finally {\n writer.releaseLock()\n }\n}\n\n/**\n * Runs `command` by `spawn` to its end, as `execFile` of Node and Deno's `output()` do: writes\n * `input` to its stdin, and ends it, and gives what it wrote to its stdout and stderr, as text, and\n * the code it exited with. A process that exits with a code but 0 resolves, with its code: the\n * caller decides what a code means. One that could not start rejects with the `SystemError` of its\n * `status`; one whose `signal` is aborted is ended, and rejects with the signal's reason.\n *\n * ```ts\n * const { stdout } = await exec(platform.spawn, 'git', ['status', '--porcelain'])\n * ```\n */\nexport const exec = async (\n spawn: Spawn,\n command: string,\n args: readonly string[],\n { input, ...options }: ExecOptions = {}\n): Promise<ExecResult> => {\n const { signal } = options\n signal?.throwIfAborted()\n const child = spawn(command, args, options)\n const [stdout, stderr, status] = await Promise.all([\n textOf(child.stdout),\n textOf(child.stderr),\n child.status,\n feed(child.stdin, input)\n ])\n signal?.throwIfAborted()\n return { stdout, stderr, code: status.code }\n}\n\n/** The number of each signal a process may end by, as POSIX has them, which its code is 128 and. */\nconst SIGNALS: Readonly<Record<string, number>> = {\n SIGHUP: 1,\n SIGINT: 2,\n SIGQUIT: 3,\n SIGKILL: 9,\n SIGTERM: 15\n}\n\n/**\n * The signal `signal`, as a `kill` of a {@link ChildProcess} sends it: a name of no\n * {@link ProcessSignal} is a `BadArgument`.\n */\nexport const sendable = (signal: unknown): ProcessSignal => {\n if (typeof signal === 'string' && Object.hasOwn(SIGNALS, signal)) return signal as ProcessSignal\n throw new BadArgument({\n module: 'Process',\n method: 'kill',\n description: `${String(signal)} is no signal a process may be sent.`\n })\n}\n\n/**\n * The status of a process a signal ended, its code 128 and the signal's number, as a shell gives\n * it: `SIGTERM` by default, as an aborted signal ends a process.\n */\nexport const signalled = (signal = 'SIGTERM'): ProcessStatus => ({\n code: 128 + (SIGNALS[signal] ?? 0),\n signal\n})\n\n/** The `SystemError` of a command that could not be started, by its reason. */\nexport const notStarted = (\n command: string,\n reason: 'NotFound' | 'PermissionDenied' | 'Unknown',\n cause?: unknown\n): SystemError =>\n new SystemError({\n reason,\n module: 'Process',\n method: 'spawn',\n pathOrDescriptor: command,\n description:\n reason === 'NotFound' ? `${command} is not there.` : `${command} could not be started.`,\n ...(cause === undefined ? {} : { cause })\n })\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@wtf/platform",
3
- "version": "1.0.0",
4
- "description": "The Platform type your code takes instead of globals, with helpers such as sleep and randomId, and a test double for each member. Web standards first: timers, crypto, console, locks, storage, channels, workers and fetch keep the standards' names; env, path, dirs, terminal, open and spawn are added where no standard exists.",
3
+ "version": "2.1.0",
4
+ "description": "The Platform type your code takes instead of globals, with helpers such as sleep and randomId, and a test double for each member. Web standards first: timers, crypto, console, locks, storage, channels, workers and fetch keep the standards' names; env, path, dirs, terminal, open, spawn and LoadModule, the loader of a module by its name, are added where no standard exists.",
5
5
  "homepage": "https://gitlab.com/wetryfun/platform/platform/-/tree/main/packages/platform",
6
6
  "bugs": {
7
7
  "url": "https://gitlab.com/wetryfun/platform/platform/-/issues"
@@ -74,6 +74,10 @@
74
74
  "types": "./dist/open.d.ts",
75
75
  "default": "./dist/open.js"
76
76
  },
77
+ "./module": {
78
+ "types": "./dist/module.d.ts",
79
+ "default": "./dist/module.js"
80
+ },
77
81
  "./process": {
78
82
  "types": "./dist/process.d.ts",
79
83
  "default": "./dist/process.js"