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.
@@ -0,0 +1,65 @@
1
+ // Deploying the mirror Worker (fm-fy2.14) with the Cloudflare CLI `cf`, never Wrangler (operator, 24 October 2026).
2
+ // The package root is the cf project: cloudflare.config.ts reads the target from MIRROR_* variables, which this sets
3
+ // from an explicit target, and builds src/mirror/worker.ts with the Cloudflare Vite plugin. Without `publish` it runs
4
+ // `cf deploy --dry-run`, which builds and checks the Worker and its bindings and sends no API request.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { createRequire } from 'node:module';
7
+ import { cpSync, mkdtempSync, symlinkSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join, sep } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ export const DEFAULT_COMPATIBILITY_DATE = '2026-09-16';
12
+ /** The MIRROR_* variables cloudflare.config.ts reads. Pure. */
13
+ export function deployEnv(target) {
14
+ for (const key of ['worker', 'bucket', 'upstream', 'prefixes'])
15
+ if (!target[key]?.trim())
16
+ throw new Error(`the mirror target needs ${key}`);
17
+ new URL(target.upstream);
18
+ return {
19
+ MIRROR_WORKER: target.worker,
20
+ MIRROR_BUCKET: target.bucket,
21
+ MIRROR_UPSTREAM: target.upstream,
22
+ MIRROR_PREFIXES: target.prefixes,
23
+ MIRROR_COMPATIBILITY_DATE: target.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE,
24
+ ...(target.site ? { MIRROR_SITE_WORKER: target.site } : {}),
25
+ ...(target.domain ? { MIRROR_DOMAIN: target.domain } : {}),
26
+ ...(target.workersDev ? { MIRROR_WORKERS_DEV: '1' } : {}),
27
+ };
28
+ }
29
+ const PACKAGE_ROOT = fileURLToPath(new URL('../..', import.meta.url));
30
+ /** Runs the package's own `cf` with `args` in the package root, with `env` added. */
31
+ export function runCf(args, env, base = process.env) {
32
+ const require = createRequire(join(PACKAGE_ROOT, 'package.json'));
33
+ const pkg = require.resolve('cf/package.json');
34
+ const bin = require(pkg).bin;
35
+ const cf = join(dirname(pkg), typeof bin === 'string' ? bin : bin['cf']);
36
+ // Node strips TypeScript types only outside node_modules, so an installed package's cf project (its .ts config)
37
+ // is run from a copy outside it, beside a link to the node_modules its imports resolve from.
38
+ let cwd = PACKAGE_ROOT;
39
+ if (PACKAGE_ROOT.includes(`${sep}node_modules${sep}`)) {
40
+ cwd = mkdtempSync(join(tmpdir(), 'model-host-cf-'));
41
+ for (const f of [
42
+ 'package.json',
43
+ 'cloudflare.config.ts',
44
+ 'vite.config.ts',
45
+ 'src/mirror/worker.ts',
46
+ ])
47
+ cpSync(join(PACKAGE_ROOT, f), join(cwd, f));
48
+ symlinkSync(dirname(dirname(pkg)), join(cwd, 'node_modules'), 'dir');
49
+ }
50
+ const r = spawnSync(process.execPath, [cf, ...args], {
51
+ cwd,
52
+ env: { ...base, ...env, CI: '1' },
53
+ encoding: 'utf8',
54
+ maxBuffer: 1 << 26,
55
+ });
56
+ return {
57
+ status: r.status,
58
+ output: `${r.stdout ?? ''}${r.stderr ?? ''}${r.error ? String(r.error) : ''}`,
59
+ };
60
+ }
61
+ /** Runs `cf deploy` in the package root for `target`; a dry run unless `publish`. */
62
+ export function deployMirror(target, options = {}) {
63
+ const r = runCf(['deploy', ...(options.publish ? [] : ['--dry-run'])], deployEnv(target), options.env);
64
+ return { published: options.publish === true && r.status === 0, ...r };
65
+ }
@@ -0,0 +1,27 @@
1
+ export interface WarmOptions {
2
+ /** The staged root whose files are the runtime paths. */
3
+ readonly root: string;
4
+ /** The mirror origin, e.g. https://mirror.example.org/ */
5
+ readonly origin: string;
6
+ /** Comma-separated mirrored prefixes (the Worker's PREFIXES). */
7
+ readonly prefixes: string;
8
+ readonly publish?: boolean;
9
+ readonly parallel?: number;
10
+ readonly retries?: number;
11
+ }
12
+ export interface WarmReport {
13
+ readonly origin: string;
14
+ readonly published: boolean;
15
+ /** Immutable paths under the prefixes. */
16
+ readonly paths: number;
17
+ /** Paths the mirror answered 200 for (0 when not published). */
18
+ readonly held: number;
19
+ readonly failed: readonly {
20
+ readonly path: string;
21
+ readonly status: number | string;
22
+ }[];
23
+ readonly requests: number;
24
+ }
25
+ /** The staged root's paths a warm requests. Reads only. */
26
+ export declare function warmPaths(root: string, config: string): string[];
27
+ export declare function warm(options: WarmOptions): Promise<WarmReport>;
@@ -0,0 +1,61 @@
1
+ // Warming a mirror (fm-fy2.14), with classic's semantics: every immutable path of a staged root under the mirrored
2
+ // prefixes is requested with HEAD from the mirror origin, 8 at a time, each retried up to 3 times on a network error
3
+ // or a transient status (408, 429, 5xx), and the run fails on any final non-200, naming each path. A mirror copies a
4
+ // file it does not hold on HEAD, so a HEAD is a write: without `publish` nothing is requested and the plan lists the
5
+ // paths. Classic: curl -s -o /dev/null -I --retry 3 --retry-all-errors in xargs -P 8.
6
+ import { listFiles } from '../verify.js';
7
+ import { mirrored, prefixes } from './worker.js';
8
+ const TRANSIENT = new Set([408, 429]);
9
+ const transient = (status) => TRANSIENT.has(status) || status >= 500;
10
+ /** The staged root's paths a warm requests. Reads only. */
11
+ export function warmPaths(root, config) {
12
+ const allowed = prefixes(config);
13
+ return listFiles(root)
14
+ .map((f) => f.path)
15
+ .filter((p) => mirrored(p, allowed));
16
+ }
17
+ export async function warm(options) {
18
+ const paths = warmPaths(options.root, options.prefixes);
19
+ const base = new URL(options.origin.endsWith('/') ? options.origin : `${options.origin}/`);
20
+ if (!options.publish)
21
+ return {
22
+ origin: base.href,
23
+ published: false,
24
+ paths: paths.length,
25
+ held: 0,
26
+ failed: [],
27
+ requests: 0,
28
+ };
29
+ const retries = options.retries ?? 3;
30
+ let requests = 0;
31
+ const failed = [];
32
+ let held = 0;
33
+ const one = async (path) => {
34
+ let last = 'no answer';
35
+ for (let attempt = 0; attempt <= retries; attempt++) {
36
+ requests++;
37
+ try {
38
+ const r = await fetch(new URL(path.split('/').map(encodeURIComponent).join('/'), base), {
39
+ method: 'HEAD',
40
+ });
41
+ last = r.status;
42
+ if (r.status === 200)
43
+ return void held++;
44
+ if (!transient(r.status))
45
+ break;
46
+ }
47
+ catch (e) {
48
+ last = e.message;
49
+ }
50
+ }
51
+ failed.push({ path, status: last });
52
+ };
53
+ const queue = [...paths];
54
+ const workers = Array.from({ length: Math.min(options.parallel ?? 8, queue.length) }, async () => {
55
+ for (let path = queue.shift(); path !== undefined; path = queue.shift())
56
+ await one(path);
57
+ });
58
+ await Promise.all(workers);
59
+ failed.sort((a, b) => (a.path < b.path ? -1 : 1));
60
+ return { origin: base.href, published: true, paths: paths.length, held, failed, requests };
61
+ }
@@ -0,0 +1,37 @@
1
+ /** The R2 object fields the Worker reads (a subset of the Workers runtime's R2Object). */
2
+ export interface HeldObject {
3
+ size: number;
4
+ httpEtag: string;
5
+ httpMetadata?: {
6
+ contentType?: string;
7
+ };
8
+ }
9
+ export interface HeldObjectBody extends HeldObject {
10
+ body: ReadableStream;
11
+ }
12
+ /** The R2 bucket methods the Worker calls. */
13
+ export interface MirrorBucket {
14
+ head(key: string): Promise<HeldObject | null>;
15
+ get(key: string): Promise<HeldObjectBody | null>;
16
+ put(key: string, value: ArrayBuffer, options: {
17
+ httpMetadata: {
18
+ contentType: string;
19
+ };
20
+ }): Promise<HeldObject>;
21
+ }
22
+ export interface MirrorEnv {
23
+ UPSTREAM?: string;
24
+ PREFIXES?: string;
25
+ MIRROR: MirrorBucket;
26
+ SITE?: {
27
+ fetch(request: Request): Promise<Response>;
28
+ };
29
+ }
30
+ /** The configured prefixes; an empty or missing list mirrors nothing. Pure. */
31
+ export declare function prefixes(config: string | undefined): string[];
32
+ /** Whether `key` is a mirrored path: under a configured prefix, with no empty or `..` segment. Pure. */
33
+ export declare function mirrored(key: string, allowed: readonly string[]): boolean;
34
+ declare const _default: {
35
+ fetch(request: Request, env: MirrorEnv): Promise<Response>;
36
+ };
37
+ export default _default;
@@ -0,0 +1,94 @@
1
+ // The mirror Worker (fm-fy2.14): a second copy of an upstream site's immutable, content-addressed runtime files,
2
+ // held in an R2 bucket and served with CORS and CORP so another origin's page can fetch them. Ported from classic
3
+ // hosting/next-mirror/worker.mjs (see ../../mirror/provenance.json): the upstream origin and the mirrored prefixes are
4
+ // configuration, so the Worker names no host of its own. On 20 October one Cloudflare edge answered HTTP 500 from
5
+ // static-asset storage for single encoder chunks for ten minutes at a time; a page retries such a file here, on
6
+ // separate storage.
7
+ //
8
+ // A file not yet held is copied from the upstream on first request (a deploy warms every runtime path with HEAD), and
9
+ // only under the configured prefixes: those paths are immutable and the page checks every byte against its pin, so a
10
+ // stale or wrong copy can only fail. Anything else is refused without a fetch.
11
+ //
12
+ // Configuration (Worker vars and bindings):
13
+ // UPSTREAM the origin copied from, e.g. https://example.org/ (required; a trailing slash is added if missing)
14
+ // PREFIXES comma-separated immutable path prefixes, e.g. runtime/chunks/,runtime/assets/ (required)
15
+ // MIRROR the R2 bucket binding
16
+ // SITE optional service binding to the upstream Worker; fetches go through it when bound
17
+ const SHARED = {
18
+ 'Access-Control-Allow-Origin': '*',
19
+ 'Cross-Origin-Resource-Policy': 'cross-origin',
20
+ 'X-Content-Type-Options': 'nosniff',
21
+ };
22
+ const IMMUTABLE = 'public, max-age=31536000, immutable';
23
+ const empty = (status, extra = {}) => new Response(null, { status, headers: { ...SHARED, 'Cache-Control': 'no-store', ...extra } });
24
+ function reply(object, body) {
25
+ return new Response(body, {
26
+ status: 200,
27
+ headers: {
28
+ ...SHARED,
29
+ 'Content-Type': object.httpMetadata?.contentType || 'application/octet-stream',
30
+ 'Content-Length': String(object.size),
31
+ ETag: object.httpEtag,
32
+ 'Cache-Control': IMMUTABLE,
33
+ },
34
+ });
35
+ }
36
+ /** The configured prefixes; an empty or missing list mirrors nothing. Pure. */
37
+ export function prefixes(config) {
38
+ return (config ?? '')
39
+ .split(',')
40
+ .map((p) => p.trim())
41
+ .filter((p) => p.length > 0)
42
+ .map((p) => (p.endsWith('/') ? p : `${p}/`));
43
+ }
44
+ /** Whether `key` is a mirrored path: under a configured prefix, with no empty or `..` segment. Pure. */
45
+ export function mirrored(key, allowed) {
46
+ return (allowed.some((prefix) => key.startsWith(prefix)) &&
47
+ !key.split('/').some((part) => part === '..' || part === ''));
48
+ }
49
+ export default {
50
+ async fetch(request, env) {
51
+ if (request.method === 'OPTIONS')
52
+ return empty(204, {
53
+ 'Access-Control-Allow-Methods': 'GET, HEAD',
54
+ 'Access-Control-Max-Age': '86400',
55
+ });
56
+ if (request.method !== 'GET' && request.method !== 'HEAD')
57
+ return empty(405, { Allow: 'GET, HEAD' });
58
+ const upstream = env.UPSTREAM?.trim();
59
+ if (!upstream)
60
+ return empty(503);
61
+ let key;
62
+ try {
63
+ key = decodeURIComponent(new URL(request.url).pathname.slice(1));
64
+ }
65
+ catch {
66
+ return empty(404);
67
+ }
68
+ if (!mirrored(key, prefixes(env.PREFIXES)))
69
+ return empty(404);
70
+ const head = request.method === 'HEAD';
71
+ const held = head ? await env.MIRROR.head(key) : await env.MIRROR.get(key);
72
+ if (held)
73
+ return reply(held, head ? null : held.body);
74
+ const base = new URL(upstream.endsWith('/') ? upstream : `${upstream}/`);
75
+ const url = new URL(key, base);
76
+ // The configured upstream is the only origin fetched.
77
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname))
78
+ return empty(404);
79
+ const source = new Request(url);
80
+ const origin = await (env.SITE ? env.SITE.fetch(source) : fetch(source));
81
+ if (origin.status !== 200) {
82
+ void origin.body?.cancel();
83
+ return empty(origin.status === 404 ? 404 : 502);
84
+ }
85
+ // Runtime files are at most 25 MiB (the static-asset limit), so buffering one is cheap.
86
+ const bytes = await origin.arrayBuffer();
87
+ const saved = await env.MIRROR.put(key, bytes, {
88
+ httpMetadata: {
89
+ contentType: origin.headers.get('Content-Type') || 'application/octet-stream',
90
+ },
91
+ });
92
+ return reply(saved, head ? null : bytes);
93
+ },
94
+ };
@@ -0,0 +1,21 @@
1
+ import { type HeaderPlan } from './headers.ts';
2
+ import { type DeployResult } from './mirror/deploy.ts';
3
+ import { type TermsChoice } from './publish.ts';
4
+ export interface ModelOrigin extends HeaderPlan {
5
+ /** Worker name; with `workersDev` it serves on <name>.<account subdomain>.workers.dev. */
6
+ readonly worker: string;
7
+ readonly workersDev?: boolean;
8
+ readonly domain?: string;
9
+ readonly compatibilityDate?: string;
10
+ /** The model terms the published bytes are redistributed under (required to publish model bytes). */
11
+ readonly terms?: TermsChoice;
12
+ }
13
+ export interface OriginResult extends DeployResult {
14
+ readonly refused: string | null;
15
+ readonly publicDir: string;
16
+ }
17
+ /** Builds the public directory (`_headers` and the root linked at its base path) and runs cf deploy for it. */
18
+ export declare function deployModelOrigin(root: string, origin: ModelOrigin, options?: {
19
+ readonly publish?: boolean;
20
+ readonly env?: NodeJS.ProcessEnv;
21
+ }): OriginResult;
@@ -0,0 +1,41 @@
1
+ // A staged model root as its own origin on Workers Static Assets (fm-fy2.14): the test origin the staging
2
+ // qualification runs against, deployed with the Cloudflare CLI `cf` in the package root's `model-origin` mode
3
+ // (cloudflare.config.ts, vite.config.ts). The root is served under its base path with the model `_headers`
4
+ // (src/headers.ts); the Worker has no script, so no request for a model file runs Worker code. Model terms are
5
+ // checked first, as for every publication (src/publish.ts). A dry run unless `publish`.
6
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync, } from 'node:fs';
7
+ import { tmpdir } from 'node:os';
8
+ import { dirname, join, resolve } from 'node:path';
9
+ import { extensionsOf, modelHeaders } from './headers.js';
10
+ import { listFiles } from './verify.js';
11
+ import { DEFAULT_COMPATIBILITY_DATE, runCf } from './mirror/deploy.js';
12
+ import { termsRefusal } from './publish.js';
13
+ /** Builds the public directory (`_headers` and the root linked at its base path) and runs cf deploy for it. */
14
+ export function deployModelOrigin(root, origin, options = {}) {
15
+ if (!origin.worker?.trim())
16
+ throw new Error('the model origin needs a Worker name');
17
+ const manifestPath = join(root, 'manifest.json');
18
+ const refused = options.publish
19
+ ? termsRefusal(existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : null, origin.terms)
20
+ : null;
21
+ const publicDir = mkdtempSync(join(tmpdir(), 'model-origin-'));
22
+ const extensions = origin.extensions ?? extensionsOf(listFiles(root).map((f) => f.path));
23
+ writeFileSync(join(publicDir, '_headers'), modelHeaders({ ...origin, extensions }));
24
+ const at = (origin.basePath ?? '/').replace(/^\/+|\/+$/g, '');
25
+ if (at) {
26
+ mkdirSync(dirname(join(publicDir, at)), { recursive: true });
27
+ symlinkSync(resolve(root), join(publicDir, at), 'dir');
28
+ }
29
+ else
30
+ throw new Error('a model origin is served under a base path, e.g. /runtime/');
31
+ if (refused)
32
+ return { published: false, status: null, output: '', refused, publicDir };
33
+ const r = runCf(['deploy', '--mode', 'model-origin', ...(options.publish ? [] : ['--dry-run'])], {
34
+ MODEL_ORIGIN_WORKER: origin.worker,
35
+ MODEL_ORIGIN_PUBLIC: publicDir,
36
+ MODEL_ORIGIN_COMPATIBILITY_DATE: origin.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE,
37
+ ...(origin.workersDev ? { MODEL_ORIGIN_WORKERS_DEV: '1' } : {}),
38
+ ...(origin.domain ? { MODEL_ORIGIN_DOMAIN: origin.domain } : {}),
39
+ }, options.env);
40
+ return { published: options.publish === true && r.status === 0, ...r, refused: null, publicDir };
41
+ }
@@ -0,0 +1,45 @@
1
+ import { type HostingProduct } from './limits.ts';
2
+ /** The model terms a target publishes under: a record file and, for unresolved terms, the row acknowledged. */
3
+ export interface TermsChoice {
4
+ readonly record: string;
5
+ readonly acknowledged?: string;
6
+ }
7
+ export type Target = {
8
+ readonly kind: 'directory';
9
+ readonly path: string;
10
+ readonly product?: HostingProduct;
11
+ readonly paidServiceApproved?: HostingProduct;
12
+ readonly terms?: TermsChoice;
13
+ } | {
14
+ readonly kind: 'cloudflare';
15
+ /** Directory holding the Cloudflare project configuration whose static assets directory is the staged root. */
16
+ readonly project: string;
17
+ readonly product: HostingProduct;
18
+ readonly paidServiceApproved?: HostingProduct;
19
+ readonly terms?: TermsChoice;
20
+ };
21
+ /** Why the model terms refuse publication of `manifest`, or null when they allow it. */
22
+ export declare function termsRefusal(manifest: unknown, terms: TermsChoice | undefined): string | null;
23
+ export interface PlannedWrite {
24
+ readonly path: string;
25
+ readonly bytes: number;
26
+ readonly action: 'write' | 'unchanged' | 'conflict';
27
+ }
28
+ export interface PublicationPlan {
29
+ readonly target: Target;
30
+ readonly product: HostingProduct;
31
+ readonly paid: boolean;
32
+ readonly refused: string | null;
33
+ readonly writes: readonly PlannedWrite[];
34
+ readonly bytes: number;
35
+ }
36
+ export interface PublicationResult extends PublicationPlan {
37
+ readonly published: boolean;
38
+ readonly written: number;
39
+ }
40
+ /** What publishing `root` to `target` would do. Reads only. */
41
+ export declare function planPublication(root: string, target: Target): PublicationPlan;
42
+ /** Publishes only when `publish` is true and the plan is not refused; otherwise returns the plan untouched. */
43
+ export declare function publishRoot(root: string, target: Target, options?: {
44
+ readonly publish?: boolean;
45
+ }): PublicationResult;
@@ -0,0 +1,85 @@
1
+ // Publication (fm-3osh): a dry run by default. Without `publish: true` nothing is written and nothing is run;
2
+ // the plan lists each file the target would receive. A target names its product; a paid product is refused
3
+ // unless the target names that same product in `paidServiceApproved`, so publication never turns on a paid
4
+ // service by itself. Targets: a directory (a static root the serving side deploys, or a local mirror) and a
5
+ // Cloudflare project directory deployed with the `cf` CLI (`cf deploy` in that directory). Model terms are checked
6
+ // first: the target names a terms record (rows shaped like the repository's import/licences.json), one row must
7
+ // cover the manifest's modelSourceSha256, and a row whose redistribution is not "permitted" refuses publication
8
+ // unless the target acknowledges that row by id.
9
+ import { spawnSync } from 'node:child_process';
10
+ import { existsSync, readFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { fileDigest, freeze } from './chunks.js';
13
+ import { PAID_PRODUCTS } from './limits.js';
14
+ import { inside } from './stage.js';
15
+ import { listFiles } from './verify.js';
16
+ /** Why the model terms refuse publication of `manifest`, or null when they allow it. */
17
+ export function termsRefusal(manifest, terms) {
18
+ const source = manifest?.modelSourceSha256;
19
+ if (typeof source !== 'string')
20
+ return 'the manifest names no modelSourceSha256';
21
+ if (!terms)
22
+ return 'the target names no model terms record';
23
+ if (!existsSync(terms.record))
24
+ return `model terms record not found: ${terms.record}`;
25
+ const rows = JSON.parse(readFileSync(terms.record, 'utf8')).rows ?? [];
26
+ const row = rows.find((r) => JSON.stringify(r).includes(source));
27
+ if (!row)
28
+ return `no model terms row covers modelSourceSha256 ${source}`;
29
+ if (row.redistribution !== 'permitted' && terms.acknowledged !== row.id)
30
+ return `model terms row ${row.id} has redistribution "${row.redistribution ?? 'unstated'}"; the target must acknowledge it`;
31
+ return null;
32
+ }
33
+ const productOf = (t) => t.product ?? 'workers-static-assets-free';
34
+ /** What publishing `root` to `target` would do. Reads only. */
35
+ export function planPublication(root, target) {
36
+ const product = productOf(target);
37
+ const paid = PAID_PRODUCTS.includes(product);
38
+ const manifestPath = join(root, 'manifest.json');
39
+ const refused = paid && target.paidServiceApproved !== product
40
+ ? `${product} is a paid service; the target must name it in paidServiceApproved to publish`
41
+ : termsRefusal(existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : null, target.terms);
42
+ const writes = listFiles(root).map((f) => {
43
+ if (target.kind !== 'directory')
44
+ return { ...f, action: 'write' };
45
+ const dest = inside(target.path, f.path);
46
+ if (!existsSync(dest))
47
+ return { ...f, action: 'write' };
48
+ const a = fileDigest(dest);
49
+ const b = fileDigest(join(root, f.path));
50
+ return { ...f, action: a.sha256 === b.sha256 && a.size === b.size ? 'unchanged' : 'conflict' };
51
+ });
52
+ const conflicts = writes.filter((w) => w.action === 'conflict');
53
+ return {
54
+ target,
55
+ product,
56
+ paid,
57
+ refused: refused ??
58
+ (conflicts.length
59
+ ? `immutable destination changed: ${conflicts.map((c) => c.path).join(', ')}`
60
+ : null),
61
+ writes,
62
+ bytes: writes.reduce((n, w) => n + w.bytes, 0),
63
+ };
64
+ }
65
+ /** Publishes only when `publish` is true and the plan is not refused; otherwise returns the plan untouched. */
66
+ export function publishRoot(root, target, options = {}) {
67
+ const plan = planPublication(root, target);
68
+ if (!options.publish || plan.refused)
69
+ return { ...plan, published: false, written: 0 };
70
+ if (target.kind === 'directory') {
71
+ let written = 0;
72
+ for (const w of plan.writes)
73
+ if (w.action === 'write') {
74
+ freeze(inside(target.path, w.path), readFileSync(join(root, w.path)));
75
+ written++;
76
+ }
77
+ return { ...plan, published: true, written };
78
+ }
79
+ const r = spawnSync('cf', ['deploy'], { cwd: target.project, stdio: 'inherit' });
80
+ if (r.error)
81
+ throw r.error;
82
+ if (r.status !== 0)
83
+ throw new Error(`cf deploy exited ${r.status}`);
84
+ return { ...plan, published: true, written: plan.writes.length };
85
+ }
@@ -0,0 +1,28 @@
1
+ import { type HeaderFinding, type HeaderPlan } from './headers.ts';
2
+ export interface QualifyOptions extends HeaderPlan {
3
+ readonly root: string;
4
+ /** The origin, e.g. https://staging.example.org */
5
+ readonly origin: string;
6
+ /** The qualified runtime's manifest, whose asset digests the served manifest must name exactly. */
7
+ readonly reference?: unknown;
8
+ readonly parallel?: number;
9
+ }
10
+ export interface QualifyReport {
11
+ readonly origin: string;
12
+ readonly ok: boolean;
13
+ readonly files: number;
14
+ readonly bytes: number;
15
+ readonly mismatched: readonly {
16
+ readonly path: string;
17
+ readonly status: number;
18
+ }[];
19
+ readonly headers: readonly HeaderFinding[];
20
+ readonly chunked: number;
21
+ readonly unreconstructed: readonly string[];
22
+ readonly contract: string | null;
23
+ readonly digests: {
24
+ readonly missing: readonly string[];
25
+ readonly extra: readonly string[];
26
+ } | null;
27
+ }
28
+ export declare function qualifyOrigin(options: QualifyOptions): Promise<QualifyReport>;
@@ -0,0 +1,87 @@
1
+ // Staging qualification of a deployed model origin (fm-fy2.14), read-only: every file of the staged root is fetched
2
+ // from the origin and must be byte-identical to the staged file and carry the required headers (src/headers.ts);
3
+ // every chunked asset must reconstruct from the chunks the origin serves; the manifest the origin serves must pass
4
+ // the manager's contract and, given a reference (the qualified runtime the engine's canaries ran on), name exactly
5
+ // its asset digests, so manager and engine agree on schema and hashes. The mirror fallback with the primary failing
6
+ // is the browser case in test/staging.e2e.ts.
7
+ import { createHash } from 'node:crypto';
8
+ import { readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { judgeHeaders } from './headers.js';
11
+ import { assets, checkContract } from './manifest.js';
12
+ import { listFiles } from './verify.js';
13
+ const sha = (b) => createHash('sha256').update(b).digest('hex');
14
+ const digestSet = (manifest) => new Set(assets(manifest).map((a) => a.asset.sha256));
15
+ export async function qualifyOrigin(options) {
16
+ const base = (options.basePath ?? '/').replace(/\/?$/, '/');
17
+ const files = listFiles(options.root);
18
+ const served = new Map(); // path -> served digest
19
+ const mismatched = [];
20
+ const headers = [];
21
+ let bytes = 0;
22
+ const queue = [...files];
23
+ await Promise.all(Array.from({ length: options.parallel ?? 8 }, async () => {
24
+ for (let f = queue.shift(); f; f = queue.shift()) {
25
+ const path = `${base}${f.path}`;
26
+ const r = await fetch(new URL(path, options.origin));
27
+ const body = new Uint8Array(await r.arrayBuffer());
28
+ bytes += body.byteLength;
29
+ headers.push(...judgeHeaders(options, path, r.status, r.headers));
30
+ const digest = sha(body);
31
+ served.set(f.path, digest);
32
+ if (r.status !== 200 || digest !== sha(readFileSync(join(options.root, f.path))))
33
+ mismatched.push({ path: f.path, status: r.status });
34
+ }
35
+ }));
36
+ const manifest = JSON.parse(readFileSync(join(options.root, 'manifest.json'), 'utf8'));
37
+ // A chunked asset reconstructs when its chunks, as served, have the declared digests and sizes and concatenate to
38
+ // the asset's digest. Chunk files are content-addressed under chunks/<sha256>.bin.
39
+ const unreconstructed = [];
40
+ let chunked = 0;
41
+ for (const { asset } of assets(manifest)) {
42
+ if (!asset.chunks)
43
+ continue;
44
+ chunked++;
45
+ const whole = createHash('sha256');
46
+ let ok = true;
47
+ for (const c of asset.chunks) {
48
+ const path = `chunks/${c.sha256}.bin`;
49
+ if (served.get(path) !== c.sha256)
50
+ ok = false;
51
+ else
52
+ whole.update(readFileSync(join(options.root, path)));
53
+ }
54
+ if (!ok || whole.digest('hex') !== asset.sha256)
55
+ unreconstructed.push(asset.sha256);
56
+ }
57
+ const contract = checkContract(manifest);
58
+ let digests = null;
59
+ if (options.reference !== undefined) {
60
+ const want = digestSet(options.reference);
61
+ const got = digestSet(manifest);
62
+ digests = {
63
+ missing: [...want].filter((d) => !got.has(d)).sort(),
64
+ extra: [...got].filter((d) => !want.has(d)).sort(),
65
+ };
66
+ }
67
+ mismatched.sort((a, b) => (a.path < b.path ? -1 : 1));
68
+ const report = {
69
+ origin: options.origin,
70
+ files: files.length,
71
+ bytes,
72
+ mismatched,
73
+ headers,
74
+ chunked,
75
+ unreconstructed,
76
+ contract: contract.ok ? null : `${contract.error.code} at ${contract.error.path}`,
77
+ digests,
78
+ };
79
+ return {
80
+ ...report,
81
+ ok: !mismatched.length &&
82
+ !headers.length &&
83
+ !unreconstructed.length &&
84
+ report.contract === null &&
85
+ (!digests || (!digests.missing.length && !digests.extra.length)),
86
+ };
87
+ }
@@ -0,0 +1,38 @@
1
+ export interface StageOptions {
2
+ /** Directory holding the manifest and the files it names. */
3
+ readonly source: string;
4
+ /** Manifest file name inside `source`. */
5
+ readonly manifest?: string;
6
+ /** Output root: `manifest.json`, the assets at their relative paths and `chunks/`. */
7
+ readonly out: string;
8
+ /** Hosted origin and prefix every published URL starts with, https only, no trailing slash needed. */
9
+ readonly base: string;
10
+ /**
11
+ * For an already hosted manifest being restaged: the old URL prefix. A URL under it maps to the same relative
12
+ * path inside `source`. Unpublished manifests name `file` paths instead and need no prefix.
13
+ */
14
+ readonly fromBase?: string;
15
+ /** Report what would be written without writing anything. */
16
+ readonly dryRun?: boolean;
17
+ }
18
+ export interface StagedFile {
19
+ readonly path: string;
20
+ readonly sha256: string;
21
+ readonly bytes: number;
22
+ }
23
+ export interface StageResult {
24
+ readonly manifest: unknown;
25
+ /** Every file the output root holds (or would hold) besides manifest.json, sorted by path. */
26
+ readonly files: readonly StagedFile[];
27
+ readonly assets: number;
28
+ readonly chunked: number;
29
+ }
30
+ export type StageErrorCode = 'not-https' | 'unsafe-path' | 'integrity' | 'unmapped-url' | 'contract' | 'private-provenance' | 'descriptor-conflict';
31
+ export declare class StageError extends Error {
32
+ readonly code: StageErrorCode;
33
+ constructor(code: StageErrorCode, message: string);
34
+ }
35
+ /** Resolves a manifest-relative path inside `root`, refusing absolute paths and `..` escapes. */
36
+ export declare function inside(root: string, rel: string): string;
37
+ /** Stages a manifest's assets; see StageOptions. Throws StageError on the first refusal. */
38
+ export declare function stage(options: StageOptions): StageResult;