@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/src/rebuild.ts CHANGED
@@ -409,6 +409,8 @@ export interface RebuildOptions {
409
409
  stateDir: string; starts: readonly string[]; unchanged: () => Promise<void>; bones: readonly string[] | null;
410
410
  /** #179: how many strip candidates run at once, at most four including the recording candidate. */
411
411
  stripConcurrency?: number;
412
+ assetPrefix?: string;
413
+ stripPrefix?: string;
412
414
  }
413
415
  /** #173: a density strip's scratch — one folder per package, holding at most the one strip on screen. */
414
416
  export const stripRoot = (stateDir: string, sourceHash: string) => join(stateDir, 'density-strip', sourceHash);
@@ -568,16 +570,17 @@ async function assembledAfter(job: PatchJob, dir: string, inputs: ProducerInputs
568
570
  }
569
571
 
570
572
  /** Hash every page the compiled model names and the model itself; names are literal relative paths inside the build. */
571
- async function hashBuild(build: string, id: string): Promise<RebuildBuild> {
573
+ async function hashBuild(build: string, id: string, assetPrefix = '/rebuild'): Promise<RebuildBuild> {
572
574
  const dir = await realpath(build), model = 'skeleton.model.json', bytes = await readFile(await safeFile(dir, model)), doc = object(JSON.parse(bytes.toString('utf8')), 'model');
573
575
  if (doc.spec !== 'rigc-compiled/3' || !Array.isArray(doc.pages)) throw new RebuildError('REBUILD_BUILD_INVALID', 'the compiled scratch model is not rigc-compiled/3 with pages');
574
576
  const files: Record<string, string> = { [model]: sha256(bytes) };
575
577
  for (const page of doc.pages) { const name = packagePath(object(page, 'model.pages[]').name, 'model.pages[].name'); files[name] = sha256(await readFile(await safeFile(dir, name))); }
576
- return { model, modelUrl: `/rebuild/${id}/${model}`, modelHash: files[model]!, files };
578
+ return { model, modelUrl: `${assetPrefix}/${id}/${model}`, modelHash: files[model]!, files };
577
579
  }
578
580
 
579
581
  /** One rebuild at a time per review instance; finished jobs stay readable by id. */
580
582
  export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
583
+ const assetPrefix = options.assetPrefix ?? '/rebuild', stripPrefix = options.stripPrefix ?? '/density-strip';
581
584
  const jobs = new Map<string, RebuildJob | PatchJob | DeltaJob | RetargetJob>();
582
585
  let running: string | null = null;
583
586
  /** #173: the density strip on screen (at most one per review): its candidates run beside each other, none of them applied. */
@@ -821,9 +824,9 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
821
824
  try {
822
825
  const stored = JSON.parse(await readFile(resultFile, 'utf8')) as J;
823
826
  if (stored.schema !== REBUILD_SCHEMA || stored.id !== id || stored.status !== 'built' || !stored.build) return null;
824
- const now = await hashBuild(join(dir, 'build'), id);
827
+ const now = await hashBuild(join(dir, 'build'), id, assetPrefix);
825
828
  if (JSON.stringify(now.files) !== JSON.stringify(stored.build.files)) return null;
826
- const job = { ...stored, reused: true };
829
+ const job = { ...stored, build: now, reused: true };
827
830
  // A retarget built before the job carried its report's frameTimes (#164): read them from the build's own report.
828
831
  if ('kind' in job && job.kind === 'retarget' && (job as RetargetJob).frameTimes === undefined) {
829
832
  let times: unknown = null;
@@ -888,7 +891,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
888
891
  // The package and its producer inputs must still be the bytes the request was made against.
889
892
  // The handoff files are in the reviewed identity, so this also catches a config, parts or rig change.
890
893
  try { await options.unchanged(); } catch { throw new RebuildError('REBUILD_INPUTS_CHANGED', 'the package or its producer handoff changed during the rebuild'); }
891
- job.build = await hashBuild(join(dir, 'build'), job.id);
894
+ job.build = await hashBuild(join(dir, 'build'), job.id, assetPrefix);
892
895
  if (steps.hashed) await steps.hashed();
893
896
  // #166: an undo's re-run must reproduce the build its record names, file for file; otherwise it is refused, not guessed.
894
897
  const changed = steps.candidate ? null : restoredDifference(job.id, job.build.files);
@@ -1244,7 +1247,7 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1244
1247
  function stripView(): DensityStripView | null {
1245
1248
  if (!strip) return null;
1246
1249
  const s = strip;
1247
- const rows = s.candidates.map(c => candidateRow({ value: c.value, id: c.id, entry: c.entry, job: c.job, part: s.part, modelUrl: c.job.build ? `/density-strip/${s.id}/${c.id}/${c.job.build.model}` : null, applied: c.applied }));
1250
+ const rows = s.candidates.map(c => candidateRow({ value: c.value, id: c.id, entry: c.entry, job: c.job, part: s.part, modelUrl: c.job.build ? `${stripPrefix}/${s.id}/${c.id}/${c.job.build.model}` : null, applied: c.applied }));
1248
1251
  return { schema: DENSITY_STRIP_SCHEMA, id: s.id, status: s.status, part: s.part, field: s.field, concurrency: s.concurrency, configHash: s.configHash, producer: s.producer, compiler: s.compiler, wallMs: s.wallMs, rows, labels: s.status === 'done' ? stripLabels(rows) : { fewest: null, widest: null } };
1249
1252
  }
1250
1253
  /** `GET /api/density-strip/<id>` (and `GET /api/density-strip`: the strip on screen, or null). */
@@ -1524,5 +1527,5 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
1524
1527
  return safeFile(await realpath(join(rebuildDir(options.stateDir, p.sourceHash, id), 'build')), packagePath(name));
1525
1528
  }
1526
1529
 
1527
- return { describe, start, read, file, running: () => running, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
1530
+ return { describe, start, read, file, running: () => running, busy: () => busy() !== null, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
1528
1531
  }
package/src/server.ts CHANGED
@@ -4,7 +4,7 @@ import { appRoot, buildWeb } from './build.ts';
4
4
  import { packagePath, safeFile, type ReviewPackage } from './manifest.ts';
5
5
  import { exportReviewStrip, stripJson } from './strip-export.ts';
6
6
  import {assertReviewUnchanged,referenceBinding,selectedReference,safeSelectedReference,serveReference} from './reference.ts';
7
- import {openGate,staleOpenStatus,accessGate,openNonceGate,stampOpen,type OpenIdentity} from './open-protocol.ts';
7
+ import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
8
8
  import { readSession, saveSession } from './session.ts';
9
9
  import { createRebuilds, RebuildError } from './rebuild.ts';
10
10
  import { DENSITY_STRIP_LIMIT } from './density-strip.ts';
@@ -14,6 +14,7 @@ import { BONES_CHECK_LIMIT, createBonesCheck } from './bones-check.ts';
14
14
  import { createRequirementsCheck } from './requirements-run.ts';
15
15
  import { REQUIREMENTS_LIMIT, RequirementsError } from './requirements.ts';
16
16
  import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError } from './environment-check.ts';
17
+ import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
17
18
  import { homedir } from 'node:os';
18
19
  import { join } from 'node:path';
19
20
  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'};
@@ -29,7 +30,7 @@ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceed
29
30
  }
30
31
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it.
31
32
  * `cwd` is where the producer is looked for after the package's own directories (review's working directory by default). */
