@powerformer/prism-client 0.8.0 → 0.10.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/build-info.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@powerformer/prism-client",
3
- "version": "0.8.0",
4
- "gitCommit": "750366feed9a11987823a7b5fe25aa69fc87b596",
5
- "sourceSha256": "4c9b45f4deb749da4fcacc48db8ee218d75012b9eda4a0674967d7e9b261b271",
3
+ "version": "0.10.0",
4
+ "gitCommit": "ad1227fead1f643a578d2bc3ca971973a7c16d3c",
5
+ "sourceSha256": "9d3bcf925346949fa2573aa66659c8e8296123d9f54f762bb4a63f7899752366",
6
6
  "contentContract": "app/contracts",
7
7
  "contentContractSha256": "443ac891fd70f4ff6c59193de4668cb7bd0136d879eead0b0e100e4f480ddd32"
8
8
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  registerReadObserver
3
- } from "./chunk-MYDJI2NW.js";
3
+ } from "./chunk-XJWMC7TR.js";
4
4
 
5
5
  // app/sdk/visual-map.ts
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -59,12 +59,31 @@ function recordLivePageReads(pathname, reads) {
59
59
  function getLivePageReads() {
60
60
  return liveRouteStore();
61
61
  }
62
+ var WORKER_TRACE_BUFFER_KEY = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/visual-trace-buffer/v1"), WORKER_TRACE_HOOKED_KEY = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/visual-trace-hooked/v1"), WORKER_TRACE_FLUSH_THRESHOLD = 500;
63
+ function workerTraceBuffer() {
64
+ let host = globalThis;
65
+ return host[WORKER_TRACE_BUFFER_KEY] ??= /* @__PURE__ */ new Map();
66
+ }
67
+ function ensureWorkerTraceExitHook() {
68
+ let host = globalThis;
69
+ host[WORKER_TRACE_HOOKED_KEY] || (host[WORKER_TRACE_HOOKED_KEY] = !0, process.once("beforeExit", () => flushWorkerTraces()), process.once("exit", () => flushWorkerTraces()));
70
+ }
71
+ function flushWorkerTraces(traceDir) {
72
+ let buffer = workerTraceBuffer(), dirs = traceDir ? [traceDir] : [...buffer.keys()];
73
+ for (let dir of dirs) {
74
+ let lines = buffer.get(dir);
75
+ if (!lines || lines.length === 0) continue;
76
+ buffer.delete(dir), mkdirSync(dir, { recursive: !0 });
77
+ let file = join(dir, `worker-${process.pid}.ndjson`);
78
+ appendFileSync(file, lines.join(""), "utf8");
79
+ }
80
+ }
62
81
  function appendWorkerTrace(traceDir, pathname, reads) {
63
82
  if (!reads.length) return;
64
- mkdirSync(traceDir, { recursive: !0 });
65
- let file = join(traceDir, `worker-${process.pid}.ndjson`);
66
- appendFileSync(file, `${JSON.stringify({ pathname: normalizePathname(pathname), reads })}
67
- `, "utf8");
83
+ ensureWorkerTraceExitHook();
84
+ let buffer = workerTraceBuffer(), lines = buffer.get(traceDir);
85
+ lines || (lines = [], buffer.set(traceDir, lines)), lines.push(`${JSON.stringify({ pathname: normalizePathname(pathname), reads })}
86
+ `), lines.length >= WORKER_TRACE_FLUSH_THRESHOLD && flushWorkerTraces(traceDir);
68
87
  }
69
88
  function normalizePathname(pathname) {
70
89
  let clean = pathname.split(/[?#]/)[0] || "/", withLead = clean.startsWith("/") ? clean : `/${clean}`;
@@ -384,19 +403,19 @@ function verifyVisualExpectations(input) {
384
403
  });
385
404
  continue;
386
405
  }
387
- let actual = matches[0].text, ok = !1, expectedStr = typeof exp.expectedValue == "string" ? normalizeSpace(exp.expectedValue) : String(exp.expectedValue);
406
+ let actual = matches[0].text, ok2 = !1, expectedStr = typeof exp.expectedValue == "string" ? normalizeSpace(exp.expectedValue) : String(exp.expectedValue);
388
407
  if (exp.matchType === "exact-text")
389
- ok = actual === expectedStr;
408
+ ok2 = actual === expectedStr;
390
409
  else if (exp.matchType === "media-src")
391
- ok = actual === String(exp.expectedValue) || actual.includes(String(exp.expectedValue));
410
+ ok2 = actual === String(exp.expectedValue) || actual.includes(String(exp.expectedValue));
392
411
  else if (exp.matchType === "override-number")
393
- ok = actual.includes(String(exp.expectedValue)) && !/\b(?:NaN|undefined|null)\b/.test(actual);
412
+ ok2 = actual.includes(String(exp.expectedValue)) && !/\b(?:NaN|undefined|null)\b/.test(actual);
394
413
  else if (exp.matchType === "template-segments") {
395
414
  let plain = normalizeSpace(expectedStr.replace(/\*\*/g, "").replace(/\{[^}]+\}/g, " ")), segments = expectedStr.replace(/\*\*/g, "").split(/\{[^}]+\}/).map(normalizeSpace).filter((s) => s.length >= 3);
396
- ok = segments.length > 0 ? segments.every((seg) => actual.includes(seg)) : actual.includes(plain);
415
+ ok2 = segments.length > 0 ? segments.every((seg) => actual.includes(seg)) : actual.includes(plain);
397
416
  } else if (exp.matchType === "richtext-html") {
398
417
  let stripped = normalizeSpace(String(exp.expectedValue).replace(/<[^>]+>/g, " ")), head = stripped.slice(0, Math.min(40, stripped.length));
399
- ok = head.length > 0 && actual.includes(head);
418
+ ok2 = head.length > 0 && actual.includes(head);
400
419
  }
