screw-bugs 0.1.5 → 0.1.7

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.
@@ -1,6 +1,6 @@
1
1
  import { Cause, Clock, Context, Duration, Effect, FileSystem, Layer, Option, Path, Predicate, Schedule, Schema, } from 'effect';
2
2
  import { AccountBook, Browser, describeSignInWhy, Engine, originOf, evidencePackOf, REPORT_STALE_MS, staleFor, Storage, } from '../core/index.js';
3
- import { AccountAbout, AccountLabel, Findings, JobId, NewJobSpec, ProjectConfig, runFiles, } from '../schema/index.js';
3
+ import { AccountAbout, AccountLabel, Findings, JobId, judgedLedger, NewJobSpec, ProjectConfig, runFiles, } from '../schema/index.js';
4
4
  import { CONFIG_FILE, loadConfig, missingConfig } from './config.js';
5
5
  import { runDoctor } from './doctor.js';
6
6
  import { ExitCode } from './exit-codes.js';
@@ -110,12 +110,18 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
110
110
  return undefined;
111
111
  })));
112
112
  });
113
+ /**
114
+ * The run's saved findings (`findings.json`); none when there are none, or the file
115
+ * cannot be read or does not decode, as the report treats it.
116
+ */
117
+ const savedFindings = (jobId) => storage.readFile(jobId, runFiles.findings).pipe(Effect.flatMap((text) => text === undefined ? Effect.succeed(undefined) : decodeFindingsText(text)), Effect.orElseSucceed(() => undefined));
113
118
  /**
114
119
  * The ledger read by `read`, and the report path of an ended run. Unless `writeReport` is
115
120
  * false, an interrupted run's report may be written now (see `reportOf`).
116
121
  */
117
122
  const ledgerOf = (jobId, read, writeReport = true) => Effect.gen(function* () {
118
123
  const ledger = yield* read(jobId).pipe(orRunNotFound(jobId));
124
+ const findings = isOver(ledger) ? yield* savedFindings(jobId) : undefined;
119
125
  const reportPath = isOver(ledger)
120
126
  ? yield* reportOf(jobId, ledger, writeReport)
121
127
  : undefined;
@@ -125,6 +131,7 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
125
131
  runDir: storage.runDir(jobId),
126
132
  reportPath,
127
133
  walkthroughPath,
134
+ judged: judgedLedger(ledger, findings),
128
135
  };
129
136
  });
130
137
  /**
@@ -337,9 +344,11 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
337
344
  }));
338
345
  // Saved findings stay saved; a report that may not be rewritten yet shows them later.
339
346
  const report = yield* rewriteReport(jobId).pipe(Effect.map((written) => written.path), Effect.catchTag('Failure', () => Effect.succeed(undefined)));
347
+ const ledger = yield* engine.status(jobId).pipe(orRunNotFound(jobId));
340
348
  return {
341
349
  jobId,
342
350
  ...saved,
351
+ judged: judgedLedger(ledger, findings),
343
352
  reportPath: report,
344
353
  walkthroughPath: yield* walkthroughOf(jobId, report),
345
354
  };
@@ -414,7 +423,15 @@ export class Operations extends Context.Service()('screw-bugs/Operations') {
414
423
  return { link, done: signIns.value.wait(label) };
415
424
  }),
416
425
  removeAccount: (raw) => decodeLabel(raw).pipe(Effect.flatMap((label) => accountBook.remove(label).pipe(Effect.mapError(accountsFailure)))),
417
- listRuns: (limit) => storage.listRuns(limit).pipe(Effect.mapError(storageFailure)),
426
+ listRuns: (limit) => storage.listRuns(limit).pipe(Effect.mapError(storageFailure), Effect.flatMap((runs) => Effect.forEach(runs, (run) => run.ledger === undefined || !isOver(run.ledger)
427
+ ? Effect.succeed({
428
+ ...run,
429
+ judged: run.ledger && judgedLedger(run.ledger, undefined),
430
+ })
431
+ : savedFindings(run.job.jobId).pipe(Effect.map((findings) => ({
432
+ ...run,
433
+ judged: judgedLedger(run.ledger, findings),
434
+ })))))),
418
435
  answer: (input) => Effect.gen(function* () {
419
436
  const jobId = yield* decodeJobId(input.jobId);
420
437
  yield* engine.answer({ jobId, questionId: input.questionId, text: input.text }).pipe(Effect.catchTags({
@@ -447,5 +464,6 @@ export const schemaProblems = (message) => {
447
464
  problems.push(pending.join(' '));
448
465
  return problems;
449
466
  };
467
+ const decodeFindingsText = Schema.decodeUnknownEffect(Schema.fromJsonString(Findings));
450
468
  const invalidInput = (error) => new Failure({ code: ExitCode.Usage, reason: 'invalid_job', message: error.message });
451
469
  const storageFailure = (error) => new Failure({ code: ExitCode.Internal, reason: 'storage_failed', message: error.message });
package/dist/cli/share.js CHANGED
@@ -112,11 +112,11 @@ const onOrigin = (url, origin) => {
112
112
  }
113
113
  };
114
114
  /** The person-facing sentence of a reply Cloud refused, from its error body when it has one. */
115
- const refusal = (response) => HttpIncomingMessage.schemaBodyJson(ShareErrorReply)(response).pipe(Effect.map((reply) => reply.message), Effect.orElseSucceed(() => `screw-bugs Cloud answered ${response.status}.`), Effect.flatMap((message) => Effect.fail(new ShareFailed({ message }))));
115
+ const refusal = (response) => HttpIncomingMessage.schemaBodyJson(ShareErrorReply)(response).pipe(Effect.map((reply) => reply.message), Effect.orElseSucceed(() => `Screw Bugs Cloud answered ${response.status}.`), Effect.flatMap((message) => Effect.fail(new ShareFailed({ message }))));
116
116
  /** `response` decoded with `schema` when it is a success; Cloud's own sentence when not. */
117
117
  const answer = (response, schema) => response.status >= 200 && response.status < 300
118
118
  ? HttpIncomingMessage.schemaBodyJson(schema)(response).pipe(Effect.mapError(() => new ShareFailed({
119
- message: 'screw-bugs Cloud gave an answer this version cannot read.',
119
+ message: 'Screw Bugs Cloud gave an answer this version cannot read.',
120
120
  })))
121
121
  : refusal(response);
122
122
  /** How much of a file is read at a time while it uploads. */
