cloudflare-model-host 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/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ All notable changes to `cloudflare-model-host` are recorded here. Versions follow [semantic versioning](https://semver.org/);
4
+ while the major version is 0, a minor release may break the API and a patch release does not. A published version
5
+ is never changed: a fix is a new version. Each tarball carries `PROVENANCE.json`, naming the commit and the digest
6
+ of the `dist/` it was built from ([releasing](../../docs/packages/RELEASING.md)).
7
+
8
+ ## 0.1.0 (not yet published)
9
+
10
+ First release.
11
+
12
+ - The `facemorph-model-host` command: `stage`, `verify`, `qualify-origin`, `publish`, `origin-deploy`, `mirror-deploy`
13
+ and `warm`.
14
+ - Staging for any HTTPS static host: digest checks, chunking of large files and a manifest rewritten to hosted URLs.
15
+ - An optional Cloudflare guide: a static-assets origin Worker and an R2 mirror Worker.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chris Dilger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ {
2
+ "schema": "facemorph.package-provenance/2",
3
+ "name": "cloudflare-model-host",
4
+ "version": "0.1.0",
5
+ "sourceCommit": "59a1544aaca0cf1fedd5bc96883ffeec76e49d60",
6
+ "sourceTreeClean": true,
7
+ "sourceIdentity": "9b401fea930912e43074bbbf8dbfcf5ac6f4a504bdd3fc4f028710c127bb3a12",
8
+ "distSha256": "8949d24c4d38337ef1f9ee045c93214dcd8c6734c4e598c7cfc928e1cba481c8",
9
+ "distFiles": 28,
10
+ "build": {
11
+ "repository": "facemorph-me/facemorph.me",
12
+ "runId": "46234816541",
13
+ "runAttempt": "1",
14
+ "workflow": "packages"
15
+ }
16
+ }
package/README.md CHANGED
@@ -1,3 +1,484 @@
1
- # Temporary Holding Version
1
+ # cloudflare-model-host
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
+ Stages, verifies and publishes converted model files for static HTTPS hosting, then checks that an origin serves
4
+ them byte for byte with the headers a browser needs. Cloudflare is optional: any static host that can set response
5
+ headers works, and Cloudflare Workers Static Assets (with an optional R2 mirror) is the documented deployment.
6
+
7
+ Where it fits:
8
+
9
+ 1. **Convert** a checkpoint with [model-conv](../model-conv/README.md) (see its
10
+ [compatibility table](../model-conv/docs/compatibility.md)). The output is a `manifest.json` and the files it
11
+ names, with SHA-256 digests and sizes.
12
+ 2. **Host** it with this package: `stage` gives every file a hosted URL, cuts files over 25 MiB into 16 MiB chunks,
13
+ `verify` reads the result back, `publish` copies it to a static root, and `qualify-origin` checks the served bytes
14
+ and headers.
15
+ 3. **Acquire** it in the browser with [browser-model-manager](../browser-model-manager/README.md), which
16
+ downloads only after the person authorizes it, verifies every byte and keeps the files in the browser's storage.
17
+ 4. **Run** it with [stylegan-js](../stylegan-js/README.md), which reads the manager's verified local
18
+ bytes and never fetches by itself.
19
+
20
+ Guides: [any static HTTPS host](docs/static-hosting.md) and [Cloudflare](docs/cloudflare.md). Every export is listed
21
+ in the [API reference](docs/api.md). Where the code came from: [extraction history](#extraction-history).
22
+
23
+ ## Install
24
+
25
+ <!-- docs-test: install -->
26
+ ```sh
27
+ npm install cloudflare-model-host browser-model-manager
28
+ ```
29
+
30
+ Node 24 or newer. The package installs the `facemorph-model-host` command; the manager is the browser half of the
31
+ quickstart. The Cloudflare tooling it depends on (the `cf` CLI and the Cloudflare Vite plugin) is used only by
32
+ `origin-deploy` and `mirror-deploy`.
33
+
34
+ ## Quickstart: host, manager, engine on your own machine
35
+
36
+ This publishes a converted model to a local HTTPS static server and has the manager load it in a browser page from a
37
+ second local origin. You need a model-conv output directory, here `./converted` (for example the AFHQ cat model from
38
+ [model-conv's usage guide](../model-conv/docs/usage.md)), Node 24, `openssl` and a Chromium-based browser.
39
+
40
+ Stage the model for the origin it will be served from, and verify the staged copy:
41
+
42
+ <!-- docs-test: run -->
43
+ ```sh
44
+ npx facemorph-model-host stage --source ./converted --out ./staged --base https://localhost:8443/models
45
+ npx facemorph-model-host verify --root ./staged --base https://localhost:8443/models
46
+ ```
47
+
48
+ Publishing needs a record of the model's terms. One row must name the manifest's `modelSourceSha256`; a row whose
49
+ `redistribution` is not `"permitted"` must be acknowledged by id in the target. Set `redistribution` to what your
50
+ model's licence actually allows:
51
+
52
+ <!-- docs-test: run -->
53
+ ```sh
54
+ MODEL_SOURCE=$(node -p "require('./staged/manifest.json').modelSourceSha256")
55
+ cat > terms.json <<EOF
56
+ { "rows": [ { "id": "my-model", "modelSourceSha256": "$MODEL_SOURCE", "redistribution": "non-commercial" } ] }
57
+ EOF
58
+ ```
59
+
60
+ <!-- docs-test: file target.json -->
61
+ ```json
62
+ {
63
+ "kind": "directory",
64
+ "path": "./site/models",
65
+ "terms": { "record": "./terms.json", "acknowledged": "my-model" }
66
+ }
67
+ ```
68
+
69
+ `publish` is a dry run until `--publish` is given:
70
+
71
+ <!-- docs-test: run -->
72
+ ```sh
73
+ npx facemorph-model-host publish --root ./staged --target target.json
74
+ npx facemorph-model-host publish --root ./staged --target target.json --publish
75
+ ```
76
+
77
+ A static HTTPS server with the headers this package requires (save it as `serve.mjs`):
78
+
79
+ <!-- docs-test: file serve.mjs -->
80
+ ```js
81
+ // A static HTTPS server with the model host's headers: node serve.mjs <directory> <port>
82
+ import { readFileSync } from 'node:fs';
83
+ import { createServer } from 'node:https';
84
+ import { resolve, sep } from 'node:path';
85
+ import { expectedType, IMMUTABLE_CACHE, MUTABLE_CACHE } from 'cloudflare-model-host';
86
+
87
+ const [dir, port] = process.argv.slice(2);
88
+ const root = resolve(dir);
89
+ const tls = { key: readFileSync('tls/key.pem'), cert: readFileSync('tls/cert.pem') };
90
+ const shared = {
91
+ 'Access-Control-Allow-Origin': '*',
92
+ 'Cross-Origin-Resource-Policy': 'cross-origin',
93
+ 'X-Content-Type-Options': 'nosniff',
94
+ // A page served from here is cross-origin isolated, so the engine's CPU route may use threads.
95
+ 'Cross-Origin-Opener-Policy': 'same-origin',
96
+ 'Cross-Origin-Embedder-Policy': 'require-corp',
97
+ };
98
+
99
+ createServer(tls, (req, res) => {
100
+ if (req.method === 'OPTIONS') return res.writeHead(204, shared).end();
101
+ const path = decodeURIComponent(new URL(req.url, 'https://localhost').pathname);
102
+ const file = resolve(root, `.${path.endsWith('/') ? `${path}index.html` : path}`);
103
+ let body;
104
+ try {
105
+ if (!file.startsWith(root + sep)) throw new Error('outside the root');
106
+ body = readFileSync(file);
107
+ } catch {
108
+ return res.writeHead(404, shared).end();
109
+ }
110
+ res.writeHead(200, {
111
+ ...shared,
112
+ 'Content-Type': expectedType(file),
113
+ 'Content-Length': body.length,
114
+ // Chunks are named by their digest and never change; everything else is revalidated.
115
+ 'Cache-Control': path.includes('/chunks/') ? IMMUTABLE_CACHE : MUTABLE_CACHE,
116
+ });
117
+ res.end(req.method === 'HEAD' ? undefined : body);
118
+ }).listen(Number(port), () => console.log(`serving ${root} at https://localhost:${port}/`));
119
+ ```
120
+
121
+ A certificate for `localhost`, then the model origin:
122
+
123
+ <!-- docs-test: run -->
124
+ ```sh
125
+ mkdir -p tls
126
+ openssl req -x509 -newkey rsa:2048 -nodes -days 7 -subj /CN=localhost \
127
+ -addext subjectAltName=DNS:localhost -keyout tls/key.pem -out tls/cert.pem
128
+ ```
129
+
130
+ <!-- docs-test: background 8443 -->
131
+ ```sh
132
+ node serve.mjs ./site 8443
133
+ ```
134
+
135
+ Check what the origin serves: every file's bytes and headers, every chunked asset's reconstruction, and the
136
+ manager's manifest contract. `NODE_EXTRA_CA_CERTS` lets Node trust the local certificate.
137
+
138
+ <!-- docs-test: run -->
139
+ ```sh
140
+ NODE_EXTRA_CA_CERTS=tls/cert.pem npx facemorph-model-host qualify-origin --root ./staged \
141
+ --origin https://localhost:8443 --base-path /models/ --immutable chunks/ --mutable manifest.json
142
+ ```
143
+
144
+ The page that loads it, served from a second origin. The manager's ES modules are copied next to it, so no bundler
145
+ is needed:
146
+
147
+ <!-- docs-test: run -->
148
+ ```sh
149
+ mkdir -p app
150
+ cp -r node_modules/browser-model-manager/dist app/manager
151
+ ```
152
+
153
+ <!-- docs-test: file app/index.html -->
154
+ ```html
155
+ <!doctype html>
156
+ <html lang="en">
157
+ <head>
158
+ <meta charset="utf-8" />
159
+ <title>Model host quickstart</title>
160
+ <script type="importmap">
161
+ { "imports": { "browser-model-manager": "./manager/index.js" } }
162
+ </script>
163
+ </head>
164
+ <body>
165
+ <button id="load">Download and verify the model</button>
166
+ <pre id="report"></pre>
167
+ <script type="module" src="./load.mjs"></script>
168
+ </body>
169
+ </html>
170
+ ```
171
+
172
+ <!-- docs-test: file app/load.mjs -->
173
+ ```js
174
+ import { createBrowserModelCache, parseModelManifest } from 'browser-model-manager';
175
+
176
+ const MODELS = 'https://localhost:8443/models/';
177
+ const OWNER = 'face:quickstart';
178
+ const hex = (buffer) =>
179
+ [...new Uint8Array(buffer)].map((b) => b.toString(16).padStart(2, '0')).join('');
180
+
181
+ async function load() {
182
+ const text = await (await fetch(`${MODELS}manifest.json`)).text();
183
+ const parsed = parseModelManifest(JSON.parse(text));
184
+ if (!parsed.ok) throw new Error(`${parsed.error.code} at ${parsed.error.path}`);
185
+ const m = parsed.value;
186
+ const assets = [m.mapping, m.synthesis, ...(m.average ? [m.average] : []), ...m.noise];
187
+ // What the person agreed to download: exactly these digests and bytes.
188
+ const grant = {
189
+ manifestSha256: hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))),
190
+ route: 'cpu',
191
+ purpose: 'generate',
192
+ owners: [OWNER],
193
+ assets: assets.map((a) => ({ sha256: a.sha256, bytes: a.size, priority: 'foreground-required' })),
194
+ remainingBytes: assets.reduce((n, a) => n + a.size, 0),
195
+ };
196
+ const cache = await createBrowserModelCache();
197
+ for (const asset of assets) await cache.acquire(asset, { grant, owner: OWNER });
198
+ // The engine reads through cache.local, which never fetches. Read every asset back to show it is held.
199
+ let bytes = 0;
200
+ for (const asset of assets) {
201
+ const read = await cache.local.read(asset);
202
+ if (!read.ok) throw new Error(`${asset.sha256}: ${read.error.code}`);
203
+ const digest = hex(await crypto.subtle.digest('SHA-256', read.value));
204
+ if (digest !== asset.sha256) throw new Error(`digest differs: ${asset.sha256}`);
205
+ bytes += read.value.byteLength;
206
+ }
207
+ return `verified ${assets.length} assets, ${bytes} bytes, from ${MODELS}`;
208
+ }
209
+
210
+ document.querySelector('#load').addEventListener('click', () => {
211
+ const report = document.querySelector('#report');
212
+ load().then(
213
+ (text) => (report.textContent = text),
214
+ (error) => (report.textContent = `failed: ${error.message}`),
215
+ );
216
+ });
217
+ ```
218
+
219
+ <!-- docs-test: background 8444 -->
220
+ ```sh
221
+ node serve.mjs ./app 8444
222
+ ```
223
+
224
+ Open `https://localhost:8443/models/manifest.json` once and accept the certificate warning, then open
225
+ `https://localhost:8444/` (accept it there too) and press the button. Nothing is downloaded before the press; the
226
+ report reads `verified 18 assets, …` for AFHQ cat.
227
+
228
+ **Then the engine.** Pass `cache.local` to the engine as its verified reader:
229
+ [stylegan-js's quick start](../stylegan-js/README.md#quick-start-load-a-model-and-make-a-face) and its
230
+ [non-face section](../stylegan-js/README.md#non-face-models) show the generator load, mapping and synthesis that
231
+ follow. The engine's ONNX Runtime JS and WASM files are model assets too: a runtime manifest names them, and they are
232
+ staged, published, served and acquired exactly like the model's own files.
233
+
234
+ ## Commands
235
+
236
+ Every command prints one JSON report on stdout. Exit codes are 0 for ok, 1 for a refusal, findings or failures, and 2
237
+ for a usage error. Nothing is written to a host and no Cloudflare API request is made without `--publish`.
238
+
239
+ - **Stage:** `facemorph-model-host stage --source <dir> --out <dir> --base <https url> [--from-base <url>]
240
+ [--manifest <name>] [--dry-run]`. Every asset the manifest names is checked against its declared SHA-256 and size
241
+ and copied to the same relative path. An asset over the 25 MiB file limit is published only as 16 MiB chunks,
242
+ `chunks/<sha256>.bin`; a chunk is written once and never changed. The manifest is rewritten to hosted URLs under
243
+ `--base`. The source can be an unpublished bundle (assets named by `file`, as model-conv writes them) or an already
244
+ hosted tree being restaged (`--from-base` maps its URLs back to paths). The manifest must pass
245
+ `browser-model-manager`'s contract before and after staging: a newer or unknown major is refused. Local
246
+ paths, `file://` URLs, sibling checkouts and private inventories (`sources.private.json`) never reach the staged
247
+ manifest. `--manifest` names a manifest file other than `manifest.json` in the source.
248
+ - **Verify:** `facemorph-model-host verify --root <dir> --base <https url> [--manifest <name>]
249
+ [--plan workers-free|workers-paid]`. Each asset is read back by its URL path, a chunked one through its chunks, and
250
+ must reproduce its digest and size. Every file must fit the per-file limit and the plan's file count (default
251
+ `workers-free`).
252
+ - **Qualify an origin:** `facemorph-model-host qualify-origin --root <dir> --origin <url> [--base-path /models/]
253
+ --immutable <prefixes> --mutable <files> [--reference <qualified-manifest.json>]`. Reads every file of the staged
254
+ root from the origin under the base path (default `/`) and checks its bytes, its headers (below), chunk
255
+ reconstruction and the manager's manifest contract. The optional reference requires the served manifest to name
256
+ exactly the reference's asset digests. It publishes nothing.
257
+ - **Publish:** `facemorph-model-host publish --root <dir> --target <target.json> [--publish]`. A dry run unless
258
+ `--publish` is given: it reads only, then reports each file it would write. The model terms are checked first
259
+ (below). A target is `{"kind": "directory", "path": ...}` (a static root, or a local mirror) or
260
+ `{"kind": "cloudflare", "project": <dir>, "product": ...}`, which runs `cf deploy` in that project directory. A
261
+ paid product is refused unless the target also names it in `"paidServiceApproved"`. An existing destination file
262
+ that differs is refused, never overwritten.
263
+ - **Model origin:** `facemorph-model-host origin-deploy --root <dir> --worker <name> --base-path /models/
264
+ --immutable <list> --mutable <list> [--workers-dev] [--domain <host>] [--compatibility-date <date>]
265
+ [--terms <record> [--acknowledge <row>]] [--publish]`. A staged root as its own origin on Workers Static Assets,
266
+ through `cf` in the package's `model-origin` mode: the root is served under the base path with `_headers` rules
267
+ (`src/headers.ts`), and the Worker has no script, so a model request never runs Worker code. Without `--publish` it
268
+ runs `cf deploy --dry-run`. Model terms are checked before anything is published.
269
+ - **Mirror deploy:** `facemorph-model-host mirror-deploy --worker <name> --bucket <r2 bucket> --upstream <url>
270
+ --prefixes <list> [--site <worker>] [--domain <host>] [--workers-dev] [--compatibility-date <date>] [--publish]`.
271
+ Deploys the mirror Worker (below) with the Cloudflare CLI `cf`, never Wrangler: the package root is the cf project
272
+ (`cloudflare.config.ts` reads every value from the arguments, `vite.config.ts` builds through the Cloudflare Vite
273
+ plugin). Without `--publish` it runs `cf deploy --dry-run`, which builds the Worker, lists its bindings and sends no
274
+ API request. The plugin is the 2.0 beta because its latest stable release (1.65.0) depends on Wrangler.
275
+ - **Warm:** `facemorph-model-host warm --root <dir> --origin <mirror url> --prefixes <list> [--publish]`. HEAD on
276
+ every immutable path of a staged root under the prefixes, 8 at a time, each retried up to 3 times on a network
277
+ error or 408/429/5xx. Any final non-200 fails the run, naming the path; the report gives the held count. A mirror
278
+ copies a file on HEAD, so without `--publish` nothing is requested.
279
+
280
+ `--compatibility-date` defaults to `2026-09-16`. `--workers-dev` also serves the Worker on
281
+ `<worker>.<account subdomain>.workers.dev`.
282
+
283
+ ## The staged root and its manifest
284
+
285
+ A staged root holds `manifest.json`, every asset at its relative path, and `chunks/` for assets over 25 MiB. Its
286
+ manifest is the manager's model manifest, major version 1
287
+ ([JSON schema](../browser-model-manager/schema/model-manifest.v1.schema.json)):
288
+
289
+ | Field | Meaning |
290
+ | --- | --- |
291
+ | `schemaVersion` | `1`. A newer or unknown major is refused by `stage`, `verify` and the manager. |
292
+ | `bundleVersion` | The producer's name for this bundle. |
293
+ | `modelSourceSha256` | SHA-256 of the source checkpoint; the model terms row must name it. |
294
+ | `noiseSha256` | Identity of the noise set. |
295
+ | `mapping`, `synthesis` | Required asset descriptors. |
296
+ | `average`, `noise[]` | Optional average latent; noise inputs, each an asset descriptor with `name` and `shape`. |
297
+ | `encoder`, `encoderStream`, `landmarks`, `kernel` | Optional photo-encoding and kernel entries. |
298
+ | anything else | Kept as parsed JSON (model-conv writes `model`, `tolerance`, `provenance`). |
299
+
300
+ An asset descriptor is `{ "url": "https://…", "sha256": "<64 lowercase hex>", "size": <bytes> }`, plus, when the
301
+ asset is chunked, `"chunks": [{ "url", "sha256", "size" }, …]` whose sizes add up to `size`. Before staging,
302
+ model-conv writes `"file": "<relative path>"` instead of `url`; a staged manifest has only `url`s, all under
303
+ `--base`.
304
+
305
+ ## Serving requirements
306
+
307
+ `qualify-origin` checks these on every file under the base path; `origin-deploy` writes them as `_headers` rules, and
308
+ the mirror Worker sends them itself.
309
+
310
+ | Header | Value | Why |
311
+ | --- | --- | --- |
312
+ | `Access-Control-Allow-Origin` | `*` | The page that loads the model is usually on another origin. |
313
+ | `Cross-Origin-Resource-Policy` | `cross-origin` | A page with `Cross-Origin-Embedder-Policy: require-corp` can load the file. |
314
+ | `X-Content-Type-Options` | `nosniff` | The declared type is the type. |
315
+ | `Content-Type` | `application/json` (`.json`), `application/wasm` (`.wasm`), `text/javascript` (`.js`, `.mjs`), `application/octet-stream` (`.bin`, `.onnx`, `.f32`, `.i32` and any extension not listed) | The manager and engine check bytes, not types, but a WASM or module import needs the right one. `expectedType()` gives the full list. |
316
+ | `Cache-Control` on immutable prefixes | `public, max-age=31536000, immutable` | Content-addressed files (`chunks/`) never change. |
317
+ | `Cache-Control` on mutable files | `no-cache` | The manifest pointer is revalidated on every use. |
318
+ | Status | `200` with the exact bytes | Every byte is checked against the manifest digest. |
319
+
320
+ Only content-addressed paths may be immutable. Other asset names (`mapping.onnx`, `noise_0.f32`) are reused by every
321
+ conversion, so publish each release under its own base path (for example `/models/afhqcat-v1/`) rather than caching
322
+ them as immutable at a shared path.
323
+
324
+ **Workers and WASM.** The engine's ONNX Runtime JS and WASM files are assets in a runtime manifest, served from the
325
+ same kind of root with the same headers; there is no separate `wasmPaths` location. They are read through the
326
+ verifying reader and imported from the verified bytes.
327
+
328
+ **COOP/COEP.** The page (not the model host) decides threading. A page served with `Cross-Origin-Opener-Policy:
329
+ same-origin` and `Cross-Origin-Embedder-Policy: require-corp` is cross-origin isolated, and the engine's CPU route
330
+ uses threads; every model file must then carry CORS and `Cross-Origin-Resource-Policy: cross-origin`, as above.
331
+ Without isolation the CPU route runs single-threaded, correctly but more slowly, and the same model host serves it
332
+ unchanged.
333
+
334
+ ## Second origin and warm
335
+
336
+ A second origin keeps chunk downloads working when the primary fails. It must serve the same files at the same paths;
337
+ the manager is told about it with `createBrowserModelCache({ alternateOrigins: ['https://<mirror origin>'] })`, and
338
+ every other retry of a chunk then goes to the next origin. This package's mirror Worker is such an origin: an R2
339
+ bucket that copies each immutable file from the upstream origin on first request, only under the configured
340
+ prefixes, and serves it with CORS, `Cross-Origin-Resource-Policy: cross-origin` and immutable caching. Its
341
+ configuration is `UPSTREAM` (the origin copied from), `PREFIXES` (comma-separated immutable prefixes), the `MIRROR`
342
+ R2 binding and an optional `SITE` service binding to the upstream Worker. Nothing about any deployment is built in.
343
+ `warm --publish` then requests every immutable path once, so the mirror holds them all before it is needed. The
344
+ [Cloudflare guide](docs/cloudflare.md#second-origin-an-r2-mirror) has the commands. Its tests run in workerd
345
+ (`npm run test:workerd`, which needs glibc 2.32 or newer).
346
+
347
+ <!-- facemorph-example:start -->
348
+ **Example: FaceMorph's own deployment.** FaceMorph serves its runtime from the site Worker at `next.facemorph.me`
349
+ under `/runtime/`, and its second origin is `models.facemorph.me`: this package's mirror Worker (Worker
350
+ `facemorph-models`) over the R2 bucket `facemorph-runtime-mirror`, with `UPSTREAM` the site origin, a `SITE` service
351
+ binding to the site Worker (`facemorph-next`), and `PREFIXES`
352
+ `runtime/assets/,runtime/chunks/,runtime/manifests/,runtime/photo/,runtime/encoder-stream/`. Its deploy runs
353
+ `mirror-deploy` with those values and then `warm --publish` against `https://models.facemorph.me/`.
354
+ <!-- facemorph-example:end -->
355
+
356
+ ## Cloudflare limits and cost
357
+
358
+ Read from developers.cloudflare.com on **24 October 2026**: Workers platform limits (static assets), Workers pricing,
359
+ Pages limits and R2 pricing. `src/limits.ts` holds the same figures; change both together. Rechecked on **27 October
360
+ 2026** (Cloudflare documentation search): the 25 MiB file limit, 20,000 (Free) and 100,000 (Paid) files per version,
361
+ free and unlimited static asset requests with no storage charge, and R2's free 10 GB-month, 1M Class A and 10M Class
362
+ B operations with free egress are unchanged.
363
+
364
+ | | |
365
+ | --- | --- |
366
+ | Chosen product and tier | Workers Static Assets on **Workers Free**. Pages has the same 25 MiB file limit and 20,000-file Free limit. |
367
+ | Per-file limit | 25 MiB on every plan. Larger inputs are published as 16 MiB chunks. |
368
+ | Files per version | 20,000 (Free), 100,000 (Paid) |
369
+ | Request routing | A request matching a static asset is served without invoking Worker code. Static asset requests are free and unlimited on both plans. The 100,000 requests/day Free limit applies only to Worker invocations. |
370
+ | Storage, request and bandwidth allowances | No separate storage charge for static assets; static asset requests free and unlimited; no egress charge. Enabling Workers Caching bills static asset requests at the Worker request rate, so it is not used here. |
371
+ | Paid alternatives (refused unless named) | Workers Paid: $5.00 per month subscription. R2 (Standard): $0.015 per GB-month, $4.50 per million Class A and $0.36 per million Class B operations beyond the free 10 GB-month, 1M Class A and 10M Class B per month; egress free. |
372
+ | Measured staged set: AFHQ cat 512 | The quickstart's model, staged on 27 October 2026: **26 files, 134,630,462 bytes**, 18 assets of which 1 (`synthesis`, 123,411,406 bytes) is chunked into 8 chunks. The largest file is 16,777,216 bytes (a chunk), under 25 MiB. 26 files fit Workers Free; an R2 mirror of it holds 0.13 GB, inside R2's free 10 GB-month. |
373
+ | Measured staged set: the qualified FFHQ runtime | The qualified runtime (manifest `d9e37e50…`) as acquired: **301 files, 2,766,791,005 bytes**, 81 assets of which 5 are chunked into 90 chunks. The largest file is 24,135,856 bytes (`b16-coefficients.bin`), under 25 MiB. 301 files fit Workers Free. `test/host.test.ts` checks this on every run where the runtime is present. |
374
+
375
+ **Model terms.** Before anything is written, the target must name a terms record: a JSON file with a `rows` list, each
376
+ row an object with an `id`. One row must cover the manifest's `modelSourceSha256` (the digest appears in the row). If
377
+ that row's `redistribution` is not `"permitted"`, the target must acknowledge the row by id (`"terms": {"record":
378
+ ..., "acknowledged": "<row id>"}`, or `--terms <record> --acknowledge <row id>` for `origin-deploy`).
379
+
380
+ <!-- facemorph-example:start -->
381
+ **Example: FaceMorph's own deployment.** FaceMorph's terms record is its repository's `import/licences.json`. For its
382
+ qualified FFHQ runtime, row `nvidia-stylegan2-ffhq-config-f-derived` is `unresolved` today, so publishing it needs
383
+ that explicit acknowledgement.
384
+ <!-- facemorph-example:end -->
385
+
386
+ **Model weights and their licence texts.** This package's code is MIT licensed; no model weights are included. The
387
+ weights it stages come under their own terms, separate from that licence and limited to non-commercial use. Publish
388
+ these texts beside the weights, under `notices/` next to the manifest, and point the manifest's
389
+ `distribution.notices` at their index:
390
+
391
+ <!-- model-terms:start -->
392
+ - NVIDIA StyleGAN2 licence: [upstream text](https://github.com/NVlabs/stylegan2/blob/master/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-NC.txt`
393
+ - NVIDIA StyleGAN2-ADA licence: [upstream text](https://github.com/NVlabs/stylegan2-ada-pytorch/blob/main/LICENSE.txt); served beside the weights as `notices/NVIDIA-StyleGAN2-ADA.txt`
394
+ - FFHQ dataset terms: [upstream text](https://github.com/NVlabs/ffhq-dataset#licenses); served beside the weights as `notices/FFHQ-terms.txt`
395
+ - e4e MIT licence: [upstream text](https://github.com/omertov/encoder4editing/blob/main/LICENSE); served beside the weights as `notices/e4e-MIT.txt`
396
+ - dlib landmark model notice: [upstream text](https://www.dlib.net/face_landmark_detection_ex.cpp.html); served beside the weights as `notices/index.html#dlib-landmarks`
397
+ <!-- model-terms:end -->
398
+
399
+ ## Testing
400
+
401
+ `npm test` runs the unit tests and the docs test (`test/docs.test.ts`), which packs this package, the manager and
402
+ the engine fresh, installs the tarballs in a clean project outside the repository and runs every code block in this
403
+ README and the guides. `npm run test:workerd` runs the mirror Worker and the `cf deploy --dry-run` builds in workerd.
404
+ `npm run test:staging` checks deployed test origins (`STAGING_ORIGIN`, `STAGING_MIRROR`). Publishing a real model is
405
+ a deployment step, and this package's tests do not run it: the directory target is tested with real writes,
406
+ `origin-deploy` and `mirror-deploy` as `cf deploy --dry-run` builds, and the `cloudflare` publish target's `cf deploy`
407
+ is untested here.
408
+
409
+ ## Extraction history
410
+
411
+ This package's code was extracted from an earlier application. Nothing here is needed to use the package; it records
412
+ where each file of the earlier hosting tree went, and the repository's inventory check reads the table below.
413
+
414
+ <!-- facemorph-example:start -->
415
+ **Example: FaceMorph's own extraction history.** The package was extracted from classic FaceMorph's
416
+ `hosting/next/prepare-runtime.py` (chunking and manifest rewriting) and `src/Next/browser/stage-assets.py`
417
+ (content-addressed staging), and the mirror Worker from classic `hosting/next-mirror/` (fm-3osh, fm-fy2.14;
418
+ provenance in `mirror/provenance.json`). Application policy stays in the app's `hosting/`: phone admission,
419
+ promotion, the photo sub-bundle, frontend staging, and the deploy values it serves with.
420
+
421
+ ### Boundary assignment table
422
+
423
+ Every file in classic's `hosting/` tree at the frozen revision has one destination: this package, the app's
424
+ `hosting/`, `historical` (kept only as history) or `split` (the reason names both homes).
425
+
426
+ | path | destination | reason |
427
+ |---|---|---|
428
+ | hosting/gallery/.gitignore | hosting/ | catalogue pipeline support file; moves with hosting/gallery (fm-8tyu) |
429
+ | hosting/gallery/README.md | hosting/ | catalogue pipeline documentation |
430
+ | hosting/gallery/hello-provenance.md | hosting/ | catalogue pipeline provenance note |
431
+ | hosting/gallery/materialize.py | hosting/ | catalogue materialization (name-catalogue.yml) |
432
+ | hosting/gallery/names-wrangler.jsonc | hosting/ | catalogue Worker config (facemorph-name-catalogue) |
433
+ | hosting/gallery/wrangler.jsonc | hosting/ | seed-gallery Worker config; catalogue pipeline, not model hosting |
434
+ | hosting/next-cloudflare/.wrangler/cache/cf.json | historical | committed local wrangler state; junk, kept only as history, not imported |
435
+ | hosting/next-cloudflare/.wrangler/state/v3/kv/miniflare-KVNamespaceObject/922797108c590c411b100c31f46f14b4f223ce83273448eaefdac5350561025a.sqlite | historical | committed local miniflare KV state; junk, kept only as history, not imported |
436
+ | hosting/next-cloudflare/.wrangler/state/v3/kv/miniflare-KVNamespaceObject/922797108c590c411b100c31f46f14b4f223ce83273448eaefdac5350561025a.sqlite-shm | historical | committed local miniflare KV state; junk, kept only as history, not imported |
437
+ | hosting/next-cloudflare/.wrangler/state/v3/kv/miniflare-KVNamespaceObject/922797108c590c411b100c31f46f14b4f223ce83273448eaefdac5350561025a.sqlite-wal | historical | committed local miniflare KV state; junk, kept only as history, not imported |
438
+ | hosting/next-cloudflare/README.md | hosting/ | diagnostics collector documentation (collector stays with the app) |
439
+ | hosting/next-cloudflare/delete-run.mjs | hosting/ | diagnostics collector retention tool (ws-diag) |
440
+ | hosting/next-cloudflare/validation.mjs | hosting/ | diagnostics validation, imported by src/Next/reporting.test.mjs (app-side) |
441
+ | hosting/next-cloudflare/worker.mjs | hosting/ | diagnostics collector Worker (stays with the app, not model hosting) |
442
+ | hosting/next-cloudflare/worker.test.mjs | hosting/ | collector tests travel with the collector |
443
+ | hosting/next-cloudflare/wrangler.toml | hosting/ | collector Worker config (route next.facemorph.me/diagnostics/*) |
444
+ | hosting/next-mirror/worker.mjs | packages/cloudflare-model-host | mirror serving Worker (R2 facemorph-runtime-mirror, copies immutable prefixes via SITE binding) |
445
+ | hosting/next-mirror/worker.test.mjs | packages/cloudflare-model-host | mirror Worker tests travel with the mirror |
446
+ | hosting/next-mirror/wrangler.jsonc | packages/cloudflare-model-host | mirror Worker config (bindings MIRROR + SITE); deploy step itself is re-homed by hosting/ deploy (fm-8tyu) |
447
+ | hosting/next-static/.gitignore | hosting/ | staging support file for the next-static staging area |
448
+ | hosting/next-static/README.md | hosting/ | staging model documentation (frontend staging stays in hosting/) |
449
+ | hosting/next-static/analytics.mjs | hosting/ | pageview counter, app-side (currently disabled) |
450
+ | hosting/next-static/analytics.test.mjs | hosting/ | analytics tests travel with analytics |
451
+ | hosting/next-static/attach-domain.py | hosting/ | domain attach is an app/domain operation, not model hosting |
452
+ | hosting/next-static/catalogue.json | hosting/ | names catalogue data staged into the site; catalogue pipeline (ws-names) |
453
+ | hosting/next-static/mirror-runtime.py | packages/cloudflare-model-host | rebuilds the runtime from pinned manifests with digest verification: digest-consistent publication + mirror serving machinery |
454
+ | hosting/next-static/promote.py | hosting/ | promotion gates and wrangler publish of the site: promotion stays in hosting/ |
455
+ | hosting/next-static/restage-runtime.py | split | overlay writing + chunk/manifest rebuild functions go to packages/cloudflare-model-host; review-artifact orchestration glue stays in hosting/ staging |
456
+ | hosting/next-static/runtime-overlay/assets/2d71c033d9812f5fb4f548de7451667cc780f0b4ab311e7c5a929e279b9ceac5/split-segment.json | packages/cloudflare-model-host | content-addressed overlay asset consumed by the manifest/publication machinery |
457
+ | hosting/next-static/runtime-overlay/assets/6ee1eb7a0a894488e450242d72cb27b10a22b0b82b9aee9b4127c58efffb52f2/fused-resample-v1.mjs | packages/cloudflare-model-host | content-addressed overlay asset (fused-resample kernel) pinned by the publication manifest |
458
+ | hosting/next-static/runtime-overlay/manifest.json | packages/cloudflare-model-host | the production manifest pin: schema + materialization belong to the package's manifest generation |
459
+ | hosting/next-static/stage.py | hosting/ | frontend staging (assembles public/ from runtime + frontend + catalogue) |
460
+ | hosting/next-static/webgpu_contract.py | split | contract-check functions (served bundle matches shipped engine) go to packages/cloudflare-model-host qualification; runner glue stays in hosting/ staging |
461
+ | hosting/next-static/webgpu_contract_test.py | split | tests travel with webgpu_contract.py: assertions to packages/cloudflare-model-host, fixtures/runner glue to hosting/ |
462
+ | hosting/next-static/worker.mjs | hosting/ | entry site Worker (assets + /diagnostics routing): app-side |
463
+ | hosting/next-static/wrangler.jsonc | hosting/ | entry site Worker config (facemorph-next): app-side |
464
+ | hosting/next/.gitignore | hosting/ | support file for the historical preview area |
465
+ | hosting/next/compose.yml | historical | preview+tunnel stack; classic-only, must not be referenced by the final site |
466
+ | hosting/next/configure-tunnel.py | historical | tunnel provisioning for the retired preview origin |
467
+ | hosting/next/notices/NVIDIA-StyleGAN2-ADA.txt | hosting/ | licence notices shipped at /runtime/notices: staging content |
468
+ | hosting/next/notices/ONNX-Runtime-1.22-ThirdPartyNotices.txt | hosting/ | licence notices shipped at /runtime/notices: staging content |
469
+ | hosting/next/notices/ONNX-Runtime-MIT.txt | hosting/ | licence notices shipped at /runtime/notices: staging content |
470
+ | hosting/next/notices/ONNX-Runtime-ThirdPartyNotices.txt | hosting/ | licence notices shipped at /runtime/notices: staging content |
471
+ | hosting/next/notices/e4e-MIT.txt | hosting/ | licence notices shipped at /runtime/notices: staging content |
472
+ | hosting/next/notices/index.html | hosting/ | notices index page shipped at /runtime/notices: staging content |
473
+ | hosting/next/phone-candidate-admission.json | hosting/ | device admission receipt consumed via prepare-runtime --phone-admission; staging input |
474
+ | hosting/next/photo-canary-provenance.json | hosting/ | canary fixture provenance; staging input documentation |
475
+ | hosting/next/prepare-runtime.py | packages/cloudflare-model-host | chunking (>25 MiB -> 16 MiB verified chunks) + manifest/qualification-manifest generation: core package machinery |
476
+ | hosting/next/server.py | historical | private preview origin with bounded diagnostics writer; classic-only |
477
+ | hosting/next/test_prepare_runtime.py | packages/cloudflare-model-host | travels with prepare-runtime.py chunking/manifest logic |
478
+ | hosting/next/test_server.py | historical | travels with server.py (classic-only preview) |
479
+
480
+ Run from the repository root:
481
+
482
+ node scripts/inventory/check-hosting-boundary.mjs
483
+ node scripts/inventory/check-hosting-boundary.mjs --rev <sha>
484
+ <!-- facemorph-example:end -->
@@ -0,0 +1,12 @@
1
+ cloudflare-model-host bundles no third-party code. Its emitted JavaScript imports only Node.js built-in modules and,
2
+ for manifest validation, browser-model-manager from the same repository.
3
+
4
+ npm installs these dependencies separately, each under its own licence; none of their code is copied into this
5
+ package:
6
+ - cf (Cloudflare's command line), which the Cloudflare commands (origin-deploy, mirror-deploy, publish) run;
7
+ - vite and @cloudflare/vite-plugin, which the shipped cloudflare.config.ts and vite.config.ts import when cf builds
8
+ the optional Cloudflare Workers.
9
+ The generic static-hosting commands (stage, verify, qualify-origin, warm) do not use them.
10
+
11
+ The model bytes it stages are not part of this package; their terms are recorded per model (see the README's
12
+ "Model terms").
@@ -0,0 +1,44 @@
1
+ // The package's cf project (fm-fy2.14), in two modes. Every deploy value comes from variables the package's commands
2
+ // set from their arguments, so this file names no host.
3
+ // - default: the mirror Worker (MIRROR_*, set by `facemorph-model-host mirror-deploy`, src/mirror/deploy.ts);
4
+ // - model-origin: a staged model root on Workers Static Assets with no Worker script (MODEL_ORIGIN_*, set by
5
+ // src/origin-deploy.ts); vite.config.ts makes the root the assets.
6
+ import { bindings, defineConfig } from 'cf/config';
7
+
8
+ const need = (name: string): string => {
9
+ const value = process.env[name];
10
+ if (!value) throw new Error(`${name} is not set: deploy with facemorph-model-host`);
11
+ return value;
12
+ };
13
+ const optional = (name: string) => process.env[name] || undefined;
14
+
15
+ export default defineConfig(({ mode }) =>
16
+ mode === 'model-origin'
17
+ ? {
18
+ worker: {
19
+ name: need('MODEL_ORIGIN_WORKER'),
20
+ compatibilityDate: need('MODEL_ORIGIN_COMPATIBILITY_DATE'),
21
+ workersDev: process.env['MODEL_ORIGIN_WORKERS_DEV'] === '1',
22
+ ...(optional('MODEL_ORIGIN_DOMAIN') ? { domains: [need('MODEL_ORIGIN_DOMAIN')] } : {}),
23
+ observability: { enabled: false },
24
+ },
25
+ }
26
+ : {
27
+ worker: {
28
+ name: need('MIRROR_WORKER'),
29
+ compatibilityDate: need('MIRROR_COMPATIBILITY_DATE'),
30
+ entrypoint: './src/mirror/worker.ts',
31
+ workersDev: process.env['MIRROR_WORKERS_DEV'] === '1',
32
+ ...(optional('MIRROR_DOMAIN') ? { domains: [need('MIRROR_DOMAIN')] } : {}),
33
+ observability: { enabled: false },
34
+ env: {
35
+ MIRROR: bindings.r2({ name: need('MIRROR_BUCKET') }),
36
+ SITE: optional('MIRROR_SITE_WORKER')
37
+ ? bindings.worker({ worker: need('MIRROR_SITE_WORKER') })
38
+ : undefined,
39
+ UPSTREAM: bindings.text(need('MIRROR_UPSTREAM')),
40
+ PREFIXES: bindings.text(need('MIRROR_PREFIXES')),
41
+ },
42
+ },
43
+ },
44
+ );
@@ -0,0 +1,35 @@
1
+ export interface ChunkDescriptor {
2
+ /** Path of the chunk relative to the published root, `chunks/<sha256>.bin`. */
3
+ readonly path: string;
4
+ readonly sha256: string;
5
+ readonly size: number;
6
+ }
7
+ export declare const sha256Hex: (bytes: Uint8Array) => string;
8
+ /** A file's digest and size, read in CHUNK_BYTES pieces so a gigabyte input never sits in memory at once. */
9
+ export declare function fileDigest(path: string): {
10
+ readonly sha256: string;
11
+ readonly size: number;
12
+ };
13
+ /** Whether an input of this size is published as chunks. */
14
+ export declare const needsChunks: (size: number) => boolean;
15
+ /** The chunk sizes for an input: full CHUNK_BYTES pieces, then the remainder. */
16
+ export declare function chunkSizes(size: number, chunkBytes?: number): number[];
17
+ /**
18
+ * Cuts `source` into chunks under `root`, freezing each one: an existing chunk must hold the same bytes, or this
19
+ * throws (`Immutable destination changed`). Returns the chunk descriptors in order. Writes nothing when `dryRun`.
20
+ */
21
+ export declare function writeChunks(source: string, root: string, options?: {
22
+ readonly dryRun?: boolean;
23
+ }): ChunkDescriptor[];
24
+ export interface Reconstruction {
25
+ readonly sha256: string;
26
+ readonly size: number;
27
+ readonly problems: readonly {
28
+ readonly path: string;
29
+ readonly problem: string;
30
+ }[];
31
+ }
32
+ /** Reads the chunks in order from `root`, checking each against its own digest, and digests the whole. */
33
+ export declare function reconstruct(chunks: readonly ChunkDescriptor[], root: string): Reconstruction;
34
+ /** Writes `bytes` at `path` once; a later write must be byte-identical. */
35
+ export declare function freeze(path: string, bytes: Uint8Array): void;