401
420
  items.push({
402
421
  resourceId: bundle.resourceId,
@@ -405,18 +424,18 @@ function verifyVisualExpectations(input) {
405
424
  xpath: exp.xpath,
406
425
  pointer: exp.pointer,
407
426
  locale: exp.locale,
408
- status: ok ? "passed" : "value_mismatch",
427
+ status: ok2 ? "passed" : "value_mismatch",
409
428
  expected: exp.expectedValue,
410
429
  actual,
411
- detail: ok ? "Matched expected rendered output" : `Expected "${expectedStr}" but rendered "${actual}"`
430
+ detail: ok2 ? "Matched expected rendered output" : `Expected "${expectedStr}" but rendered "${actual}"`
412
431
  });
413
432
  }
414
433
  let passed = items.filter((i) => i.status === "passed").length, failed = items.length - passed;
415
- return { ok: failed === 0, checkedAt: (/* @__PURE__ */ new Date()).toISOString(), total: items.length, passed, failed, items };
434
+ return { ok: failed === 0 && (!input.requireNonEmpty || items.length > 0), checkedAt: (/* @__PURE__ */ new Date()).toISOString(), total: items.length, passed, failed, items };
416
435
  }
417
436
  function finalizeVisualArtifacts(options) {
418
437
  let prismDir = resolve(options.rootDir, ".prism"), traceDir = join(prismDir, "trace"), cacheDir = join(prismDir, "cache"), cacheFile = join(cacheDir, "trace-state.json");
419
- mkdirSync(cacheDir, { recursive: !0 });
438
+ flushWorkerTraces(traceDir), mkdirSync(cacheDir, { recursive: !0 });
420
439
  let merged = /* @__PURE__ */ new Map();
421
440
  if (existsSync(cacheFile))
422
441
  try {
@@ -453,11 +472,15 @@ function finalizeVisualArtifacts(options) {
453
472
  tracedPages: merged.size
454
473
  }, null, 2) + `
455
474
  `, "utf8"), mkdirSync(options.outDir, { recursive: !0 });
456
- let publicConfigPath = resolve(options.outDir, "prism-visual.json"), outputBody = options.encryptPublicKeyPem ? encryptVisualEnvelope(publicConfig, options.encryptPublicKeyPem, options.encryptKeyId ?? "prism-visual-v1") : publicConfig;
457
- writeFileSync(publicConfigPath, JSON.stringify(outputBody) + `
458
- `, "utf8");
475
+ let targetPublicConfigPath = resolve(options.outDir, "prism-visual.json"), publicKeyPem = options.encryptPublicKeyPem?.trim() || "", requireEncryption = options.requireEncryption ?? options.environment === "prod", publicConfigPath = null;
476
+ if (publicKeyPem) {
477
+ let envelope = encryptVisualEnvelope(publicConfig, publicKeyPem, options.encryptKeyId ?? "prism-visual-v1");
478
+ writeFileSync(targetPublicConfigPath, JSON.stringify(envelope) + `
479
+ `, "utf8"), publicConfigPath = targetPublicConfigPath;
480
+ } else requireEncryption ? rmSync(targetPublicConfigPath, { force: !0 }) : (writeFileSync(targetPublicConfigPath, JSON.stringify(publicConfig) + `
481
+ `, "utf8"), publicConfigPath = targetPublicConfigPath);
459
482
  let verifyReport;
