create-cgull 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Matthew Phillips
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,106 @@
1
- # Temporary Holding Version
1
+ # cgull
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Write Cloudflare Workers in C. The manual is **[The cgull Book](https://cgull.org)**.
4
+
5
+ ```c
6
+ #include <cgull.h>
7
+
8
+ static void hello(cg_req *req, cg_res *res) {
9
+ cg_printf(res, "<h1>Hello, %s!</h1>", cg_esc(cg_param(req, "name")));
10
+ }
11
+
12
+ int main(void) {
13
+ cg_get("/hello/:name", hello);
14
+ return cg_run();
15
+ }
16
+ ```
17
+
18
+ ```sh
19
+ npm create cgull my-app && cd my-app && npm install
20
+ npx cgull run -i /hello/you # one request, no server
21
+ npm run dev # wrangler dev on :8787
22
+ npm run deploy # wrangler deploy
23
+ ```
24
+
25
+ The npm package is `create-cgull`, so that `npm create cgull` works; it
26
+ also provides the `cgull` command used inside a project. The first build
27
+ downloads wasi-sdk 33 into `~/.cache/wasi-sdk` (or uses
28
+ `$WASI_SDK_PATH`).
29
+
30
+ ## How it works
31
+
32
+ A cgull program is a CGI program. `cgull build` compiles `src/**/*.c`
33
+ with the runtime (`runtime/cgull.c`) to a WASI module, `build/app.wasm`.
34
+ Next to it, it writes a small Worker (`build/worker.js`) and the shim it
35
+ uses (`runtime/shim.js`).
36
+
37
+ For each request the shim starts a fresh instance of the module. The
38
+ request goes in the CGI way, as environment variables (`REQUEST_METHOD`,
39
+ `REQUEST_URI`, `HTTP_*`, ...) and stdin. The shim then parses what the
40
+ program writes to stdout (headers, a blank line, the body) into a
41
+ `Response`. It implements only the WASI calls a CGI program needs. The
42
+ instance is thrown away after the request, so:
43
+
44
+ - **Never free anything.** All memory goes when the request ends. Strings
45
+ from `cg_*` functions are valid for the whole request.
46
+ - **No state carries over between requests.** Each one starts from `main()`.
47
+ - **A crash only takes down its own request.** `abort()`, a failed
48
+ `assert()`, a bad memory access or a nonzero exit gives a 500, and
49
+ the message goes to the Worker's logs.
50
+
51
+ Because the contract is plain CGI, the same code builds natively:
52
+ `cgull build --native` makes `build/app`, which runs under any CGI server
53
+ and works with gdb and sanitizers. `cgull run --native` sends it a request.
54
+
55
+ ## The API
56
+
57
+ All of it is in [`runtime/cgull.h`](runtime/cgull.h).
58
+
59
+ - **Routing:** `cg_get/post/put/patch/delete/any(pattern, handler)`, with
60
+ `:name` and trailing `*` segments. `cg_use(middleware)` runs before every
61
+ handler, and returning false stops the request. `cg_not_found(handler)`
62
+ replaces the 404 page. Unknown methods get a 405 with `Allow`, and HEAD
63
+ falls back to GET.
64
+ - **Request:** `cg_method`, `cg_path`, `cg_param`, `cg_query`, `cg_header`,
65
+ `cg_cookie`, `cg_form` (urlencoded bodies), `cg_body`.
66
+ - **Response:** `cg_status`, `cg_set_header`/`cg_add_header`,
67
+ `cg_set_cookie`, `cg_write`/`cg_puts`/`cg_printf`, and the shortcuts
68
+ `cg_text`, `cg_html`, `cg_json`, `cg_redirect`.
69
+ - **Strings:** `cg_esc` (HTML), `cg_json_str`, `cg_url_encode`,
70
+ `cg_sprintf`.
71
+ - **Env and logs:** `cg_env("NAME")` reads Worker vars and secrets.
72
+ `cg_log(...)` writes to the Worker's logs. `CGULL_VERSION` is the
73
+ version string.
74
+
75
+ Files in `public/` are served as static assets before the C code runs.
76
+ Extra compiler flags go in `package.json`:
77
+ `"cgull": { "cflags": ["-DFOO"], "ldflags": [] }`.
78
+
79
+ ## Developing cgull
80
+
81
+ ```sh
82
+ npm test # builds test/fixture as wasm and natively; checks both
83
+ ```
84
+
85
+ `npm test` also builds `docs/`, the cgull Book, and checks that its
86
+ Appendix A covers every name in `cgull.h`. Add an entry to
87
+ `docs/src/reference.c` whenever the header gains one.
88
+
89
+ ## Documentation
90
+
91
+ The full manual is `docs/`, itself a cgull program, deployed at
92
+ https://cgull.org. Deploy it from `docs/` with
93
+ `npm run deploy`.
94
+
95
+ ## Not yet
96
+
97
+ - Async calls from C (`fetch`, KV, D1, R2). JSPI (`WebAssembly.Suspending`)
98
+ works on Workers, so the shim could expose blocking `cg_fetch()` and
99
+ `cg_kv_get()` that suspend the wasm while the promise settles.
100
+ - Streaming responses: output is buffered until the handler returns.
101
+ - Multipart form bodies and a JSON parser.
102
+
103
+ ## License
104
+
105
+ BSD 3-Clause; see [LICENSE](LICENSE). The fonts in `docs/public/fonts` have
106
+ their own licenses, listed in [LICENSES.md](docs/public/fonts/LICENSES.md).
package/bin/cgull.js ADDED
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ // The cgull CLI: builds a C project into a Cloudflare Worker.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+
11
+ const PKG = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
12
+ const RUNTIME = path.join(PKG, "runtime");
13
+ const VERSION = JSON.parse(fs.readFileSync(path.join(PKG, "package.json"), "utf8")).version;
14
+
15
+ const USAGE = `cgull ${VERSION}: Cloudflare Workers in C
16
+
17
+ Usage:
18
+ cgull new <dir> Make a new project (or: npm create cgull <dir>)
19
+ cgull build [--debug] Compile src/**/*.c to build/ (app.wasm + worker.js)
20
+ cgull build --native Compile a native CGI binary, build/app
21
+ cgull run [options] <path>
22
+ Build, then run one request and print the response
23
+ -X, --method <method> GET by default (POST with -d)
24
+ -H, --header 'Name: v' Add a request header (repeatable)
25
+ -d, --data <body> Request body (@file reads a file), sent as a
26
+ form unless -H gives a Content-Type
27
+ -e, --env NAME=value Set a Worker var (repeatable)
28
+ -i, --include Print the status and headers too
29
+ --native Run build/app instead of the wasm
30
+ cgull dev [args] wrangler dev
31
+ cgull deploy [args] wrangler deploy
32
+ cgull setup Download wasi-sdk if it isn't there yet
33
+
34
+ Compiler flags can go in package.json: "cgull": { "cflags": [...], "ldflags": [...] }.
35
+ wasi-sdk is looked for in $WASI_SDK_PATH, then ~/.cache/wasi-sdk.
36
+ `;
37
+
38
+ function die(msg) {
39
+ console.error(`cgull: ${msg}`);
40
+ process.exit(1);
41
+ }
42
+
43
+ function sh(cmd, args, opts = {}) {
44
+ const r = spawnSync(cmd, args, { stdio: "inherit", ...opts });
45
+ if (r.error) die(`couldn't run ${cmd}: ${r.error.message}`);
46
+ if (r.status !== 0) process.exit(r.status ?? 1);
47
+ return r;
48
+ }
49
+
50
+ // --- wasi-sdk --------------------------------------------------------------
51
+
52
+ const WASI_SDK_VERSION = "33";
53
+ const WASI_SDK_SHA256 = {
54
+ "x86_64-linux": "0ba8b5bfaeb2adf3f29bab5841d76cf5318ab8e1642ea195f88baba1abd47bce",
55
+ "arm64-linux": "4f98ee738c7abb45c81a94d1461fc53cc569d1cd01498951c8184d841a027844",
56
+ "x86_64-macos": "18f3f201ba9734e6a4455b0b6410690395a55e9ffa9f6f5066f66083a94b93b3",
57
+ "arm64-macos": "85c997a2665ead91673b5bb88b7d0df3fc8900df3bfa244f720d478187bbdc78",
58
+ };
59
+
60
+ function sdkPlatform() {
61
+ const arch = { x64: "x86_64", arm64: "arm64" }[process.arch];
62
+ const plat = { linux: "linux", darwin: "macos" }[process.platform];
63
+ if (!arch || !plat) die(`no wasi-sdk build for ${process.platform}/${process.arch}`);
64
+ return `${arch}-${plat}`;
65
+ }
66
+
67
+ function sdkCacheDir() {
68
+ const cache = process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");
69
+ return path.join(cache, "wasi-sdk", `wasi-sdk-${WASI_SDK_VERSION}.0-${sdkPlatform()}`);
70
+ }
71
+
72
+ function findWasiSdk() {
73
+ const candidates = [process.env.WASI_SDK_PATH, sdkCacheDir(), "/opt/wasi-sdk"];
74
+ return candidates.find((dir) => dir && fs.existsSync(path.join(dir, "bin", "clang")));
75
+ }
76
+
77
+ async function setup() {
78
+ const found = findWasiSdk();
79
+ if (found) return found;
80
+ const dir = sdkCacheDir();
81
+ const name = path.basename(dir);
82
+ const url = `https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_SDK_VERSION}/${name}.tar.gz`;
83
+ console.error(`cgull: downloading wasi-sdk ${WASI_SDK_VERSION} (about 120 MB, once)`);
84
+ const res = await fetch(url);
85
+ if (!res.ok) die(`download failed: ${res.status} ${url}`);
86
+ const data = Buffer.from(await res.arrayBuffer());
87
+ const sum = createHash("sha256").update(data).digest("hex");
88
+ if (sum !== WASI_SDK_SHA256[sdkPlatform()]) die(`checksum mismatch for ${url}`);
89
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
90
+ const tmp = fs.mkdtempSync(path.join(path.dirname(dir), "download."));
91
+ try {
92
+ fs.writeFileSync(path.join(tmp, "sdk.tar.gz"), data);
93
+ sh("tar", ["xzf", "sdk.tar.gz"], { cwd: tmp });
94
+ fs.renameSync(path.join(tmp, name), dir);
95
+ } finally {
96
+ fs.rmSync(tmp, { recursive: true, force: true });
97
+ }
98
+ console.error(`cgull: wasi-sdk is in ${dir}`);
99
+ return dir;
100
+ }
101
+
102
+ // --- Building --------------------------------------------------------------
103
+
104
+ function projectRoot() {
105
+ let dir = process.cwd();
106
+ while (!fs.existsSync(path.join(dir, "package.json")) || !fs.existsSync(path.join(dir, "src"))) {
107
+ const up = path.dirname(dir);
108
+ if (up === dir) die("no project here (looked for package.json and src/)");
109
+ dir = up;
110
+ }
111
+ return dir;
112
+ }
113
+
114
+ function sources(dir) {
115
+ return fs
116
+ .readdirSync(dir, { recursive: true })
117
+ .filter((f) => f.endsWith(".c"))
118
+ .sort()
119
+ .map((f) => path.join(dir, f));
120
+ }
121
+
122
+ function projectFlags(root) {
123
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
124
+ const cfg = pkg.cgull ?? {};
125
+ return { cflags: cfg.cflags ?? [], ldflags: cfg.ldflags ?? [] };
126
+ }
127
+
128
+ const WORKER_JS = `// Generated by cgull. Don't edit; it's rebuilt on every build.
129
+ import app from "./app.wasm";
130
+ import { runCgi, stringVars } from "./shim.js";
131
+
132
+ export default {
133
+ fetch(request, env) {
134
+ return runCgi(app, request, stringVars(env));
135
+ },
136
+ };
137
+ `;
138
+
139
+ async function build({ debug = false, native = false } = {}) {
140
+ const root = projectRoot();
141
+ const src = path.join(root, "src");
142
+ const out = path.join(root, "build");
143
+ const files = sources(src);
144
+ if (!files.length) die("no .c files in src/");
145
+ fs.mkdirSync(out, { recursive: true });
146
+
147
+ const { cflags, ldflags } = projectFlags(root);
148
+ const common = [
149
+ "-std=c17",
150
+ "-Wall",
151
+ "-Wextra",
152
+ "-Wno-unused-parameter",
153
+ `-DCGULL_VERSION="${VERSION}"`,
154
+ `-I${RUNTIME}`,
155
+ `-I${src}`,
156
+ ...(debug ? ["-O0", "-g"] : ["-O2"]),
157
+ ...cflags,
158
+ ...files,
159
+ path.join(RUNTIME, "cgull.c"),
160
+ ];
161
+
162
+ if (native) {
163
+ const cc = process.env.CC || "cc";
164
+ sh(cc, [...common, "-o", path.join(out, "app"), ...ldflags]);
165
+ return path.join(out, "app");
166
+ }
167
+
168
+ const sdk = await setup();
169
+ sh(path.join(sdk, "bin", "clang"), [
170
+ "--target=wasm32-wasip1",
171
+ ...common,
172
+ "-o",
173
+ path.join(out, "app.wasm"),
174
+ ...(debug ? [] : ["-Wl,--strip-all"]),
175
+ ...ldflags,
176
+ ]);
177
+ fs.copyFileSync(path.join(RUNTIME, "shim.js"), path.join(out, "shim.js"));
178
+ fs.writeFileSync(path.join(out, "worker.js"), WORKER_JS);
179
+ return path.join(out, "app.wasm");
180
+ }
181
+
182
+ // --- Running one request ---------------------------------------------------
183
+
184
+ function parseRunArgs(args) {
185
+ const opts = { method: null, headers: [], data: null, env: {}, include: false, native: false, debug: false };
186
+ let target = null;
187
+ for (let i = 0; i < args.length; i++) {
188
+ const a = args[i];
189
+ const next = () => args[++i] ?? die(`${a} needs a value`);
190
+ if (a === "-X" || a === "--method") opts.method = next().toUpperCase();
191
+ else if (a === "-H" || a === "--header") opts.headers.push(next());
192
+ else if (a === "-d" || a === "--data") opts.data = next();
193
+ else if (a === "-e" || a === "--env") {
194
+ const [k, ...v] = next().split("=");
195
+ opts.env[k] = v.join("=");
196
+ } else if (a === "-i" || a === "--include") opts.include = true;
197
+ else if (a === "--native") opts.native = true;
198
+ else if (a === "--debug") opts.debug = true;
199
+ else if (a.startsWith("-")) die(`unknown option ${a}`);
200
+ else target = a;
201
+ }
202
+ if (!target) die("run needs a path, e.g. cgull run /hello");
203
+ opts.url = new URL(target, "http://localhost:8787/").href;
204
+ if (opts.data?.startsWith("@")) opts.data = fs.readFileSync(opts.data.slice(1));
205
+ opts.method ??= opts.data == null ? "GET" : "POST";
206
+ return opts;
207
+ }
208
+
209
+ async function run(args) {
210
+ const opts = parseRunArgs(args);
211
+ const built = await build({ debug: opts.debug, native: opts.native });
212
+ const headers = new Headers(
213
+ opts.headers.map((h) => {
214
+ const i = h.indexOf(":");
215
+ if (i < 0) die(`bad header ${h}`);
216
+ return [h.slice(0, i).trim(), h.slice(i + 1).trim()];
217
+ }),
218
+ );
219
+ // As with curl -d, a body is a form unless it says otherwise.
220
+ if (opts.data != null && !headers.has("content-type"))
221
+ headers.set("content-type", "application/x-www-form-urlencoded");
222
+ const request = new Request(opts.url, { method: opts.method, headers, body: opts.data });
223
+
224
+ let response;
225
+ if (opts.native) {
226
+ response = await runNative(built, request, opts.env);
227
+ } else {
228
+ const { runCgi } = await import(pathToFileURL(path.join(path.dirname(built), "shim.js")));
229
+ const module = new WebAssembly.Module(fs.readFileSync(built));
230
+ response = await runCgi(module, request, opts.env);
231
+ }
232
+
233
+ if (opts.include) {
234
+ console.log(`HTTP ${response.status} ${response.statusText}`);
235
+ for (const [k, v] of response.headers) console.log(`${k}: ${v}`);
236
+ console.log();
237
+ }
238
+ process.stdout.write(Buffer.from(await response.arrayBuffer()));
239
+ }
240
+
241
+ // The native binary through the same CGI plumbing, so both behave alike.
242
+ async function runNative(bin, request, vars) {
243
+ const shim = await import(pathToFileURL(path.join(RUNTIME, "shim.js")));
244
+ const body = Buffer.from(await request.arrayBuffer());
245
+ const env = { PATH: process.env.PATH, ...vars, ...shim.cgiEnv(request, body.length) };
246
+ const r = spawnSync(bin, [], { input: body, env, maxBuffer: 1 << 30 });
247
+ if (r.stderr.length) console.error(r.stderr.toString().trimEnd());
248
+ if (r.status !== 0) die(`build/app exited with ${r.status ?? r.signal}`);
249
+ return shim.parseResponse(new Uint8Array(r.stdout));
250
+ }
251
+
252
+ // --- New project -----------------------------------------------------------
253
+
254
+ function newProject(dir) {
255
+ if (!dir) die("new needs a directory, e.g. npm create cgull my-app");
256
+ const dest = path.resolve(dir);
257
+ if (fs.existsSync(dest) && fs.readdirSync(dest).length) die(`${dir} isn't empty`);
258
+ const name = path.basename(dest).toLowerCase().replace(/[^a-z0-9-]+/g, "-");
259
+ // Until cgull is on npm, point at this checkout.
260
+ const inNodeModules = PKG.split(path.sep).includes("node_modules");
261
+ const dep = inNodeModules ? `^${VERSION}` : `file:${PKG}`;
262
+ const vars = { NAME: name, CGULL_DEP: dep, DATE: new Date().toISOString().slice(0, 10) };
263
+
264
+ const template = path.join(PKG, "template");
265
+ for (const rel of fs.readdirSync(template, { recursive: true })) {
266
+ const from = path.join(template, rel);
267
+ const to = path.join(dest, rel.replace(/^_/, ".").replace(/\/_/g, "/."));
268
+ if (fs.statSync(from).isDirectory()) {
269
+ fs.mkdirSync(to, { recursive: true });
270
+ continue;
271
+ }
272
+ const text = fs.readFileSync(from, "utf8").replace(/\{\{(\w+)\}\}/g, (_, k) => vars[k]);
273
+ fs.mkdirSync(path.dirname(to), { recursive: true });
274
+ fs.writeFileSync(to, text);
275
+ }
276
+ console.log(`Made ${dir}. Next:
277
+
278
+ cd ${dir}
279
+ npm install
280
+ npx cgull run -i / # one request, no server
281
+ npm run dev # http://localhost:8787
282
+ npm run deploy`);
283
+ }
284
+
285
+ // --- Main ------------------------------------------------------------------
286
+
287
+ function wrangler(cmd, args) {
288
+ const root = projectRoot();
289
+ const local = path.join(root, "node_modules", ".bin", "wrangler");
290
+ const bin = fs.existsSync(local) ? local : "wrangler";
291
+ sh(bin, [cmd, ...args], { cwd: root });
292
+ }
293
+
294
+ const [cmd, ...args] = process.argv.slice(2);
295
+ switch (cmd) {
296
+ case "new":
297
+ newProject(args[0]);
298
+ break;
299
+ case "build": {
300
+ const built = await build({ debug: args.includes("--debug"), native: args.includes("--native") });
301
+ console.error(`cgull: built ${path.relative(process.cwd(), built)}`);
302
+ break;
303
+ }
304
+ case "run":
305
+ await run(args);
306
+ break;
307
+ case "dev":
308
+ case "deploy":
309
+ wrangler(cmd, args);
310
+ break;
311
+ case "setup":
312
+ console.log(await setup());
313
+ break;
314
+ case undefined:
315
+ case "-h":
316
+ case "--help":
317
+ case "help":
318
+ process.stdout.write(USAGE);
319
+ break;
320
+ case "-v":
321
+ case "--version":
322
+ console.log(VERSION);
323
+ break;
324
+ default:
325
+ die(`unknown command ${cmd}; try cgull --help`);
326
+ }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // `npm create cgull <dir>` runs this: it is `cgull new <dir>`.
3
+ process.argv.splice(2, 0, "new");
4
+ await import("./cgull.js");
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
- "name": "create-cgull",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "create-cgull",
3
+ "version": "0.1.0",
4
+ "description": "Write Cloudflare Workers in C",
5
+ "type": "module",
6
+ "license": "BSD-3-Clause",
7
+ "homepage": "https://cgull.org",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/matthewp/cgull.git"
11
+ },
12
+ "bin": {
13
+ "cgull": "bin/cgull.js",
14
+ "create-cgull": "bin/create-cgull.js"
15
+ },
16
+ "files": [
17
+ "bin",
18
+ "runtime",
19
+ "template"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test test/*.test.js"
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ }
27
+ }