@powerformer/prism-client 0.8.0 → 0.9.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.9.0",
4
+ "gitCommit": "1596ecb5ff8ba3c1f1f03f60aadd079334dec6ab",
5
+ "sourceSha256": "1bf12198a5945044fe7286a72c1a2b9ac10b55741ab3969af35fa23a52283516",
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}`;
@@ -416,7 +435,7 @@ function verifyVisualExpectations(input) {
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 {
@@ -468,6 +487,7 @@ export {
468
487
  recordPrismRead,
469
488
  recordLivePageReads,
470
489
  getLivePageReads,
490
+ flushWorkerTraces,
471
491
  appendWorkerTrace,
472
492
  normalizePathname,
473
493
  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
  };
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-3GDVHLYY.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
@@ -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;
@@ -51,12 +51,17 @@ export declare function verifyPreviewNoindex(url: string, options?: {
51
51
  maxAttempts?: number;
52
52
  retryDelayMs?: number;
53
53
  }): Promise<void>;
54
+ /** Compute `X-Prism-Callback-Signature` (`sha256=<hex>`) for a serialized callback JSON body. */
55
+ export declare function signVisualCallbackBody(bodyText: string, secret: string): string;
54
56
  /**
55
57
  * Report verification lane status, preview URL, and XPath assertion report back to Prism.
58
+ * Supports either HMAC-SHA256 signing via `callbackSecret` (recommended for CI secrets)
59
+ * or per-run Bearer token via `callbackToken` (for generic webhooks).
56
60
  */
57
61
  export declare function postVisualLaneCallback(input: {
58
62
  callbackUrl: string;
59
- callbackToken: string;
63
+ callbackToken?: string;
64
+ callbackSecret?: string;
60
65
  runId: string;
61
66
  status: 'running' | 'passed' | 'failed';
62
67
  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-3GDVHLYY.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] : [];
@@ -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[]): {
@@ -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-3GDVHLYY.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-3GDVHLYY.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.9.0",
4
4
  "type": "module",
5
5
  "description": "Read published Prism multilingual content with shared caching and Astro development updates.",
6
6
  "license": "UNLICENSED",