Repository navigation
Expand file tree
/
Copy pathworkers_openapi.js
More file actions
222 lines (198 loc) · 7.2 KB
/
Copy pathworkers_openapi.js
File metadata and controls
222 lines (198 loc) · 7.2 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#! /usr/bin/env node
import { writeFileSync, readFileSync, existsSync, rmSync, readdirSync, stat, statSync } from 'node:fs';
import { execSync, spawn } from 'node:child_process';
import { cwd, exit as __raw_exit__ } from 'node:process';
import { join } from 'node:path';
const app = (() => {
class App {
/** @type {string} @readonly */
WASMPACK_OUT_DIR = ".ohkami";
/** @type {string} @readonly */
WASMPACK_OUT_NAME = "workers_openapi";
/** @type {string} */
#outputPath = "openapi.json";
/** @type {[string]} */
#additionalOptions = [];
constructor() {
if (!(existsSync("wrangler.toml") || existsSync("wrangler.jsonc"))) {
this.exit(150, `Expected a wrangler project, but ${e}`)
}
const cliArgsStartIndex = (() => {
/** this script is executed via `node -e ...` and no CLI arguments are given */
if (process.argv.length === 1) return 1;
const argv1 = process.argv[1];
if (argv1.startsWith("/") || argv1.startsWith("C:") || argv1.startsWith("D:")) {
/** this script is executed by `node workers_openapi.js` */
return 2;
} else {
/** this script is executed via `node -e ...` */
return 1;
}
})();
if (process.argv.length > cliArgsStartIndex) {
let i = cliArgsStartIndex;
while (i < process.argv.length) {
switch (process.argv[i]) {
case "--out":
case "-o":
this.#outputPath = process.argv[i + 1];
i += 2;
break;
case "--":
this.#additionalOptions = process.argv.slice(i + 1);
i = process.argv.length;
break;
default:
this.#additionalOptions = process.argv.slice(i);
i = process.argv.length;
break;
}
}
}
}
/** @returns {string} */
get outputPath() {
return this.#outputPath;
}
/** @returns {string} */
get additionalOptions() {
return this.#additionalOptions;
}
/**
* @param {number} code
* @param {string | undefined} message
* @returns {void}
*/
exit(code, message) {
if (existsSync(this.WASMPACK_OUT_DIR)) {
rmSync(this.WASMPACK_OUT_DIR, { recursive: true, force: true });
}
if (typeof message == 'string') {
console.error("[workers_openapi.js] Fatal:", message);
}
__raw_exit__(code);
}
/**
* @param {string} message
* @returns {void}
*/
warn(message) {
if (typeof message == 'string') {
console.error("[workers_openapi.js] Warning:", message);
}
}
}
return new App();
})();
try {
const wasmpack_is_installed = (() => {
try {
execSync("which wasm-pack");
return true;
} catch (e) {
return false;
}
})();
if (!wasmpack_is_installed) {
const cargo_install_wasmpack = spawn("cargo", [
"install",
"wasm-pack"
], { stdio: "inherit" });
await new Promise((resolve, reject) => {
cargo_install_wasmpack.on("close", (code) => {
if (code === 0) {resolve()} else {reject(`'cargo install' closed with ${code}`)}
});
cargo_install_wasmpack.on("exit", (code) => {
if (code === 0) {resolve()} else {reject(`'cargo install' exited with ${code}`)}
});
cargo_install_wasmpack.on("error", (err) => {
reject(`'cargo install' failed: ${err}`);
});
cargo_install_wasmpack.on("disconnect", () => {
reject(`'cargo install' disconnected`);
});
});
}
if (existsSync(app.WASMPACK_OUT_DIR)) {
rmSync(app.WASMPACK_OUT_DIR, { recursive: true, force: true });
}
const wasmpack_build = spawn("wasm-pack", [
"build",
"--dev",
"--no-opt",
"--no-pack",
"--no-typescript",
"--target", "nodejs",
"--out-dir", app.WASMPACK_OUT_DIR,
"--out-name", app.WASMPACK_OUT_NAME,
"--", ...app.additionalOptions
], { stdio: "inherit" });
await new Promise((resolve, reject) => {
wasmpack_build.on("close", (code) => {
if (code === 0) {resolve()} else {reject(`'wasm-pack build' closed with ${code}`)}
});
wasmpack_build.on("exit", (code) => {
if (code === 0) {resolve()} else {reject(`'wasm-pack build' exited with ${code}`)}
});
wasmpack_build.on("error", (err) => {
reject(`'wasm-pack build' failed: ${err}`);
});
wasmpack_build.on("disconnect", () => {
reject(`'wasm-pack build' disconnected`);
});
});
} catch (e) {
app.exit(151, `Build failed: ${e}`);
}
try {
const wasmpack_js_path = join(
cwd(),
app.WASMPACK_OUT_DIR,
`${app.WASMPACK_OUT_NAME}.js`
);
{
writeFileSync(wasmpack_js_path, readFileSync(wasmpack_js_path, 'utf-8')
.replace(/^.+cloudflare:workers.+$/gm, ""));
if (existsSync(join(wasmpack_js_path, '..', 'snippets'))) {
for (const snippet_entry of readdirSync(join(wasmpack_js_path, '..', 'snippets'), {
recursive: true,
withFileTypes: true,
})) {
if (snippet_entry.isFile()) {
const path = join(snippet_entry.parentPath, snippet_entry.name);
writeFileSync(path, readFileSync(path, 'utf-8')
.replace(/^.+cloudflare:workers.+$/gm, ""));
}
}
}
}
const wasmpack_js = await import(wasmpack_js_path);
if (!wasmpack_js.OpenAPIDocumentBytes) {
throw new Error("Not activating Ohkami's `openapi` feature flag");
}
/** @type {Uint8Array} */
let OpenAPIDocumentBytes = await wasmpack_js.OpenAPIDocumentBytes();
{
let OpenAPIDocumentJSON = JSON.parse(
(new TextDecoder()).decode(OpenAPIDocumentBytes)
);
if ((OpenAPIDocumentJSON.servers ?? []).length === 0) {
OpenAPIDocumentJSON.servers = [{
url: `http://localhost:8787`,
description: "local dev",
}];
}
OpenAPIDocumentBytes = (new TextEncoder()).encode(
JSON.stringify(OpenAPIDocumentJSON, null, 2)
+ "\n"
);
}
writeFileSync(app.outputPath, OpenAPIDocumentBytes);
} catch (e) {
app.exit(152, `Generation failed: ${e}`);
}
try {
rmSync(app.WASMPACK_OUT_DIR, { recursive: true, force: true });
} catch (e) {
app.exit(153, `Cleaning up failed: ${e}`);
}