460
- return options.verify && expectations.length > 0 && (verifyReport = verifyVisualExpectations({ outDir: options.outDir, bundles: expectations }), writeFileSync(join(prismDir, "visual-verify-report.json"), JSON.stringify(verifyReport, null, 2) + `
483
+ return options.verify && (verifyReport = verifyVisualExpectations({ outDir: options.outDir, bundles: expectations, requireNonEmpty: !0 }), writeFileSync(join(prismDir, "visual-verify-report.json"), JSON.stringify(verifyReport, null, 2) + `
461
484
  `, "utf8")), { visualMapPath, publicConfigPath, publicConfig, verifyReport };
462
485
  }
463
486
 
@@ -468,6 +491,7 @@ export {
468
491
  recordPrismRead,
469
492
  recordLivePageReads,
470
493
  getLivePageReads,
494
+ flushWorkerTraces,
471
495
  appendWorkerTrace,
472
496
  normalizePathname,
473
497
  stripLocalePrefix,
@@ -2,7 +2,7 @@ import {
2
2
  Prism,
3
3
  PrismError,
4
4
  storeFor
5
- } from "./chunk-MYDJI2NW.js";
5
+ } from "./chunk-XJWMC7TR.js";
6
6
 
7
7
  // app/sdk/runtime.ts
8
8
  var key = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/runtime/v1"), globalRegistry = globalThis, registry = globalRegistry[key] ??= /* @__PURE__ */ new Map();
@@ -20,9 +20,36 @@ var PrismError = class extends Error {
20
20
  resourceId;
21
21
  status;
22
22
  constructor(code, message, details = {}) {
23
- super(message), this.name = "PrismError", this.code = code, this.resourceId = details.resourceId, this.status = details.status;
23
+ super(message, { cause: details.cause }), this.name = "PrismError", this.code = code, this.resourceId = details.resourceId, this.status = details.status;
24
24
  }
25
25
  };
26
+ function isTransientDownloadError(error) {
27
+ if (error instanceof PrismError) {
28
+ if (error.code === "HTTP_ERROR") return [408, 429, 500, 502, 503, 504].includes(error.status ?? 0);
29
+ if (error.code !== "NETWORK_ERROR") return !1;
30
+ }
31
+ let seen = /* @__PURE__ */ new Set();
32
+ for (; error && typeof error == "object" && !seen.has(error); ) {
33
+ seen.add(error);
34
+ let detail = error;
35
+ if ([
36
+ "ECONNRESET",
37
+ "ECONNREFUSED",
38
+ "ECONNABORTED",
39
+ "ETIMEDOUT",
40
+ "EPIPE",
41
+ "EAI_AGAIN",
42
+ "ENETUNREACH",
43
+ "EHOSTUNREACH",
44
+ "UND_ERR_SOCKET",
45
+ "UND_ERR_CONNECT_TIMEOUT",
46
+ "UND_ERR_HEADERS_TIMEOUT",
47
+ "UND_ERR_BODY_TIMEOUT"
48
+ ].includes(detail.code ?? "")) return !0;
49
+ error = detail.cause;
50
+ }
51
+ return !1;
52
+ }
26
53
 
27
54
  // app/sdk/dev-server.ts
28
55
  function startDevServer(store, options) {
@@ -148,15 +175,18 @@ function positive(value, field) {
148
175
  return value;
149
176
  }
150
177
  async function responseJson(response, id, signal) {
151
- if (!response.ok) throw new PrismError(
152
- response.status === 404 ? "NOT_PUBLISHED" : "HTTP_ERROR",
153
- `Prism returned HTTP ${response.status} for ${id}`,
154
- { resourceId: id, status: response.status }
155
- );
178
+ if (!response.ok)
179
+ throw await response.body?.cancel().catch(() => {
180
+ }), new PrismError(
181
+ response.status === 404 ? "NOT_PUBLISHED" : "HTTP_ERROR",
182
+ `Prism returned HTTP ${response.status} for ${id}`,
183
+ { resourceId: id, status: response.status }
184
+ );
185
+ let bytes = await response.arrayBuffer();
156
186
  try {
157
- return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(await response.arrayBuffer()));
187
+ return JSON.parse(new TextDecoder("utf-8", { fatal: !0 }).decode(bytes));
158
188
  } catch (error) {
159
- throw signal.aborted ? error : new PrismError("INVALID_BUNDLE", `Invalid JSON for ${id}`, { resourceId: id });
189
+ throw signal.aborted ? error : new PrismError("INVALID_BUNDLE", `Invalid JSON for ${id}`, { resourceId: id, cause: error });
160
190
  }
161
191
  }
162
192
  function canonical(value) {
@@ -196,13 +226,18 @@ var ClientStore = class {
196
226
  constructor(options) {
197
227
  if (!options || typeof options != "object") throw new PrismError("INVALID_CONFIG", "Prism options are required");
198
228
  let environment = checked(resourceEnvironmentSchema.parse, options.environment, "environment"), overrides = resolveEnvVersionOverrides(environment);
199
- this.envOverrides = overrides.byResource, this.envFallbackVersion = overrides.fallbackVersion, this.options = {
229
+ if (this.envOverrides = overrides.byResource, this.envFallbackVersion = overrides.fallbackVersion, this.options = {
200
230
  environment,
201
231
  visibility: checked(resourceVisibilitySchema.parse, options.visibility ?? "public", "visibility"),
202
232
  channel: checked(channelNameSchema.parse, options.channel ?? DEFAULT_EDITORIAL_CHANNEL, "channel"),
203
233
  timeoutMs: positive(options.timeoutMs ?? 8e3, "timeoutMs"),
234
+ maxAttempts: positive(options.maxAttempts ?? 1, "maxAttempts"),
235
+ retryDelayMs: positive(options.retryDelayMs ?? 1e3, "retryDelayMs"),
236
+ onDownloadError: options.onDownloadError,
204
237
  ...options.version === void 0 ? {} : { version: checked(versionAddressSchema.parse, options.version, "version") }
205
- };
238
+ }, this.options.maxAttempts > 5) throw new PrismError("INVALID_CONFIG", "maxAttempts must not exceed 5");
239
+ if (this.options.onDownloadError !== void 0 && typeof this.options.onDownloadError != "function")
240
+ throw new PrismError("INVALID_CONFIG", "onDownloadError must be a function");
206
241
  }
207
242
  versionFor(id) {
208
243
  return this.envOverrides.get(id) ?? this.options.version ?? this.envFallbackVersion;
@@ -211,8 +246,8 @@ var ClientStore = class {
211
246
  let main;
212
247
  try {
213
248
  main = parseResourceMainV2(value);
214
- } catch {
215
- throw new PrismError("INVALID_BUNDLE", `Invalid main.json for ${id}`, { resourceId: id });
249
+ } catch (cause) {
250
+ throw new PrismError("INVALID_BUNDLE", `Invalid main.json for ${id}`, { resourceId: id, cause });
216
251
  }
217
252
  if (main.resourceId !== id || main.environment !== this.options.environment || main.channel !== this.options.channel)
218
253
  throw new PrismError("IDENTITY_MISMATCH", `main.json identity does not match ${id}`, { resourceId: id });
@@ -247,63 +282,101 @@ var ClientStore = class {
247
282
  return this.pending.set(id, { promise, controller }), promise;
248
283
  }
249
284
  async download(id, controller) {
250
- let previous = this.cache.get(id), timedOut = !1, timer = setTimeout(() => {
285
+ let selectedVersion = this.versionFor(id), path = selectedVersion === void 0 ? resourcePublicMainPath(id, this.options.channel) : resourceVersionMainPath(id, this.options.channel, selectedVersion), origin = resourceDeliveryOrigin(this.options.environment, this.options.visibility), url = new URL(path, origin), timedOut = !1, timer = setTimeout(() => {
251
286
  timedOut = !0, controller.abort();
252
- }, this.options.timeoutMs);
287
+ }, this.options.timeoutMs), failure = (cause) => {
288
+ if (cause instanceof PrismError) return cause;
289
+ let code = timedOut ? "TIMEOUT" : controller.signal.aborted ? "CLOSED" : "NETWORK_ERROR";
290
+ return new PrismError(code, `${code === "TIMEOUT" ? "Request timed out" : code === "CLOSED" ? "Request cancelled" : "Network request failed"} for ${id}`, { resourceId: id, cause });
291
+ }, report = (error, attempt, retryDelayMs) => {
292
+ try {
293
+ this.options.onDownloadError?.({
294
+ resourceId: id,
295
+ url: url.href,
296
+ environment: this.options.environment,
297
+ channel: this.options.channel,
298
+ attempt,
299
+ maxAttempts: this.options.maxAttempts,
300
+ retryDelayMs,
301
+ error
302
+ });
303
+ } catch {
304
+ }
305
+ };
253
306
  try {
254
- let selectedVersion = this.versionFor(id), path = selectedVersion === void 0 ? resourcePublicMainPath(id, this.options.channel) : resourceVersionMainPath(id, this.options.channel, selectedVersion), expectedVersionId = selectedVersion === void 0 ? void 0 : previous?.main.versionId, origin = resourceDeliveryOrigin(this.options.environment, this.options.visibility);
255
- if (selectedVersion !== void 0 && !expectedVersionId) {
256
- let response2 = await fetch(new URL(resourceVersionManifestPath(id, this.options.channel, selectedVersion), origin), {
257
- method: "GET",
258
- cache: "no-store",
259
- credentials: "omit",
260
- redirect: "error",
261
- signal: controller.signal
262
- }), value2 = await responseJson(response2, id, controller.signal), manifest;
307
+ for (let attempt = 1; ; attempt++)
263
308
  try {
264
- manifest = parseResourceManifestV4(value2);
265
- } catch {
266
- throw new PrismError("INVALID_BUNDLE", `Invalid version manifest for ${id}`, { resourceId: id });
309
+ return await this.downloadAttempt(id, selectedVersion, path, origin, url, controller);
310
+ } catch (cause) {
311
+ let error = failure(cause), retryDelayMs = !controller.signal.aborted && attempt < this.options.maxAttempts && isTransientDownloadError(error) ? Math.min(this.options.retryDelayMs * 2 ** (attempt - 1), 3e4) : null;
312
+ if (report(error, attempt, retryDelayMs), retryDelayMs === null) throw error;
313
+ try {
314
+ await new Promise((resolveTimer, rejectTimer) => {
315
+ let abort = () => {
316
+ clearTimeout(delay), rejectTimer(controller.signal.reason);
317
+ }, delay = setTimeout(() => {
318
+ controller.signal.removeEventListener("abort", abort), resolveTimer();
319
+ }, retryDelayMs);
320
+ controller.signal.addEventListener("abort", abort, { once: !0 }), controller.signal.aborted && abort();
321
+ });
322
+ } catch (waitCause) {
323
+ let waitError = failure(waitCause);
324
+ throw report(waitError, attempt, null), waitError;
325
+ }
267
326
  }
268
- if (manifest.resourceId !== id || manifest.environment !== this.options.environment || manifest.channel !== this.options.channel || manifest.mainUrl !== path)
269
- throw new PrismError("IDENTITY_MISMATCH", `Version manifest identity does not match ${id}`, { resourceId: id });
270
- expectedVersionId = manifest.versionId;
271
- }
272
- let response = await fetch(new URL(path, origin), {
327
+ } finally {
328
+ clearTimeout(timer);
329
+ }
330
+ }
331
+ async downloadAttempt(id, selectedVersion, path, origin, url, controller) {
332
+ let previous = this.cache.get(id);
333
+ controller.signal.throwIfAborted();
334
+ let expectedVersionId = selectedVersion === void 0 ? void 0 : previous?.main.versionId;
335
+ if (selectedVersion !== void 0 && !expectedVersionId) {
336
+ let response2 = await fetch(new URL(resourceVersionManifestPath(id, this.options.channel, selectedVersion), origin), {
273
337
  method: "GET",
274
338
  cache: "no-store",
275
339
  credentials: "omit",
276
340
  redirect: "error",
277
- headers: previous?.etag ? { "If-None-Match": previous.etag } : {},
278
341
  signal: controller.signal
279
- });
280
- if (response.status === 304) {
281
- if (!previous) throw new PrismError("INVALID_BUNDLE", `304 without cached content for ${id}`, { resourceId: id });
282
- return previous;
283
- }
284
- let value = await responseJson(response, id, controller.signal);
285
- if (controller.signal.aborted) throw new Error("Aborted");
286
- let main = this.parse(value, id);
287
- if (expectedVersionId !== void 0 && main.versionId !== expectedVersionId)
288
- throw new PrismError("IDENTITY_MISMATCH", `main.json Version does not match its manifest for ${id}`, { resourceId: id });
289
- let fingerprint = canonical(main);
290
- if (previous) {
291
- if (main.generation < previous.main.generation) return previous;
292
- if (main.generation === previous.main.generation && fingerprint !== previous.fingerprint)
293
- throw new PrismError("PUBLICATION_CONFLICT", `Publication changed without a new generation for ${id}`, { resourceId: id });
294
- if (main.generation > previous.main.generation && main.publicationId === previous.main.publicationId)
295
- throw new PrismError("PUBLICATION_CONFLICT", `Publication ID reused for ${id}`, { resourceId: id });
342
+ }), value2 = await responseJson(response2, id, controller.signal), manifest;
343
+ try {
344
+ manifest = parseResourceManifestV4(value2);
345
+ } catch (cause) {
346
+ throw new PrismError("INVALID_BUNDLE", `Invalid version manifest for ${id}`, { resourceId: id, cause });
296
347
  }
297
- for (let requirement of this.requirements.get(id) ?? []) select(main, requirement);
298
- let entry = { main, etag: response.headers.get("etag"), fingerprint };
299
- return this.cache.set(id, entry), entry;
300
- } catch (error) {
301
- if (error instanceof PrismError) throw error;
302
- let code = timedOut ? "TIMEOUT" : controller.signal.aborted ? "CLOSED" : "NETWORK_ERROR";
303
- throw new PrismError(code, `${code === "TIMEOUT" ? "Request timed out" : code === "CLOSED" ? "Request cancelled" : "Network request failed"} for ${id}`, { resourceId: id });
304
- } finally {
305
- clearTimeout(timer);
348
+ if (manifest.resourceId !== id || manifest.environment !== this.options.environment || manifest.channel !== this.options.channel || manifest.mainUrl !== path)
349
+ throw new PrismError("IDENTITY_MISMATCH", `Version manifest identity does not match ${id}`, { resourceId: id });
350
+ expectedVersionId = manifest.versionId;
351
+ }
352
+ let response = await fetch(url, {
353
+ method: "GET",
354
+ cache: "no-store",
355
+ credentials: "omit",
356
+ redirect: "error",
357
+ headers: previous?.etag ? { "If-None-Match": previous.etag } : {},
358
+ signal: controller.signal
359
+ });
360
+ if (response.status === 304) {
361
+ if (!previous) throw new PrismError("INVALID_BUNDLE", `304 without cached content for ${id}`, { resourceId: id });
362
+ return previous;
306
363
  }
364
+ let value = await responseJson(response, id, controller.signal);
365
+ if (controller.signal.aborted) throw new Error("Aborted");
366
+ let main = this.parse(value, id);
367
+ if (expectedVersionId !== void 0 && main.versionId !== expectedVersionId)
368
+ throw new PrismError("IDENTITY_MISMATCH", `main.json Version does not match its manifest for ${id}`, { resourceId: id });
369
+ let fingerprint = canonical(main);
370
+ if (previous) {
371
+ if (main.generation < previous.main.generation) return previous;
372
+ if (main.generation === previous.main.generation && fingerprint !== previous.fingerprint)
373
+ throw new PrismError("PUBLICATION_CONFLICT", `Publication changed without a new generation for ${id}`, { resourceId: id });
374
+ if (main.generation > previous.main.generation && main.publicationId === previous.main.publicationId)
375
+ throw new PrismError("PUBLICATION_CONFLICT", `Publication ID reused for ${id}`, { resourceId: id });
376
+ }
377
+ for (let requirement of this.requirements.get(id) ?? []) select(main, requirement);
378
+ let entry = { main, etag: response.headers.get("etag"), fingerprint };
379
+ return this.cache.set(id, entry), entry;
307
380
  }
308
381
  }, stores = /* @__PURE__ */ new WeakMap();
309
382
  function storeFor(client) {
@@ -311,6 +384,14 @@ function storeFor(client) {
311
384
  if (!store) throw new PrismError("INVALID_CONFIG", "Unknown Prism client");
312
385
  return store;
313
386
  }
387
+ function seedPrismResource(client, resourceId, value) {
388
+ let id = checked(resourceUuidSchema.parse, resourceId, "resourceId"), store = storeFor(client);
389
+ store.parse(value, id), store.seed([value]);
390
+ }
391
+ function prismResourceMainUrl(options) {
392
+ let env = checked(resourceEnvironmentSchema.parse, options.environment, "environment"), id = checked(resourceUuidSchema.parse, options.resourceId, "resourceId"), channel = checked(channelNameSchema.parse, options.channel ?? DEFAULT_EDITORIAL_CHANNEL, "channel"), visibility = checked(resourceVisibilitySchema.parse, options.visibility ?? "public", "visibility"), overrides = resolveEnvVersionOverrides(env), effectiveVersion = (options.version === void 0 ? void 0 : checked(versionAddressSchema.parse, options.version, "version")) ?? overrides.byResource.get(id) ?? overrides.fallbackVersion, path = effectiveVersion === void 0 ? resourcePublicMainPath(id, channel) : resourceVersionMainPath(id, channel, effectiveVersion);
393
+ return new URL(path, resourceDeliveryOrigin(env, visibility)).href;
394
+ }
314
395
  var Prism = class _Prism {
315
396
  locale;
316
397
  constructor(options) {
@@ -342,8 +423,11 @@ var Prism = class _Prism {
342
423
 
343
424
  export {
344
425
  PrismError,
426
+ isTransientDownloadError,
345
427
  registerReadObserver,
346
428
  resolveEnvVersionOverrides,
347
429
  storeFor,
430
+ seedPrismResource,
431
+ prismResourceMainUrl,
348
432
  Prism
349
433
  };
@@ -21,6 +21,8 @@ export interface PrismVisualMapOptions {
21
21
  /** Optional RSA public key PEM for envelope encrypting out/prism-visual.json (plaintext in local dev). */
22
22
  encryptPublicKeyPem?: string;
23
23
  encryptKeyId?: string;
24
+ /** Require public-key encryption to emit out/prism-visual.json. Defaults to `true` in `prod` (fail-closed: no key => feature disabled). */
25
+ requireEncryption?: boolean;
24
26
  /** Dev-only optional resolver so Chrome extension can inspect live 11-locale slices locally on 127.0.0.1. */
25
27
  devSliceResolver?: (params: {
26
28
  resourceId: string;
package/dist/sdk/astro.js CHANGED
@@ -5,15 +5,15 @@ import {
5
5
  getLivePageReads,
6
6
  readOverridesFile,
7
7
  resolveBuildRef
8
- } from "../chunk-NSC3MYAU.js";
8
+ } from "../chunk-7NEPBMKR.js";
9
9
  import {
10
10
  getRuntime,
11
11
  releaseRuntime,
12
12
  runtimeSeeds
13
- } from "../chunk-2G5GDKYE.js";
13
+ } from "../chunk-G73WZGOW.js";
14
14
  import {
15
15
  PrismError
16
- } from "../chunk-MYDJI2NW.js";
16
+ } from "../chunk-XJWMC7TR.js";
17
17
  import "../chunk-3B2PZHLA.js";
18
18
 
19
19
  // app/sdk/astro.ts
@@ -156,16 +156,21 @@ function prismVisualMap(options = {}) {
156
156
  },
157
157
  "astro:build:done": ({ logger }) => {
158
158
  if (isDev) return;
159
- let verifyEnabled = process.env.PRISM_VISUAL_VERIFY === "1" && !!(process.env.PRISM_VERSION_OVERRIDE || process.env.PRISM_VERSION), publicKeyPem = options.encryptPublicKeyPem ?? process.env.PRISM_VISUAL_PUBLIC_KEY_PEM, result = finalizeVisualArtifacts({
159
+ let verifyEnabled = process.env.PRISM_VISUAL_VERIFY === "1" && !!(process.env.PRISM_VERSION_OVERRIDE || process.env.PRISM_VERSION), publicKeyPem = options.encryptPublicKeyPem ?? process.env.PRISM_VISUAL_PUBLIC_KEY_PEM, requireEncryption = options.requireEncryption ?? activeEnv === "prod", result = finalizeVisualArtifacts({
160
160
  rootDir,
161
161
  outDir,
162
162
  environment: activeEnv,
163
163
  overridesFile: options.overridesFile ?? "prism.visual.json",
164
164
  encryptPublicKeyPem: publicKeyPem,
165
165
  encryptKeyId: options.encryptKeyId ?? process.env.PRISM_VISUAL_KEY_ID ?? "prism-visual-v1",
166
+ requireEncryption,
166
167
  verify: verifyEnabled
167
168
  });
168
- if (logger.info(`Wrote ${result.visualMapPath} and ${result.publicConfigPath} (${result.publicConfig.routes.length} routes).`), result.verifyReport && (logger.info(`Visual XPath verification: ${result.verifyReport.passed}/${result.verifyReport.total} passed.`), !result.verifyReport.ok)) {
169
+ if (result.publicConfigPath ? logger.info(`Wrote ${result.visualMapPath} and ${result.publicConfigPath} (${result.publicConfig.routes.length} routes).`) : logger.warn(
170
+ `PRISM_VISUAL_PUBLIC_KEY_PEM is not configured for ${activeEnv}; skipped writing out/prism-visual.json so visual editing remains disabled (fail-closed).`
171
+ ), result.verifyReport && (logger.info(`Visual XPath verification: ${result.verifyReport.passed}/${result.verifyReport.total} passed.`), !result.verifyReport.ok)) {
172
+ if (result.verifyReport.total === 0)
173
+ throw new Error("Prism visual XPath verification failed: 0 assertions executed (refusing empty pass).");
169
174
  let summary = result.verifyReport.items.filter((item) => item.status !== "passed").map((item) => ` - [${item.status}] ${item.pagePath} ${item.xpath}: ${item.detail}`).join(`
170
175
  `);
171
176
  throw new Error(`Prism visual XPath verification failed (${result.verifyReport.failed}/${result.verifyReport.total}):
@@ -6,6 +6,16 @@ export declare function resolveEnvVersionOverrides(environment: 'dev' | 'prod'):
6
6
  byResource: ReadonlyMap<string, string>;
7
7
  fallbackVersion?: string;
8
8
  };
9
+ /** Validate and seed a pre-fetched/revalidated `main.json` payload into a Prism client cache. */
10
+ export declare function seedPrismResource(client: Prism, resourceId: string, value: unknown): void;
11
+ /** Build the canonical delivery URL for a Resource's channel head or version-pinned snapshot using the authoritative contract. */
12
+ export declare function prismResourceMainUrl(options: {
13
+ environment: 'dev' | 'prod';
14
+ resourceId: string;
15
+ channel?: string;
16
+ version?: string;
17
+ visibility?: 'public' | 'internal';
18
+ }): string;
9
19
  export declare class Prism {
10
20
  private readonly locale?;
11
21
  constructor(options: PrismOptions);
@@ -6,5 +6,8 @@ export declare class PrismError extends Error {
6
6
  constructor(code: PrismErrorCode, message: string, details?: {
7
7
  resourceId?: string;
8
8
  status?: number;
9
+ cause?: unknown;
9
10
  });
10
11
  }
12
+ /** Retry transport failures, never publication, identity or content failures. */
13
+ export declare function isTransientDownloadError(error: unknown): boolean;
@@ -1,5 +1,5 @@
1
- export { Prism, registerReadObserver, resolveEnvVersionOverrides } from './client.js';
2
- export { PrismError } from './errors.js';
1
+ export { Prism, prismResourceMainUrl, registerReadObserver, resolveEnvVersionOverrides, seedPrismResource } from './client.js';
2
+ export { isTransientDownloadError, PrismError } from './errors.js';
3
3
  export type { PrismErrorCode } from './errors.js';
4
- export type { PrismOptions, Environment, Visibility, ResourceOptions, ResourceQuery, PublicationMeta, ResourceResult, ResourceBundleResult, DevServerOptions, DevServerHandle, DevUpdate, PrismReadEvent, PrismReadObserver, VisualExpectation, } from './types.js';
4
+ export type { PrismOptions, PrismDownloadErrorEvent, Environment, Visibility, ResourceOptions, ResourceQuery, PublicationMeta, ResourceResult, ResourceBundleResult, DevServerOptions, DevServerHandle, DevUpdate, PrismReadEvent, PrismReadObserver, VisualExpectation, } from './types.js';
5
5
  export type { ScopeRole, ResourceMembership } from '../contracts/access.js';
package/dist/sdk/index.js CHANGED
@@ -1,13 +1,19 @@
1
1
  import {
2
2
  Prism,
3
3
  PrismError,
4
+ isTransientDownloadError,
5
+ prismResourceMainUrl,
4
6
  registerReadObserver,
5
- resolveEnvVersionOverrides
6
- } from "../chunk-MYDJI2NW.js";
7
+ resolveEnvVersionOverrides,
8
+ seedPrismResource
9
+ } from "../chunk-XJWMC7TR.js";
7
10
  import "../chunk-3B2PZHLA.js";
8
11
  export {
9
12
  Prism,
10
13
  PrismError,
14
+ isTransientDownloadError,
15
+ prismResourceMainUrl,
11
16
  registerReadObserver,
12
- resolveEnvVersionOverrides
17
+ resolveEnvVersionOverrides,
18
+ seedPrismResource
13
19
  };
@@ -2,8 +2,8 @@ import {
2
2
  getRuntime,
3
3
  releaseRuntime,
4
4
  runtimeSeeds
5
- } from "../chunk-2G5GDKYE.js";
6
- import "../chunk-MYDJI2NW.js";
5
+ } from "../chunk-G73WZGOW.js";
6
+ import "../chunk-XJWMC7TR.js";
7
7
  import "../chunk-3B2PZHLA.js";