@@ -157,13 +157,13 @@ export const uploadShare = (input) => Effect.gen(function* () {
157
157
  const client = yield* HttpClient.HttpClient;
158
158
  const source = yield* ShareSource;
159
159
  const unreachable = (error) => new ShareFailed({
160
- message: `Could not reach screw-bugs Cloud at ${input.cloud}: ${String(error)}.`,
160
+ message: `Could not reach Screw Bugs Cloud at ${input.cloud}: ${String(error)}.`,
161
161
  });
162
162
  /** `effect`, failing as Cloud not answering after `duration`. */
163
163
  const answeredWithin = (duration) => (effect) => effect.pipe(Effect.timeoutOrElse({
164
164
  duration,
165
165
  orElse: () => Effect.fail(new ShareFailed({
166
- message: `screw-bugs Cloud at ${input.cloud} stopped answering; the share was not made.`,
166
+ message: `Screw Bugs Cloud at ${input.cloud} stopped answering; the share was not made.`,
167
167
  })),
168
168
  }));
169
169
  const bundle = scrubBundle(yield* source
@@ -171,7 +171,7 @@ export const uploadShare = (input) => Effect.gen(function* () {
171
171
  .pipe(Effect.mapError(() => new ShareFailed({ message: `Could not read the run ${input.jobId}.` }))));
172
172
  if (bundle.generator === undefined)
173
173
  return yield* new ShareFailed({
174
- message: 'This screw-bugs build does not know its version, which screw-bugs Cloud needs to show the report.',
174
+ message: 'This screw-bugs build does not know its version, which Screw Bugs Cloud needs to show the report.',
175
175
  });
176
176
  const generator = bundle.generator;
177
177
  // Each file by its real path, and only one that really is a file Cloud takes inside the run
@@ -224,7 +224,7 @@ export const uploadShare = (input) => Effect.gen(function* () {
224
224
  })))
225
225
  .pipe(Effect.mapError(unreachable), Effect.flatMap((response) => answer(response, CreatedShare)), answeredWithin(CLOUD_ANSWER_TIMEOUT));
226
226
  const wrongPlace = new ShareFailed({
227
- message: 'screw-bugs Cloud asked for an upload somewhere else; nothing more was sent.',
227
+ message: 'Screw Bugs Cloud asked for an upload somewhere else; nothing more was sent.',
228
228
  });
229
229
  let done = 0;
230
230
  for (const upload of created.uploads) {
@@ -254,7 +254,7 @@ export const uploadShare = (input) => Effect.gen(function* () {
254
254
  }).pipe(Effect.scoped, Effect.timeoutOrElse({
255
255
  duration: UPLOAD_DEADLINE,
256
256
  orElse: () => Effect.fail(new ShareFailed({
257
- message: 'The upload took longer than screw-bugs Cloud allows; the share was not made.',
257
+ message: 'The upload took longer than Screw Bugs Cloud allows; the share was not made.',
258
258
  })),
259
259
  }));
260
260
  /**
@@ -313,7 +313,7 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
313
313
  const callback = (query) => Effect.gen(function* () {
314
314
  const params = Schema.decodeUnknownOption(ShareCallback)(Object.fromEntries(query));
315
315
  if (Option.isNone(params))
316
- return sharePage('Share not started', 'This link is not from screw-bugs Cloud.', {
316
+ return sharePage('Share not started', 'This link is not from Screw Bugs Cloud.', {
317
317
  status: 400,
318
318
  });
319
319
  const { state, ticket, api } = params.value;
@@ -324,7 +324,7 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
324
324
  now - entry.created >= SHARE_WAIT_MS)
325
325
  return sharePage('Share not started', 'This share was not started here, was already used, or waited too long. Click Share in the report again.', { status: 410 });
326
326
  if (originOf(api) !== cloud)
327
- return sharePage('Share not started', `The ticket is for another screw-bugs Cloud than ${cloud}; nothing was sent.`, { status: 400, back: back(entry.jobId) });
327
+ return sharePage('Share not started', `The ticket is for another Screw Bugs Cloud than ${cloud}; nothing was sent.`, { status: 400, back: back(entry.jobId) });
328
328
  const free = yield* Ref.modify(uploading, (busy) => [!busy, true]);
329
329
  if (!free)
330
330
  return sharePage('Another share is uploading', 'This server uploads one share at a time. Reload this page once the other one is done.', { status: 409, back: back(entry.jobId) });
@@ -352,7 +352,7 @@ export const makeShareRoutes = (root) => Effect.gen(function* () {
352
352
  const phase = entry.phase;
353
353
  switch (phase._tag) {
354
354
  case 'uploading':
355
- return sharePage('Sharing on screw-bugs Cloud', phase.total === 0
355
+ return sharePage('Sharing on Screw Bugs Cloud', phase.total === 0
356
356
  ? 'Uploading the report…'
357
357
  : `Uploading screenshots and videos: ${phase.done} of ${phase.total}.`, { refresh: PROGRESS_REFRESH_S });
358
358
  case 'done':
@@ -253,29 +253,43 @@ export class Engine extends Context.Service()('screw-bugs/Engine') {
253
253
  const end = (next) => write(() => next, true);
254
254
  /** The session that is open, if one is: its number, video and when its video started. */
255
255
  let open;
256
+ /**
257
+ * The session that ended while its video is being measured, so a run interrupted then
258
+ * still records it (without `still`).
259
+ */
260
+ let measuring;
256
261
  /**
257
262
  * Checks the video of the open session once its browser is closed: it exists, is not
258
- * empty, and is about as long as the session ran (`videoProblemOf`).
263
+ * empty, and is about as long as the session ran (`videoProblemOf`); with `measure`, also
264
+ * where it stands still (`Browser.stillVideo`).
259
265
  */
260
- const sessionEnd = Effect.gen(function* () {
266
+ const sessionEnd = (measure) => Effect.gen(function* () {
261
267
  if (open === undefined)
262
- return undefined;
268
+ return measuring;
263
269
  const { number, video, startedAt } = open;
264
270
  open = undefined;
265
271
  const durationMs = Math.round((yield* Clock.currentTimeMillis) - startedAt);
266
272
  const file = yield* storage.probe(jobId, video, VIDEO_HEAD_BYTES);
267
273
  const videoDurationMs = file === undefined ? undefined : webmDurationMs(file.head);
268
274
  const problem = videoProblemOf(file === undefined ? undefined : { size: file.size, durationMs: videoDurationMs }, durationMs);
269
- return {
275
+ const saved = file !== undefined && file.size > 0;
276
+ const ended = {
270
277
  number,
271
278
  fields: {
272
279
  endedAt: yield* now,
273
280
  durationMs,
274
- ...(file !== undefined && file.size > 0 ? { video } : {}),
281
+ ...(saved ? { video } : {}),
275
282
  ...(videoDurationMs !== undefined ? { videoDurationMs } : {}),
276
283
  ...(problem !== undefined ? { videoProblem: problem } : {}),
277
284
  },
278
285
  };
286
+ if (!measure || !saved)
287
+ return ended;
288
+ // Where the video stands still, for the walkthrough's "Skip inactive".
289
+ measuring = ended;
290
+ const still = yield* browser.stillVideo(storage.filePath(jobId, video));
291
+ measuring = undefined;
292
+ return still === undefined ? ended : { number, fields: { ...ended.fields, still } };
279
293
  });
280
294
  /** The sessions of `current` with the one that just ended filled in. */
281
295
  const withSession = (current, ended, videoProblem) => current.sessions === undefined
@@ -292,7 +306,8 @@ export class Engine extends Context.Service()('screw-bugs/Engine') {
292
306
  };
293
307
  /** Ends the job early: whatever has not run stays not verified, with `reason`. */
294
308
  const stop = (error, reason) => Effect.gen(function* () {
295
- const ended = yield* sessionEnd;
309
+ // An interrupted run ends at once: its video is not measured.
310
+ const ended = yield* sessionEnd(error !== RUN_INTERRUPTED);
296
311
  yield* end({
297
312
  ...ledger,
298
313
  state: 'errored',
@@ -365,7 +380,7 @@ export class Engine extends Context.Service()('screw-bugs/Engine') {
365
380
  }
366
381
  }
367
382
  const { videoProblem } = yield* session.close;
368
- const ended = yield* sessionEnd;
383
+ const ended = yield* sessionEnd(true);
369
384
  if (crash !== undefined) {
370
385
  const error = `The browser stopped working during case "${crash.caseId}": ${crash.message}`;
371
386
  yield* end({
@@ -1,5 +1,5 @@
1
1
  import { Context, type Effect, type Scope } from 'effect';
2
- import type { AccountEntry, Box, Candidate, CaseLedger, Device, ElementTarget, JobId, JobRecord, JobSpec, JobState, OnScreen, PageFacts, PageNode, Point, ReportBundle, SavedSession, ShotFrame, SignInInput, Target, Truncated, VisualViewport, WaitState } from '../schema/index.js';
2
+ import type { AccountEntry, Box, Candidate, CaseLedger, Device, ElementTarget, JobId, JobRecord, JobSpec, JobState, OnScreen, PageFacts, PageNode, Point, ReportBundle, SavedSession, ShotFrame, SignInInput, StillStretch, Target, Truncated, VisualViewport, WaitState } from '../schema/index.js';
3
3
  import type { BrowserNotFound, PageActionFailed, RunNotFound, StorageFailed } from './errors.js';
4
4
  export type BrowserKind = 'chrome' | 'msedge' | 'playwright-chromium';
5
5
  export interface BrowserInfo {
@@ -376,6 +376,11 @@ declare const Browser_base: Context.ServiceClass<Browser, "screw-bugs/Browser",
376
376
  readonly detect: Effect.Effect<BrowserInfo, BrowserNotFound>;
377
377
  /** Whether sessions can be recorded; looked up without downloading or launching anything. */
378
378
  readonly videoSupport: Effect.Effect<VideoSupport>;
379
+ /**
380
+ * Where the saved video at `file` (an absolute path) stands still (see `stillStretches`);
381
+ * undefined when that could not be measured. Reads the video only.
382
+ */
383
+ readonly stillVideo: (file: string) => Effect.Effect<ReadonlyArray<StillStretch> | undefined>;
379
384
  readonly open: (options: {
380
385
  readonly headed: boolean;
381
386
  }) => Effect.Effect<BrowserSession, BrowserNotFound, Scope.Scope>;
@@ -1,3 +1,4 @@
1
+ import type { StillStretch } from '../schema/index.js';
1
2
  /** How many bytes from the start of a video file `webmDurationMs` needs. */
2
3
  export declare const VIDEO_HEAD_BYTES: number;
3
4
  /**
@@ -14,3 +15,33 @@ export declare const videoProblemOf: (file: {
14
15
  readonly size: number;
15
16
  readonly durationMs: number | undefined;
16
17
  } | undefined, sessionMs: number) => string | undefined;
18
+ /** Frames a second the video is sampled at to find where it stands still. */
19
+ export declare const STILL_FPS = 4;
20
+ /** How wide, in pixels, each sampled frame is (its height keeps the video's shape). */
21
+ export declare const STILL_WIDTH = 64;
22
+ /** A pixel changed when its grey level moved by more than this (the video's own noise stays under it). */
23
+ export declare const STILL_LEVEL = 8;
24
+ /** A frame changed when at least this many of its pixels did. */
25
+ export declare const STILL_PIXELS = 3;
26
+ /** Still stretches shorter than this are not recorded. */
27
+ export declare const STILL_MIN_MS = 1000;
28
+ /** A grey image: one byte a pixel, row by row. */
29
+ export interface GrayImage {
30
+ readonly width: number;
31
+ readonly height: number;
32
+ readonly pixels: Uint8Array;
33
+ }
34
+ /**
35
+ * The pixels of an 8-bit greyscale, non-interlaced PNG (what ffmpeg writes with `-pix_fmt gray`),
36
+ * with `inflate` to undo its zlib compression; undefined for any other PNG or a broken one.
37
+ */
38
+ export declare const grayPng: (bytes: Uint8Array, inflate: (data: Uint8Array) => Uint8Array) => GrayImage | undefined;
39
+ /** Whether `next` shows something other than `previous`: `STILL_PIXELS` or more moved past `STILL_LEVEL`. */
40
+ export declare const frameChanged: (previous: GrayImage, next: GrayImage) => boolean;
41
+ /**
42
+ * The stretches in which frames sampled every `frameMs` (the first at 0) did not change (from one
43
+ * to the next, nor from the first of the stretch), at least
44
+ * `STILL_MIN_MS` long: from the first frame of each still run to its last, and to the end of the
45
+ * last frame for a run that lasts to the end. In time order.
46
+ */
47
+ export declare const stillStretches: (frames: ReadonlyArray<GrayImage>, frameMs: number) => ReadonlyArray<StillStretch>;
@@ -99,3 +99,135 @@ export const videoProblemOf = (file, sessionMs) => {
99
99
  ? `The video is ${seconds(file.durationMs)} long, but the session ran for ${seconds(sessionMs)}.`
100
100
  : undefined;
101
101
  };
102
+ /*
103
+ * Where a session's video stands still, for the walkthrough's "Skip inactive". After a session,
104
+ * Playwright's ffmpeg writes the video as small grey PNG frames (`STILL_FPS` a second,
105
+ * `STILL_WIDTH` pixels wide); here, in pure code, they are decoded and compared one after
106
+ * another. Measuring never changes the video, a status or anything a run did.
107
+ */
108
+ /** Frames a second the video is sampled at to find where it stands still. */
109
+ export const STILL_FPS = 4;
110
+ /** How wide, in pixels, each sampled frame is (its height keeps the video's shape). */
111
+ export const STILL_WIDTH = 64;
112
+ /** A pixel changed when its grey level moved by more than this (the video's own noise stays under it). */
113
+ export const STILL_LEVEL = 8;
114
+ /** A frame changed when at least this many of its pixels did. */
115
+ export const STILL_PIXELS = 3;
116
+ /** Still stretches shorter than this are not recorded. */
117
+ export const STILL_MIN_MS = 1000;
118
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
119
+ const paeth = (a, b, c) => {
120
+ const p = a + b - c;
121
+ const pa = Math.abs(p - a);
122
+ const pb = Math.abs(p - b);
123
+ const pc = Math.abs(p - c);
124
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
125
+ };
126
+ /**
127
+ * The pixels of an 8-bit greyscale, non-interlaced PNG (what ffmpeg writes with `-pix_fmt gray`),
128
+ * with `inflate` to undo its zlib compression; undefined for any other PNG or a broken one.
129
+ */
130
+ export const grayPng = (bytes, inflate) => {
131
+ if (bytes.length < 8 || PNG_SIGNATURE.some((b, i) => bytes[i] !== b))
132
+ return undefined;
133
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
134
+ const tag = (at) => String.fromCharCode(...bytes.subarray(at, at + 4));
135
+ let width = 0;
136
+ let height = 0;
137
+ const data = [];
138
+ let at = 8;
139
+ while (at + 12 <= bytes.length) {
140
+ const length = view.getUint32(at);
141
+ const type = tag(at + 4);
142
+ const body = at + 8;
143
+ if (body + length > bytes.length)
144
+ return undefined;
145
+ if (type === 'IHDR') {
146
+ if (length < 13)
147
+ return undefined;
148
+ width = view.getUint32(body);
149
+ height = view.getUint32(body + 4);
150
+ const [depth, color, , , interlace] = bytes.subarray(body + 8, body + 13);
151
+ if (depth !== 8 || color !== 0 || interlace !== 0)
152
+ return undefined;
153
+ }
154
+ else if (type === 'IDAT')
155
+ data.push(bytes.subarray(body, body + length));
156
+ else if (type === 'IEND')
157
+ break;
158
+ at = body + length + 4;
159
+ }
160
+ if (width === 0 || height === 0 || data.length === 0)
161
+ return undefined;
162
+ const joined = new Uint8Array(data.reduce((n, d) => n + d.length, 0));
163
+ data.reduce((offset, d) => (joined.set(d, offset), offset + d.length), 0);
164
+ let raw;
165
+ try {
166
+ raw = inflate(joined);
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ if (raw.length < height * (width + 1))
172
+ return undefined;
173
+ const pixels = new Uint8Array(width * height);
174
+ for (let y = 0; y < height; y++) {
175
+ const filter = raw[y * (width + 1)];
176
+ const row = y * width;
177
+ for (let x = 0; x < width; x++) {
178
+ const value = raw[y * (width + 1) + 1 + x];
179
+ const left = x > 0 ? pixels[row + x - 1] : 0;
180
+ const up = y > 0 ? pixels[row - width + x] : 0;
181
+ const corner = x > 0 && y > 0 ? pixels[row - width + x - 1] : 0;
182
+ const predicted = filter === 0
183
+ ? 0
184
+ : filter === 1
185
+ ? left
186
+ : filter === 2
187
+ ? up
188
+ : filter === 3
189
+ ? (left + up) >> 1
190
+ : filter === 4
191
+ ? paeth(left, up, corner)
192
+ : undefined;
193
+ if (predicted === undefined)
194
+ return undefined;
195
+ pixels[row + x] = (value + predicted) & 0xff;
196
+ }
197
+ }
198
+ return { width, height, pixels };
199
+ };
200
+ /** Whether `next` shows something other than `previous`: `STILL_PIXELS` or more moved past `STILL_LEVEL`. */
201
+ export const frameChanged = (previous, next) => {
202
+ if (previous.width !== next.width || previous.height !== next.height)
203
+ return true;
204
+ let changed = 0;
205
+ for (let i = 0; i < next.pixels.length; i++)
206
+ if (Math.abs(next.pixels[i] - previous.pixels[i]) > STILL_LEVEL && ++changed >= STILL_PIXELS)
207
+ return true;
208
+ return false;
209
+ };
210
+ /**
211
+ * The stretches in which frames sampled every `frameMs` (the first at 0) did not change (from one
212
+ * to the next, nor from the first of the stretch), at least
213
+ * `STILL_MIN_MS` long: from the first frame of each still run to its last, and to the end of the
214
+ * last frame for a run that lasts to the end. In time order.
215
+ */
216
+ export const stillStretches = (frames, frameMs) => {
217
+ const stretches = [];
218
+ const add = (from, to) => {
219
+ if (to - from >= STILL_MIN_MS)
220
+ stretches.push({ fromMs: from, toMs: to });
221
+ };
222
+ let start = 0;
223
+ // Each frame is compared with the one before and with the first of its still run, so a change
224
+ // too slow to show between two frames (a fade) still ends the run.
225
+ for (let i = 1; i < frames.length; i++)
226
+ if (frameChanged(frames[i - 1], frames[i]) || frameChanged(frames[start], frames[i])) {
227
+ add(start * frameMs, (i - 1) * frameMs);
228
+ start = i;
229
+ }
230
+ if (frames.length > 0)
231
+ add(start * frameMs, frames.length * frameMs);
232
+ return stretches;
233
+ };
@@ -19,7 +19,7 @@ import { type RenderOptions } from './assets.js';
19
19
  * failed. Without script: the video has its own controls, timecodes open the video at their time
20
20
  * and screenshots open the image.
21
21
  */
22
- export declare const REPORT_SCRIPT = "(()=>{const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),empty=d.getElementById(p+'-none');let cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{if(!v.error)return;dead.add(cur);if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n\nconst badImg=i=>{const f=i.closest('figure');if(!f||f.classList.contains('broken'))return;f.classList.add('broken');f.querySelectorAll('.unloaded').forEach(u=>u.removeAttribute('aria-hidden'))};\nconst scan=()=>d.querySelectorAll('figure img').forEach(i=>{if(i.complete&&i.naturalWidth===0)badImg(i)});\nd.addEventListener('error',e=>{const t=e.target;if(t instanceof Element&&t.matches('figure img'))badImg(t)},true);\naddEventListener('load',scan);\nd.addEventListener('DOMContentLoaded',()=>{\n chrome();scan();\n const cards=[...d.querySelectorAll('.case[data-i]')],segs=[...d.querySelectorAll('.seg[data-case]')];\n const np=d.getElementById('rp-now'),loopB=d.getElementById('rp-loop'),dlg=d.getElementById('viewer');\n const N=cards.length,dash=String.fromCharCode(8211);let cur=null,loop=true,lock=0,lastT=0,P=null,sr=0;\n const timed=c=>!!c&&c.dataset.t0!==undefined;\n const span=c=>[Number(c.dataset.t0),Number(c.dataset.t1)];\n const shown=()=>cards.filter(c=>!c.hidden);\n const line=()=>{const b=topEdge();if(matchMedia('(max-width: 900px)').matches){const s=d.querySelector('.rp-left');return s?s.getBoundingClientRect().bottom+24:b+120}return Math.round(b+(innerHeight-b)*0.3)};\n const playable=c=>timed(c)&&!!P&&P.has(c.dataset.s);\n const chip=c=>{if(!playable(c)||P.down()!==null)return '';const s=span(c);return (loop?'Looping ':'Playing ')+clock(s[0])+dash+clock(s[1])};\n const paintNow=()=>{\n if(!np||!cur)return;\n np.querySelector('.np-st').replaceChildren(cur.querySelector('.case-head .st').cloneNode(true));\n np.querySelector('.np-n').textContent=cur.dataset.i+' / '+N;\n np.querySelector('.np-title').textContent=cur.querySelector('.case-go').textContent;\n np.querySelector('.np-status').textContent=cur.dataset.label+': ';\n const ch=np.querySelector('.np-chip'),t=chip(cur);ch.querySelector('span').textContent=t||'No video';ch.classList.toggle('none',!t);\n };\n const toCard=c=>{lock=Date.now()+700;const y=c.getBoundingClientRect().top+scrollY-line()+2;scrollTo({top:Math.max(0,y),behavior:still()?'auto':'smooth'})};\n const setCurrent=(c,seek,scroll)=>{\n if(!c)return;\n if(c!==cur){if(cur){cur.classList.remove('on');cur.removeAttribute('aria-current')}cur=c;c.classList.add('on');c.setAttribute('aria-current','true');segs.forEach(x=>x.classList.toggle('on',x.dataset.case===c.dataset.id));paintNow()}\n if(seek&&P){if(playable(c)){const a=span(c)[0];lastT=a;P.load(c.dataset.s,a,P.playing())}else P.none()}\n if(scroll)toCard(c);\n };\n const caseAt=(s,t)=>{let f=null;for(const c of shown()){if(timed(c)&&c.dataset.s===s){const x=span(c);if(t>=x[0]&&t<x[1])f=c}}return f};\n const onScroll=()=>{\n if(Date.now()<lock)return;const vis=shown();if(!vis.length)return;\n const L=line();let pick=vis[0];for(const c of vis){if(c.getBoundingClientRect().top<=L)pick=c}\n const last=vis[vis.length-1];if(innerHeight+scrollY>=r.scrollHeight-2&&last.getBoundingClientRect().bottom<=innerHeight)pick=last;\n if(pick!==cur)setCurrent(pick,true,false);\n };\n const stk=d.querySelector('.rp-sticky'),head=d.querySelector('.rp-head');\n const fit=()=>{if(stk)stk.style.setProperty('--rp-top',Math.round(stk.getBoundingClientRect().top)+'px')};\n fit();addEventListener('resize',fit);addEventListener('load',fit);\n if(head&&window.ResizeObserver)new ResizeObserver(fit).observe(head);\n addEventListener('scroll',()=>{if(!sr)sr=requestAnimationFrame(()=>{sr=0;fit();onScroll()})},{passive:true});\n if(d.getElementById('rp-video'))P=player('rp',{\n broken:paintNow,fine:paintNow,\n tick:t=>{\n if(!cur||P.down()!==null||P.v.seeking)return;const s=P.cur();\n if(loop){if(timed(cur)&&cur.dataset.s===s){const x=span(cur);if(!P.v.paused&&t>=x[1]-0.03&&lastT<x[1]){lastT=x[0];P.v.currentTime=x[0];return}}}\n else{const c=caseAt(s,t);if(c&&c!==cur)setCurrent(c,false,true)}\n lastT=t;\n },\n seek:t=>{lastT=t;const c=caseAt(P.cur(),t);if(c&&c!==cur)setCurrent(c,false,true)},\n ended:()=>{\n if(!cur)return false;\n if(loop&&timed(cur)&&cur.dataset.s===P.cur()){P.load(P.cur(),span(cur)[0],true);return true}\n if(!loop){const later=shown().find(c=>timed(c)&&Number(c.dataset.s)>Number(P.cur())&&P.has(c.dataset.s));if(later){setCurrent(later,false,true);P.load(later.dataset.s,span(later)[0],true);return true}}\n return false;\n },\n });\n if(loopB)loopB.addEventListener('click',()=>{loop=!loop;loopB.setAttribute('aria-pressed',String(loop));paintNow()});\n const filter=f=>{\n d.querySelectorAll('[data-filter]').forEach(x=>x.setAttribute('aria-pressed',String(x.dataset.filter===f)));\n cards.forEach(c=>{c.hidden=!(f==='all'||c.dataset.status===f)});\n segs.forEach(x=>{const c=cards.find(k=>k.dataset.id===x.dataset.case);x.classList.toggle('off',!!c&&c.hidden)});\n if(cur&&cur.hidden)setCurrent(shown()[0],true,false);\n };\n d.querySelectorAll('[data-filter]').forEach(b=>b.addEventListener('click',()=>filter(b.dataset.filter)));\n d.querySelectorAll('.filters').forEach(f=>f.classList.add('live'));\n let vCase=null,vIdx=0,opener=null;\n const q=s=>dlg.querySelector(s);\n const list=c=>{const t=c&&c.querySelector('template.shots');return t?[...t.content.children]:[]};\n const showShot=()=>{\n const l=list(vCase),f=l[vIdx];if(!f)return;\n q('.v-body').replaceChildren(f.cloneNode(true));\n q('.v-st').replaceChildren(vCase.querySelector('.case-head .st').cloneNode(true));\n q('.v-title').textContent=vCase.querySelector('.case-go').textContent;\n q('.v-what').textContent=f.dataset.cap+(l.length>1?' ('+(vIdx+1)+' of '+l.length+')':'');\n q('.v-prev').disabled=vIdx===0;q('.v-next').disabled=vIdx>=l.length-1;scan();\n };\n if(dlg){\n q('.v-prev').addEventListener('click',()=>{if(vIdx>0){vIdx--;showShot()}});\n q('.v-next').addEventListener('click',()=>{if(vIdx<list(vCase).length-1){vIdx++;showShot()}});\n q('.v-close').addEventListener('click',()=>dlg.close());\n dlg.addEventListener('click',e=>{if(e.target===dlg)dlg.close()});\n dlg.addEventListener('keydown',e=>{if(e.key==='ArrowLeft'){e.preventDefault();q('.v-prev').click()}else if(e.key==='ArrowRight'){e.preventDefault();q('.v-next').click()}});\n dlg.addEventListener('close',()=>{q('.v-body').replaceChildren();if(opener&&opener.isConnected)opener.focus()});\n }\n d.addEventListener('click',e=>{\n const t=e.target;if(!(t instanceof Element))return;\n const tc=t.closest('a.tc[data-t]');\n if(tc){if(!P||!P.has(tc.dataset.s))return;e.preventDefault();const s=tc.dataset.s,at=Number(tc.dataset.t),c=caseAt(s,at)||tc.closest('.case')||(dlg&&dlg.open?vCase:null);if(dlg&&dlg.open)dlg.close();if(c)setCurrent(c,false,!tc.closest('.case'));lastT=at;P.load(s,at,P.playing());return}\n const go=t.closest('a[href^=\"#case-\"]');\n if(go){const c=d.getElementById(go.getAttribute('href').slice(1));if(!c||!c.matches('.case[data-i]'))return;e.preventDefault();if(c.hidden)filter('all');toCard(c);setCurrent(c,true,false);return}\n const shot=t.closest('[data-shot]');\n if(shot&&dlg&&dlg.showModal){e.preventDefault();opener=shot;vCase=shot.closest('.case');vIdx=Number(shot.dataset.shot)||0;showShot();dlg.showModal();q('.v-close').focus();return}\n const c=t.closest('.case[data-i]');\n if(!c||t.closest('a,summary,details,input,label')||(t.closest('button')&&!t.closest('.case-go')))return;\n toCard(c);setCurrent(c,true,false);\n });\n const first=cards.find(c=>timed(c)&&(!P||P.has(c.dataset.s)))||cards[0];\n if(first){setCurrent(first,false,false);if(timed(first))lastT=span(first)[0]}\n});\n})();";
22
+ export declare const REPORT_SCRIPT = "(()=>{const d=document,r=d.documentElement,K='screw-bugs-theme';\nconst still=()=>matchMedia('(prefers-reduced-motion: reduce)').matches;\nconst topEdge=()=>{const b=d.querySelector('.menubar');return b?Math.max(0,b.getBoundingClientRect().bottom):0};\nconst pad=n=>String(n).padStart(2,'0');\nconst clock=s=>{s=Math.max(0,Math.floor(s||0));const h=Math.floor(s/3600),m=Math.floor(s%3600/60);return(h?h+':'+pad(m):String(m))+':'+pad(s%60)};\nlet theme='system';try{theme=localStorage.getItem(K)||theme}catch(e){}r.dataset.theme=theme;\nconst themeCycle=(b,key)=>{\n const r=document.documentElement,T=['light','dark','system'],N={light:'Light theme',dark:'Dark theme',system:'Theme from system'};\n const at=()=>{const i=T.indexOf(r.dataset.theme);return i<0?2:i};\n const show=()=>{const i=at(),f=document.getElementById('favicon'),h=f&&f.dataset[T[i]];if(h)f.href=h;b.setAttribute('aria-label',N[T[i]]+'. Switch to '+N[T[(i+1)%3]].toLowerCase());b.title=N[T[i]]};\n show();\n b.addEventListener('click',()=>{const m=T[(at()+1)%3];r.dataset.theme=m;if(key)try{localStorage.setItem(key,m)}catch(e){}show()});\n};\nconst chrome=()=>{\n d.querySelectorAll('.menubar .theme').forEach(b=>{themeCycle(b,K);b.hidden=false});\n if(location.protocol==='http:'&&(location.hostname==='127.0.0.1'||location.hostname==='localhost'))d.querySelectorAll('a.share-btn').forEach(a=>{a.hidden=false});\n d.querySelectorAll('time.when[datetime]').forEach(e=>{\n const t=new Date(e.getAttribute('datetime'));if(isNaN(t.getTime()))return;const p={};\n try{new Intl.DateTimeFormat('en-US',{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit',hourCycle:'h23'}).formatToParts(t).forEach(x=>{p[x.type]=x.value});\n const y=d.createElement('span');y.className='year';y.textContent=', '+p.year;\n e.replaceChildren(p.month+' '+p.day,y,' '+String.fromCharCode(183)+' '+p.hour+':'+p.minute);\n e.title=new Intl.DateTimeFormat('en-US',{dateStyle:'full',timeStyle:'long'}).format(t)}catch(x){}\n });\n d.querySelectorAll('.prompt').forEach(p=>{\n const t=p.querySelector('.prompt-text'),b=p.querySelector('.prompt-more');if(!t||!b)return;\n const fits=()=>{if(!p.classList.contains('open'))b.hidden=t.scrollHeight<=t.clientHeight+1};\n fits();if(window.ResizeObserver)new ResizeObserver(fits).observe(t);if(d.fonts&&d.fonts.ready)d.fonts.ready.then(fits);\n b.addEventListener('click',()=>{const o=p.classList.toggle('open');b.textContent=o?'Show less':'Show full prompt';b.setAttribute('aria-expanded',String(o));fits()});\n });\n};\nconst bare=u=>{const i=u.indexOf('://');return i<0?u:u.slice(i+3)};\nconst player=(p,o)=>{\n const v=d.getElementById(p+'-video'),fig=v.closest('.player'),note=d.getElementById(p+'-unloaded'),c=d.getElementById(p+'-controls'),url=d.getElementById(p+'-url');\n const srcs=new Map([...fig.querySelectorAll('[data-session-src]')].map(e=>[e.dataset.session,e.dataset.sessionSrc]));\n const order=[...srcs.keys()];\n const urls=[...fig.querySelectorAll('[data-url]')].map(e=>({s:e.dataset.s,t:Number(e.dataset.at),u:e.dataset.url}));\n const dead=new Set(),errs=new Map(),empty=d.getElementById(p+'-none');let shown=0,cur=v.dataset.session,down=null,held=false,ask=0,auto=false,rate=1,raf=0,drag=false;\n const play=c.querySelector('.play'),now=c.querySelector('.now'),total=c.querySelector('.total'),bar=c.querySelector('.scrub'),head=c.querySelector('.head'),tracks=[...c.querySelectorAll('.track')];\n v.removeAttribute('controls');c.hidden=false;\n const big=d.getElementById(p+'-start');\n if(big){big.hidden=false;big.addEventListener('click',()=>{grow();v.play().catch(()=>{})});v.addEventListener('play',()=>big.remove(),{once:true})}\n const track=()=>tracks.find(t=>t.dataset.s===cur);\n const len=()=>{const t=track(),n=t?Number(t.dataset.total):0;return n>0?n:(isFinite(v.duration)?v.duration:0)};\n const paint=()=>{\n const L=len(),t=v.currentTime,f=L?Math.min(1,t/L):0,k=track();\n tracks.forEach(x=>{x.hidden=x!==k});head.style.left=(f*100)+'%';\n const done=k&&k.querySelector('.done');if(done)done.style.width=(f*100)+'%';\n now.textContent=clock(t);total.textContent=clock(L);\n bar.setAttribute('aria-valuemax',String(Math.round(L)));bar.setAttribute('aria-valuenow',String(Math.round(t)));bar.setAttribute('aria-valuetext',clock(t)+' of '+clock(L));\n play.classList.toggle('playing',!v.paused);play.setAttribute('aria-label',v.paused?'Play':'Pause');\n if(url){let u='';if(down!=='')for(const x of urls){if(x.s===cur&&x.t<=t+0.02)u=x.u}url.textContent=bare(u);url.parentElement.title=u}\n };\n const update=()=>{paint();if(o.tick)o.tick(v.currentTime)};\n const frame=()=>{update();raf=v.paused?0:requestAnimationFrame(frame)};\n const show=s=>{if(down===null)held=!v.paused;down=s;v.pause();fig.classList.add('broken');c.hidden=true;if(empty)empty.hidden=true;if(note){++shown;note.hidden=false;const a=note.querySelector('a');if(a){a.href=srcs.get(s);a.textContent=srcs.get(s)}const ft=note.querySelector('.fix-text'),fd=note.querySelector('.fix-done');if(ft){ft.hidden=true;ft.value=''}if(fd)fd.textContent=''}if(o.broken)o.broken()};\n const fine=()=>{if(down===null)return;down=null;fig.classList.remove('broken');c.hidden=false;if(note)note.hidden=true;if(empty)empty.hidden=true;if(o.fine)o.fine()};\n const none=()=>{if(down===null)held=!v.paused;++ask;auto=false;down='';v.pause();fig.classList.add('broken');c.hidden=true;if(note)note.hidden=true;if(empty)empty.hidden=false;paint();if(o.broken)o.broken()};\n const playing=()=>down===null?!v.paused:held;\n const next=s=>order.slice(order.indexOf(s)+1).find(n=>!dead.has(n));\n const load=(s,t,go,a)=>{\n const my=++ask;auto=!!a;if(dead.has(s))return show(s);\n if(s!==cur||!v.currentSrc||v.error){cur=s;v.dataset.session=s;v.src=srcs.get(s);v.load()}\n const done=()=>{if(my!==ask)return;auto=false;fine();v.playbackRate=rate;v.currentTime=t;update();if(go)v.play().catch(()=>{})};\n if(v.readyState>0)done();else v.addEventListener('loadedmetadata',done,{once:true});\n };\n const bad=()=>{const e=v.error;if(!e)return;dead.add(cur);errs.set(cur,'error code '+e.code+(e.message?': '+e.message:''));if(down==='')return;const n=auto?next(cur):undefined;if(n!==undefined)return load(n,0,true,true);auto=false;show(cur)};\n ['timeupdate','seeked','loadedmetadata','pause','play','durationchange'].forEach(n=>v.addEventListener(n,update));\n v.addEventListener('play',()=>{if(!raf)raf=requestAnimationFrame(frame)});\n addEventListener('resize',update);\n v.addEventListener('error',bad);if(v.error)queueMicrotask(bad);\n const fix=d.getElementById(p+'-fix');\n if(fix){const box=fix.parentElement,ta=box.querySelector('.fix-text'),said=box.querySelector('.fix-done');\n fix.addEventListener('click',()=>{\n let t=ta.dataset.template||'';\n [['video',down?srcs.get(down)||'':''],['page',location.href],['browser',navigator.userAgent],['error',errs.get(down)||'nothing']].forEach(([k,x])=>{t=t.split('{'+k+'}').join(x)});\n const g=shown;ta.value=t;const ok=()=>{if(g!==shown)return;said.textContent='Copied. Paste it into your coding agent.'};\n const by=()=>{if(g!==shown)return;ta.hidden=false;ta.focus();ta.setSelectionRange(0,t.length);ta.scrollTop=0;let c=false;try{c=d.execCommand('copy')}catch(x){}if(c)ok();else said.textContent='Copy the prompt below.'};\n if(navigator.clipboard&&window.isSecureContext)navigator.clipboard.writeText(t).then(ok,by);else by();\n })}\n v.addEventListener('ended',()=>{if(o.ended&&o.ended())return;const n=next(cur);if(n!==undefined)load(n,0,true,true)});\n play.addEventListener('click',()=>{if(v.paused)v.play().catch(()=>{});else v.pause()});\n v.addEventListener('click',()=>{if(down!==null)return;if(grow())v.play().catch(()=>{});else play.click()});\n c.querySelectorAll('[data-rate]').forEach(b=>b.addEventListener('click',()=>{rate=Number(b.dataset.rate);v.playbackRate=rate;v.defaultPlaybackRate=rate;c.querySelectorAll('[data-rate]').forEach(x=>x.setAttribute('aria-pressed',String(x===b)))}));\n const seek=t=>{const L=len();t=Math.max(0,L?Math.min(L,t):t);v.currentTime=t;if(o.seek)o.seek(t);update()};\n const at=e=>{const b=bar.getBoundingClientRect();return Math.max(0,Math.min(1,(e.clientX-b.left)/b.width))*len()};\n bar.addEventListener('pointerdown',e=>{if(e.button>0||down!==null)return;drag=true;bar.setPointerCapture(e.pointerId);seek(at(e))});\n bar.addEventListener('pointermove',e=>{if(drag)seek(at(e))});\n ['pointerup','pointercancel'].forEach(n=>bar.addEventListener(n,()=>{drag=false}));\n bar.addEventListener('keydown',e=>{\n const k=e.key,t=v.currentTime,by={ArrowLeft:-1,ArrowDown:-1,ArrowRight:1,ArrowUp:1,PageDown:-10,PageUp:10}[k];\n const to=by!==undefined?t+by:k==='Home'?0:k==='End'?len():null;if(to===null)return;e.preventDefault();seek(to);\n });\n const full=c.querySelector('.full'),screen=o.full||fig.querySelector('.screen');\n const api=!!(d.fullscreenEnabled&&screen.requestFullscreen),inPage=()=>!!o.inPage&&(o.inPage()||!api);\n const mark=()=>{const f=d.fullscreenElement===screen||screen.classList.contains('focus');full.classList.toggle('out',f);full.setAttribute('aria-label',f?'Exit fullscreen':'Fullscreen');update()};\n let back=0;const focus=on=>{if(on)back=scrollY;screen.classList.toggle('focus',on);scrollTo({top:on?0:back,behavior:'auto'});mark()};\n const grow=()=>{if(!o.expand||!o.inPage||!o.inPage()||d.fullscreenElement||screen.classList.contains('focus'))return false;focus(true);return true};\n if(!api&&!o.inPage)full.hidden=true;\n else{full.addEventListener('click',()=>{const f=screen.classList.contains('focus');if(d.fullscreenElement){d.exitFullscreen().catch(()=>{});if(f)focus(false)}else if(f)focus(false);else if(inPage())focus(true);else screen.requestFullscreen().catch(()=>{})});\n d.addEventListener('fullscreenchange',mark);\n d.addEventListener('keydown',e=>{if(e.key==='Escape'&&!e.defaultPrevented&&screen.classList.contains('focus')&&!d.querySelector('dialog[open]')){e.preventDefault();focus(false)}})}\n d.addEventListener('keydown',e=>{if(e.key!==' '||down!==null||e.defaultPrevented||d.querySelector('dialog[open]')||e.target.closest('button,a,input,textarea,select,summary,[role=slider]'))return;e.preventDefault();play.click()});\n return {v,load,none,playing,update,len,cur:()=>cur,down:()=>down,has:s=>srcs.has(s)};\n};\n\nconst badImg=i=>{const f=i.closest('figure');if(!f||f.classList.contains('broken'))return;f.classList.add('broken');f.querySelectorAll('.unloaded').forEach(u=>u.removeAttribute('aria-hidden'))};\nconst scan=()=>d.querySelectorAll('figure img').forEach(i=>{if(i.complete&&i.naturalWidth===0)badImg(i)});\nd.addEventListener('error',e=>{const t=e.target;if(t instanceof Element&&t.matches('figure img'))badImg(t)},true);\naddEventListener('load',scan);\nd.addEventListener('DOMContentLoaded',()=>{\n chrome();scan();\n const cards=[...d.querySelectorAll('.case[data-i]')],segs=[...d.querySelectorAll('.seg[data-case]')];\n const np=d.getElementById('rp-now'),loopB=d.getElementById('rp-loop'),dlg=d.getElementById('viewer');\n const N=cards.length,dash=String.fromCharCode(8211);let cur=null,loop=true,lock=0,lastT=0,P=null,sr=0;\n const timed=c=>!!c&&c.dataset.t0!==undefined;\n const span=c=>[Number(c.dataset.t0),Number(c.dataset.t1)];\n const shown=()=>cards.filter(c=>!c.hidden);\n const line=()=>{const b=topEdge();if(matchMedia('(max-width: 900px)').matches){const s=d.querySelector('.rp-left');return s?s.getBoundingClientRect().bottom+24:b+120}return Math.round(b+(innerHeight-b)*0.3)};\n const playable=c=>timed(c)&&!!P&&P.has(c.dataset.s);\n const chip=c=>{if(!playable(c)||P.down()!==null)return '';const s=span(c);return (loop?'Looping ':'Playing ')+clock(s[0])+dash+clock(s[1])};\n const paintNow=()=>{\n if(!np||!cur)return;\n np.querySelector('.np-st').replaceChildren(cur.querySelector('.case-head .st').cloneNode(true));\n np.querySelector('.np-n').textContent=cur.dataset.i+' / '+N;\n np.querySelector('.np-title').textContent=cur.querySelector('.case-go').textContent;\n np.querySelector('.np-status').textContent=cur.dataset.label+': ';\n const ch=np.querySelector('.np-chip'),t=chip(cur);ch.querySelector('span').textContent=t||'No video';ch.classList.toggle('none',!t);\n };\n const toCard=c=>{lock=Date.now()+700;const y=c.getBoundingClientRect().top+scrollY-line()+2;scrollTo({top:Math.max(0,y),behavior:still()?'auto':'smooth'})};\n const setCurrent=(c,seek,scroll)=>{\n if(!c)return;\n if(c!==cur){if(cur){cur.classList.remove('on');cur.removeAttribute('aria-current')}cur=c;c.classList.add('on');c.setAttribute('aria-current','true');segs.forEach(x=>x.classList.toggle('on',x.dataset.case===c.dataset.id));paintNow()}\n if(seek&&P){if(playable(c)){const a=span(c)[0];lastT=a;P.load(c.dataset.s,a,P.playing())}else P.none()}\n if(scroll)toCard(c);\n };\n const caseAt=(s,t)=>{let f=null;for(const c of shown()){if(timed(c)&&c.dataset.s===s){const x=span(c);if(t>=x[0]&&t<x[1])f=c}}return f};\n const onScroll=()=>{\n if(Date.now()<lock)return;const vis=shown();if(!vis.length)return;\n const L=line();let pick=vis[0];for(const c of vis){if(c.getBoundingClientRect().top<=L)pick=c}\n const last=vis[vis.length-1];if(innerHeight+scrollY>=r.scrollHeight-2&&last.getBoundingClientRect().bottom<=innerHeight)pick=last;\n if(pick!==cur)setCurrent(pick,true,false);\n };\n const stk=d.querySelector('.rp-sticky'),head=d.querySelector('.rp-head');\n const fit=()=>{if(stk)stk.style.setProperty('--rp-top',Math.round(stk.getBoundingClientRect().top)+'px')};\n fit();addEventListener('resize',fit);addEventListener('load',fit);\n if(head&&window.ResizeObserver)new ResizeObserver(fit).observe(head);\n addEventListener('scroll',()=>{if(!sr)sr=requestAnimationFrame(()=>{sr=0;fit();onScroll()})},{passive:true});\n if(d.getElementById('rp-video'))P=player('rp',{\n broken:paintNow,fine:paintNow,\n tick:t=>{\n if(!cur||P.down()!==null||P.v.seeking)return;const s=P.cur();\n if(loop){if(timed(cur)&&cur.dataset.s===s){const x=span(cur);if(!P.v.paused&&t>=x[1]-0.03&&lastT<x[1]){lastT=x[0];P.v.currentTime=x[0];return}}}\n else{const c=caseAt(s,t);if(c&&c!==cur)setCurrent(c,false,true)}\n lastT=t;\n },\n seek:t=>{lastT=t;const c=caseAt(P.cur(),t);if(c&&c!==cur)setCurrent(c,false,true)},\n ended:()=>{\n if(!cur)return false;\n if(loop&&timed(cur)&&cur.dataset.s===P.cur()){P.load(P.cur(),span(cur)[0],true);return true}\n if(!loop){const later=shown().find(c=>timed(c)&&Number(c.dataset.s)>Number(P.cur())&&P.has(c.dataset.s));if(later){setCurrent(later,false,true);P.load(later.dataset.s,span(later)[0],true);return true}}\n return false;\n },\n });\n if(loopB)loopB.addEventListener('click',()=>{loop=!loop;loopB.setAttribute('aria-pressed',String(loop));paintNow()});\n const filter=f=>{\n d.querySelectorAll('[data-filter]').forEach(x=>x.setAttribute('aria-pressed',String(x.dataset.filter===f)));\n cards.forEach(c=>{c.hidden=!(f==='all'||c.dataset.status===f)});\n segs.forEach(x=>{const c=cards.find(k=>k.dataset.id===x.dataset.case);x.classList.toggle('off',!!c&&c.hidden)});\n if(cur&&cur.hidden)setCurrent(shown()[0],true,false);\n };\n d.querySelectorAll('[data-filter]').forEach(b=>b.addEventListener('click',()=>filter(b.dataset.filter)));\n d.querySelectorAll('.filters').forEach(f=>f.classList.add('live'));\n let vCase=null,vIdx=0,opener=null;\n const q=s=>dlg.querySelector(s);\n const list=c=>{const t=c&&c.querySelector('template.shots');return t?[...t.content.children]:[]};\n const showShot=()=>{\n const l=list(vCase),f=l[vIdx];if(!f)return;\n q('.v-body').replaceChildren(f.cloneNode(true));\n q('.v-st').replaceChildren(vCase.querySelector('.case-head .st').cloneNode(true));\n q('.v-title').textContent=vCase.querySelector('.case-go').textContent;\n q('.v-what').textContent=f.dataset.cap+(l.length>1?' ('+(vIdx+1)+' of '+l.length+')':'');\n q('.v-prev').disabled=vIdx===0;q('.v-next').disabled=vIdx>=l.length-1;scan();\n };\n if(dlg){\n q('.v-prev').addEventListener('click',()=>{if(vIdx>0){vIdx--;showShot()}});\n q('.v-next').addEventListener('click',()=>{if(vIdx<list(vCase).length-1){vIdx++;showShot()}});\n q('.v-close').addEventListener('click',()=>dlg.close());\n dlg.addEventListener('click',e=>{if(e.target===dlg)dlg.close()});\n dlg.addEventListener('keydown',e=>{if(e.key==='ArrowLeft'){e.preventDefault();q('.v-prev').click()}else if(e.key==='ArrowRight'){e.preventDefault();q('.v-next').click()}});\n dlg.addEventListener('close',()=>{q('.v-body').replaceChildren();if(opener&&opener.isConnected)opener.focus()});\n }\n d.addEventListener('click',e=>{\n const t=e.target;if(!(t instanceof Element))return;\n const tc=t.closest('a.tc[data-t]');\n if(tc){if(!P||!P.has(tc.dataset.s))return;e.preventDefault();const s=tc.dataset.s,at=Number(tc.dataset.t),c=caseAt(s,at)||tc.closest('.case')||(dlg&&dlg.open?vCase:null);if(dlg&&dlg.open)dlg.close();if(c)setCurrent(c,false,!tc.closest('.case'));lastT=at;P.load(s,at,P.playing());return}\n const go=t.closest('a[href^=\"#case-\"]');\n if(go){const c=d.getElementById(go.getAttribute('href').slice(1));if(!c||!c.matches('.case[data-i]'))return;e.preventDefault();if(c.hidden)filter('all');toCard(c);setCurrent(c,true,false);return}\n const shot=t.closest('[data-shot]');\n if(shot&&dlg&&dlg.showModal){e.preventDefault();opener=shot;vCase=shot.closest('.case');vIdx=Number(shot.dataset.shot)||0;showShot();dlg.showModal();q('.v-close').focus();return}\n const c=t.closest('.case[data-i]');\n if(!c||t.closest('a,summary,details,input,label')||(t.closest('button')&&!t.closest('.case-go')))return;\n toCard(c);setCurrent(c,true,false);\n });\n const first=cards.find(c=>timed(c)&&(!P||P.has(c.dataset.s)))||cards[0];\n if(first){setCurrent(first,false,false);if(timed(first))lastT=span(first)[0]}\n});\n})();";
23
23
  /**
24
24
  * Images and video load from the run folder by relative path (`'self'`, and `file:` for a report
25
25
  * opened from disk); styles are inline, but for Google Fonts' stylesheet, whose fonts come from