@rig-c/review 0.16.0 → 0.18.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/README.md CHANGED
@@ -51,7 +51,7 @@ http://127.0.0.1:4318/instances/<key>/?input=…&handoff=…#cap=…
51
51
  | <a id="feedback-ownership"></a>Retrieve submitted feedback | `feedback` | [Feedback ownership — WORKFLOWS](docs/WORKFLOWS.md#feedback-ownership) |
52
52
  | <a id="frame-strip-export"></a>Export feedback intervals as strips | `strip` | [Frame strip export — WORKFLOWS](docs/WORKFLOWS.md#frame-strip-export) |
53
53
  | **Inspect** | | |
54
- | <a id="workspace-settings-and-panels"></a>Navigate the workspace | Setup, Animate, Settings | [Workspace panels — PANELS](docs/PANELS.md#workspace-settings-and-panels) |
54
+ | <a id="workspace-settings-and-panels"></a>Navigate the workspace | Setup, Animate, Compare, Settings | [Workspace panels — PANELS](docs/PANELS.md#workspace-settings-and-panels) |
55
55
  | <a id="inspect-animation-keys"></a>Inspect stored animation keys | Timeline, Curves, Bone tree | [Animation keys — PANELS](docs/PANELS.md#inspect-animation-keys) |
56
56
  | <a id="inspect-a-part"></a>Select and fit a model slot | Parts explorer | [Part inspection — PANELS](docs/PANELS.md#inspect-a-part) |
57
57
  | <a id="weights-setup-pose-watch-only"></a>Inspect setup-pose weights | Weights | [Weights — PANELS](docs/PANELS.md#weights-setup-pose-watch-only) |
package/docs/PANELS.md CHANGED
@@ -8,8 +8,14 @@ The review page has a left column (Parts explorer, with checkpoints and the
8
8
  reference select folded above it), the stage, the Inspector below it with
9
9
  **Setup** and **Animate** sections, and a status footer. The compare page
10
10
  keeps sources on the left and the Parts explorer on the right. The page
11
- header carries the **Setup** / **Animate** mode switch next to the package
12
- title; it is the only way to change the Inspector's section. Setup is the
11
+ header carries the **Setup · Animate · Compare** mode switch next to the package
12
+ title. In a single-build session (`rig-review open <built>`), **Compare** is
13
+ disabled with a tooltip explaining that a second build and reference video are
14
+ required (`--compare <built> --reference <video>`). In a comparison session, the
15
+ page starts in **Compare** mode with Reference, Build A and Build B side by
16
+ side, and switching to **Setup** or **Animate** keeps time, animation and
17
+ selection while exposing the **Editing Build A / Build B** picker so the shared
18
+ Setup and Animate panels operate on the picked build only. Setup is the
13
19
  mesh-review composition (selected part, part presets, modeling-review
14
20
  proposals) and holds nothing that seeks or plays; the angle inspection, the
15
21
  transport and frame navigation are in Animate. **Write review** at the top
package/docs/WORKFLOWS.md CHANGED
@@ -160,10 +160,17 @@ rig-review strip /absolute/output --reference-video /absolute/original.mp4 --ani
160
160
  Only tool-owned instances with matching content, canonical input locations, tool
161
161
  fingerprint and a private capability handshake are reused. The URL hash is
162
162
  checked before serving the app; a stale link never selects another instance's
163
- package. Input hashes are freshly computed, not trusted from mtime caches. Idle
164
- open-managed workers stop after 30 minutes. Their private registry, requests and
165
- logs live beside feedback under `~/.local/state/rig-c-review/open/`; nothing is
166
- written into supplied folders. `RIG_REVIEW_STATE_DIR` selects another state root
163
+ package. Input hashes are freshly computed, not trusted from mtime caches. In both
164
+ `open` and foreground `review` / `review compare`, each open window holds a live
165
+ WebSocket connection (`/api/live`); once the last window closes and stays at zero connections
166
+ for the 3-second grace period, or if no window ever connects within 30 minutes
167
+ (reusing a windowless worker via `open` gives it a fresh 30-minute unopened window),
168
+ the server finishes any in-flight request or Apply, flushes state, prints one line
169
+ stating why it exited, and exits `0`. A browser that unloads a background tab to
170
+ save memory looks the same as a closed tab, so the server stops; saved feedback
171
+ survives and `open` brings it back. Their
172
+ private registry, requests and logs live beside feedback under
173
+ `~/.local/state/rig-c-review/open/`; nothing is written into supplied folders. `RIG_REVIEW_STATE_DIR` selects another state root
167
174
  outside all input packages, judged by its canonical location (symlinks in the path
168
175
  and its existing ancestors resolved). Existing foreground review commands still work.
169
176
 
@@ -216,7 +223,7 @@ request, and refuses an unknown, expired or replaced instance by name
216
223
  (`FRONT_INSTANCE_UNKNOWN`, `FRONT_INSTANCE_EXPIRED`, `FRONT_INSTANCE_REPLACED`).
217
224
  Worker error text is not passed through; failures become named `FRONT_*` codes.
218
225
  Package assets keep their `sandbox` CSP through the front. It never reads packages.
219
- Idle fronts exit after 30 minutes once no live instance remains.
226
+ Idle fronts exit after the 3-second grace period once no live instance remains.
220
227
 
221
228
  If another listener holds the front port, `open` fails with
222
229
  `FRONT_PORT_BUSY: 127.0.0.1:4318 is held by another listener; use --direct` and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -89,7 +89,7 @@ export function createBonesCheck(p: ReviewPackage, options: { stateDir: string;
89
89
  await rm(dir, { recursive: true, force: true }).catch(() => {});
90
90
  }
91
91
  }
92
- return { run };
92
+ return { run, running: () => running };
93
93
  }
94
94
 
95
95
  /** `propose --from-config` on the scratch config, or the line naming the missing source painting. */
package/src/cli.ts CHANGED
@@ -112,7 +112,9 @@ export async function main(args:string[],options:{stateDir?:string}={}){
112
112
  const p=await loadCompare({a,b,reference,animation});
113
113
  if(command==='feedback'){printFeedback(await readFeedbackCompareSession(p,options.stateDir));return;}
114
114
  if(command==='check'){console.log(`Comparison valid: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nAnimation: ${animation}\nReference SHA-256: ${p.response.reference.sha256}\nPlayback: two compiled models present`);return;}
115
- const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability});console.log(`Compare ready: http://127.0.0.1:${server.port}/#cap=${capability}\nComparison: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nPress Ctrl+C to stop.`);return;
115
+ const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability,exitOnClose:true});
116
+ const stop=(sig:string)=>{server.stop(true);console.log(`review compare: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
117
+ console.log(`Compare ready: http://127.0.0.1:${server.port}/#cap=${capability}\nComparison: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nPress Ctrl+C to stop.`);return;
116
118
  }
117
119
  const input=args.shift();if(!input)throw new Error(usage);let port=4317;let checkpoint:string|undefined,reference:string|undefined,compare:string|undefined,animation:string|undefined;const handoff:OpenInputs={input};
118
120
  while(args.length){const flag=args.shift();const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);if(handoffOption(flag!)){handoff[handoffOption(flag!)!]=value;continue;}if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0…65535');}else if(flag==='--checkpoint')checkpoint=value;else if(flag==='--reference')reference=value;else if(flag==='--compare')compare=value;else if(flag==='--animation')animation=value;else throw new Error(`Unknown option ${flag}\n${usage}`);}
@@ -123,7 +125,8 @@ export async function main(args:string[],options:{stateDir?:string}={}){
123
125
  const selection=animation!==undefined||fromReport?selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],animation,true):null;const initialAnimation=selection?.name;if(command==='feedback'){const saved=await readFeedbackSession(p,options.stateDir);await assertReviewUnchanged(p);printFeedback(saved);return;}if(command==='check'){console.log(`Package valid: ${p.manifest.title}\nRevision: ${p.manifest.revision}\nSource SHA-256: ${p.sourceHash}\nDeclared files: ${p.files.size}\nPlayback: ${p.manifest.model?'compiled model present':'unavailable (no model)'}`);return;}
124
126
  if(checkpoint&&!p.manifest.checkpoints.some(v=>v.id===checkpoint))throw new Error(`Unknown checkpoint ${checkpoint}`);
125
127
  // Foreground serving uses the same `#cap=` fragment handoff as open: the printed link alone can submit.
126
- const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
128
+ const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability,exitOnClose:true});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
129
+ const stop=(sig:string)=>{server.stop(true);console.log(`review: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
127
130
  if(fromReport&&selection)console.error(animationDiagnostic(selection));
128
131
  console.log(`Review ready: ${url}\nPackage: ${p.manifest.title} (${p.manifest.revision})\nSource SHA-256: ${p.sourceHash}\nPress Ctrl+C to stop.`);
129
132
  }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Single-source Setup and Animate workspace markup for comparison sessions (#234).
3
+ *
4
+ * `web/index.html` owns the Setup and Animate panel markup; `web/compare.html` holds placeholders for those shared
5
+ * sections and `renderCompareHtml` splices them from `web/index.html` at serve time, refusing missing landmarks,
6
+ * duplicate IDs or any byte difference between the two pages' Setup and Animate sections.
7
+ */
8
+
9
+ export interface SharedWorkspaceMarkup {
10
+ viewTools: string;
11
+ stageBars: string;
12
+ stageHandles: string;
13
+ appliedRecords: string;
14
+ setupBlockRow: string;
15
+ setupPanels: string;
16
+ animateBlockRow: string;
17
+ transportStrips: string;
18
+ animatePanels: string;
19
+ }
20
+
21
+ const REGIONS: readonly {
22
+ key: keyof SharedWorkspaceMarkup;
23
+ placeholder: string;
24
+ start: string;
25
+ end: string;
26
+ compareEnd: string;
27
+ }[] = [
28
+ {
29
+ key: 'viewTools',
30
+ placeholder: '<!-- shared:view-tools -->',
31
+ start: '<div class="view-tools">',
32
+ end: '<div class="zoom-controls">',
33
+ compareEnd: '<div class="row"><label class="camera-sync">',
34
+ },
35
+ {
36
+ key: 'stageBars',
37
+ placeholder: '<!-- shared:stage-bars -->',
38
+ start: '<div id="chest-editor-bar"',
39
+ end: '<div id="stage-layout"',
40
+ compareEnd: '<div id="stage-layout"',
41
+ },
42
+ {
43
+ key: 'stageHandles',
44
+ placeholder: '<!-- shared:stage-handles -->',
45
+ start: '<div id="idle-handles"',
46
+ end: '<div id="rig-empty"',
47
+ compareEnd: '<p id="a-empty"',
48
+ },
49
+ {
50
+ key: 'appliedRecords',
51
+ placeholder: '<!-- shared:applied-records -->',
52
+ start: '<section id="applied-records"',
53
+ end: '<section id="inspector-rig"',
54
+ compareEnd: '<section id="inspector-view"',
55
+ },
56
+ {
57
+ key: 'setupBlockRow',
58
+ placeholder: '<!-- shared:setup-block-row -->',
59
+ start: '<nav class="block-row" aria-label="Setup blocks">',
60
+ end: '<section id="selected-part"',
61
+ compareEnd: '<section id="selected-part"',
62
+ },
63
+ {
64
+ key: 'setupPanels',
65
+ placeholder: '<!-- shared:setup-panels -->',
66
+ start: '<section id="modeling-tools">',
67
+ end: '</section><section id="inspector-playback"',
68
+ compareEnd: '</section><section id="inspector-playback"',
69
+ },
70
+ {
71
+ key: 'animateBlockRow',
72
+ placeholder: '<!-- shared:animate-block-row -->',
73
+ start: '<nav class="block-row" aria-label="Animate blocks">',
74
+ end: '<section id="transport"',
75
+ compareEnd: '<section id="transport"',
76
+ },
77
+ {
78
+ key: 'transportStrips',
79
+ placeholder: '<!-- shared:transport-strips -->',
80
+ start: '<div id="reading-ticks"',
81
+ end: '</section><section id="frame-controls"',
82
+ compareEnd: '</section><div class="compare-info">',
83
+ },
84
+ {
85
+ key: 'animatePanels',
86
+ placeholder: '<!-- shared:animate-panels -->',
87
+ start: '<section id="motion-tools">',
88
+ end: '</section></div></section></main>',
89
+ compareEnd: '</section><section id="inspector-feedback"',
90
+ },
91
+ ];
92
+
93
+ function sliceRegion(html: string, start: string, end: string, label: string): string {
94
+ const a = html.indexOf(start);
95
+ if (a < 0) throw new Error(`COMPARE_SHARED_MARKUP_MISSING: ${label} start landmark not found (${start})`);
96
+ const b = html.indexOf(end, a);
97
+ if (b < a) throw new Error(`COMPARE_SHARED_MARKUP_MISSING: ${label} end landmark not found (${end})`);
98
+ return html.slice(a, b);
99
+ }
100
+
101
+ export function extractSharedWorkspaceMarkup(indexHtml: string): SharedWorkspaceMarkup {
102
+ const out = {} as Record<keyof SharedWorkspaceMarkup, string>;
103
+ for (const r of REGIONS) out[r.key] = sliceRegion(indexHtml, r.start, r.end, r.key);
104
+ return out;
105
+ }
106
+
107
+ export function assertNoDuplicateIds(html: string, label = 'compare.html'): void {
108
+ const seen = new Set<string>();
109
+ for (const m of html.matchAll(/\bid="([^"]+)"/g)) {
110
+ const id = m[1]!;
111
+ if (seen.has(id)) throw new Error(`COMPARE_DUPLICATE_ID: duplicate id="${id}" in ${label}`);
112
+ seen.add(id);
113
+ }
114
+ }
115
+
116
+ export function assertSharedCompareMarkup(compareHtml: string, indexHtml: string): void {
117
+ const shared = extractSharedWorkspaceMarkup(indexHtml);
118
+ for (const r of REGIONS) {
119
+ const piece = shared[r.key].trim();
120
+ let actual: string;
121
+ try {
122
+ actual = sliceRegion(compareHtml, r.start, r.compareEnd, r.key).trim();
123
+ } catch {
124
+ throw new Error(`COMPARE_SHARED_MARKUP_DRIFT: ${r.key} in compare markup differs from web/index.html`);
125
+ }
126
+ if (actual !== piece) {
127
+ throw new Error(`COMPARE_SHARED_MARKUP_DRIFT: ${r.key} in compare markup differs from web/index.html`);
128
+ }
129
+ }
130
+ assertNoDuplicateIds(compareHtml, 'rendered compare HTML');
131
+ }
132
+
133
+ export function renderCompareHtml(compareTemplate: string, indexHtml: string): string {
134
+ const shared = extractSharedWorkspaceMarkup(indexHtml);
135
+ let out = compareTemplate;
136
+ for (const r of REGIONS) {
137
+ if (!out.includes(r.placeholder)) {
138
+ throw new Error(`COMPARE_SHARED_MARKUP_MISSING: placeholder ${r.placeholder} missing in web/compare.html`);
139
+ }
140
+ out = out.replace(r.placeholder, shared[r.key]);
141
+ }
142
+ if (out.includes('<!-- shared:')) {
143
+ throw new Error('COMPARE_SHARED_MARKUP_MISSING: unreplaced shared placeholder in web/compare.html');
144
+ }
145
+ assertSharedCompareMarkup(out, indexHtml);
146
+ return out;
147
+ }
@@ -1,21 +1,34 @@
1
1
  import {createControlServer,type ControlIdentity} from './control-server.ts';
2
- import {openGate,staleOpenStatus,accessGate,openNonceGate,stampOpen,type OpenIdentity} from './open-protocol.ts';
2
+ import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
3
3
  import { readFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
4
6
  import { appRoot, buildWeb } from './build.ts';
5
- import { packagePath, safeFile } from './manifest.ts';
7
+ import { packagePath, safeFile, type ReviewPackage } from './manifest.ts';
6
8
  import { assertCompareUnchanged, safeCompareReference, type ComparePackage } from './compare.ts';
7
- import { serveReference } from './reference.ts';
9
+ import { assertReviewUnchanged, serveReference } from './reference.ts';
8
10
  import {referenceFrameIndex} from './reference-frame-index.ts';
9
11
  import { exportCompareStrip, stripJson } from './strip-export.ts';
10
12
  import { readCompareSession, saveCompareSession } from './compare-session.ts';
13
+ import { createRebuilds, RebuildError } from './rebuild.ts';
14
+ import { DENSITY_STRIP_LIMIT } from './density-strip.ts';
15
+ import { createReadings } from './readings-run.ts';
16
+ import { ReadingsError } from './readings.ts';
17
+ import { BONES_CHECK_LIMIT, createBonesCheck } from './bones-check.ts';
18
+ import { createRequirementsCheck } from './requirements-run.ts';
19
+ import { REQUIREMENTS_LIMIT, RequirementsError } from './requirements.ts';
20
+ import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError } from './environment-check.ts';
21
+ import { renderCompareHtml } from './compare-html.ts';
22
+ import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
11
23
 
12
- const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
24
+ const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
25
+ const MALFORMED=new Set(['REBUILD_REQUEST_INVALID','DENSITY_STRIP_REQUEST_INVALID','DENSITY_STRIP_FIELD','MESH_PATCH_SCOPE','EDIT_PATCH_INVALID','EDIT_PATCH_OP_UNKNOWN','EDIT_PATCH_POINTER_INVALID','EDIT_PATCH_CMD_UNKNOWN','EDIT_PATCH_ARG_UNKNOWN','BONES_OP_OUT_OF_SCOPE','RETARGET_REQUEST_INVALID']);
13
26
  const json=(value:unknown,status=200)=>Response.json(value,{status,headers});
14
- async function bodyJson(req:Request):Promise<unknown>{
27
+ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceeds 1 MiB'):Promise<unknown>{
15
28
  if(!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type')??''))throw new Error('Expected application/json');
16
- if(Number(req.headers.get('content-length')??0)>1024*1024)throw new Error('Session payload exceeds 1 MiB');
29
+ if(Number(req.headers.get('content-length')??0)>limit)throw new Error(what);
17
30
  if(!req.body)throw new Error('JSON body required');const reader=req.body.getReader(),chunks:Uint8Array[]=[];let size=0;
18
- while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>1024*1024){await reader.cancel();throw new Error('Session payload exceeds 1 MiB');}chunks.push(value);}
31
+ while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>limit){await reader.cancel();throw new Error(what);}chunks.push(value);}
19
32
  const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}return JSON.parse(new TextDecoder().decode(bytes));
20
33
  }
21
34
  function serveAsset(req:Request,path:string):Response{
@@ -29,16 +42,45 @@ function serveAsset(req:Request,path:string):Response{
29
42
  return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
30
43
  }
31
44
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
32
- export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string}={}){
45
+ export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
33
46
  const bundle=await buildWeb('compare');
34
47
  const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
48
+ const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
49
+ const makeSideTools=(side:'a'|'b',pkg:ReviewPackage)=>{
50
+ const unchanged=()=>assertReviewUnchanged(pkg),starts=[pkg.root,options.cwd??process.cwd()];
51
+ const rebuilds=createRebuilds(pkg,{stateDir,starts,unchanged,bones:pkg.feedbackCatalog.bones,assetPrefix:`/compare-rebuild/${side}`,stripPrefix:`/compare-density-strip/${side}`,...(options.stripConcurrency?{stripConcurrency:options.stripConcurrency}:{})});
52
+ const readings=createReadings(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
53
+ const bonesCheck=createBonesCheck(pkg,{stateDir,starts,unchanged});
54
+ const requirements=createRequirementsCheck(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
55
+ const environmentCheck=createEnvironmentCheck(pkg,{stateDir,starts,unchanged,latest:rebuilds.latest});
56
+ return {rebuilds,readings,bonesCheck,requirements,environmentCheck,busy:()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running())};
57
+ };
58
+ const sideTools={a:makeSideTools('a',p.a),b:makeSideTools('b',p.b)};
35
59
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.response.sourceHash,mode:'compare',unchanged:()=>assertCompareUnchanged(p),activity:options.activity}):null;
36
- const handle=async(req:Request,port:number|undefined):Promise<Response>=>{try{
60
+ let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
61
+ const live=createLiveLifecycle({
62
+ label:'review compare',
63
+ graceMs:options.graceMs,
64
+ unopenedTimeoutMs:options.unopenedTimeoutMs,
65
+ exitOnClose:options.exitOnClose,
66
+ onClose:options.onClose,
67
+ log:options.log,
68
+ busy:()=>sideTools.a.busy()||sideTools.b.busy(),
69
+ stopServer:()=>{rawStop?.(true);},
70
+ });
71
+ const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try{
37
72
  const url=new URL(req.url),origin=`http://127.0.0.1:${port}`;
38
73
  if(url.origin!==origin)return json({error:'Loopback host required'},403);
39
74
  const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
75
+ if(req.method==='GET'&&url.pathname===LIVE_PATH){
76
+ const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
77
+ if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
78
+ options.activity?.();return live.upgrade(req,srv,headers,options.open?.key);
79
+ }
80
+ live.onRequestStart(url.pathname);
81
+ try {
40
82
  const controlled=await control?.(req,origin);if(controlled)return controlled;
41
- options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}}return gate;}
83
+ options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
42
84
  if(req.method==='PUT'&&url.pathname==='/api/compare/session'){
43
85
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
44
86
  return json(await saveCompareSession(p,await bodyJson(req),options.stateDir));
@@ -48,16 +90,88 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
48
90
  const result=await exportCompareStrip(p,await bodyJson(req));
49
91
  return new Response(result.png?new Uint8Array(result.png):stripJson(result),{headers:{...headers,'Content-Type':result.png?'image/png':'application/json; charset=utf-8','Content-Disposition':`attachment; filename="review-strip.${result.png?'png':'json'}"`}});
50
92
  }
93
+ const sideApi=/^\/api\/compare\/(a|b)(\/.+)$/.exec(url.pathname);
94
+ if(sideApi){
95
+ const side=sideApi[1] as 'a'|'b',sub=sideApi[2]!,tools=sideTools[side];
96
+ if(req.method==='POST'){
97
+ if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
98
+ if(sub==='/rebuild'){
99
+ try{const result=await tools.rebuilds.start(await bodyJson(req,64*1024,'REBUILD_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
100
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
101
+ }
102
+ if(sub==='/rebuild/undo'){
103
+ try{const result=await tools.rebuilds.undo(await bodyJson(req,1024,'REBUILD_BODY_LIMIT: maximum 1 KiB'));return json(result.body,result.status);}
104
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
105
+ }
106
+ if(sub==='/density-strip'){
107
+ try{const result=await tools.rebuilds.startStrip(await bodyJson(req,DENSITY_STRIP_LIMIT,'DENSITY_STRIP_BODY_LIMIT: maximum 320 KiB'));return json(result.body,result.status);}
108
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
109
+ }
110
+ if(sub==='/density-strip/close'){
111
+ try{const result=await tools.rebuilds.closeStrip(await bodyJson(req,1024,'DENSITY_STRIP_BODY_LIMIT: maximum 1 KiB'));return json(result.body,result.status);}
112
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message,producerLine:null},MALFORMED.has(e.code)?400:200);throw e;}
113
+ }
114
+ if(sub==='/bones-check'){
115
+ try{return json(await tools.bonesCheck.run(await bodyJson(req,BONES_CHECK_LIMIT,'BONES_CHECK_BODY_LIMIT: maximum 64 KiB')));}
116
+ catch(e){if(e instanceof RebuildError)return json({status:'refused',error:e.message},MALFORMED.has(e.code)?400:200);throw e;}
117
+ }
118
+ if(sub==='/requirements'){
119
+ try{const result=await tools.requirements.start(await bodyJson(req,REQUIREMENTS_LIMIT,'REQUIREMENTS_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
120
+ catch(e){if(e instanceof RequirementsError)return json({status:'refused',error:e.message},e.code==='REQUIREMENTS_REQUEST_INVALID'?400:200);throw e;}
121
+ }
122
+ if(sub==='/environment-check'){
123
+ try{const result=await tools.environmentCheck.start(await bodyJson(req,ENVIRONMENT_CHECK_LIMIT,'ENVIRONMENT_CHECK_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
124
+ catch(e){if(e instanceof EnvironmentCheckError)return json({status:'refused',error:e.message},e.code==='ENVIRONMENT_CHECK_REQUEST_INVALID'?400:200);throw e;}
125
+ }
126
+ if(sub==='/readings'){
127
+ try{const result=await tools.readings.start(await bodyJson(req,64*1024,'READINGS_BODY_LIMIT: maximum 64 KiB'));return json(result.body,result.status);}
128
+ catch(e){if(e instanceof ReadingsError)return json({status:'refused',error:e.message},e.code==='READINGS_REQUEST_INVALID'?400:200);throw e;}
129
+ }
130
+ return json({error:'Not found'},404);
131
+ }
132
+ if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
133
+ if(sub==='/rebuild')return json(await tools.rebuilds.describe());
134
+ if(sub==='/rebuild/history')return json(await tools.rebuilds.history());
135
+ if(sub==='/density-strip')return json({strip:tools.rebuilds.readStrip()});
136
+ const stripStatus=/^\/density-strip\/([a-f0-9]{64})(?:\/([a-f0-9]{64}))?$/.exec(sub);
137
+ if(stripStatus){try{return json(stripStatus[2]?tools.rebuilds.stripJob(stripStatus[1]!,stripStatus[2]):tools.rebuilds.readStrip(stripStatus[1]!));}catch(e){if(e instanceof RebuildError)return json({error:e.message},404);throw e;}}
138
+ const rebuildStatus=/^\/rebuild\/([a-f0-9]{64})$/.exec(sub);
139
+ if(rebuildStatus){try{return json(tools.rebuilds.read(rebuildStatus[1]!));}catch(e){if(e instanceof RebuildError)return json({error:e.message},404);throw e;}}
140
+ if(sub==='/requirements')return json(await tools.requirements.describe());
141
+ const requirementsStatus=/^\/requirements\/([a-f0-9]{64})$/.exec(sub);
142
+ if(requirementsStatus){try{return json(tools.requirements.read(requirementsStatus[1]!));}catch(e){if(e instanceof RequirementsError)return json({error:e.message},404);throw e;}}
143
+ const environmentCheckStatus=/^\/environment-check\/([a-f0-9]{64})$/.exec(sub);
144
+ if(environmentCheckStatus){try{return json(tools.environmentCheck.read(environmentCheckStatus[1]!));}catch(e){if(e instanceof EnvironmentCheckError)return json({error:e.message},404);throw e;}}
145
+ const readingsStatus=/^\/readings\/([a-f0-9]{64})$/.exec(sub);
146
+ if(readingsStatus){try{return json(tools.readings.read(readingsStatus[1]!));}catch(e){if(e instanceof ReadingsError)return json({error:e.message},404);throw e;}}
147
+ return json({error:'Not found'},404);
148
+ }
51
149
  if(req.method!=='GET'&&req.method!=='HEAD')return json({error:'Method not allowed'},405);
150
+ const compareRebuildFile=/^\/compare-rebuild\/(a|b)\/([a-f0-9]{64})\/(.+)$/.exec(url.pathname);
151
+ if(compareRebuildFile){
152
+ const side=compareRebuildFile[1] as 'a'|'b';
153
+ let full:string;try{full=await sideTools[side].rebuilds.file(compareRebuildFile[2]!,decodeURIComponent(compareRebuildFile[3]!));}catch(e){return json({error:e instanceof Error?e.message:'Not found'},404);}
154
+ const file=Bun.file(full);return new Response(req.method==='HEAD'?null:file,{headers:{...headers,'Content-Security-Policy':"default-src 'none'; script-src 'none'; sandbox",'Content-Type':file.type||'application/octet-stream','Content-Length':String(file.size)}});
155
+ }
156
+ const compareStripFile=/^\/compare-density-strip\/(a|b)\/([a-f0-9]{64})\/([a-f0-9]{64})\/(.+)$/.exec(url.pathname);
157
+ if(compareStripFile){
158
+ const side=compareStripFile[1] as 'a'|'b';
159
+ let full:string;try{full=await sideTools[side].rebuilds.stripFile(compareStripFile[2]!,compareStripFile[3]!,decodeURIComponent(compareStripFile[4]!));}catch(e){return json({error:e instanceof Error?e.message:'Not found'},404);}
160
+ const file=Bun.file(full);return new Response(req.method==='HEAD'?null:file,{headers:{...headers,'Content-Security-Policy':"default-src 'none'; script-src 'none'; sandbox",'Content-Type':file.type||'application/octet-stream','Content-Length':String(file.size)}});
161
+ }
52
162
  if(url.pathname==='/api/compare/reference-frames'){if(url.search)return json({error:'Reference frame index accepts no parameters'},400);await assertCompareUnchanged(p);await safeCompareReference(p);return json(await frames());}
53
163
  if(url.pathname==='/api/compare'){await assertCompareUnchanged(p);return json(p.response);}
54
164
  if(url.pathname==='/api/compare/session')return json(await readCompareSession(p,options.stateDir));
55
165
  if(url.pathname==='/compare-reference')return await serveReference(req,await safeCompareReference(p),p.response.binding.reference.sha256,headers);
56
166
  if(url.pathname.startsWith('/compare-assets/')){const match=/^\/compare-assets\/(a|b)\/(.+)$/.exec(url.pathname);if(!match)return json({error:'Unknown comparison side'},404);const side=match[1] as 'a'|'b',path=packagePath(decodeURIComponent(match[2]!));if(!p[side].files.has(path))return json({error:'Asset not declared by package'},404);return serveAsset(req,await safeFile(p[side].root,path));}
57
167
  if(url.pathname==='/main.js')return new Response(req.method==='HEAD'?null:bundle,{headers:{...headers,'Content-Type':'text/javascript'}});
58
- if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
168
+ if(url.pathname==='/'||url.pathname==='/index.html'){const html=renderCompareHtml(await readFile(appRoot+'web/compare.html','utf8'),await readFile(appRoot+'web/index.html','utf8'));return new Response(req.method==='HEAD'?null:html,{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});}
59
169
  if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.css'),{headers:{...headers,'Content-Type':'text/css'}});
60
170
  return json({error:'Not found'},404);
171
+ } finally { live.onRequestEnd(url.pathname); }
61
172
  }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
62
- return Bun.serve({hostname:'127.0.0.1',port:options.port??4317,async fetch(req,server){return stampOpen(req,await handle(req,server.port),options.open);}});
173
+ const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
174
+ rawStop=server.stop.bind(server);
175
+ server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
176
+ return Object.assign(server,{live});
63
177
  }