32
- export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number}={}){
33
+ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;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
34
  const bundle=await buildWeb();
34
35
  const unchanged=()=>assertReviewUnchanged(p);
35
36
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
@@ -43,12 +44,30 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
43
44
  // Check under this world (#112): the exported schedule written into scratch; the installed producer's check --environment reads it.
44
45
  const environmentCheck=createEnvironmentCheck(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
45
46
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.sourceHash,mode:'single',unchanged,activity:options.activity}):null;
46
- const handle=async(req:Request,port:number|undefined):Promise<Response>=>{try {
47
+ let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
48
+ const live=createLiveLifecycle({
49
+ label:'review',
50
+ graceMs:options.graceMs,
51
+ unopenedTimeoutMs:options.unopenedTimeoutMs,
52
+ exitOnClose:options.exitOnClose,
53
+ onClose:options.onClose,
54
+ log:options.log,
55
+ busy:()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running()),
56
+ stopServer:()=>{rawStop?.(true);},
57
+ });
58
+ const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try {
47
59
  const url=new URL(req.url);const origin=`http://127.0.0.1:${port}`;
48
60
  if(url.origin!==origin)return json({error:'Loopback host required'},403);
49
61
  const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
62
+ if(req.method==='GET'&&url.pathname===LIVE_PATH){
63
+ const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
64
+ if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
65
+ options.activity?.();return live.upgrade(req,srv,headers,options.open?.key);
66
+ }
67
+ live.onRequestStart(url.pathname);
68
+ try {
50
69
  const controlled=await control?.(req,origin);if(controlled)return controlled;
51
- options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}}return gate;}
70
+ options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
52
71
  if(req.method==='PUT'&&url.pathname==='/api/session'){
53
72
  if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
54
73
  const input=await bodyJson(req);await unchanged();return json(await saveSession(p,input,options.stateDir));
@@ -148,6 +167,10 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
148
167
  if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/index.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
149
168
  if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
150
169
  return json({error:'Not found'},404);
170
+ } finally { live.onRequestEnd(url.pathname); }
151
171
  }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
152
- 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);}});
172
+ 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);}});
173
+ rawStop=server.stop.bind(server);
174
+ server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
175
+ return Object.assign(server,{live});
153
176
  }
@@ -26,8 +26,8 @@ export function stageCommentMode(value:unknown):CommentMode {
26
26
  const c=obj(value);
27
27
  if(!Object.hasOwn(c,'mode'))throw new Error('COMMENT_MODE_MISSING: placement mode is required');
28
28
  if(!commentModes.includes(c.mode))throw new Error('COMMENT_MODE_UNKNOWN: expected setup, animate or compare');
29
- const b=c.bookmark;
30
- if(c.mode==='compare' ? b?.binding?.mode!=='compare'||c.viewport==='rig' : b?.binding?.mode!=='single'||!['rig','reference'].includes(c.viewport)||b?.selection?.inspector!==(c.mode==='setup'?'rig':'playback'))throw new Error('COMMENT_MODE_MISMATCH: placement mode differs from page, viewport or saved inspector');
29
+ const b=c.bookmark,bm=b?.binding?.mode,selMode=b?.selection?.mode;
30
+ if(bm==='single' ? c.mode==='compare'||!['rig','reference'].includes(c.viewport)||b?.selection?.inspector!==(c.mode==='setup'?'rig':'playback') : bm!=='compare'||c.viewport==='rig'||selMode!==undefined&&selMode!==c.mode||(c.mode==='setup'&&b?.selection?.inspector!=='rig')||(c.mode==='animate'&&b?.selection?.inspector!=='playback'))throw new Error('COMMENT_MODE_MISMATCH: placement mode differs from page, viewport or saved inspector');
31
31
  return c.mode;
32
32
  }
33
33
  export function parseStageComment(value:unknown):StageComment {