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/dist/chunks.js ADDED
@@ -0,0 +1,97 @@
1
+ // Chunking and reconstruction (fm-3osh), from classic hosting/next/prepare-runtime.py: an input above the static
2
+ // file limit is cut into CHUNK_BYTES pieces named by their own SHA-256 (chunks/<sha>.bin), written once and
3
+ // never changed; reconstruction reads them in order and must reproduce the asset's declared digest and size.
4
+ import { createHash } from 'node:crypto';
5
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync, } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { CHUNK_BYTES, STATIC_ASSET_FILE_LIMIT_BYTES } from './limits.js';
8
+ export const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
+ /** A file's digest and size, read in CHUNK_BYTES pieces so a gigabyte input never sits in memory at once. */
10
+ export function fileDigest(path) {
11
+ const hash = createHash('sha256');
12
+ let size = 0;
13
+ forEachPiece(path, CHUNK_BYTES, (piece) => {
14
+ hash.update(piece);
15
+ size += piece.length;
16
+ });
17
+ return { sha256: hash.digest('hex'), size };
18
+ }
19
+ /** Whether an input of this size is published as chunks. */
20
+ export const needsChunks = (size) => size > STATIC_ASSET_FILE_LIMIT_BYTES;
21
+ /** The chunk sizes for an input: full CHUNK_BYTES pieces, then the remainder. */
22
+ export function chunkSizes(size, chunkBytes = CHUNK_BYTES) {
23
+ if (!Number.isSafeInteger(size) || size < 0)
24
+ throw new RangeError(`invalid size ${size}`);
25
+ const out = [];
26
+ for (let at = 0; at < size; at += chunkBytes)
27
+ out.push(Math.min(chunkBytes, size - at));
28
+ return out;
29
+ }
30
+ /**
31
+ * Cuts `source` into chunks under `root`, freezing each one: an existing chunk must hold the same bytes, or this
32
+ * throws (`Immutable destination changed`). Returns the chunk descriptors in order. Writes nothing when `dryRun`.
33
+ */
34
+ export function writeChunks(source, root, options = {}) {
35
+ const out = [];
36
+ forEachPiece(source, CHUNK_BYTES, (piece) => {
37
+ const sha256 = sha256Hex(piece);
38
+ const path = `chunks/${sha256}.bin`;
39
+ if (!options.dryRun)
40
+ freeze(join(root, path), piece);
41
+ out.push({ path, sha256, size: piece.length });
42
+ });
43
+ return out;
44
+ }
45
+ /** Reads the chunks in order from `root`, checking each against its own digest, and digests the whole. */
46
+ export function reconstruct(chunks, root) {
47
+ const hash = createHash('sha256');
48
+ const problems = [];
49
+ let size = 0;
50
+ for (const c of chunks) {
51
+ const path = join(root, c.path);
52
+ if (!existsSync(path)) {
53
+ problems.push({ path: c.path, problem: 'missing' });
54
+ continue;
55
+ }
56
+ const bytes = readFileSync(path);
57
+ if (bytes.length !== c.size || sha256Hex(bytes) !== c.sha256)
58
+ problems.push({ path: c.path, problem: 'chunk digest differs' });
59
+ hash.update(bytes);
60
+ size += bytes.length;
61
+ }
62
+ return { sha256: hash.digest('hex'), size, problems };
63
+ }
64
+ /** Writes `bytes` at `path` once; a later write must be byte-identical. */
65
+ export function freeze(path, bytes) {
66
+ if (existsSync(path)) {
67
+ const have = readFileSync(path);
68
+ if (have.length !== bytes.length || !have.equals(bytes))
69
+ throw new Error(`Immutable destination changed: ${path}`);
70
+ return;
71
+ }
72
+ mkdirSync(dirname(path), { recursive: true });
73
+ writeFileSync(path, bytes, { flag: 'wx' });
74
+ }
75
+ function forEachPiece(path, pieceBytes, each) {
76
+ const fd = openSync(path, 'r');
77
+ try {
78
+ const buffer = Buffer.allocUnsafe(pieceBytes);
79
+ for (;;) {
80
+ let filled = 0;
81
+ while (filled < pieceBytes) {
82
+ const n = readSync(fd, buffer, filled, pieceBytes - filled, null);
83
+ if (n === 0)
84
+ break;
85
+ filled += n;
86
+ }
87
+ if (filled === 0)
88
+ break;
89
+ each(Buffer.from(buffer.subarray(0, filled)));
90
+ if (filled < pieceBytes)
91
+ break;
92
+ }
93
+ }
94
+ finally {
95
+ closeSync(fd);
96
+ }
97
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function main(argv: readonly string[]): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ // facemorph-model-host: stage, verify and publish model bytes (fm-3osh). One JSON report on stdout.
3
+ // facemorph-model-host stage --source <dir> --out <dir> --base <https url> [--from-base <url>] [--manifest <name>] [--dry-run]
4
+ // facemorph-model-host verify --root <dir> --base <https url> [--manifest <name>] [--plan workers-free|workers-paid]
5
+ // facemorph-model-host publish --root <dir> --target <target.json> [--publish]
6
+ // facemorph-model-host warm --root <dir> --origin <mirror url> --prefixes <list> [--publish]
7
+ // facemorph-model-host mirror-deploy --worker <name> --bucket <r2 bucket> --upstream <url> --prefixes <list>
8
+ // [--site <worker>] [--domain <host>] [--workers-dev] [--compatibility-date <date>]
9
+ // [--publish]
10
+ // facemorph-model-host origin-deploy --root <dir> --worker <name> --base-path <path> --immutable <list>
11
+ // --mutable <list> [--workers-dev] [--domain <host>] [--terms <record>]
12
+ // [--acknowledge <terms row>] [--publish]
13
+ // publish, warm and mirror-deploy write nothing unless --publish is given (warm's HEAD makes the mirror copy a file;
14
+ // mirror-deploy runs cf deploy --dry-run). Exit 0 ok, 1 refused, findings or failures, 2 usage error.
15
+ import { readFileSync } from 'node:fs';
16
+ import { parseArgs } from 'node:util';
17
+ import { deployMirror } from './mirror/deploy.js';
18
+ import { deployModelOrigin } from './origin-deploy.js';
19
+ import { warm } from './mirror/warm.js';
20
+ import { publishRoot } from './publish.js';
21
+ import { qualifyOrigin } from './qualify.js';
22
+ import { stage, StageError } from './stage.js';
23
+ import { verifyRoot } from './verify.js';
24
+ const USAGE = 'usage: facemorph-model-host <stage|verify|qualify-origin|publish|warm|mirror-deploy|origin-deploy> [options] (see the package README)';
25
+ export async function main(argv) {
26
+ const [command, ...rest] = argv;
27
+ let values;
28
+ try {
29
+ ({ values } = parseArgs({
30
+ args: [...rest],
31
+ options: {
32
+ source: { type: 'string' },
33
+ out: { type: 'string' },
34
+ base: { type: 'string' },
35
+ 'from-base': { type: 'string' },
36
+ manifest: { type: 'string' },
37
+ reference: { type: 'string' },
38
+ 'dry-run': { type: 'boolean' },
39
+ root: { type: 'string' },
40
+ plan: { type: 'string' },
41
+ target: { type: 'string' },
42
+ publish: { type: 'boolean' },
43
+ origin: { type: 'string' },
44
+ prefixes: { type: 'string' },
45
+ worker: { type: 'string' },
46
+ bucket: { type: 'string' },
47
+ upstream: { type: 'string' },
48
+ site: { type: 'string' },
49
+ domain: { type: 'string' },
50
+ 'compatibility-date': { type: 'string' },
51
+ 'base-path': { type: 'string' },
52
+ immutable: { type: 'string' },
53
+ mutable: { type: 'string' },
54
+ 'workers-dev': { type: 'boolean' },
55
+ terms: { type: 'string' },
56
+ acknowledge: { type: 'string' },
57
+ },
58
+ strict: true,
59
+ }));
60
+ }
61
+ catch (e) {
62
+ console.error(`${e.message}\n${USAGE}`);
63
+ return 2;
64
+ }
65
+ const need = (...names) => {
66
+ const missing = names.filter((n) => typeof values[n] !== 'string');
67
+ if (missing.length)
68
+ console.error(`missing ${missing.map((n) => `--${n}`).join(', ')}\n${USAGE}`);
69
+ return missing.length === 0;
70
+ };
71
+ const str = (n) => typeof values[n] === 'string' ? values[n] : undefined;
72
+ const print = (v) => console.log(JSON.stringify(v));
73
+ try {
74
+ if (command === 'stage') {
75
+ if (!need('source', 'out', 'base'))
76
+ return 2;
77
+ const fromBase = str('from-base');
78
+ const manifest = str('manifest');
79
+ const r = stage({
80
+ source: str('source'),
81
+ out: str('out'),
82
+ base: str('base'),
83
+ ...(fromBase ? { fromBase } : {}),
84
+ ...(manifest ? { manifest } : {}),
85
+ dryRun: values['dry-run'] === true,
86
+ });
87
+ print({
88
+ staged: !values['dry-run'],
89
+ assets: r.assets,
90
+ chunked: r.chunked,
91
+ files: r.files.length,
92
+ bytes: r.files.reduce((n, f) => n + f.bytes, 0),
93
+ });
94
+ return 0;
95
+ }
96
+ if (command === 'qualify-origin') {
97
+ if (!need('root', 'origin', 'immutable', 'mutable'))
98
+ return 2;
99
+ const basePath = str('base-path');
100
+ const reference = str('reference');
101
+ const report = await qualifyOrigin({
102
+ root: str('root'),
103
+ origin: str('origin'),
104
+ immutable: str('immutable').split(',').filter(Boolean),
105
+ mutable: str('mutable').split(',').filter(Boolean),
106
+ ...(basePath ? { basePath } : {}),
107
+ ...(reference ? { reference: JSON.parse(readFileSync(reference, 'utf8')) } : {}),
108
+ });
109
+ print(report);
110
+ return report.ok ? 0 : 1;
111
+ }
112
+ if (command === 'verify') {
113
+ if (!need('root', 'base'))
114
+ return 2;
115
+ const plan = (str('plan') ?? 'workers-free');
116
+ if (plan !== 'workers-free' && plan !== 'workers-paid')
117
+ return (console.error(USAGE), 2);
118
+ const manifest = str('manifest');
119
+ const r = verifyRoot({
120
+ root: str('root'),
121
+ base: str('base'),
122
+ plan,
123
+ ...(manifest ? { manifest } : {}),
124
+ });
125
+ print(r);
126
+ return r.ok ? 0 : 1;
127
+ }
128
+ if (command === 'publish') {
129
+ if (!need('root', 'target'))
130
+ return 2;
131
+ const target = JSON.parse(readFileSync(str('target'), 'utf8'));
132
+ const r = publishRoot(str('root'), target, { publish: values.publish === true });
133
+ print({ ...r, writes: r.writes.length });
134
+ return r.refused ? 1 : 0;
135
+ }
136
+ if (command === 'warm') {
137
+ if (!need('root', 'origin', 'prefixes'))
138
+ return 2;
139
+ const r = await warm({
140
+ root: str('root'),
141
+ origin: str('origin'),
142
+ prefixes: str('prefixes'),
143
+ publish: values.publish === true,
144
+ });
145
+ print(r);
146
+ return r.failed.length ? 1 : 0;
147
+ }
148
+ if (command === 'origin-deploy') {
149
+ if (!need('root', 'worker', 'base-path', 'immutable', 'mutable'))
150
+ return 2;
151
+ const list = (n) => str(n)
152
+ .split(',')
153
+ .map((x) => x.trim())
154
+ .filter(Boolean);
155
+ const domain = str('domain');
156
+ const date = str('compatibility-date');
157
+ const terms = str('terms');
158
+ const acknowledged = str('acknowledge');
159
+ const r = deployModelOrigin(str('root'), {
160
+ worker: str('worker'),
161
+ basePath: str('base-path'),
162
+ immutable: list('immutable'),
163
+ mutable: list('mutable'),
164
+ workersDev: values['workers-dev'] === true,
165
+ ...(domain ? { domain } : {}),
166
+ ...(date ? { compatibilityDate: date } : {}),
167
+ ...(terms ? { terms: { record: terms, ...(acknowledged ? { acknowledged } : {}) } } : {}),
168
+ }, { publish: values.publish === true });
169
+ console.error(r.output);
170
+ print({ published: r.published, status: r.status, refused: r.refused });
171
+ return r.status === 0 && !r.refused ? 0 : 1;
172
+ }
173
+ if (command === 'mirror-deploy') {
174
+ if (!need('worker', 'bucket', 'upstream', 'prefixes'))
175
+ return 2;
176
+ const site = str('site');
177
+ const domain = str('domain');
178
+ const date = str('compatibility-date');
179
+ const r = deployMirror({
180
+ worker: str('worker'),
181
+ bucket: str('bucket'),
182
+ upstream: str('upstream'),
183
+ prefixes: str('prefixes'),
184
+ ...(site ? { site } : {}),
185
+ ...(domain ? { domain } : {}),
186
+ ...(date ? { compatibilityDate: date } : {}),
187
+ workersDev: values['workers-dev'] === true,
188
+ }, { publish: values.publish === true });
189
+ console.error(r.output);
190
+ print({ published: r.published, status: r.status });
191
+ return r.status === 0 ? 0 : 1;
192
+ }
193
+ }
194
+ catch (e) {
195
+ if (e instanceof StageError) {
196
+ print({ error: e.code, message: e.message });
197
+ return 1;
198
+ }
199
+ throw e;
200
+ }
201
+ console.error(USAGE);
202
+ return 2;
203
+ }
204
+ if (import.meta.main)
205
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,34 @@
1
+ /** What a staged root serves, relative to its base path. */
2
+ export interface HeaderPlan {
3
+ /** The URL path the root is served under, e.g. /runtime/ (default /). */
4
+ readonly basePath?: string;
5
+ /** Immutable, content-addressed prefixes, e.g. assets/, chunks/. */
6
+ readonly immutable: readonly string[];
7
+ /** Mutable files revalidated on every use, e.g. manifest.json. */
8
+ readonly mutable: readonly string[];
9
+ /** The file extensions the root holds (without the dot); those the upload does not type get one. */
10
+ readonly extensions?: readonly string[];
11
+ }
12
+ export declare const IMMUTABLE_CACHE = "public, max-age=31536000, immutable";
13
+ export declare const MUTABLE_CACHE = "no-cache";
14
+ /** The `_headers` file for a staged root. Pure. */
15
+ export declare function modelHeaders(plan: HeaderPlan): string;
16
+ /** The Content-Type a model file must be served with, by extension (application/octet-stream when unknown). */
17
+ export declare function expectedType(path: string): string;
18
+ /** The extensions of `paths`, for HeaderPlan.extensions. Pure. */
19
+ export declare function extensionsOf(paths: readonly string[]): string[];
20
+ export interface HeaderFinding {
21
+ readonly path: string;
22
+ readonly header: string;
23
+ readonly expected: string;
24
+ readonly actual: string | null;
25
+ }
26
+ /** Every required header `headers` lacks for `path` under `plan`. Pure. */
27
+ export declare function judgeHeaders(plan: HeaderPlan, path: string, status: number, headers: {
28
+ get(name: string): string | null;
29
+ }): HeaderFinding[];
30
+ /** Fetches each path from `origin` (GET, body discarded) and judges its headers. */
31
+ export declare function checkHeaders(origin: string, plan: HeaderPlan, paths: readonly string[]): Promise<{
32
+ readonly checked: number;
33
+ readonly findings: readonly HeaderFinding[];
34
+ }>;
@@ -0,0 +1,94 @@
1
+ // Serving headers for a staged model root (fm-fy2.14). A page with Cross-Origin-Embedder-Policy: require-corp can
2
+ // load model files from this origin or another only when each answers with CORS and Cross-Origin-Resource-Policy;
3
+ // immutable, content-addressed files are cached for a year, and the mutable manifest pointer is revalidated every
4
+ // time. Workers Static Assets applies a `_headers` file at the root without running any Worker code, so serving a
5
+ // model file never invokes a Worker. The rules are classic hosting/next-static/stage.py's runtime rules, plus a
6
+ // Content-Type for each extension the asset upload leaves untyped: on 25 October the staging origin served .f32,
7
+ // .i32 and .onnx files with no Content-Type at all.
8
+ /** Content types by extension; the upload attaches these itself (seen on the staging origin, 25 October). */
9
+ const TYPES = {
10
+ json: 'application/json',
11
+ js: 'text/javascript',
12
+ mjs: 'text/javascript',
13
+ wasm: 'application/wasm',
14
+ png: 'image/png',
15
+ webp: 'image/webp',
16
+ jpg: 'image/jpeg',
17
+ svg: 'image/svg+xml',
18
+ txt: 'text/plain',
19
+ html: 'text/html',
20
+ css: 'text/css',
21
+ bin: 'application/octet-stream',
22
+ };
23
+ const extensionOf = (path) => /\.([A-Za-z0-9]+)$/.exec(path)?.[1]?.toLowerCase();
24
+ export const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';
25
+ export const MUTABLE_CACHE = 'no-cache';
26
+ const base = (plan) => {
27
+ const b = plan.basePath ?? '/';
28
+ return `${b.startsWith('/') ? '' : '/'}${b}${b.endsWith('/') ? '' : '/'}`;
29
+ };
30
+ /** The `_headers` file for a staged root. Pure. */
31
+ export function modelHeaders(plan) {
32
+ const b = base(plan);
33
+ const lines = [
34
+ `${b}*`,
35
+ ' Access-Control-Allow-Origin: *',
36
+ ' Cross-Origin-Resource-Policy: cross-origin',
37
+ ' X-Content-Type-Options: nosniff',
38
+ ];
39
+ for (const prefix of plan.immutable)
40
+ lines.push(`${b}${prefix.replace(/\/?$/, '/')}*`, ` Cache-Control: ${IMMUTABLE_CACHE}`);
41
+ for (const file of plan.mutable)
42
+ lines.push(`${b}${file}`, ` Cache-Control: ${MUTABLE_CACHE}`);
43
+ for (const ext of [...new Set(plan.extensions ?? [])].sort())
44
+ if (!TYPES[ext.toLowerCase()])
45
+ lines.push(`${b}*.${ext}`, ' Content-Type: application/octet-stream');
46
+ return `${lines.join('\n')}\n`;
47
+ }
48
+ /** The Content-Type a model file must be served with, by extension (application/octet-stream when unknown). */
49
+ export function expectedType(path) {
50
+ return TYPES[extensionOf(path) ?? ''] ?? 'application/octet-stream';
51
+ }
52
+ /** The extensions of `paths`, for HeaderPlan.extensions. Pure. */
53
+ export function extensionsOf(paths) {
54
+ return [...new Set(paths.map(extensionOf).filter((e) => Boolean(e)))].sort();
55
+ }
56
+ /** Every required header `headers` lacks for `path` under `plan`. Pure. */
57
+ export function judgeHeaders(plan, path, status, headers) {
58
+ const rel = path.slice(base(plan).length);
59
+ const cache = plan.mutable.includes(rel)
60
+ ? MUTABLE_CACHE
61
+ : plan.immutable.some((p) => rel.startsWith(p.replace(/\/?$/, '/')))
62
+ ? IMMUTABLE_CACHE
63
+ : null;
64
+ const want = [
65
+ ['status', '200', () => status === 200],
66
+ ['access-control-allow-origin', '*', (v) => v === '*'],
67
+ ['cross-origin-resource-policy', 'cross-origin', (v) => v === 'cross-origin'],
68
+ ['x-content-type-options', 'nosniff', (v) => v === 'nosniff'],
69
+ [
70
+ 'content-type',
71
+ expectedType(path),
72
+ (v) => v.split(';')[0].trim().toLowerCase() === expectedType(path),
73
+ ],
74
+ ];
75
+ if (cache)
76
+ want.push(['cache-control', cache, (v) => v === cache]);
77
+ const out = [];
78
+ for (const [header, expected, ok] of want) {
79
+ const actual = header === 'status' ? String(status) : headers.get(header);
80
+ if (actual === null || !ok(actual))
81
+ out.push({ path, header, expected, actual });
82
+ }
83
+ return out;
84
+ }
85
+ /** Fetches each path from `origin` (GET, body discarded) and judges its headers. */
86
+ export async function checkHeaders(origin, plan, paths) {
87
+ const findings = [];
88
+ for (const path of paths) {
89
+ const r = await fetch(new URL(path, origin));
90
+ void r.body?.cancel().catch(() => { });
91
+ findings.push(...judgeHeaders(plan, path, r.status, r.headers));
92
+ }
93
+ return { checked: paths.length, findings };
94
+ }
@@ -0,0 +1,12 @@
1
+ export declare const PACKAGE: 'cloudflare-model-host';
2
+ export * from './limits.ts';
3
+ export * from './chunks.ts';
4
+ export * from './manifest.ts';
5
+ export * from './stage.ts';
6
+ export * from './verify.ts';
7
+ export * from './publish.ts';
8
+ export * from './mirror/deploy.ts';
9
+ export * from './headers.ts';
10
+ export * from './origin-deploy.ts';
11
+ export * from './mirror/warm.ts';
12
+ export { mirrored, prefixes, type MirrorBucket, type MirrorEnv } from './mirror/worker.ts';
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ // cloudflare-model-host: chunk staging, manifest rewriting, reconstruction verification and dry-run-first
2
+ // publication of verified model bytes to Cloudflare static hosting (fm-3osh); the mirror Worker, its deploy and its
3
+ // warm (fm-fy2.14).
4
+ export const PACKAGE = 'cloudflare-model-host';
5
+ export * from './limits.js';
6
+ export * from './chunks.js';
7
+ export * from './manifest.js';
8
+ export * from './stage.js';
9
+ export * from './verify.js';
10
+ export * from './publish.js';
11
+ export * from './mirror/deploy.js';
12
+ export * from './headers.js';
13
+ export * from './origin-deploy.js';
14
+ export * from './mirror/warm.js';
15
+ export { mirrored, prefixes } from './mirror/worker.js';
@@ -0,0 +1,23 @@
1
+ export declare const MIB: number;
2
+ /** One published file may not exceed this, on every plan. */
3
+ export declare const STATIC_ASSET_FILE_LIMIT_BYTES: number;
4
+ /** Inputs above the file limit are cut into chunks of this size (the last is shorter). */
5
+ export declare const CHUNK_BYTES: number;
6
+ export type Plan = 'workers-free' | 'workers-paid';
7
+ /** Static asset files per Worker version. */
8
+ export declare const STATIC_ASSET_FILES_PER_VERSION: Readonly<Record<Plan, number>>;
9
+ /** Products a publication target may name; only the first costs nothing. */
10
+ export type HostingProduct = 'workers-static-assets-free' | 'workers-static-assets-paid' | 'r2';
11
+ export declare const PAID_PRODUCTS: readonly HostingProduct[];
12
+ /** Monthly figures from the pricing page read on the same date, for the README and the delivery inventory. */
13
+ export declare const PRODUCT_COST: Readonly<Record<HostingProduct, string>>;
14
+ export interface LimitFinding {
15
+ readonly path: string;
16
+ readonly bytes: number;
17
+ readonly problem: 'over-file-limit' | 'too-many-files';
18
+ }
19
+ /** Every file must fit the per-file limit, and the count must fit the plan. */
20
+ export declare function limitFindings(files: readonly {
21
+ readonly path: string;
22
+ readonly bytes: number;
23
+ }[], plan: Plan): LimitFinding[];
package/dist/limits.js ADDED
@@ -0,0 +1,31 @@
1
+ // The Cloudflare product this package publishes to and the limits it is checked against (fm-3osh). Read from
2
+ // developers.cloudflare.com on 24 October 2026: /workers/platform/limits/#static-assets and
3
+ // /workers/platform/pricing/ (static asset requests are free and unlimited on both plans), and
4
+ // /pages/platform/limits/ (the same 25 MiB file limit; larger files belong in R2). The README's limits
5
+ // table states the same figures; change both together.
6
+ export const MIB = 1024 * 1024;
7
+ /** One published file may not exceed this, on every plan. */
8
+ export const STATIC_ASSET_FILE_LIMIT_BYTES = 25 * MIB;
9
+ /** Inputs above the file limit are cut into chunks of this size (the last is shorter). */
10
+ export const CHUNK_BYTES = 16 * MIB;
11
+ /** Static asset files per Worker version. */
12
+ export const STATIC_ASSET_FILES_PER_VERSION = Object.freeze({
13
+ 'workers-free': 20_000,
14
+ 'workers-paid': 100_000,
15
+ });
16
+ export const PAID_PRODUCTS = ['workers-static-assets-paid', 'r2'];
17
+ /** Monthly figures from the pricing page read on the same date, for the README and the delivery inventory. */
18
+ export const PRODUCT_COST = Object.freeze({
19
+ 'workers-static-assets-free': '$0: static asset requests free and unlimited; 20,000 files per version',
20
+ 'workers-static-assets-paid': '$5.00 per month Workers Paid subscription; static asset requests free and unlimited',
21
+ r2: 'R2 storage and operations beyond the free allowance (10 GB-month, 1M Class A, 10M Class B); egress free',
22
+ });
23
+ /** Every file must fit the per-file limit, and the count must fit the plan. */
24
+ export function limitFindings(files, plan) {
25
+ const out = files
26
+ .filter((f) => f.bytes > STATIC_ASSET_FILE_LIMIT_BYTES)
27
+ .map((f) => ({ path: f.path, bytes: f.bytes, problem: 'over-file-limit' }));
28
+ if (files.length > STATIC_ASSET_FILES_PER_VERSION[plan])
29
+ out.push({ path: '', bytes: files.length, problem: 'too-many-files' });
30
+ return out;
31
+ }
@@ -0,0 +1,42 @@
1
+ import { type ManifestError } from 'browser-model-manager';
2
+ /** A descriptor as it appears anywhere in a manifest: hosted (`url`) or unpublished (`file`). */
3
+ export interface AssetNode {
4
+ url?: string;
5
+ file?: string;
6
+ sha256: string;
7
+ size: number;
8
+ chunks?: {
9
+ url?: string;
10
+ file?: string;
11
+ sha256: string;
12
+ size: number;
13
+ }[];
14
+ [key: string]: unknown;
15
+ }
16
+ /** Whether a manifest value is an asset descriptor (digest, size and a location). */
17
+ export declare function isAssetNode(v: unknown): v is AssetNode;
18
+ /** Every asset descriptor in a manifest with its JSON path, depth first in key order. Chunks are not visited. */
19
+ export declare function assets(manifest: unknown): {
20
+ readonly path: string;
21
+ readonly asset: AssetNode;
22
+ }[];
23
+ export type ContractCheck = {
24
+ readonly ok: true;
25
+ } | {
26
+ readonly ok: false;
27
+ readonly error: ManifestError;
28
+ };
29
+ /** The manager's own parser: a newer or unknown major, or a malformed asset, is rejected. */
30
+ export declare function checkContract(manifest: unknown, options?: {
31
+ readonly unpublished?: boolean;
32
+ }): ContractCheck;
33
+ /** Patterns that mark private provenance: local filesystem paths, sibling checkouts, private inventories. */
34
+ export declare const PRIVATE_PROVENANCE: readonly {
35
+ readonly rule: string;
36
+ readonly pattern: RegExp;
37
+ }[];
38
+ /** Every string in the manifest that matches a private-provenance pattern, plus any `source`-path key. */
39
+ export declare function provenanceFindings(manifest: unknown): {
40
+ readonly path: string;
41
+ readonly rule: string;
42
+ }[];
@@ -0,0 +1,63 @@
1
+ // Manifest walking, contract validation and the private-provenance rule (fm-3osh). The contract is
2
+ // browser-model-manager's: its parser here, and its JSON schema in the tests. A published manifest
3
+ // names hosted URLs and digests only; local paths, private inventories and source checkouts never appear in it.
4
+ import { parseModelManifest } from 'browser-model-manager';
5
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
6
+ /** Whether a manifest value is an asset descriptor (digest, size and a location). */
7
+ export function isAssetNode(v) {
8
+ return (isRecord(v) &&
9
+ typeof v['sha256'] === 'string' &&
10
+ typeof v['size'] === 'number' &&
11
+ (typeof v['url'] === 'string' || typeof v['file'] === 'string'));
12
+ }
13
+ /** Every asset descriptor in a manifest with its JSON path, depth first in key order. Chunks are not visited. */
14
+ export function assets(manifest) {
15
+ const out = [];
16
+ const walk = (v, path) => {
17
+ if (isAssetNode(v)) {
18
+ out.push({ path, asset: v });
19
+ return;
20
+ }
21
+ if (Array.isArray(v))
22
+ v.forEach((x, i) => walk(x, `${path}[${i}]`));
23
+ else if (isRecord(v))
24
+ for (const [k, x] of Object.entries(v))
25
+ walk(x, `${path}.${k}`);
26
+ };
27
+ walk(manifest, '$');
28
+ return out;
29
+ }
30
+ /** The manager's own parser: a newer or unknown major, or a malformed asset, is rejected. */
31
+ export function checkContract(manifest, options = {}) {
32
+ const r = parseModelManifest(manifest, options);
33
+ return r.ok ? { ok: true } : { ok: false, error: r.error };
34
+ }
35
+ /** Patterns that mark private provenance: local filesystem paths, sibling checkouts, private inventories. */
36
+ export const PRIVATE_PROVENANCE = [
37
+ { rule: 'absolute-path', pattern: /(^|[\s"'(=])\/(home|Users|tmp|root|mnt|srv|var)\//u },
38
+ { rule: 'windows-path', pattern: /\b[A-Za-z]:\\\\/u },
39
+ { rule: 'file-url', pattern: /file:\/\//u },
40
+ { rule: 'sibling-checkout', pattern: /\.\.\/[\w.-]+-classic\b|\.\.\/review-artifacts\b/u },
41
+ { rule: 'private-inventory', pattern: /sources\.private\.json|review-artifacts/u },
42
+ ];
43
+ /** Every string in the manifest that matches a private-provenance pattern, plus any `source`-path key. */
44
+ export function provenanceFindings(manifest) {
45
+ const out = [];
46
+ const walk = (v, path) => {
47
+ if (typeof v === 'string') {
48
+ for (const { rule, pattern } of PRIVATE_PROVENANCE)
49
+ if (pattern.test(v))
50
+ out.push({ path, rule });
51
+ }
52
+ else if (Array.isArray(v))
53
+ v.forEach((x, i) => walk(x, `${path}[${i}]`));
54
+ else if (isRecord(v))
55
+ for (const [k, x] of Object.entries(v)) {
56
+ if (/^(source|sourcePath|localPath)$/u.test(k) && typeof x === 'string')
57
+ out.push({ path: `${path}.${k}`, rule: 'source-path-key' });
58
+ walk(x, `${path}.${k}`);
59
+ }
60
+ };
61
+ walk(manifest, '$');
62
+ return out;
63
+ }
@@ -0,0 +1,36 @@
1
+ /** Where the mirror goes: every value FaceMorph (or anyone) deploys with, none built in. */
2
+ export interface MirrorTarget {
3
+ /** Worker name. */
4
+ readonly worker: string;
5
+ /** R2 bucket the Worker holds its copies in. */
6
+ readonly bucket: string;
7
+ /** Origin copied from. */
8
+ readonly upstream: string;
9
+ /** Comma-separated immutable path prefixes. */
10
+ readonly prefixes: string;
11
+ /** Worker the SITE service binding points at, when the upstream is a Worker on the same account. */
12
+ readonly site?: string;
13
+ /** Custom domain the Worker serves. */
14
+ readonly domain?: string;
15
+ /** Also serve on <worker>.<account subdomain>.workers.dev (a test mirror). */
16
+ readonly workersDev?: boolean;
17
+ readonly compatibilityDate?: string;
18
+ }
19
+ export declare const DEFAULT_COMPATIBILITY_DATE = "2026-09-16";
20
+ /** The MIRROR_* variables cloudflare.config.ts reads. Pure. */
21
+ export declare function deployEnv(target: MirrorTarget): Record<string, string>;
22
+ export interface DeployResult {
23
+ readonly published: boolean;
24
+ readonly status: number | null;
25
+ readonly output: string;
26
+ }
27
+ /** Runs the package's own `cf` with `args` in the package root, with `env` added. */
28
+ export declare function runCf(args: readonly string[], env: Record<string, string>, base?: NodeJS.ProcessEnv): {
29
+ status: number | null;
30
+ output: string;
31
+ };
32
+ /** Runs `cf deploy` in the package root for `target`; a dry run unless `publish`. */
33
+ export declare function deployMirror(target: MirrorTarget, options?: {
34
+ readonly publish?: boolean;
35
+ readonly env?: NodeJS.ProcessEnv;
36
+ }): DeployResult;