@hypersocial/decks-cli 0.9.12 → 0.9.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hypersocial/decks-cli",
3
- "version": "0.9.12",
3
+ "version": "0.9.13",
4
4
  "description": "Command-line client for Hypersocial Decks live analytics and share management.",
5
5
  "type": "module",
6
6
  "main": "./src/commands.mjs",
@@ -25,7 +25,7 @@ import { tmpdir } from 'node:os';
25
25
  import { dirname, extname, join } from 'node:path';
26
26
  import { execFile } from 'node:child_process';
27
27
  import { promisify } from 'node:util';
28
- import { allowCaptureDestination, allowCaptureRequest, installChromium, isMissingBrowser, noteSoftwareWebgl, recorderArgs, routeCaptureRequest } from './preview-capture.mjs';
28
+ import { allowCaptureDestination, allowCaptureRequest, installChromium, redactCaptureUrl, isMissingBrowser, noteSoftwareWebgl, recorderArgs, routeCaptureRequest } from './preview-capture.mjs';
29
29
  import { installFrameClock } from './frame-clock.mjs';
30
30
 
31
31
  const run = promisify(execFile);
@@ -325,7 +325,8 @@ const readLog = (page, ms = 5000) => within(page.evaluate(() => {
325
325
  // `blocked` holds the URLs the capture rules refused; `failed` is the last
326
326
  // request that failed for another reason ({ url, error }).
327
327
  export function readySaw({ refused = 0, unreachable = [], failed = null } = {}) {
328
- const cut = (u) => (u.length > 160 ? `${u.slice(0, 157)}…` : u);
328
+ // No query and no view grant (redactCaptureUrl): these lines reach the terminal and job logs.
329
+ const cut = (url) => { const u = redactCaptureUrl(url); return u.length > 160 ? `${u.slice(0, 157)}…` : u; };
329
330
  const parts = [];
330
331
  // Passed the recorder's rules but could not be fetched (DNS, timeout, a redirect): these can stop a deck.
331
332
  if (unreachable.length) parts.push(`${unreachable.length} request${unreachable.length === 1 ? '' : 's'} could not be fetched, last ${cut(unreachable.at(-1))}`);
@@ -107,6 +107,22 @@ export async function serveSource({ file, html, port = 0 }) {
107
107
  const url = `http://127.0.0.1:${server.address().port}${entry}`;
108
108
  return { url, close: () => new Promise((ok, fail) => { server.close(e => e ? fail(e) : ok()); server.closeAllConnections(); }) };
109
109
  }
110
+ // The avatar routes a deck's player loads heads from on the app's origin:
111
+ // a public avatar's document (app/avatar/[token]) and a private avatar's
112
+ // document, head model and still, with the deck's view grant in the path or
113
+ // without one (app/avatar/private/[id]/[...asset]). /avatar/<token>/face is a
114
+ // redirect to Minimoji, which the route refuses anyway.
115
+ const AVATAR_PATH = /^\/avatar\/(?:private\/[A-Za-z0-9_-]{1,128}\/(?:[a-f0-9]{64}\/)?(?:doc|head\.glb|thumbnail\.png)|[A-Za-z0-9_-]{1,128})$/;
116
+ // A request URL fit for a log or a warning: no query or fragment, any 64-hex
117
+ // path segment (an avatar view grant) replaced, and a public avatar's token
118
+ // (/avatar/<token>, any spelling) replaced, so no token is printed.
119
+ export function redactCaptureUrl(url) {
120
+ try {
121
+ const u = new URL(url);
122
+ if (u.protocol === 'data:' || u.protocol === 'blob:') return `${u.protocol}…`;
123
+ return u.origin + u.pathname.replace(/\/[a-f0-9]{64}(?=\/|$)/gi, '/<view>').replace(/^\/avatar\/(?!private\/)[^/]+/, '/avatar/<token>');
124
+ } catch { return '<unreadable url>'; }
125
+ }
110
126
  // `type` is Playwright's resourceType, except that a document loading into a
111
127
  // child frame (an <iframe>) is 'subdocument' (captureResourceType): the top
112
128
  // page stays pinned to the entry URL, while an embedded page gets the rules
@@ -122,7 +138,9 @@ export function allowCaptureRequest(url, method, type, entryUrl, firstPartyOrigi
122
138
  if (firstPartyOrigins.some(v => new URL(v).origin === u.origin) || /\.convex\.(cloud|site)$/.test(u.hostname)) {
123
139
  // Stored assets, and the hosted player a player/v1 deck loads (player.js, its
124
140
  // modules, css, emote bursts). Views (/v/) and telemetry stay refused above.
125
- return /^\/(api\/storage|player)\//.test(path);
141
+ if (/^\/(api\/storage|player)\//.test(path)) return true;
142
+ // The app's avatar routes, for the narrator's and guests' heads.
143
+ return firstPartyOrigins.some(v => new URL(v).origin === u.origin) && AVATAR_PATH.test(path);
126
144
  }
127
145
  // Prevent page code from reaching local services or cloud metadata. Only the
128
146
  // capability file server is available on loopback; redirects are checked too.
@@ -182,20 +200,33 @@ export function unconditionalHeaders(headers) {
182
200
 
183
201
  // Playwright's continue() follows redirects without routing each hop. Fetch
184
202
  // without following redirects and never fulfill a 3xx response into Chromium.
185
- export async function routeCaptureRequest(route, entryUrl, origins = []) {
203
+ // `net` (all optional): `onRefused({ url, type, reason })` hears each request
204
+ // not fulfilled, its URL redacted (redactCaptureUrl); reason is 'rule',
205
+ // 'destination', 'redirect' or the fetch error. `resolver` and `upstream`
206
+ // (route, options) => APIResponse stand in for DNS and the network in tests.
207
+ export async function routeCaptureRequest(route, entryUrl, origins = [], net = {}) {
208
+ const { onRefused = () => {}, resolver, upstream = (rt, options) => rt.fetch(options) } = net;
186
209
  const r = route.request();
210
+ let type = 'other';
211
+ const refuse = async (reason) => {
212
+ // Heard before the abort, so the page's requestfailed for it comes after.
213
+ try { onRefused({ url: redactCaptureUrl(r.url()), type, reason }); } catch { /* reporting never stops a capture */ }
214
+ await route.abort().catch(() => {});
215
+ return false;
216
+ };
187
217
  try {
188
- if (!allowCaptureRequest(r.url(), r.method(), captureResourceType(r), entryUrl, origins) || !await allowCaptureDestination(r.url(), entryUrl)) {
189
- await route.abort(); return false;
190
- }
191
- const response = await route.fetch({ headers: unconditionalHeaders(r.headers()), maxRedirects:0, timeout:15000 });
192
- if (response.status() >= 300 && response.status() < 400) {
193
- await response.dispose(); await route.abort(); return false;
194
- }
195
- await route.fulfill({ response });
196
- await response.dispose();
197
- return true;
198
- } catch { await route.abort().catch(() => {}); return false; }
218
+ type = captureResourceType(r);
219
+ if (!allowCaptureRequest(r.url(), r.method(), type, entryUrl, origins)) return await refuse('rule');
220
+ if (!await allowCaptureDestination(r.url(), entryUrl, resolver)) return await refuse('destination');
221
+ let response;
222
+ try { response = await upstream(route, { headers: unconditionalHeaders(r.headers()), maxRedirects:0, timeout:15000 }); }
223
+ catch (e) { return await refuse(String(e?.message ?? e).split('\n')[0].replace(/[a-f0-9]{64}/gi, '<view>').slice(0, 120)); }
224
+ try {
225
+ if (response.status() >= 300 && response.status() < 400) return await refuse('redirect');
226
+ await route.fulfill({ response });
227
+ return true;
228
+ } finally { await response.dispose().catch(() => {}); }
229
+ } catch (e) { return refuse(String(e?.message ?? e).split('\n')[0].replace(/[a-f0-9]{64}/gi, '<view>').slice(0, 120)); }
199
230
  }
200
231
 
201
232
  // Bounds a page.evaluate on the Node side: in-page timers cannot fire while the
@@ -268,23 +299,24 @@ async function encodeOutputs(ffmpeg, { dir, out, width, height, fps, duration })
268
299
  // Even output dimensions for `width` at `aspect`, as the encoders need them.
269
300
  const outputSize = (width, aspect) => { const w = width % 2 ? width + 1 : width; return { width: w, height: Math.round(w / aspect / 2) * 2 }; };
270
301
 
271
- async function captureMoment(config, chromium, ffmpeg) {
302
+ async function captureMoment(config, chromium, ffmpeg, net) {
272
303
  const { recordMoment, withTempDir } = await import('./preview-moment.mjs');
273
304
  const fps = 10, frames = Math.round(config.duration * fps);
274
305
  return withTempDir(async dir => {
275
- const recorded = await recordMoment({ ...config, frames, fps, playerDir: config.playerDir ?? process.env.HYPERDECKS_PLAYER_DIR ?? null }, { chromium, serveSource, dir });
306
+ const recorded = await recordMoment({ ...config, frames, fps, playerDir: config.playerDir ?? process.env.HYPERDECKS_PLAYER_DIR ?? null }, { chromium, serveSource, dir, net });
276
307
  const files = await encodeOutputs(ffmpeg, { dir, out: config.out, ...outputSize(config.width, recorded.aspect), fps, duration: frames / fps });
277
308
  return { files, warnings: recorded.warnings, moment: recorded.moment };
278
309
  });
279
310
  }
280
311
 
281
- export async function capturePreview(config) {
312
+ // `net` is routeCaptureRequest's resolver/upstream stand-ins, for tests only.
313
+ export async function capturePreview(config, net) {
282
314
  const { chromium } = await import('playwright');
283
315
  let ffmpeg;
284
316
  try { ffmpeg = (await import('@ffmpeg-installer/ffmpeg')).default.path; await run(ffmpeg, ['-version'], { timeout:10000 }); }
285
317
  catch { throw new Error('Portable FFmpeg missing. Reinstall the CLI with optional dependencies and install scripts enabled (`npm install -g hyperdecks --include=optional`); pnpm users must approve @ffmpeg-installer platform build scripts.'); }
286
318
  // --scene / --start: one moment of the narration, on the page clock (preview-moment.mjs).
287
- if (config.scene != null || config.start != null) return captureMoment(config, chromium, ffmpeg);
319
+ if (config.scene != null || config.start != null) return captureMoment(config, chromium, ffmpeg, net);
288
320
  let browser, server, temp, deadline, timedOut = false, phase = 'launch';
289
321
  const warnings = [];
290
322
  try {
@@ -18,7 +18,7 @@ import { tmpdir } from 'node:os';
18
18
  import { extname, join } from 'node:path';
19
19
  import { installFrameClock } from './frame-clock.mjs';
20
20
  import { exportPageUrl, launchRecorder, planTimeline } from './export-video.mjs';
21
- import { recorderArgs, routeCaptureRequest } from './preview-capture.mjs';
21
+ import { recorderArgs, redactCaptureUrl, routeCaptureRequest } from './preview-capture.mjs';
22
22
 
23
23
  // Page-clock milliseconds per step while seeking to `start`: timers fire in
24
24
  // order within a step, so a coarser step only means fewer animation frames
@@ -28,6 +28,8 @@ const SEEK_STEP_MS = 100;
28
28
  const READY_MS = 60000;
29
29
  // Real milliseconds a slide's heads may take to finish loading once on it.
30
30
  const HEADS_MS = 15000;
31
+ // Real milliseconds a failed head is watched for its automatic retry (head-slots.js retryMs is 1200).
32
+ const HEAD_RETRY_MS = 3000;
31
33
 
32
34
  // Where to start: the slide (`scene`, the first slide when omitted) and the
33
35
  // seconds into its narration, checked against the player's own plan
@@ -73,10 +75,47 @@ function readMoment() {
73
75
  };
74
76
  }
75
77
 
78
+ // The character heads on slide `id` that are not live, by name (the name on
79
+ // each head's retry button, head-slots.js headSlotUI), with their state.
80
+ // With `narrator`, the narrator's own head slot too (in the presenter, outside the slide).
81
+ // A silent cameo is named by its avatar id: every cameo's button says "Character".
82
+ function unreadyHeads({ id, narrator }) {
83
+ const slots = [...(document.getElementById(id)?.querySelectorAll('[data-hd-head-state]') ?? [])];
84
+ const own = narrator && document.querySelector('.hd-presenter [data-hd-head-state]');
85
+ return [...(own ? [own] : []), ...slots]
86
+ .filter((e) => e.dataset.hdHeadState !== 'ready')
87
+ .map((e) => {
88
+ const label = e.querySelector(':scope > .hd-head-state button')?.getAttribute('aria-label') ?? '';
89
+ let name = /^Retry (.+)'s avatar$/.exec(label)?.[1] ?? null;
90
+ const cameo = e.closest('[data-hd-avatar]')?.getAttribute('data-hd-avatar');
91
+ if (e === own) name = 'the narrator';
92
+ else if ((!name || name === 'Character') && cameo) name = `cameo ${cameo.replace(/[a-f0-9]{64}/gi, '<view>').slice(0, 80)}`;
93
+ return { name, state: e.dataset.hdHeadState };
94
+ });
95
+ }
96
+
97
+ // What the network refused or could not fetch, for an error or a warning:
98
+ // up to three redacted URLs with their resource type and reason.
99
+ export function networkSaid(refused = [], failed = []) {
100
+ const seen = new Set();
101
+ // The heads' own requests first: a cancelled clip or image must not crowd them out.
102
+ const avatarFirst = (list) => [...list.filter((x) => /\/avatar\//.test(x.url)), ...list.filter((x) => !/\/avatar\//.test(x.url))];
103
+ refused = avatarFirst(refused); failed = avatarFirst(failed);
104
+ const lines = [...failed.filter((f) => !refused.some((r) => r.url === f.url)).map((f) => `${f.url} (${f.type}, ${f.reason})`), ...refused.filter((r) => r.reason !== 'rule').map((r) => `${r.url} (${r.type}, ${r.reason})`), ...refused.filter((r) => r.reason === 'rule').map((r) => `${r.url} (${r.type}, refused by rule)`)]
105
+ .filter((l) => !seen.has(l) && seen.add(l));
106
+ return lines.length ? `; requests not loaded: ${lines.slice(0, 3).join(', ')}${lines.length > 3 ? ` and ${lines.length - 3} more` : ''}` : '';
107
+ }
108
+
76
109
  // Records `frames` PNGs (frame-0000.png…) into `dir` and returns
77
110
  // { aspect, moment, warnings }. config: { html | file, scene, start, frames,
78
- // fps, delay, label, aspect, firstPartyOrigins, playerDir }.
79
- export async function recordMoment(config, { chromium, serveSource, dir }) {
111
+ // fps, delay, label, aspect, firstPartyOrigins, playerDir }. `net` is
112
+ // routeCaptureRequest's resolver/upstream stand-ins, for tests only.
113
+ //
114
+ // Every head on the slide must be live before the first frame: the narrator's
115
+ // (when the deck asks for one) and each guest's. A head that can't load fails
116
+ // the capture by name, with the requests that were refused or failed, rather
117
+ // than producing a GIF of empty boxes.
118
+ export async function recordMoment(config, { chromium, serveSource, dir, net = {} }) {
80
119
  const warnings = [];
81
120
  let browser, server, phase = 'launch';
82
121
  try {
@@ -88,9 +127,10 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
88
127
  server = await serveSource(config);
89
128
  const pageUrl = exportPageUrl(server.url);
90
129
  const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1, serviceWorkers: 'block', acceptDownloads: false });
91
- let blocked = 0;
130
+ // Refused by the capture rules or unreachable ({ url (redacted), type, reason }); and allowed requests that failed in the page.
131
+ const refused = [], failed = [];
92
132
  await context.route('**/*', async (route) => {
93
- if (!await routeCaptureRequest(route, pageUrl, config.firstPartyOrigins)) blocked++;
133
+ await routeCaptureRequest(route, pageUrl, config.firstPartyOrigins, { ...net, onRefused: (r) => refused.push(r) });
94
134
  });
95
135
  // A development checkout (or a test) plays its own player/v1, as video export does.
96
136
  const missingPlayer = [];
@@ -119,6 +159,11 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
119
159
  page.setDefaultTimeout(30000);
120
160
  const pageErrors = [];
121
161
  page.on('pageerror', (e) => pageErrors.push(String(e?.message ?? e)));
162
+ page.on('requestfailed', (r) => {
163
+ const url = redactCaptureUrl(r.url()), reason = r.failure()?.errorText ?? 'failed';
164
+ // ERR_ABORTED: the player cancelled it (a clip seeked past, an image replaced), not a load failure.
165
+ if (reason !== 'net::ERR_ABORTED' && !refused.some((x) => x.url === url)) failed.push({ url, type: r.resourceType(), reason });
166
+ });
122
167
  // Every call into the page is bounded: a deck that holds its main thread fails, it doesn't hang the CLI.
123
168
  const ask = async (fn, arg, what) => {
124
169
  const none = Symbol('timeout');
@@ -144,7 +189,8 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
144
189
  const duration = config.frames / config.fps;
145
190
  if (!state.silent && target.start + duration > target.seconds + 0.05) warnings.push(`slide ${target.id} ends ${Math.max(0, target.seconds - target.start).toFixed(1)}s after --start; the rest of the ${duration}s preview shows the deck moving on`);
146
191
  const face = state.presenter;
147
- if (face?.wanted === 'head' && face.shown !== 'head') warnings.push(`the deck's live head did not load${face.why ? ` (${face.why})` : ''}; the preview shows ${face.shown === 'static' ? 'its still image' : 'captions only'}`);
192
+ // Without the narrator's head no guest head mounts either (player.js mountGuests): the GIF would be empty boxes.
193
+ if (face?.wanted === 'head' && face.shown !== 'head') throw new Error(`the narrator's live head did not load${face.why ? ` (${face.why})` : ''}, so no character head can show${networkSaid(refused, failed)}`);
148
194
 
149
195
  phase = 'layout probe';
150
196
  // The deck's own shape, as the ordinary preview reads it (preview-capture.mjs), unless --aspect-ratio names one.
@@ -167,15 +213,22 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
167
213
  // The slide's heads load before the tour starts: once it runs, the player gives late guest heads
168
214
  // a budget on the page clock (player.js holdForGuestHeads), which the seek spends in moments.
169
215
  // Polled from here: in-page waits run on timers and rAF, which the frozen clock holds.
170
- const headsSettled = async () => {
216
+ // Before the clock freezes (real time), a failed head is given its one automatic retry
217
+ // (head-slots.js failed(): 1.2 s later), so a passing blip doesn't fail the preview.
218
+ const headsSettled = async ({ retries = false } = {}) => {
219
+ let failedSince = null;
171
220
  for (const until = Date.now() + HEADS_MS; Date.now() < until; await new Promise((ok) => setTimeout(ok, 250))) {
172
- const loading = await ask((id) => [...(document.getElementById(id)?.querySelectorAll('[data-hd-head-state="loading"]') ?? [])].length, target.id, 'while heads loaded');
173
- if (!loading) return true;
221
+ const { loading, failed } = await ask((id) => {
222
+ const states = [...(document.getElementById(id)?.querySelectorAll('[data-hd-head-state]') ?? [])].map((e) => e.dataset.hdHeadState);
223
+ return { loading: states.filter((s) => s === 'loading').length, failed: states.filter((s) => s === 'failed').length };
224
+ }, target.id, 'while heads loaded');
225
+ failedSince = failed ? failedSince ?? Date.now() : null;
226
+ if (!loading && !(retries && failed && Date.now() - failedSince < HEAD_RETRY_MS)) return true;
174
227
  }
175
228
  return false;
176
229
  };
177
230
  phase = 'heads';
178
- await headsSettled();
231
+ await headsSettled({ retries: true });
179
232
 
180
233
  phase = 'seek';
181
234
  // Clip lengths come from the manifest (player.js clipLength), as a recipient's <audio> would roughly end them.
@@ -199,8 +252,16 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
199
252
 
200
253
  phase = 'heads';
201
254
  // The clock is frozen, so waiting changes nothing on the slide: it lets heads and images finish loading.
202
- const headsLoaded = await headsSettled();
203
- if (!headsLoaded) warnings.push(`a character head on ${target.id} was still loading after ${HEADS_MS / 1000}s; it shows as a still or silhouette`);
255
+ await headsSettled();
256
+ const notLive = await ask(unreadyHeads, { id: target.id, narrator: face?.wanted === 'head' }, 'to the heads check');
257
+ // Parked: past the player's live-head cap (head-slots.js capacity), shown as its still by design.
258
+ const parked = notLive.filter((h) => h.state === 'parked');
259
+ if (parked.length) warnings.push(`${parked.length} character head(s) on ${target.id} are parked past the player's live-head limit and show as stills: ${parked.map((h) => h.name ?? 'an unnamed head').join(', ')}`);
260
+ const unready = notLive.filter((h) => h.state !== 'parked');
261
+ if (unready.length) {
262
+ const named = unready.map((h) => `${h.name ?? 'an unnamed head'} (${h.state === 'loading' ? `still loading after ${HEADS_MS / 1000}s` : h.state})`).join(', ');
263
+ throw new Error(`${unready.length} character head(s) on ${target.id} are not live: ${named}${networkSaid(refused, failed)}`);
264
+ }
204
265
  phase = 'delay';
205
266
  await page.waitForTimeout(config.delay);
206
267
  await step(0, 'after the delay');
@@ -214,8 +275,6 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
214
275
  }, config.label, 'to the label overlay');
215
276
  const moment = { scene: target.id, start: target.start, ...(await ask(readMoment, undefined, 'to the moment check')) };
216
277
  if (moment.slide !== target.id) throw new Error(`the player showed ${moment.slide ?? 'no slide'}, not ${target.id}`);
217
- const unready = moment.heads.filter((s) => s !== 'ready').length;
218
- if (headsLoaded && unready) warnings.push(`${unready} character head(s) on ${target.id} are not live (${[...new Set(moment.heads.filter((s) => s !== 'ready'))].join(', ')}); they show as stills or silhouettes`);
219
278
 
220
279
  phase = 'frames';
221
280
  const session = await context.newCDPSession(page);
@@ -226,7 +285,9 @@ export async function recordMoment(config, { chromium, serveSource, dir }) {
226
285
  await writeFile(join(dir, `frame-${String(n).padStart(4, '0')}.png`), Buffer.from(shot.data, 'base64'));
227
286
  }
228
287
  if (failure(log)) warnings.push(`${failure(log)} while recording; the preview may stop moving there`);
229
- if (blocked) warnings.push(`${blocked} navigation/telemetry/unsafe request(s) blocked; no recipient page was visited.`);
288
+ const byRule = refused.filter((r) => r.reason === 'rule'), unreachable = refused.filter((r) => r.reason !== 'rule');
289
+ if (byRule.length) warnings.push(`${byRule.length} navigation/telemetry/unsafe request(s) blocked; no recipient page was visited`);
290
+ if (unreachable.length) warnings.push(`${unreachable.length} request(s) could not be fetched${networkSaid(unreachable, [])}`);
230
291
  if (pageErrors.length) warnings.push(`${pageErrors.length} page error(s): ${pageErrors.slice(0, 2).join('; ').slice(0, 300)}`);
231
292
  return { aspect, moment, warnings };
232
293
  } catch (e) {
package/src/runtime.mjs CHANGED
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { ConvexHttpClient } from "convex/browser";
9
9
  import { makeFunctionReference } from "convex/server";
10
10
 
11
- export const VERSION = "0.9.12";
11
+ export const VERSION = "0.9.13";
12
12
  const UPLOAD_TIMEOUT_MS = 125_000;
13
13
 
14
14
  // The app's home. HYPERDECKS_HOST points the prod target's broker and share