8
8
  export {
9
9
  getRuntime,
@@ -2,6 +2,16 @@ import type { VisualExpectation } from '../contracts/types.js';
2
2
  export type { VisualExpectation } from '../contracts/types.js';
3
3
  export type Environment = 'dev' | 'prod';
4
4
  export type Visibility = 'public' | 'internal';
5
+ export interface PrismDownloadErrorEvent {
6
+ resourceId: string;
7
+ url: string;
8
+ environment: Environment;
9
+ channel: string;
10
+ attempt: number;
11
+ maxAttempts: number;
12
+ retryDelayMs: number | null;
13
+ error: import('./errors.js').PrismError;
14
+ }
5
15
  export interface PrismOptions {
6
16
  environment: Environment;
7
17
  visibility?: Visibility;
@@ -10,6 +20,10 @@ export interface PrismOptions {
10
20
  version?: string;
11
21
  locale?: string;
12
22
  timeoutMs?: number;
23
+ /** Total attempts within timeoutMs, including the initial request. Defaults to 1 (max 5). */
24
+ maxAttempts?: number;
25
+ retryDelayMs?: number;
26
+ onDownloadError?: (failure: PrismDownloadErrorEvent) => void;
13
27
  }
14
28
  export interface ResourceOptions<T = unknown> {
15
29
  locale?: string;
@@ -32,6 +32,8 @@ export declare function runVisualVerifyLane(options?: {
32
32
  expectationsDir?: string;
33
33
  reportPath?: string;
34
34
  bundles?: readonly VisualLaneExpectationBundle[];
35
+ /** By default (`false`), zero executed assertions (`total === 0`) fails closed (`ok: false`). */
36
+ allowEmpty?: boolean;
35
37
  }): VisualLaneReport;
36
38
  /**
37
39
  * Extract an immutable preview URL from deployment stdout/stderr logs.
@@ -51,12 +53,17 @@ export declare function verifyPreviewNoindex(url: string, options?: {
51
53
  maxAttempts?: number;
52
54
  retryDelayMs?: number;
53
55
  }): Promise<void>;
56
+ /** Compute `X-Prism-Callback-Signature` (`sha256=<hex>`) for a serialized callback JSON body. */
57
+ export declare function signVisualCallbackBody(bodyText: string, secret: string): string;
54
58
  /**
55
59
  * Report verification lane status, preview URL, and XPath assertion report back to Prism.
60
+ * Supports either HMAC-SHA256 signing via `callbackSecret` (recommended for CI secrets)
61
+ * or per-run Bearer token via `callbackToken` (for generic webhooks).
56
62
  */
57
63
  export declare function postVisualLaneCallback(input: {
58
64
  callbackUrl: string;
59
- callbackToken: string;
65
+ callbackToken?: string;
66
+ callbackSecret?: string;
60
67
  runId: string;
61
68
  status: 'running' | 'passed' | 'failed';
62
69
  previewUrl?: string | null;
@@ -1,14 +1,15 @@
1
1
  import {
2
2
  verifyVisualExpectations
3
- } from "../chunk-NSC3MYAU.js";
4
- import "../chunk-MYDJI2NW.js";
3
+ } from "../chunk-7NEPBMKR.js";
4
+ import "../chunk-XJWMC7TR.js";
5
5
  import "../chunk-3B2PZHLA.js";
6
6
 
7
7
  // app/sdk/visual-lane.ts
8
+ import { createHmac } from "node:crypto";
8
9
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
9
10
  import { dirname, join, resolve } from "node:path";
10
11
  function mapSdkVerifyStatus(status) {
11
- return status === "passed" ? "passed" : status === "missing_page" ? "missing-page" : status === "missing_xpath" ? "missing-xpath" : "failed";
12
+ return status === "passed" ? "passed" : status === "missing_page" || status === "page_not_found" ? "missing-page" : status === "missing_xpath" || status === "xpath_not_found" ? "missing-xpath" : "failed";
12
13
  }
13
14
  function runVisualVerifyLane(options = {}) {
14
15
  let rootDir = resolve(options.rootDir ?? process.cwd()), outDir = resolve(rootDir, options.outDir ?? "out"), expectationsDir = resolve(rootDir, options.expectationsDir ?? join(".prism", "expectations")), reportPath = resolve(rootDir, options.reportPath ?? join(".prism", "visual-verify-report.json")), bundles = options.bundles ? [...options.bundles] : [];
@@ -21,7 +22,7 @@ function runVisualVerifyLane(options = {}) {
21
22
  expectations: parsed.expectations
22
23
  });
23
24
  }
24
- let rawReport = verifyVisualExpectations({ outDir, bundles }), matchTypeByKey = /* @__PURE__ */ new Map();
25
+ let rawReport = verifyVisualExpectations({ outDir, bundles, requireNonEmpty: options.allowEmpty !== !0 }), matchTypeByKey = /* @__PURE__ */ new Map();
25
26
  for (let bundle of bundles)
26
27
  for (let exp of bundle.expectations)
27
28
  matchTypeByKey.set(`${exp.pagePath}|${exp.xpath}|${exp.pointer}|${exp.locale}`, exp.matchType);
@@ -79,21 +80,28 @@ async function verifyPreviewNoindex(url, options = {}) {
79
80
  }
80
81
  throw lastError ?? new Error("Preview readiness deadline exceeded");
81
82
  }
83
+ function signVisualCallbackBody(bodyText, secret) {
84
+ return `sha256=${createHmac("sha256", secret).update(bodyText, "utf8").digest("hex")}`;
85
+ }
82
86
  async function postVisualLaneCallback(input) {
83
- let response = await (input.fetchImpl ?? fetch)(input.callbackUrl, {
87
+ let token = input.callbackToken?.trim() ?? "", secret = input.callbackSecret?.trim() ?? "";
88
+ if (!token && !secret)
89
+ throw new Error("Either callbackSecret or callbackToken is required for Prism callback authentication");
90
+ let fetchImpl = input.fetchImpl ?? fetch, bodyText = JSON.stringify({
91
+ runId: input.runId,
92
+ status: input.status,
93
+ ...input.previewUrl !== void 0 ? { previewUrl: input.previewUrl } : {},
94
+ ...input.ciRunUrl !== void 0 ? { ciRunUrl: input.ciRunUrl } : {},
95
+ ...input.report !== void 0 ? { report: input.report } : {},
96
+ ...input.errorMessage !== void 0 ? { errorMessage: input.errorMessage } : {}
97
+ }), headers = {
98
+ "Content-Type": "application/json"
99
+ };
100
+ secret && (headers["X-Prism-Callback-Signature"] = signVisualCallbackBody(bodyText, secret)), token && (headers.Authorization = `Bearer ${token}`);
101
+ let response = await fetchImpl(input.callbackUrl, {
84
102
  method: "POST",
85
- headers: {
86
- "Content-Type": "application/json",
87
- Authorization: `Bearer ${input.callbackToken}`
88
- },
89
- body: JSON.stringify({
90
- runId: input.runId,
91
- status: input.status,
92
- ...input.previewUrl !== void 0 ? { previewUrl: input.previewUrl } : {},
93
- ...input.ciRunUrl !== void 0 ? { ciRunUrl: input.ciRunUrl } : {},
94
- ...input.report !== void 0 ? { report: input.report } : {},
95
- ...input.errorMessage !== void 0 ? { errorMessage: input.errorMessage } : {}
96
- }),
103
+ headers,
104
+ body: bodyText,
97
105
  signal: AbortSignal.timeout(2e4)
98
106
  });
99
107
  if (!response.ok) {
@@ -106,5 +114,6 @@ export {
106
114
  mapSdkVerifyStatus,
107
115
  postVisualLaneCallback,
108
116
  runVisualVerifyLane,
117
+ signVisualCallbackBody,
109
118
  verifyPreviewNoindex
110
119
  };
@@ -98,6 +98,7 @@ export declare function currentPageTrace(): TraceStore | undefined;
98
98
  export declare function recordPrismRead(record: PrismReadTraceRecord): void;
99
99
  export declare function recordLivePageReads(pathname: string, reads: PrismReadTraceRecord[]): void;
100
100
  export declare function getLivePageReads(): Map<string, PrismReadTraceRecord[]>;
101
+ export declare function flushWorkerTraces(traceDir?: string): void;
101
102
  export declare function appendWorkerTrace(traceDir: string, pathname: string, reads: PrismReadTraceRecord[]): void;
102
103
  export declare function normalizePathname(pathname: string): string;
103
104
  export declare function stripLocalePrefix(pathname: string, locales: readonly string[]): {
@@ -155,6 +156,8 @@ export declare function verifyVisualExpectations(input: {
155
156
  versionId: string;
156
157
  expectations: VisualExpectation[];
157
158
  }>;
159
+ /** When true, zero executed assertions (`total === 0`) is treated as failed (`ok: false`). */
160
+ requireNonEmpty?: boolean;
158
161
  }): VisualVerifyReport;
159
162
  export declare function finalizeVisualArtifacts(options: {
160
163
  rootDir: string;
@@ -163,10 +166,12 @@ export declare function finalizeVisualArtifacts(options: {
163
166
  overridesFile?: string;
164
167
  encryptPublicKeyPem?: string;
165
168
  encryptKeyId?: string;
169
+ /** Require public-key encryption to emit `out/prism-visual.json`. Defaults to `true` for `prod` (fail-closed: no key => feature disabled). */
170
+ requireEncryption?: boolean;
166
171
  verify?: boolean;
167
172
  }): {
168
173
  visualMapPath: string;
169
- publicConfigPath: string;
174
+ publicConfigPath: string | null;
170
175
  publicConfig: VisualPublicConfig;
171
176
  verifyReport?: VisualVerifyReport;
172
177
  };
@@ -7,6 +7,7 @@ import {
7
7
  encryptVisualEnvelope,
8
8
  evaluateHtmlXPath,
9
9
  finalizeVisualArtifacts,
10
+ flushWorkerTraces,
10
11
  getLivePageReads,
11
12
  isVisualEnvelope,
12
13
  normalizePathname,
@@ -17,8 +18,8 @@ import {
17
18
  runWithPageTrace,
18
19
  stripLocalePrefix,
19
20
  verifyVisualExpectations
20
- } from "../chunk-NSC3MYAU.js";
21
- import "../chunk-MYDJI2NW.js";
21
+ } from "../chunk-7NEPBMKR.js";
22
+ import "../chunk-XJWMC7TR.js";
22
23
  import "../chunk-3B2PZHLA.js";
23
24
  export {
24
25
  appendWorkerTrace,
@@ -29,6 +30,7 @@ export {
29
30
  encryptVisualEnvelope,
30
31
  evaluateHtmlXPath,
31
32
  finalizeVisualArtifacts,
33
+ flushWorkerTraces,
32
34
  getLivePageReads,
33
35
  isVisualEnvelope,
34
36
  normalizePathname,
@@ -4,8 +4,8 @@ import {
4
4
  enableAutomaticReadTracing,
5
5
  recordLivePageReads,
6
6
  runWithPageTrace
7
- } from "../chunk-NSC3MYAU.js";
8
- import "../chunk-MYDJI2NW.js";
7
+ } from "../chunk-7NEPBMKR.js";
8
+ import "../chunk-XJWMC7TR.js";
9
9
  import "../chunk-3B2PZHLA.js";
10
10
 
11
11
  // app/sdk/visual-middleware.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerformer/prism-client",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "description": "Read published Prism multilingual content with shared caching and Astro development updates.",
6
6
  "license": "UNLICENSED",