@snowcone-app/sdk 0.20.1 → 0.20.3

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/react.cjs CHANGED
@@ -20,8 +20,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/react.ts
21
21
  var react_exports = {};
22
22
  __export(react_exports, {
23
+ MockupStage: () => MockupStage,
23
24
  ReactAdapter: () => ReactAdapter,
24
25
  createReactComponent: () => createReactComponent,
26
+ useMockupStage: () => useMockupStage,
25
27
  useReactAdapter: () => useFrameworkAdapter,
26
28
  useRealtimeMockup: () => useRealtimeMockup
27
29
  });
@@ -34,6 +36,13 @@ var import_react = require("react");
34
36
  var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
35
37
 
36
38
  // src/realtime/websocket.ts
39
+ function pruneUndefined(obj) {
40
+ const out = {};
41
+ for (const [k, v] of Object.entries(obj)) {
42
+ if (v !== void 0) out[k] = v;
43
+ }
44
+ return out;
45
+ }
37
46
  function randHex(len) {
38
47
  const arr = new Uint8Array(len);
39
48
  globalThis.crypto.getRandomValues(arr);
@@ -97,6 +106,13 @@ var RealtimeMockupService = class {
97
106
  // Session-grant auth: when set, connect() fetches a short-lived token, opens
98
107
  // the WS with `?token=`, and renews ~15s before expiry via a `renew` message.
99
108
  tokenProvider;
109
+ // Binary-delivered frames waiting for their mockup_rendered metadata,
110
+ // keyed `${requestId ?? ''}:${mockupId}`. The server sends the binary
111
+ // frame before the JSON result on the same socket, so ordering guarantees
112
+ // the entry exists when the result arrives.
113
+ pendingFrames = /* @__PURE__ */ new Map();
114
+ // Last object URL handed out per mockup — revoked when replaced.
115
+ liveObjectUrls = /* @__PURE__ */ new Map();
100
116
  renewTimer = null;
101
117
  isConnecting = false;
102
118
  connectAttempt = 0;
@@ -151,6 +167,7 @@ var RealtimeMockupService = class {
151
167
  const url = token ? `${this.wsUrl}${this.wsUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}` : this.wsUrl;
152
168
  this.addLog(`Connecting to ${this.wsUrl}...`);
153
169
  this.ws = new WebSocket(url);
170
+ this.ws.binaryType = "arraybuffer";
154
171
  this.ws.onopen = () => {
155
172
  console.log(`[WS] connection OPENED to ${this.wsUrl}`);
156
173
  this.addLog("WebSocket connection opened");
@@ -158,6 +175,10 @@ var RealtimeMockupService = class {
158
175
  this.isConnecting = false;
159
176
  };
160
177
  this.ws.onmessage = (event) => {
178
+ if (event.data instanceof ArrayBuffer) {
179
+ this.handleBinaryFrame(event.data);
180
+ return;
181
+ }
161
182
  try {
162
183
  const data = JSON.parse(event.data);
163
184
  this.addLog(JSON.stringify(data, null, 2), "received");
@@ -267,6 +288,7 @@ var RealtimeMockupService = class {
267
288
  this.addLog("\u{1F3A8} Mockup rendering has started...");
268
289
  break;
269
290
  case "mockup_rendered": {
291
+ this.applyBinaryFrame(data);
270
292
  const sentAt = data.requestId ? this.requestSendTimes.get(data.requestId) : void 0;
271
293
  const clientRoundTripMs = sentAt !== void 0 ? Date.now() - sentAt : void 0;
272
294
  console.log(`[WS] mockup_rendered received: mockupId=${data.mockupId} hasImageUrl=${!!data.imageUrl} v=${data.requestVersion} req=${data.requestId ?? "?"} placement="${data.placement}" renderMs=${data.renderMs} blobToRenderMs=${data.blobToRenderMs} clientRoundTripMs=${clientRoundTripMs ?? "?"} at ${Date.now()}`);
@@ -294,6 +316,8 @@ var RealtimeMockupService = class {
294
316
  blobToRenderMs: data.blobToRenderMs,
295
317
  costUsd: data.costUsd,
296
318
  renderCache: data.renderCache,
319
+ cropRect: data.cropRect,
320
+ serverTiming: data.serverTiming,
297
321
  canvasRenderTiming: data.canvasRenderTiming
298
322
  };
299
323
  const existingIndex = this.mockupResults.findIndex((m) => m.mockupId === data.mockupId);
@@ -329,7 +353,18 @@ var RealtimeMockupService = class {
329
353
  }
330
354
  return true;
331
355
  });
332
- this.mockupResults = freshMockups;
356
+ this.mockupResults = freshMockups.map((mockup) => {
357
+ const existing = this.mockupResults.find(
358
+ (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
359
+ );
360
+ if (!existing) return mockup;
361
+ const merged = { ...existing, ...pruneUndefined(mockup) };
362
+ if (existing.imageUrl.startsWith("blob:")) {
363
+ merged.imageUrl = existing.imageUrl;
364
+ merged.renderUrl = existing.renderUrl;
365
+ }
366
+ return merged;
367
+ });
333
368
  this.lastError = null;
334
369
  this.renderError = null;
335
370
  this.addLog(`\u{1F389} All mockups rendered: ${freshMockups.length} fresh (${data.mockups.length - freshMockups.length} stale filtered)`);
@@ -365,6 +400,35 @@ var RealtimeMockupService = class {
365
400
  this.ws = null;
366
401
  }
367
402
  }
403
+ handleBinaryFrame(buf) {
404
+ try {
405
+ const view = new DataView(buf);
406
+ const headerLen = view.getUint32(0);
407
+ const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 4, headerLen)));
408
+ if (header.type !== "mockup_frame") return;
409
+ const bytes = new Uint8Array(buf, 4 + headerLen);
410
+ const objectUrl = URL.createObjectURL(new Blob([bytes], { type: header.contentType || "image/avif" }));
411
+ const key = `${header.requestId ?? ""}:${header.mockupId}`;
412
+ const prev = this.pendingFrames.get(key);
413
+ if (prev) URL.revokeObjectURL(prev.objectUrl);
414
+ this.pendingFrames.set(key, { objectUrl, bytes: bytes.byteLength });
415
+ this.addLog(`\u{1F4E6} mockup_frame received over ws: ${header.mockupId} (${bytes.byteLength}B)`);
416
+ } catch (e) {
417
+ this.addLog(`\u26A0\uFE0F failed to parse binary frame: ${e}`);
418
+ }
419
+ }
420
+ /** Swap a ws-delivered frame in for the imageUrl on a render result. */
421
+ applyBinaryFrame(data) {
422
+ if (data.imageDelivery !== "ws" || !data.mockupId) return;
423
+ const key = `${data.requestId ?? ""}:${data.mockupId}`;
424
+ const frame = this.pendingFrames.get(key);
425
+ if (!frame) return;
426
+ this.pendingFrames.delete(key);
427
+ const prevLive = this.liveObjectUrls.get(data.mockupId);
428
+ if (prevLive) URL.revokeObjectURL(prevLive);
429
+ this.liveObjectUrls.set(data.mockupId, frame.objectUrl);
430
+ data.imageUrl = frame.objectUrl;
431
+ }
368
432
  sendConfig(config) {
369
433
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
370
434
  this.addLog("WebSocket not connected, caching config");
@@ -411,7 +475,11 @@ var RealtimeMockupService = class {
411
475
  this.configSent = true;
412
476
  const message = {
413
477
  type: "config",
414
- config
478
+ // binaryFrames: ask the server to push rendered image bytes down this
479
+ // socket (mockup_frame binary messages) instead of making us fetch the
480
+ // imageUrl — saves a network round trip per render. Servers that don't
481
+ // know the flag ignore it and we fall back to the URL.
482
+ config: { ...config, binaryFrames: true }
415
483
  };
416
484
  const messageStr = JSON.stringify(message);
417
485
  this.addLog(`\u{1F4E4} Sending config: ${JSON.stringify(message, null, 2)}`, "sent");
@@ -934,6 +1002,327 @@ function useRealtimeMockup(options = {}) {
934
1002
  };
935
1003
  }
936
1004
 
1005
+ // src/realtime/stage.ts
1006
+ var import_react2 = require("react");
1007
+ var FULL_RECT = { x: 0, y: 0, w: 1, h: 1 };
1008
+ function useMockupStage(options) {
1009
+ const {
1010
+ shop,
1011
+ product,
1012
+ mockup,
1013
+ variant,
1014
+ placements,
1015
+ ar,
1016
+ bg,
1017
+ getToken,
1018
+ wsUrl,
1019
+ delivery = "cropped",
1020
+ debugKey
1021
+ } = options;
1022
+ const mockupIds = (0, import_react2.useMemo)(
1023
+ () => [mockup, ...options.extraMockups ?? []],
1024
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1025
+ [mockup, JSON.stringify(options.extraMockups ?? [])]
1026
+ );
1027
+ const [stages, setStages] = (0, import_react2.useState)({});
1028
+ const [isRendering, setIsRendering] = (0, import_react2.useState)(false);
1029
+ const [error, setError] = (0, import_react2.useState)(null);
1030
+ const [lastResult, setLastResult] = (0, import_react2.useState)(null);
1031
+ const backgroundsRef = (0, import_react2.useRef)({});
1032
+ const croppedActiveRef = (0, import_react2.useRef)(false);
1033
+ const pendingEditsRef = (0, import_react2.useRef)(0);
1034
+ const optionsRef = (0, import_react2.useRef)(options);
1035
+ optionsRef.current = options;
1036
+ const mockupIdsRef = (0, import_react2.useRef)(mockupIds);
1037
+ mockupIdsRef.current = mockupIds;
1038
+ const onFrameRef = (0, import_react2.useRef)(options.onFrame);
1039
+ onFrameRef.current = options.onFrame;
1040
+ const onErrorRef = (0, import_react2.useRef)(options.onError);
1041
+ onErrorRef.current = options.onError;
1042
+ const {
1043
+ isConnected,
1044
+ sessionId,
1045
+ isConfigured,
1046
+ connect,
1047
+ sendConfig,
1048
+ sendCanvasState,
1049
+ sendCanvasBlob,
1050
+ sendInitialEmptyCanvases
1051
+ } = useRealtimeMockup({
1052
+ wsUrl,
1053
+ getToken,
1054
+ onMockupRendered: (result) => {
1055
+ if (!result.imageUrl || !result.mockupId) return;
1056
+ const id = result.mockupId;
1057
+ setLastResult(result);
1058
+ pendingEditsRef.current = Math.max(0, pendingEditsRef.current - 1);
1059
+ if (pendingEditsRef.current === 0) setIsRendering(false);
1060
+ onFrameRef.current?.(result);
1061
+ if (!backgroundsRef.current[id]) {
1062
+ backgroundsRef.current[id] = result.imageUrl;
1063
+ setStages((prev) => ({
1064
+ ...prev,
1065
+ [id]: { background: result.imageUrl, frame: { url: result.imageUrl, rect: FULL_RECT } }
1066
+ }));
1067
+ const allSeeded = mockupIdsRef.current.every((m) => backgroundsRef.current[m]);
1068
+ if (allSeeded && !croppedActiveRef.current && optionsRef.current.delivery !== "full-frame") {
1069
+ croppedActiveRef.current = true;
1070
+ sendStageConfig(true);
1071
+ }
1072
+ return;
1073
+ }
1074
+ setStages((prev) => ({
1075
+ ...prev,
1076
+ [id]: {
1077
+ background: backgroundsRef.current[id],
1078
+ frame: { url: result.imageUrl, rect: result.cropRect ?? FULL_RECT }
1079
+ }
1080
+ }));
1081
+ },
1082
+ onError: (_msg, detail) => {
1083
+ setError(detail);
1084
+ setIsRendering(false);
1085
+ onErrorRef.current?.(detail);
1086
+ }
1087
+ });
1088
+ const sendConfigRef = (0, import_react2.useRef)(sendConfig);
1089
+ sendConfigRef.current = sendConfig;
1090
+ const sendStageConfig = (0, import_react2.useCallback)(
1091
+ (withCrop) => {
1092
+ const o = optionsRef.current;
1093
+ const width = typeof o.width === "function" ? o.width() : o.width ?? 1400;
1094
+ const config = {
1095
+ productId: o.product,
1096
+ mockupIds: mockupIdsRef.current,
1097
+ variantId: o.variant ?? "",
1098
+ shop: o.shop,
1099
+ width,
1100
+ ...o.ar && { ar: o.ar },
1101
+ ...o.bg && { bg: o.bg },
1102
+ ...withCrop && { overlayCrop: "auto" },
1103
+ ...o.debugKey && { debugKey: o.debugKey }
1104
+ };
1105
+ sendConfigRef.current(config);
1106
+ },
1107
+ []
1108
+ );
1109
+ (0, import_react2.useEffect)(() => {
1110
+ connect();
1111
+ }, [connect]);
1112
+ (0, import_react2.useEffect)(() => {
1113
+ if (isConnected && sessionId) {
1114
+ sendStageConfig(croppedActiveRef.current);
1115
+ }
1116
+ }, [isConnected, sessionId, shop, product, mockupIds, variant, ar, bg, sendStageConfig]);
1117
+ const initialSentRef = (0, import_react2.useRef)(false);
1118
+ (0, import_react2.useEffect)(() => {
1119
+ const placementsToSeed = optionsRef.current.initialEmptyPlacements;
1120
+ if (isConfigured && placementsToSeed?.length && !initialSentRef.current) {
1121
+ initialSentRef.current = true;
1122
+ void sendInitialEmptyCanvases(placementsToSeed);
1123
+ }
1124
+ }, [isConfigured, sendInitialEmptyCanvases]);
1125
+ const setDesign = (0, import_react2.useCallback)(
1126
+ (placement, state) => {
1127
+ pendingEditsRef.current += 1;
1128
+ setIsRendering(true);
1129
+ setError(null);
1130
+ sendCanvasState(placement, state, 1, 0);
1131
+ },
1132
+ [sendCanvasState]
1133
+ );
1134
+ const setArtwork = (0, import_react2.useCallback)(
1135
+ (placement, blob) => {
1136
+ pendingEditsRef.current += 1;
1137
+ setIsRendering(true);
1138
+ setError(null);
1139
+ sendCanvasBlob(placement, blob, 1, 0);
1140
+ },
1141
+ [sendCanvasBlob]
1142
+ );
1143
+ const refreeze = (0, import_react2.useCallback)(() => {
1144
+ backgroundsRef.current = {};
1145
+ croppedActiveRef.current = false;
1146
+ setStages({});
1147
+ sendStageConfig(false);
1148
+ }, [sendStageConfig]);
1149
+ const primary = stages[mockup] ?? { background: null, frame: null };
1150
+ const status = error ? "error" : !isConnected ? "connecting" : !isConfigured ? "configuring" : !primary.background ? "first-frame" : "live";
1151
+ void placements;
1152
+ return {
1153
+ status,
1154
+ background: primary.background,
1155
+ frame: primary.frame,
1156
+ stages,
1157
+ isRendering,
1158
+ error,
1159
+ lastResult,
1160
+ setDesign,
1161
+ setArtwork,
1162
+ refreeze
1163
+ };
1164
+ }
1165
+ function MockupStage(props) {
1166
+ const {
1167
+ stage,
1168
+ mockupId,
1169
+ feather = 12,
1170
+ aspect = 16 / 9,
1171
+ className,
1172
+ style,
1173
+ placeholder,
1174
+ renderingIndicator
1175
+ } = props;
1176
+ const layers = mockupId ? stage.stages[mockupId] ?? { background: null, frame: null } : { background: stage.background, frame: stage.frame };
1177
+ const [displayed, setDisplayed] = (0, import_react2.useState)(null);
1178
+ const [incoming, setIncoming] = (0, import_react2.useState)(null);
1179
+ (0, import_react2.useEffect)(() => {
1180
+ if (!layers.frame) return;
1181
+ if (!displayed) {
1182
+ setDisplayed(layers.frame);
1183
+ return;
1184
+ }
1185
+ if (layers.frame.url !== displayed.url) setIncoming(layers.frame);
1186
+ }, [layers.frame]);
1187
+ const handleIncomingLoad = (0, import_react2.useCallback)(() => {
1188
+ setIncoming((inc) => {
1189
+ if (inc) setDisplayed(inc);
1190
+ return null;
1191
+ });
1192
+ }, []);
1193
+ const frameStyle = (0, import_react2.useCallback)(
1194
+ (f) => {
1195
+ const full = f.rect.x === 0 && f.rect.y === 0 && f.rect.w === 1 && f.rect.h === 1;
1196
+ const base = {
1197
+ position: "absolute",
1198
+ left: `${f.rect.x * 100}%`,
1199
+ top: `${f.rect.y * 100}%`,
1200
+ width: `${f.rect.w * 100}%`,
1201
+ height: `${f.rect.h * 100}%`
1202
+ };
1203
+ if (!full && feather > 0) {
1204
+ const m = `linear-gradient(to right, transparent 0, black ${feather}px, black calc(100% - ${feather}px), transparent 100%), linear-gradient(to bottom, transparent 0, black ${feather}px, black calc(100% - ${feather}px), transparent 100%)`;
1205
+ base.WebkitMaskImage = m;
1206
+ base.maskImage = m;
1207
+ base.WebkitMaskComposite = "source-in";
1208
+ base.maskComposite = "intersect";
1209
+ }
1210
+ return base;
1211
+ },
1212
+ [feather]
1213
+ );
1214
+ const containerStyle = (0, import_react2.useMemo)(
1215
+ () => ({
1216
+ position: "relative",
1217
+ aspectRatio: String(aspect),
1218
+ overflow: "hidden",
1219
+ ...style
1220
+ }),
1221
+ [aspect, style]
1222
+ );
1223
+ const children = [];
1224
+ if (layers.background) {
1225
+ children.push(
1226
+ (0, import_react2.createElement)("img", {
1227
+ key: "bg",
1228
+ src: layers.background,
1229
+ alt: "",
1230
+ "data-sc-part": "background",
1231
+ style: { position: "absolute", inset: 0, width: "100%", height: "100%" }
1232
+ })
1233
+ );
1234
+ }
1235
+ if (displayed) {
1236
+ children.push(
1237
+ (0, import_react2.createElement)("img", {
1238
+ key: `frame-${displayed.url}`,
1239
+ src: displayed.url,
1240
+ alt: "",
1241
+ "data-sc-part": "frame",
1242
+ style: frameStyle(displayed)
1243
+ })
1244
+ );
1245
+ }
1246
+ if (incoming) {
1247
+ children.push(
1248
+ (0, import_react2.createElement)("img", {
1249
+ key: `incoming-${incoming.url}`,
1250
+ src: incoming.url,
1251
+ alt: "",
1252
+ "data-sc-part": "frame-incoming",
1253
+ onLoad: handleIncomingLoad,
1254
+ style: { ...frameStyle(incoming), opacity: 0.999 }
1255
+ })
1256
+ );
1257
+ }
1258
+ if (!layers.background) {
1259
+ children.push(
1260
+ (0, import_react2.createElement)(
1261
+ "div",
1262
+ {
1263
+ key: "placeholder",
1264
+ "data-sc-part": "placeholder",
1265
+ style: {
1266
+ position: "absolute",
1267
+ inset: 0,
1268
+ display: "flex",
1269
+ alignItems: "center",
1270
+ justifyContent: "center"
1271
+ }
1272
+ },
1273
+ placeholder !== void 0 ? placeholder : (0, import_react2.createElement)("div", {
1274
+ style: {
1275
+ width: "38%",
1276
+ height: "55%",
1277
+ borderRadius: 12,
1278
+ background: "rgba(127,127,127,0.15)",
1279
+ animation: "sc-stage-pulse 1.2s ease-in-out infinite"
1280
+ }
1281
+ })
1282
+ )
1283
+ );
1284
+ }
1285
+ if (stage.isRendering && layers.background) {
1286
+ children.push(
1287
+ (0, import_react2.createElement)(
1288
+ "div",
1289
+ {
1290
+ key: "rendering",
1291
+ "data-sc-part": "rendering-indicator",
1292
+ style: { position: "absolute", inset: 0, pointerEvents: "none" }
1293
+ },
1294
+ renderingIndicator !== void 0 ? renderingIndicator : (0, import_react2.createElement)("div", {
1295
+ style: {
1296
+ position: "absolute",
1297
+ top: 8,
1298
+ right: 8,
1299
+ width: 8,
1300
+ height: 8,
1301
+ borderRadius: "50%",
1302
+ background: "rgba(127,127,127,0.6)",
1303
+ animation: "sc-stage-pulse 0.8s ease-in-out infinite"
1304
+ }
1305
+ })
1306
+ )
1307
+ );
1308
+ }
1309
+ children.push(
1310
+ (0, import_react2.createElement)("style", { key: "kf" }, "@keyframes sc-stage-pulse{0%,100%{opacity:.35}50%{opacity:.9}}")
1311
+ );
1312
+ return (0, import_react2.createElement)(
1313
+ "div",
1314
+ {
1315
+ className,
1316
+ style: containerStyle,
1317
+ "data-sc-part": "stage",
1318
+ "data-sc-status": stage.status,
1319
+ "data-sc-rendering": stage.isRendering ? "true" : "false",
1320
+ ...stage.error && { "data-sc-error": stage.error.code ?? "error" }
1321
+ },
1322
+ ...children
1323
+ );
1324
+ }
1325
+
937
1326
  // src/framework/adapters/react.ts
938
1327
  var ReactAdapter = class {
939
1328
  name = "react";
@@ -1054,8 +1443,10 @@ function useFrameworkAdapter(React) {
1054
1443
  }
1055
1444
  // Annotate the CommonJS export names for ESM import in node:
1056
1445
  0 && (module.exports = {
1446
+ MockupStage,
1057
1447
  ReactAdapter,
1058
1448
  createReactComponent,
1449
+ useMockupStage,
1059
1450
  useReactAdapter,
1060
1451
  useRealtimeMockup
1061
1452
  });
package/dist/react.d.cts CHANGED
@@ -1,4 +1,5 @@
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-DXRDbLDN.cjs';
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-CScS7UR-.cjs';
2
+ import { CSSProperties, ReactNode } from 'react';
2
3
 
3
4
  interface UseRealtimeMockupOptions {
4
5
  wsUrl?: string;
@@ -60,6 +61,143 @@ declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
60
61
  renderError: RealtimeRenderError | null;
61
62
  };
62
63
 
64
+ /**
65
+ * Mockup stage — the fast-render primitive for live product previews.
66
+ *
67
+ * Wraps a realtime session with the cropped-overlay delivery strategy:
68
+ * the FIRST render arrives full-frame and is frozen as a static background
69
+ * layer; the session then switches to `overlayCrop: 'auto'`, so every
70
+ * subsequent edit ships only the pixels inside the product region (the
71
+ * server derives the rect from the mockup's real mask geometry and reports
72
+ * it back with each frame). The stage composites the tiny frame over the
73
+ * frozen background — visually identical to a full render at a fraction of
74
+ * the bytes and latency.
75
+ *
76
+ * Two layers, use either:
77
+ * - `useMockupStage(options)` — headless. Owns the session + state machine
78
+ * and returns layers/status; bring your own rendering.
79
+ * - `MockupStage` — a ready view over a stage: layered <img>s, double-
80
+ * buffered frame swap (no flicker), feathered crop seam, and a default
81
+ * rendering shimmer. Every state is exposed as `data-sc-*` attributes so
82
+ * hosts key their own loading/animation treatments off it.
83
+ */
84
+
85
+ interface CropRect {
86
+ x: number;
87
+ y: number;
88
+ w: number;
89
+ h: number;
90
+ }
91
+ type MockupStageStatus = "connecting" | "configuring" | "first-frame" | "live" | "error";
92
+ interface UseMockupStageOptions {
93
+ /** Shop id the renders bill to (grant is minted for this shop). */
94
+ shop: string;
95
+ /** Product id. */
96
+ product: string;
97
+ /** Mockup (scene) id to render. */
98
+ mockup: string;
99
+ /** Additional mockup ids rendered by the same session (gallery views).
100
+ * Each gets its own background/frame pair in `stages`. */
101
+ extraMockups?: string[];
102
+ /** Variant id — fills color placements automatically when the product has them. */
103
+ variant?: string;
104
+ /** Render width in px, or a lazy getter (measured at config time — e.g.
105
+ * container width × devicePixelRatio). Default 1400. */
106
+ width?: number | (() => number);
107
+ /** Placement labels this stage sends artwork for. Default ['Front']. */
108
+ placements?: string[];
109
+ /** Aspect ratio, same grammar as the render URL param. Server default 16:9. */
110
+ ar?: string;
111
+ /** Background color behind scene alpha — 6-hex or 'transparent'. */
112
+ bg?: string;
113
+ /**
114
+ * Grant fetcher (recommended; connects to the public endpoint with zero
115
+ * further config). Omit only for self-hosted endpoints via `wsUrl`.
116
+ */
117
+ getToken?: () => Promise<{
118
+ token: string;
119
+ expiresAt: number;
120
+ }>;
121
+ /** Self-hosted realtime endpoint override. */
122
+ wsUrl?: string;
123
+ /**
124
+ * The fast path is the default: after the first full frame the session
125
+ * switches to server-cropped frames. Opt out with "full-frame" (every
126
+ * render ships the whole scene — the pre-crop behavior).
127
+ */
128
+ delivery?: "cropped" | "full-frame";
129
+ /** Operator timing debug key — relays Server-Timing on results. */
130
+ debugKey?: string;
131
+ /** Called with every rendered frame (timing, byte size, crop rect). */
132
+ onFrame?: (result: MockupResult) => void;
133
+ /** Structured render/session error (also exposed on state.error). */
134
+ onError?: (error: RealtimeRenderError) => void;
135
+ /** Placements to blank-initialize once configured (buyer flows render a
136
+ * product preview before any design exists). */
137
+ initialEmptyPlacements?: Array<{
138
+ label: string;
139
+ width?: number;
140
+ height?: number;
141
+ }>;
142
+ }
143
+ interface MockupStageFrame {
144
+ url: string;
145
+ /** Fractional rect the frame covers. Full frame = {0,0,1,1}. */
146
+ rect: CropRect;
147
+ }
148
+ interface MockupStageLayers {
149
+ /** Frozen full-frame background url (null until the first frame lands). */
150
+ background: string | null;
151
+ /** Latest frame to composite over the background. */
152
+ frame: MockupStageFrame | null;
153
+ }
154
+ interface MockupStageState {
155
+ status: MockupStageStatus;
156
+ /** Layers for the PRIMARY mockup (options.mockup). */
157
+ background: string | null;
158
+ frame: MockupStageFrame | null;
159
+ /** Per-mockup layers — primary plus every extraMockups entry. */
160
+ stages: Record<string, MockupStageLayers>;
161
+ /** An edit is in flight. */
162
+ isRendering: boolean;
163
+ error: RealtimeRenderError | null;
164
+ /** Last result's metadata (serverTiming, imageSize, …). */
165
+ lastResult: MockupResult | null;
166
+ /** Send a design (canvas_state JSON) for a placement — the production path. */
167
+ setDesign: (placement: string, state: object) => void;
168
+ /** Send pre-rendered artwork pixels for a placement. */
169
+ setArtwork: (placement: string, blob: Blob) => void;
170
+ /** Promote the latest full frame to the background (e.g. after prop changes). */
171
+ refreeze: () => void;
172
+ }
173
+ declare function useMockupStage(options: UseMockupStageOptions): MockupStageState;
174
+ interface MockupStageProps {
175
+ /** The stage returned by useMockupStage. */
176
+ stage: MockupStageState;
177
+ /** Render a specific mockup's layers (default: the primary mockup). */
178
+ mockupId?: string;
179
+ /** Feather (px) blending the frame edge into the background. Default 12. */
180
+ feather?: number;
181
+ /** Aspect ratio of the scene for layout, e.g. 16/9. Default 16/9. */
182
+ aspect?: number;
183
+ className?: string;
184
+ style?: CSSProperties;
185
+ /**
186
+ * Shown while connecting/configuring/waiting for the first frame. Default
187
+ * is a minimal pulse; pass a node for a custom one, or null to render
188
+ * nothing (host-owned loading UI keyed off data-sc-status).
189
+ */
190
+ placeholder?: ReactNode;
191
+ /** Shown while an edit renders. Default subtle shimmer; null = none. */
192
+ renderingIndicator?: ReactNode;
193
+ }
194
+ /**
195
+ * Default view: background layer + double-buffered frame layer. The next
196
+ * frame's <img> only swaps in after it has loaded, so edits never flash the
197
+ * old pixels away before the new ones are ready.
198
+ */
199
+ declare function MockupStage(props: MockupStageProps): ReactNode;
200
+
63
201
  /**
64
202
  * React framework adapter implementation
65
203
  */
@@ -112,4 +250,4 @@ declare function createReactComponent(descriptor: ComponentDescriptor, React: an
112
250
  */
113
251
  declare function useFrameworkAdapter(React: any): ReactAdapter;
114
252
 
115
- export { MockupResult, ReactAdapter, type UseRealtimeMockupOptions, WebSocketConfig, createReactComponent, useFrameworkAdapter as useReactAdapter, useRealtimeMockup };
253
+ export { MockupResult, MockupStage, type MockupStageFrame, type MockupStageProps, type MockupStageState, type MockupStageStatus, ReactAdapter, type UseMockupStageOptions, type UseRealtimeMockupOptions, WebSocketConfig, createReactComponent, useMockupStage, useFrameworkAdapter as useReactAdapter, useRealtimeMockup };