@snowcone-app/sdk 0.26.0 → 0.27.1

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/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  REALTIME_WS_URL,
6
6
  RealtimeMockupService
7
- } from "./chunk-4NCMFK5L.js";
7
+ } from "./chunk-IW7DXXGY.js";
8
8
  import {
9
9
  buildMockupUrl,
10
10
  buildPublicMockupUrl,
@@ -24,7 +24,14 @@ var CatalogProductSchema = z.object({
24
24
  lowestPrice: z.number().int().optional(),
25
25
  highestPrice: z.number().int().optional(),
26
26
  mockups: z.array(
27
- z.object({ id: z.string(), ar: z.number(), gvids: z.array(z.string()) })
27
+ z.object({
28
+ id: z.string(),
29
+ ar: z.number(),
30
+ gvids: z.array(z.string()),
31
+ // Kept through a successful parse (zod strips undeclared keys): the PDP shows one size picture, the chosen size's.
32
+ // Any mark is kept (a parse must not strip it): only an absent one is an ordinary picture (mockupRole.ts).
33
+ linkedAs: z.string().optional()
34
+ })
28
35
  ).optional(),
29
36
  options: z.object({
30
37
  selected: z.record(z.string(), z.union([z.string(), z.number(), z.null()])).optional(),
@@ -629,6 +636,32 @@ function bffSigner(endpoint = "/api/sign", opts) {
629
636
  };
630
637
  }
631
638
 
639
+ // src/mockup/mockupRole.ts
640
+ var SIZE_PICTURE = "size-picture";
641
+ function mockupRole(m) {
642
+ const mark = m?.linkedAs;
643
+ if (mark === void 0 || mark === null || mark === "") return "ordinary";
644
+ return mark === SIZE_PICTURE ? SIZE_PICTURE : "other";
645
+ }
646
+ function ordinaryMockups(mockups) {
647
+ return (mockups ?? []).filter((m) => mockupRole(m) === "ordinary");
648
+ }
649
+ function pictureForVariant(mockups, variantId) {
650
+ const ordinary = ordinaryMockups(mockups);
651
+ if (variantId) {
652
+ const listed = ordinary.find((m) => (m.gvids ?? []).includes(variantId));
653
+ if (listed) return listed;
654
+ }
655
+ return ordinary[0] ?? null;
656
+ }
657
+ function primaryMockup(mockups) {
658
+ return ordinaryMockups(mockups)[0] ?? null;
659
+ }
660
+ function gallerySizePicture(mockups, selectedVariantId) {
661
+ if (!selectedVariantId) return null;
662
+ return (mockups ?? []).find((m) => mockupRole(m) === SIZE_PICTURE && (m.gvids ?? []).includes(selectedVariantId)) ?? null;
663
+ }
664
+
632
665
  // src/state/optionSelection.ts
633
666
  function resolveBestCombination(selection, attributes, combinations) {
634
667
  const relevant = Object.fromEntries(
@@ -1478,10 +1511,7 @@ function getVariant(selection, product) {
1478
1511
  const variantId = combination?.variantId;
1479
1512
  let mockupId;
1480
1513
  if (variantId && product.mockups && product.mockups.length > 0) {
1481
- const mockupForVariant = product.mockups.find(
1482
- (m) => m.gvids && m.gvids.includes(variantId)
1483
- );
1484
- mockupId = mockupForVariant?.id || product.mockups[0].id;
1514
+ mockupId = pictureForVariant(product.mockups, variantId)?.id;
1485
1515
  }
1486
1516
  return {
1487
1517
  variantId,
@@ -1520,7 +1550,7 @@ var SIZE_ATTRIBUTE = /^size$/i;
1520
1550
  var NOT_THE_PICTURE = /* @__PURE__ */ new Set(["variantId", "price"]);
1521
1551
  function resolvePreviewVariantId(context, variantId, mockupId) {
1522
1552
  const all = context?.product?.mockups ?? [];
1523
- const mockups = mockupId ? all.filter((m) => m.id === mockupId) : all;
1553
+ const mockups = mockupId ? all.filter((m) => m.id === mockupId) : [...ordinaryMockups(all)];
1524
1554
  const lists = (m, id) => (m.gvids ?? []).includes(id);
1525
1555
  if (mockups.length === 0 || mockups.some((m) => lists(m, variantId))) return variantId;
1526
1556
  const combinations = context?.combinations ?? [];
@@ -1548,15 +1578,7 @@ function resolvePreviewVariantId(context, variantId, mockupId) {
1548
1578
  function resolveMockupId(context, variantId, providedMockupId) {
1549
1579
  if (providedMockupId) return providedMockupId;
1550
1580
  if (context?.product?.mockups?.length) {
1551
- if (variantId) {
1552
- const mockupForVariant = context.product.mockups.find(
1553
- (m) => m.gvids && m.gvids.includes(variantId)
1554
- );
1555
- if (mockupForVariant) {
1556
- return mockupForVariant.id;
1557
- }
1558
- }
1559
- return context.product.mockups[0].id;
1581
+ return pictureForVariant(context.product.mockups, variantId)?.id ?? null;
1560
1582
  }
1561
1583
  return null;
1562
1584
  }
@@ -5211,6 +5233,7 @@ export {
5211
5233
  REALTIME_WS_URL,
5212
5234
  RealtimeMockupService,
5213
5235
  RenderSession,
5236
+ SIZE_PICTURE,
5214
5237
  SnowconeSdkError,
5215
5238
  StandardComponents,
5216
5239
  StandardEvents,
@@ -5266,6 +5289,7 @@ export {
5266
5289
  findVariantForSelection,
5267
5290
  formatPrice,
5268
5291
  formatValidationErrors,
5292
+ gallerySizePicture,
5269
5293
  getBuyUrl,
5270
5294
  getDefaultVariantId,
5271
5295
  getEffectiveAlignment,
@@ -5287,9 +5311,13 @@ export {
5287
5311
  isValidTileCount,
5288
5312
  listProducts,
5289
5313
  mintRealtimeGrant,
5314
+ mockupRole,
5290
5315
  mockupUrl,
5291
5316
  normalizeChoice,
5317
+ ordinaryMockups,
5318
+ pictureForVariant,
5292
5319
  prepareOptionRenderData,
5320
+ primaryMockup,
5293
5321
  registerStandardComponents,
5294
5322
  resolveBestCombination,
5295
5323
  resolveMockupId,
package/dist/react.cjs CHANGED
@@ -122,6 +122,12 @@ var RealtimeMockupService = class {
122
122
  pendingFrames = /* @__PURE__ */ new Map();
123
123
  // Last object URL handed out per mockup — revoked when replaced.
124
124
  liveObjectUrls = /* @__PURE__ */ new Map();
125
+ // Frame flow control (negotiated per config): window, acked/newest seq per mockup, acks waiting for the next flush.
126
+ acks = null;
127
+ ackedSeq = /* @__PURE__ */ new Map();
128
+ newestSeq = /* @__PURE__ */ new Map();
129
+ pendingAcks = /* @__PURE__ */ new Map();
130
+ ackFlushScheduled = false;
125
131
  // Live frames a newer frame for the same mockup has replaced (and revoked), newest last, bounded. Lets a consumer
126
132
  // still loading an old frame tell "superseded" from "broken" the moment it fails (isFrameSuperseded).
127
133
  supersededFrameUrls = /* @__PURE__ */ new Set();
@@ -137,6 +143,7 @@ var RealtimeMockupService = class {
137
143
  }
138
144
  getState() {
139
145
  return {
146
+ acks: this.acks ? { ...this.acks } : null,
140
147
  isConnected: this.ws?.readyState === WebSocket.OPEN,
141
148
  sessionId: this.sessionId,
142
149
  box: this.box,
@@ -182,6 +189,10 @@ var RealtimeMockupService = class {
182
189
  this.ws = new WebSocket(url);
183
190
  this.ws.binaryType = "arraybuffer";
184
191
  this.ws.onopen = () => {
192
+ this.acks = null;
193
+ this.ackedSeq.clear();
194
+ this.newestSeq.clear();
195
+ this.pendingAcks.clear();
185
196
  console.log(`[WS] connection OPENED to ${this.wsUrl}`);
186
197
  this.addLog("WebSocket connection opened");
187
198
  this.status = "Connected";
@@ -262,6 +273,16 @@ var RealtimeMockupService = class {
262
273
  break;
263
274
  case "config_received":
264
275
  case "configured":
276
+ if (this.config?.acks && data.acks && typeof data.acks.window === "number") {
277
+ this.acks = {
278
+ window: data.acks.window,
279
+ timeoutMs: typeof data.acks.timeoutMs === "number" ? data.acks.timeoutMs : 0,
280
+ timeouts: this.acks?.timeouts ?? 0,
281
+ badAcks: this.acks?.badAcks ?? 0
282
+ };
283
+ } else {
284
+ this.acks = null;
285
+ }
265
286
  this.isConfigured = true;
266
287
  this.status = "Configured";
267
288
  this.addLog("\u2705 Configuration accepted! You can now send blobs.");
@@ -318,12 +339,20 @@ var RealtimeMockupService = class {
318
339
  if (lastAccepted !== void 0 && responseVersion < lastAccepted) {
319
340
  console.log(`[WS] STALE mockup dropped: v${responseVersion} for "${responsePlacement}" (already displayed: v${lastAccepted}, latest sent: v${this.latestSentVersionByPlacement[responsePlacement]})`);
320
341
  this.addLog(`\u23ED\uFE0F Ignoring stale mockup v${responseVersion} for "${responsePlacement}" (displayed: v${lastAccepted})`);
342
+ if (typeof data.seq === "number") this.ackFrame(data.mockupId, data.seq);
321
343
  break;
322
344
  }
323
345
  this.latestAcceptedVersionByPlacement[responsePlacement] = responseVersion;
324
346
  }
347
+ if (typeof data.seq === "number") {
348
+ const prevSeq = this.newestSeq.get(data.mockupId);
349
+ if (prevSeq !== void 0 && prevSeq < data.seq) this.ackFrame(data.mockupId, prevSeq);
350
+ if (prevSeq === void 0 || prevSeq < data.seq) this.newestSeq.set(data.mockupId, data.seq);
351
+ }
325
352
  const mockupResult = {
326
353
  mockupId: data.mockupId,
354
+ ...typeof data.seq === "number" ? { seq: data.seq } : {},
355
+ ...typeof data.coalesced === "number" ? { coalesced: data.coalesced } : {},
327
356
  imageUrl: data.imageUrl,
328
357
  renderUrl: data.renderUrl || data.imageUrl,
329
358
  imageSize: data.imageSize || 0,
@@ -400,7 +429,23 @@ var RealtimeMockupService = class {
400
429
  this.addLog(`\u26A0\uFE0F all_mockups_rendered message dropped: missing 'mockups' array. Full data keys: [${Object.keys(data).join(", ")}]`);
401
430
  }
402
431
  break;
432
+ case "ack_timeout": {
433
+ if (this.acks) this.acks.timeouts += 1;
434
+ const message = `E_RT_ACK_TIMEOUT: the box waited ${this.acks?.timeoutMs ?? "?"} ms for an ack of ${data.mockupId} seq ${data.seq}; fix: every frame must be acked once drawn, superseded, not shown or failed (ackFrame).`;
435
+ console.error(`[WS] ${message}`);
436
+ this.addLog(`\u23F1\uFE0F ${message}`);
437
+ this.callbacks.onAckFault?.({ code: "E_RT_ACK_TIMEOUT", mockupId: data.mockupId, seq: data.seq, message });
438
+ break;
439
+ }
403
440
  case "error": {
441
+ if (data.code === "E_RT_ACK_BAD") {
442
+ if (this.acks) this.acks.badAcks += 1;
443
+ const message = `E_RT_ACK_BAD (${data.reason ?? "?"}) for ${data.mockupId ?? "?"}: ${data.message ?? ""}`;
444
+ console.error(`[WS] ${message}`);
445
+ this.addLog(`\u274C ${message}`);
446
+ this.callbacks.onAckFault?.({ code: "E_RT_ACK_BAD", mockupId: data.mockupId, reason: data.reason, message });
447
+ break;
448
+ }
404
449
  const errorMessage = data.message || "Unknown error occurred";
405
450
  const renderError = {
406
451
  code: data.code || "render_error",
@@ -834,6 +879,39 @@ ${versionToSend}
834
879
  isFrameSuperseded(url) {
835
880
  return this.supersededFrameUrls.has(url);
836
881
  }
882
+ /**
883
+ * The client is done with frame `seq` of `mockupId`: drawn on screen, superseded, not shown by any element, or
884
+ * failed. Cumulative per mockup. A no-op unless flow control was negotiated (see WebSocketConfig.acks). Acks are
885
+ * batched into one frame_ack message per animation frame.
886
+ */
887
+ ackFrame(mockupId, seq) {
888
+ if (!this.acks || !(seq > 0)) return false;
889
+ if (seq <= (this.ackedSeq.get(mockupId) ?? 0) || seq <= (this.pendingAcks.get(mockupId) ?? 0)) return true;
890
+ this.pendingAcks.set(mockupId, seq);
891
+ if (!this.ackFlushScheduled) {
892
+ this.ackFlushScheduled = true;
893
+ const flush = () => this.flushAcks();
894
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);
895
+ else setTimeout(flush, 16);
896
+ }
897
+ return true;
898
+ }
899
+ flushAcks() {
900
+ this.ackFlushScheduled = false;
901
+ if (!this.acks || this.pendingAcks.size === 0) {
902
+ this.pendingAcks.clear();
903
+ return;
904
+ }
905
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
906
+ const acks = [...this.pendingAcks].map(([mockupId, seq]) => ({ mockupId, seq }));
907
+ this.pendingAcks.clear();
908
+ acks.forEach(({ mockupId, seq }) => this.ackedSeq.set(mockupId, seq));
909
+ this.ws.send(JSON.stringify(acks.length === 1 ? { type: "frame_ack", ...acks[0] } : { type: "frame_ack", acks }));
910
+ }
911
+ /** Whether frame flow control is active on this session (negotiated with the box for the current config). */
912
+ isAcking() {
913
+ return this.acks !== null;
914
+ }
837
915
  rerender(mockupIds) {
838
916
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.config || mockupIds.length === 0) return false;
839
917
  const { requestId, traceparent } = newRenderCorrelation();
@@ -944,9 +1022,11 @@ var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
944
1022
  function useRealtimeMockup(options = {}) {
945
1023
  const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
946
1024
  const serviceRef = (0, import_react.useRef)(null);
1025
+ const stateFrameScheduledRef = (0, import_react.useRef)(false);
947
1026
  const getTokenRef = (0, import_react.useRef)(options.getToken);
948
1027
  getTokenRef.current = options.getToken;
949
1028
  const [state, setState] = (0, import_react.useState)({
1029
+ acks: null,
950
1030
  isConnected: false,
951
1031
  sessionId: null,
952
1032
  box: null,
@@ -980,7 +1060,15 @@ function useRealtimeMockup(options = {}) {
980
1060
  options.onBlobSent?.(placement);
981
1061
  },
982
1062
  onMockupRendered: (result) => {
983
- console.log(`[useRealtimeMockup] onMockupRendered: mockupId=${result.mockupId} hasImageUrl=${!!result.imageUrl}`);
1063
+ if (service.isAcking() && !stateFrameScheduledRef.current) {
1064
+ stateFrameScheduledRef.current = true;
1065
+ const apply = () => {
1066
+ stateFrameScheduledRef.current = false;
1067
+ setState(service.getState());
1068
+ };
1069
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(apply);
1070
+ else setTimeout(apply, 16);
1071
+ }
984
1072
  options.onMockupRendered?.(result);
985
1073
  },
986
1074
  onAllMockupsRendered: (results) => {
@@ -989,6 +1077,10 @@ function useRealtimeMockup(options = {}) {
989
1077
  setState(newState);
990
1078
  options.onAllMockupsRendered?.(results);
991
1079
  },
1080
+ onAckFault: (fault) => {
1081
+ setState(service.getState());
1082
+ options.onAckFault?.(fault);
1083
+ },
992
1084
  onError: (error, detail) => {
993
1085
  setState(service.getState());
994
1086
  options.onError?.(error, detail);
@@ -1062,6 +1154,9 @@ function useRealtimeMockup(options = {}) {
1062
1154
  const isFrameSuperseded = (0, import_react.useCallback)((url) => {
1063
1155
  return serviceRef.current?.isFrameSuperseded(url) ?? false;
1064
1156
  }, []);
1157
+ const ackFrame = (0, import_react.useCallback)((mockupId, seq) => {
1158
+ return serviceRef.current?.ackFrame(mockupId, seq) ?? false;
1159
+ }, []);
1065
1160
  const getLastSentVersion = (0, import_react.useCallback)(() => {
1066
1161
  return serviceRef.current?.getLastSentVersion() ?? 0;
1067
1162
  }, []);
@@ -1086,7 +1181,8 @@ function useRealtimeMockup(options = {}) {
1086
1181
  getLastSentVersion,
1087
1182
  getLatestSentVersions,
1088
1183
  rerender,
1089
- isFrameSuperseded
1184
+ isFrameSuperseded,
1185
+ ackFrame
1090
1186
  };
1091
1187
  }
1092
1188
 
package/dist/react.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as MockupResult, R as RealtimeRenderError, W as WebSocketConfig, P as PlacementSettings, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CTbhT64Y.cjs';
1
+ import { M as MockupResult, R as RealtimeRenderError, j as RealtimeMockupCallbacks, W as WebSocketConfig, P as PlacementSettings, w as RealtimeAcksState, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CvN0UU2j.cjs';
2
2
  import { CSSProperties, ReactNode } from 'react';
3
3
 
4
4
  interface UseRealtimeMockupOptions {
@@ -31,6 +31,8 @@ interface UseRealtimeMockupOptions {
31
31
  * stale mockup) instead of only logging it.
32
32
  */
33
33
  onError?: (error: string, detail: RealtimeRenderError) => void;
34
+ /** Flow-control fault (E_RT_ACK_TIMEOUT / E_RT_ACK_BAD): never a picture refusal; see RealtimeMockupCallbacks. */
35
+ onAckFault?: RealtimeMockupCallbacks['onAckFault'];
34
36
  }
35
37
  declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
36
38
  connect: () => void;
@@ -57,6 +59,8 @@ declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
57
59
  getLatestSentVersions: () => Record<string, number>;
58
60
  rerender: (mockupIds: string[]) => boolean;
59
61
  isFrameSuperseded: (url: string) => boolean;
62
+ ackFrame: (mockupId: string, seq: number) => boolean;
63
+ acks: RealtimeAcksState | null;
60
64
  isConnected: boolean;
61
65
  sessionId: string | null;
62
66
  box: string | null;
package/dist/react.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as MockupResult, R as RealtimeRenderError, W as WebSocketConfig, P as PlacementSettings, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CTbhT64Y.js';
1
+ import { M as MockupResult, R as RealtimeRenderError, j as RealtimeMockupCallbacks, W as WebSocketConfig, P as PlacementSettings, w as RealtimeAcksState, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CvN0UU2j.js';
2
2
  import { CSSProperties, ReactNode } from 'react';
3
3
 
4
4
  interface UseRealtimeMockupOptions {
@@ -31,6 +31,8 @@ interface UseRealtimeMockupOptions {
31
31
  * stale mockup) instead of only logging it.
32
32
  */
33
33
  onError?: (error: string, detail: RealtimeRenderError) => void;
34
+ /** Flow-control fault (E_RT_ACK_TIMEOUT / E_RT_ACK_BAD): never a picture refusal; see RealtimeMockupCallbacks. */
35
+ onAckFault?: RealtimeMockupCallbacks['onAckFault'];
34
36
  }
35
37
  declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
36
38
  connect: () => void;
@@ -57,6 +59,8 @@ declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
57
59
  getLatestSentVersions: () => Record<string, number>;
58
60
  rerender: (mockupIds: string[]) => boolean;
59
61
  isFrameSuperseded: (url: string) => boolean;
62
+ ackFrame: (mockupId: string, seq: number) => boolean;
63
+ acks: RealtimeAcksState | null;
60
64
  isConnected: boolean;
61
65
  sessionId: string | null;
62
66
  box: string | null;
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  RealtimeMockupService
3
- } from "./chunk-4NCMFK5L.js";
3
+ } from "./chunk-IW7DXXGY.js";
4
4
 
5
5
  // src/realtime/react.ts
6
6
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -8,9 +8,11 @@ var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
8
8
  function useRealtimeMockup(options = {}) {
9
9
  const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
10
10
  const serviceRef = useRef(null);
11
+ const stateFrameScheduledRef = useRef(false);
11
12
  const getTokenRef = useRef(options.getToken);
12
13
  getTokenRef.current = options.getToken;
13
14
  const [state, setState] = useState({
15
+ acks: null,
14
16
  isConnected: false,
15
17
  sessionId: null,
16
18
  box: null,
@@ -44,7 +46,15 @@ function useRealtimeMockup(options = {}) {
44
46
  options.onBlobSent?.(placement);
45
47
  },
46
48
  onMockupRendered: (result) => {
47
- console.log(`[useRealtimeMockup] onMockupRendered: mockupId=${result.mockupId} hasImageUrl=${!!result.imageUrl}`);
49
+ if (service.isAcking() && !stateFrameScheduledRef.current) {
50
+ stateFrameScheduledRef.current = true;
51
+ const apply = () => {
52
+ stateFrameScheduledRef.current = false;
53
+ setState(service.getState());
54
+ };
55
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(apply);
56
+ else setTimeout(apply, 16);
57
+ }
48
58
  options.onMockupRendered?.(result);
49
59
  },
50
60
  onAllMockupsRendered: (results) => {
@@ -53,6 +63,10 @@ function useRealtimeMockup(options = {}) {
53
63
  setState(newState);
54
64
  options.onAllMockupsRendered?.(results);
55
65
  },
66
+ onAckFault: (fault) => {
67
+ setState(service.getState());
68
+ options.onAckFault?.(fault);
69
+ },
56
70
  onError: (error, detail) => {
57
71
  setState(service.getState());
58
72
  options.onError?.(error, detail);
@@ -126,6 +140,9 @@ function useRealtimeMockup(options = {}) {
126
140
  const isFrameSuperseded = useCallback((url) => {
127
141
  return serviceRef.current?.isFrameSuperseded(url) ?? false;
128
142
  }, []);
143
+ const ackFrame = useCallback((mockupId, seq) => {
144
+ return serviceRef.current?.ackFrame(mockupId, seq) ?? false;
145
+ }, []);
129
146
  const getLastSentVersion = useCallback(() => {
130
147
  return serviceRef.current?.getLastSentVersion() ?? 0;
131
148
  }, []);
@@ -150,7 +167,8 @@ function useRealtimeMockup(options = {}) {
150
167
  getLastSentVersion,
151
168
  getLatestSentVersions,
152
169
  rerender,
153
- isFrameSuperseded
170
+ isFrameSuperseded,
171
+ ackFrame
154
172
  };
155
173
  }
156
174
 
@@ -211,6 +211,14 @@ interface PlacementSettings {
211
211
  }
212
212
  interface WebSocketConfig {
213
213
  productId: string;
214
+ /**
215
+ * Ask the box for frame flow control: it keeps at most `window` un-acked frames per mockup and coalesces the rest
216
+ * (latest wins), so a slow link or a slow screen never queues a backlog behind Cloudflare. ONLY for a client that
217
+ * calls {@link RealtimeMockupService.ackFrame} when it has drawn a frame: every frame must be acked (the service
218
+ * acks superseded and stale-dropped frames itself). Dormant on a box that does not negotiate it (config_received
219
+ * without `acks`).
220
+ */
221
+ acks?: boolean;
214
222
  mockupIds: string[];
215
223
  variantId: string;
216
224
  shop: string;
@@ -311,6 +319,10 @@ interface MockupResult {
311
319
  * (see {@link RealtimeMockupService.getLatestSentVersions}).
312
320
  */
313
321
  versions?: Record<string, number>;
322
+ /** Frame sequence number (per socket, increasing; boxes with flow control). Ack it with ackFrame once drawn. */
323
+ seq?: number;
324
+ /** Older frames of this mockup the box dropped in favour of this one (flow control, latest wins). */
325
+ coalesced?: number;
314
326
  /** Server-side render time in ms */
315
327
  renderMs?: number;
316
328
  /** Time from blob received to render start in ms */
@@ -352,6 +364,17 @@ interface MockupResult {
352
364
  }
353
365
  interface WebSocketMessage {
354
366
  type: string;
367
+ /** config_received: frame flow control the box agreed to (only when the config asked for acks). */
368
+ acks?: {
369
+ window: number;
370
+ timeoutMs?: number;
371
+ };
372
+ /** Frame sequence number (mockup_rendered, mockup_frame, ack_timeout). */
373
+ seq?: number;
374
+ /** Older frames of this mockup dropped in favour of this one (flow control). */
375
+ coalesced?: number;
376
+ /** E_RT_ACK_BAD: why the ack was rejected. */
377
+ reason?: string;
355
378
  sessionId?: string;
356
379
  mockups?: MockupResult[];
357
380
  imageUrl?: string;
@@ -428,7 +451,18 @@ interface RealtimeRenderError {
428
451
  */
429
452
  mockupId?: string;
430
453
  }
454
+ /** Frame flow control as negotiated with the box (null: not asked, or the box does not support it). */
455
+ interface RealtimeAcksState {
456
+ window: number;
457
+ timeoutMs: number;
458
+ /** Frames the box gave up waiting for (E_RT_ACK_TIMEOUT): a frame the client never acked within timeoutMs. */
459
+ timeouts: number;
460
+ /** Acks the box rejected (E_RT_ACK_BAD): a client protocol fault. */
461
+ badAcks: number;
462
+ }
431
463
  interface RealtimeMockupState {
464
+ /** Frame flow control, when negotiated (see WebSocketConfig.acks). */
465
+ acks: RealtimeAcksState | null;
432
466
  isConnected: boolean;
433
467
  sessionId: string | null;
434
468
  /** Render node that answered the handshake (`connected.box`); null until
@@ -471,6 +505,15 @@ interface RealtimeMockupCallbacks {
471
505
  */
472
506
  onError?: (error: string, detail: RealtimeRenderError) => void;
473
507
  onLog?: (message: string, type: 'info' | 'sent' | 'received') => void;
508
+ /** A flow-control fault: the box timed out waiting for an ack (E_RT_ACK_TIMEOUT) or rejected one (E_RT_ACK_BAD).
509
+ * Never a picture refusal and never the session's renderError: the frames keep coming. */
510
+ onAckFault?: (fault: {
511
+ code: 'E_RT_ACK_TIMEOUT' | 'E_RT_ACK_BAD';
512
+ mockupId?: string;
513
+ seq?: number;
514
+ reason?: string;
515
+ message: string;
516
+ }) => void;
474
517
  }
475
518
  declare class RealtimeMockupService {
476
519
  private wsUrl;
@@ -502,6 +545,11 @@ declare class RealtimeMockupService {
502
545
  private tokenProvider?;
503
546
  private pendingFrames;
504
547
  private liveObjectUrls;
548
+ private acks;
549
+ private ackedSeq;
550
+ private newestSeq;
551
+ private pendingAcks;
552
+ private ackFlushScheduled;
505
553
  private supersededFrameUrls;
506
554
  private renewTimer;
507
555
  private isConnecting;
@@ -597,6 +645,15 @@ declare class RealtimeMockupService {
597
645
  * already here; it reaches the results with its batch's all_mockups_rendered) from a real failure.
598
646
  */
599
647
  isFrameSuperseded(url: string): boolean;
648
+ /**
649
+ * The client is done with frame `seq` of `mockupId`: drawn on screen, superseded, not shown by any element, or
650
+ * failed. Cumulative per mockup. A no-op unless flow control was negotiated (see WebSocketConfig.acks). Acks are
651
+ * batched into one frame_ack message per animation frame.
652
+ */
653
+ ackFrame(mockupId: string, seq: number): boolean;
654
+ private flushAcks;
655
+ /** Whether frame flow control is active on this session (negotiated with the box for the current config). */
656
+ isAcking(): boolean;
600
657
  rerender(mockupIds: string[]): boolean;
601
658
  getLastSentVersion(): number;
602
659
  sendColorBlob(placement: string, hexColor: string): boolean;
@@ -611,4 +668,4 @@ declare class RealtimeMockupService {
611
668
  clearMockups(): void;
612
669
  }
613
670
 
614
- export { AdapterRegistry as A, type Combination as C, type EventHandler as E, type FrameworkAdapter as F, type MockupResult as M, type OptionAttribute as O, type PlacementSettings as P, type RealtimeRenderError as R, type WebSocketConfig as W, type OptionSelection as a, type ComponentProps as b, type ComponentDescriptor as c, type ComponentState as d, type ComponentContext as e, type ComponentLifecycleHooks as f, type FrameworkUtilities as g, RealtimeMockupService as h, type ProductComponentContext as i, type RealtimeMockupCallbacks as j, type RealtimeMockupState as k, type RenderResult as l, type WebSocketMessage as m, adapterRegistry as n, computeDisabledChoices as o, createComponent as p, defineComponent as q, deriveDefaultSelection as r, findBestCombination as s, getPricePreview as t, isOptionAvailable as u, resolveBestCombination as v };
671
+ export { AdapterRegistry as A, type Combination as C, type EventHandler as E, type FrameworkAdapter as F, type MockupResult as M, type OptionAttribute as O, type PlacementSettings as P, type RealtimeRenderError as R, type WebSocketConfig as W, type OptionSelection as a, type ComponentProps as b, type ComponentDescriptor as c, type ComponentState as d, type ComponentContext as e, type ComponentLifecycleHooks as f, type FrameworkUtilities as g, RealtimeMockupService as h, type ProductComponentContext as i, type RealtimeMockupCallbacks as j, type RealtimeMockupState as k, type RenderResult as l, type WebSocketMessage as m, adapterRegistry as n, computeDisabledChoices as o, createComponent as p, defineComponent as q, deriveDefaultSelection as r, findBestCombination as s, getPricePreview as t, isOptionAvailable as u, resolveBestCombination as v, type RealtimeAcksState as w };
@@ -211,6 +211,14 @@ interface PlacementSettings {
211
211
  }
212
212
  interface WebSocketConfig {
213
213
  productId: string;
214
+ /**
215
+ * Ask the box for frame flow control: it keeps at most `window` un-acked frames per mockup and coalesces the rest
216
+ * (latest wins), so a slow link or a slow screen never queues a backlog behind Cloudflare. ONLY for a client that
217
+ * calls {@link RealtimeMockupService.ackFrame} when it has drawn a frame: every frame must be acked (the service
218
+ * acks superseded and stale-dropped frames itself). Dormant on a box that does not negotiate it (config_received
219
+ * without `acks`).
220
+ */
221
+ acks?: boolean;
214
222
  mockupIds: string[];
215
223
  variantId: string;
216
224
  shop: string;
@@ -311,6 +319,10 @@ interface MockupResult {
311
319
  * (see {@link RealtimeMockupService.getLatestSentVersions}).
312
320
  */
313
321
  versions?: Record<string, number>;
322
+ /** Frame sequence number (per socket, increasing; boxes with flow control). Ack it with ackFrame once drawn. */
323
+ seq?: number;
324
+ /** Older frames of this mockup the box dropped in favour of this one (flow control, latest wins). */
325
+ coalesced?: number;
314
326
  /** Server-side render time in ms */
315
327
  renderMs?: number;
316
328
  /** Time from blob received to render start in ms */
@@ -352,6 +364,17 @@ interface MockupResult {
352
364
  }
353
365
  interface WebSocketMessage {
354
366
  type: string;
367
+ /** config_received: frame flow control the box agreed to (only when the config asked for acks). */
368
+ acks?: {
369
+ window: number;
370
+ timeoutMs?: number;
371
+ };
372
+ /** Frame sequence number (mockup_rendered, mockup_frame, ack_timeout). */
373
+ seq?: number;
374
+ /** Older frames of this mockup dropped in favour of this one (flow control). */
375
+ coalesced?: number;
376
+ /** E_RT_ACK_BAD: why the ack was rejected. */
377
+ reason?: string;
355
378
  sessionId?: string;
356
379
  mockups?: MockupResult[];
357
380
  imageUrl?: string;
@@ -428,7 +451,18 @@ interface RealtimeRenderError {
428
451
  */
429
452
  mockupId?: string;
430
453
  }
454
+ /** Frame flow control as negotiated with the box (null: not asked, or the box does not support it). */
455
+ interface RealtimeAcksState {
456
+ window: number;
457
+ timeoutMs: number;
458
+ /** Frames the box gave up waiting for (E_RT_ACK_TIMEOUT): a frame the client never acked within timeoutMs. */
459
+ timeouts: number;
460
+ /** Acks the box rejected (E_RT_ACK_BAD): a client protocol fault. */
461
+ badAcks: number;
462
+ }
431
463
  interface RealtimeMockupState {
464
+ /** Frame flow control, when negotiated (see WebSocketConfig.acks). */
465
+ acks: RealtimeAcksState | null;
432
466
  isConnected: boolean;
433
467
  sessionId: string | null;
434
468
  /** Render node that answered the handshake (`connected.box`); null until
@@ -471,6 +505,15 @@ interface RealtimeMockupCallbacks {
471
505
  */
472
506
  onError?: (error: string, detail: RealtimeRenderError) => void;
473
507
  onLog?: (message: string, type: 'info' | 'sent' | 'received') => void;
508
+ /** A flow-control fault: the box timed out waiting for an ack (E_RT_ACK_TIMEOUT) or rejected one (E_RT_ACK_BAD).
509
+ * Never a picture refusal and never the session's renderError: the frames keep coming. */
510
+ onAckFault?: (fault: {
511
+ code: 'E_RT_ACK_TIMEOUT' | 'E_RT_ACK_BAD';
512
+ mockupId?: string;
513
+ seq?: number;
514
+ reason?: string;
515
+ message: string;
516
+ }) => void;
474
517
  }
475
518
  declare class RealtimeMockupService {
476
519
  private wsUrl;
@@ -502,6 +545,11 @@ declare class RealtimeMockupService {
502
545
  private tokenProvider?;
503
546
  private pendingFrames;
504
547
  private liveObjectUrls;
548
+ private acks;
549
+ private ackedSeq;
550
+ private newestSeq;
551
+ private pendingAcks;
552
+ private ackFlushScheduled;
505
553
  private supersededFrameUrls;
506
554
  private renewTimer;
507
555
  private isConnecting;
@@ -597,6 +645,15 @@ declare class RealtimeMockupService {
597
645
  * already here; it reaches the results with its batch's all_mockups_rendered) from a real failure.
598
646
  */
599
647
  isFrameSuperseded(url: string): boolean;
648
+ /**
649
+ * The client is done with frame `seq` of `mockupId`: drawn on screen, superseded, not shown by any element, or
650
+ * failed. Cumulative per mockup. A no-op unless flow control was negotiated (see WebSocketConfig.acks). Acks are
651
+ * batched into one frame_ack message per animation frame.
652
+ */
653
+ ackFrame(mockupId: string, seq: number): boolean;
654
+ private flushAcks;
655
+ /** Whether frame flow control is active on this session (negotiated with the box for the current config). */
656
+ isAcking(): boolean;
600
657
  rerender(mockupIds: string[]): boolean;
601
658
  getLastSentVersion(): number;
602
659
  sendColorBlob(placement: string, hexColor: string): boolean;
@@ -611,4 +668,4 @@ declare class RealtimeMockupService {
611
668
  clearMockups(): void;
612
669
  }
613
670
 
614
- export { AdapterRegistry as A, type Combination as C, type EventHandler as E, type FrameworkAdapter as F, type MockupResult as M, type OptionAttribute as O, type PlacementSettings as P, type RealtimeRenderError as R, type WebSocketConfig as W, type OptionSelection as a, type ComponentProps as b, type ComponentDescriptor as c, type ComponentState as d, type ComponentContext as e, type ComponentLifecycleHooks as f, type FrameworkUtilities as g, RealtimeMockupService as h, type ProductComponentContext as i, type RealtimeMockupCallbacks as j, type RealtimeMockupState as k, type RenderResult as l, type WebSocketMessage as m, adapterRegistry as n, computeDisabledChoices as o, createComponent as p, defineComponent as q, deriveDefaultSelection as r, findBestCombination as s, getPricePreview as t, isOptionAvailable as u, resolveBestCombination as v };
671
+ export { AdapterRegistry as A, type Combination as C, type EventHandler as E, type FrameworkAdapter as F, type MockupResult as M, type OptionAttribute as O, type PlacementSettings as P, type RealtimeRenderError as R, type WebSocketConfig as W, type OptionSelection as a, type ComponentProps as b, type ComponentDescriptor as c, type ComponentState as d, type ComponentContext as e, type ComponentLifecycleHooks as f, type FrameworkUtilities as g, RealtimeMockupService as h, type ProductComponentContext as i, type RealtimeMockupCallbacks as j, type RealtimeMockupState as k, type RenderResult as l, type WebSocketMessage as m, adapterRegistry as n, computeDisabledChoices as o, createComponent as p, defineComponent as q, deriveDefaultSelection as r, findBestCombination as s, getPricePreview as t, isOptionAvailable as u, resolveBestCombination as v, type RealtimeAcksState as w };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/sdk",
3
- "version": "0.26.0",
3
+ "version": "0.27.1",
4
4
  "description": "Snowcone SDK for product mockups and print-on-demand",
5
5
  "keywords": [
6
6
  "merch",