-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmain.ts
More file actions
191 lines (174 loc) · 6.11 KB
/
main.ts
File metadata and controls
191 lines (174 loc) · 6.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import { createContext } from "./context.ts";
import type { Operation } from "./types.ts";
import { callcc } from "./callcc.ts";
import { run } from "./run.ts";
import { useScope } from "./scope.ts";
import { call } from "./call.ts";
/**
* Halt process execution immediately and initiate shutdown. If a message is
* provided, it will be logged to the console after shutdown:
*
* ```js
* if (invalidArgs()) {
* yield* exit(5, "invalid arguments")
* }
* ```
* @param status - the exit code to use for the process exit
* @param message - message to print to the console before exiting.
* @param returns an operation that exits the program
*/
export function* exit(status: number, message?: string): Operation<void> {
let escape = yield* ExitContext.expect();
yield* escape({ status, message });
}
/**
* Top-level entry point to programs written in Effection. That means that your
* program should only call `main` once, and everything the program does is
* handled from within `main` including an orderly shutdown. Unlike `run`, `main`
* automatically prints errors that occurred to the console.
*
* Use the {@link exit} operation form within to halt program execution
* immediately and initiate shutdown.
*
* The behavior of `main` is slightly different depending on the environment it
* is running in.
*
* ### Deno, Node
*
* When running within Deno or Node, any error which reaches `main` causes the
* entire process to exit with an exit code of `1`.
*
* Additionally, handlers for `SIGINT` are attached to the
* process, so that sending an exit signal to it causes the main task
* to become halted. This means that hitting CTRL-C on an Effection program
* using `main` will cause an orderly shutdown and run all cleanup code.
*
* > Warning! do not call `Deno.exit()` on Deno or `process.exit()` on Node
* > directly, as this will not gracefully shutdown. Instead, use the
* > {@link exit} operation.
*
* ### Browser
*
* When running in a browser, The `main` operation gets shut down on the
* `unload` event.
*
* @param body - an operation to run as the body of the program
* @returns a promise that resolves right after the program exits
*/
export async function main(
body: (args: string[]) => Operation<void>,
): Promise<void> {
let hardexit = (_status: number) => {};
let result = await run(() =>
callcc<Exit>(function* (resolve) {
// action will return shutdown immediately upon resolve, so stash
// this function in the exit context so it can be called anywhere.
yield* ExitContext.set(resolve);
// this will hold the event loop and prevent runtimes such as
// Node and Deno from exiting prematurely.
let interval = setInterval(() => {}, Math.pow(2, 30));
let scope = yield* useScope();
try {
let interrupt = {
SIGINT: () =>
scope.run(() => resolve({ status: 130, signal: "SIGINT" })),
SIGTERM: () =>
scope.run(() => resolve({ status: 143, signal: "SIGTERM" })),
};
yield* withHost({
*deno() {
hardexit = (status) => Deno.exit(status);
try {
Deno.addSignalListener("SIGINT", interrupt.SIGINT);
/**
* Windows only supports ctrl-c (SIGINT), ctrl-break (SIGBREAK), and ctrl-close (SIGUP)
*/
if (Deno.build.os !== "windows") {
Deno.addSignalListener("SIGTERM", interrupt.SIGTERM);
}
yield* body(Deno.args.slice());
} finally {
Deno.removeSignalListener("SIGINT", interrupt.SIGINT);
if (Deno.build.os !== "windows") {
Deno.removeSignalListener("SIGTERM", interrupt.SIGTERM);
}
}
},
*node() {
// Annotate dynamic import so that webpack ignores it.
// See https://webpack.js.org/api/module-methods/#webpackignore
let { default: process } = yield* call(() =>
import(/* webpackIgnore: true */ "node:process")
);
hardexit = (status) => process.exit(status);
try {
process.on("SIGINT", interrupt.SIGINT);
if (process.platform !== "win32") {
process.on("SIGTERM", interrupt.SIGTERM);
}
yield* body(process.argv.slice(2));
} finally {
process.off("SIGINT", interrupt.SIGINT);
if (process.platform !== "win32") {
process.off("SIGTERM", interrupt.SIGINT);
}
}
},
*browser() {
try {
self.addEventListener("unload", interrupt.SIGINT);
yield* body([]);
} finally {
self.removeEventListener("unload", interrupt.SIGINT);
}
},
});
yield* exit(0);
} catch (error) {
yield* resolve({ status: 1, error: error as Error });
} finally {
clearInterval(interval);
}
})
);
if (result.message) {
if (result.status === 0) {
console.log(result.message);
} else {
console.error(result.message);
}
}
if (result.error) {
console.error(result.error);
}
hardexit(result.status);
}
const ExitContext = createContext<(exit: Exit) => Operation<void>>("exit");
interface Exit {
status: number;
message?: string;
signal?: string;
error?: Error;
}
interface HostOperation<T> {
deno(): Operation<T>;
node(): Operation<T>;
browser(): Operation<T>;
}
function* withHost<T>(op: HostOperation<T>): Operation<T> {
let global = globalThis as Record<string, unknown>;
if (typeof global.Deno !== "undefined") {
return yield* op.deno();
// this snippet is from the detect-node npm package
// @see https://github.com/iliakan/detect-node/blob/master/index.js
} else if (
Object.prototype.toString.call(
// @ts-expect-error we are just detecting the possibility, so type strictness not required
typeof globalThis.process !== "undefined" ? globalThis.process : 0,
) === "[object process]"
) {
return yield* op.node();
} else {
return yield* op.browser();
}
}