@snowcone-app/sdk 0.20.2 → 0.23.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/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  RealtimeMockupService
3
- } from "./chunk-MKLLTNKJ.js";
3
+ } from "./chunk-P3ZYTA5F.js";
4
4
 
5
5
  // src/realtime/react.ts
6
6
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -13,6 +13,7 @@ function useRealtimeMockup(options = {}) {
13
13
  const [state, setState] = useState({
14
14
  isConnected: false,
15
15
  sessionId: null,
16
+ box: null,
16
17
  isConfigured: false,
17
18
  mockupResults: [],
18
19
  status: "Disconnected",
@@ -24,9 +25,9 @@ function useRealtimeMockup(options = {}) {
24
25
  const service = new RealtimeMockupService(wsUrl);
25
26
  serviceRef.current = service;
26
27
  service.setCallbacks({
27
- onConnected: (sessionId) => {
28
+ onConnected: (sessionId, info) => {
28
29
  setState(service.getState());
29
- options.onConnected?.(sessionId);
30
+ options.onConnected?.(sessionId, info);
30
31
  },
31
32
  onDisconnected: () => {
32
33
  setState(service.getState());
@@ -116,6 +117,9 @@ function useRealtimeMockup(options = {}) {
116
117
  const hasPendingBlobs = useCallback(() => {
117
118
  return serviceRef.current?.hasPendingBlobs() || false;
118
119
  }, []);
120
+ const getLastSentVersion = useCallback(() => {
121
+ return serviceRef.current?.getLastSentVersion() ?? 0;
122
+ }, []);
119
123
  return {
120
124
  ...state,
121
125
  connect,
@@ -133,9 +137,338 @@ function useRealtimeMockup(options = {}) {
133
137
  clearLogs,
134
138
  clearMockups,
135
139
  flushPendingBlobs,
136
- hasPendingBlobs
140
+ hasPendingBlobs,
141
+ getLastSentVersion
142
+ };
143
+ }
144
+
145
+ // src/realtime/stage.ts
146
+ import {
147
+ createElement,
148
+ useCallback as useCallback2,
149
+ useEffect as useEffect2,
150
+ useMemo,
151
+ useRef as useRef2,
152
+ useState as useState2
153
+ } from "react";
154
+ var FULL_RECT = { x: 0, y: 0, w: 1, h: 1 };
155
+ function useMockupStage(options) {
156
+ const {
157
+ shop,
158
+ product,
159
+ mockup,
160
+ variant,
161
+ placements,
162
+ ar,
163
+ bg,
164
+ getToken,
165
+ wsUrl,
166
+ delivery = "cropped",
167
+ debugKey
168
+ } = options;
169
+ const mockupIds = useMemo(
170
+ () => [mockup, ...options.extraMockups ?? []],
171
+ // eslint-disable-next-line react-hooks/exhaustive-deps
172
+ [mockup, JSON.stringify(options.extraMockups ?? [])]
173
+ );
174
+ const [stages, setStages] = useState2({});
175
+ const [isRendering, setIsRendering] = useState2(false);
176
+ const [error, setError] = useState2(null);
177
+ const [lastResult, setLastResult] = useState2(null);
178
+ const backgroundsRef = useRef2({});
179
+ const croppedActiveRef = useRef2(false);
180
+ const pendingEditsRef = useRef2(0);
181
+ const optionsRef = useRef2(options);
182
+ optionsRef.current = options;
183
+ const mockupIdsRef = useRef2(mockupIds);
184
+ mockupIdsRef.current = mockupIds;
185
+ const onFrameRef = useRef2(options.onFrame);
186
+ onFrameRef.current = options.onFrame;
187
+ const onErrorRef = useRef2(options.onError);
188
+ onErrorRef.current = options.onError;
189
+ const {
190
+ isConnected,
191
+ sessionId,
192
+ isConfigured,
193
+ connect,
194
+ sendConfig,
195
+ sendCanvasState,
196
+ sendCanvasBlob,
197
+ sendInitialEmptyCanvases
198
+ } = useRealtimeMockup({
199
+ wsUrl,
200
+ getToken,
201
+ onMockupRendered: (result) => {
202
+ if (!result.imageUrl || !result.mockupId) return;
203
+ const id = result.mockupId;
204
+ setLastResult(result);
205
+ pendingEditsRef.current = Math.max(0, pendingEditsRef.current - 1);
206
+ if (pendingEditsRef.current === 0) setIsRendering(false);
207
+ onFrameRef.current?.(result);
208
+ if (!backgroundsRef.current[id]) {
209
+ backgroundsRef.current[id] = result.imageUrl;
210
+ setStages((prev) => ({
211
+ ...prev,
212
+ [id]: { background: result.imageUrl, frame: { url: result.imageUrl, rect: FULL_RECT } }
213
+ }));
214
+ const allSeeded = mockupIdsRef.current.every((m) => backgroundsRef.current[m]);
215
+ if (allSeeded && !croppedActiveRef.current && optionsRef.current.delivery !== "full-frame") {
216
+ croppedActiveRef.current = true;
217
+ sendStageConfig(true);
218
+ }
219
+ return;
220
+ }
221
+ setStages((prev) => ({
222
+ ...prev,
223
+ [id]: {
224
+ background: backgroundsRef.current[id],
225
+ frame: { url: result.imageUrl, rect: result.cropRect ?? FULL_RECT }
226
+ }
227
+ }));
228
+ },
229
+ onError: (_msg, detail) => {
230
+ setError(detail);
231
+ setIsRendering(false);
232
+ onErrorRef.current?.(detail);
233
+ }
234
+ });
235
+ const sendConfigRef = useRef2(sendConfig);
236
+ sendConfigRef.current = sendConfig;
237
+ const sendStageConfig = useCallback2(
238
+ (withCrop) => {
239
+ const o = optionsRef.current;
240
+ const width = typeof o.width === "function" ? o.width() : o.width ?? 1400;
241
+ const config = {
242
+ productId: o.product,
243
+ mockupIds: mockupIdsRef.current,
244
+ variantId: o.variant ?? "",
245
+ shop: o.shop,
246
+ width,
247
+ ...o.ar && { ar: o.ar },
248
+ ...o.bg && { bg: o.bg },
249
+ ...withCrop && { overlayCrop: "auto" },
250
+ ...o.debugKey && { debugKey: o.debugKey }
251
+ };
252
+ sendConfigRef.current(config);
253
+ },
254
+ []
255
+ );
256
+ useEffect2(() => {
257
+ connect();
258
+ }, [connect]);
259
+ useEffect2(() => {
260
+ if (isConnected && sessionId) {
261
+ sendStageConfig(croppedActiveRef.current);
262
+ }
263
+ }, [isConnected, sessionId, shop, product, mockupIds, variant, ar, bg, sendStageConfig]);
264
+ const initialSentRef = useRef2(false);
265
+ useEffect2(() => {
266
+ const placementsToSeed = optionsRef.current.initialEmptyPlacements;
267
+ if (isConfigured && placementsToSeed?.length && !initialSentRef.current) {
268
+ initialSentRef.current = true;
269
+ void sendInitialEmptyCanvases(placementsToSeed);
270
+ }
271
+ }, [isConfigured, sendInitialEmptyCanvases]);
272
+ const setDesign = useCallback2(
273
+ (placement, state) => {
274
+ pendingEditsRef.current += 1;
275
+ setIsRendering(true);
276
+ setError(null);
277
+ sendCanvasState(placement, state, 1, 0);
278
+ },
279
+ [sendCanvasState]
280
+ );
281
+ const setArtwork = useCallback2(
282
+ (placement, blob) => {
283
+ pendingEditsRef.current += 1;
284
+ setIsRendering(true);
285
+ setError(null);
286
+ sendCanvasBlob(placement, blob, 1, 0);
287
+ },
288
+ [sendCanvasBlob]
289
+ );
290
+ const refreeze = useCallback2(() => {
291
+ backgroundsRef.current = {};
292
+ croppedActiveRef.current = false;
293
+ setStages({});
294
+ sendStageConfig(false);
295
+ }, [sendStageConfig]);
296
+ const primary = stages[mockup] ?? { background: null, frame: null };
297
+ const status = error ? "error" : !isConnected ? "connecting" : !isConfigured ? "configuring" : !primary.background ? "first-frame" : "live";
298
+ void placements;
299
+ return {
300
+ status,
301
+ background: primary.background,
302
+ frame: primary.frame,
303
+ stages,
304
+ isRendering,
305
+ error,
306
+ lastResult,
307
+ setDesign,
308
+ setArtwork,
309
+ refreeze
137
310
  };
138
311
  }
312
+ function MockupStage(props) {
313
+ const {
314
+ stage,
315
+ mockupId,
316
+ feather = 12,
317
+ aspect = 16 / 9,
318
+ className,
319
+ style,
320
+ placeholder,
321
+ renderingIndicator
322
+ } = props;
323
+ const layers = mockupId ? stage.stages[mockupId] ?? { background: null, frame: null } : { background: stage.background, frame: stage.frame };
324
+ const [displayed, setDisplayed] = useState2(null);
325
+ const [incoming, setIncoming] = useState2(null);
326
+ useEffect2(() => {
327
+ if (!layers.frame) return;
328
+ if (!displayed) {
329
+ setDisplayed(layers.frame);
330
+ return;
331
+ }
332
+ if (layers.frame.url !== displayed.url) setIncoming(layers.frame);
333
+ }, [layers.frame]);
334
+ const handleIncomingLoad = useCallback2(() => {
335
+ setIncoming((inc) => {
336
+ if (inc) setDisplayed(inc);
337
+ return null;
338
+ });
339
+ }, []);
340
+ const frameStyle = useCallback2(
341
+ (f) => {
342
+ const full = f.rect.x === 0 && f.rect.y === 0 && f.rect.w === 1 && f.rect.h === 1;
343
+ const base = {
344
+ position: "absolute",
345
+ left: `${f.rect.x * 100}%`,
346
+ top: `${f.rect.y * 100}%`,
347
+ width: `${f.rect.w * 100}%`,
348
+ height: `${f.rect.h * 100}%`
349
+ };
350
+ if (!full && feather > 0) {
351
+ 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%)`;
352
+ base.WebkitMaskImage = m;
353
+ base.maskImage = m;
354
+ base.WebkitMaskComposite = "source-in";
355
+ base.maskComposite = "intersect";
356
+ }
357
+ return base;
358
+ },
359
+ [feather]
360
+ );
361
+ const containerStyle = useMemo(
362
+ () => ({
363
+ position: "relative",
364
+ aspectRatio: String(aspect),
365
+ overflow: "hidden",
366
+ ...style
367
+ }),
368
+ [aspect, style]
369
+ );
370
+ const children = [];
371
+ if (layers.background) {
372
+ children.push(
373
+ createElement("img", {
374
+ key: "bg",
375
+ src: layers.background,
376
+ alt: "",
377
+ "data-sc-part": "background",
378
+ style: { position: "absolute", inset: 0, width: "100%", height: "100%" }
379
+ })
380
+ );
381
+ }
382
+ if (displayed) {
383
+ children.push(
384
+ createElement("img", {
385
+ key: `frame-${displayed.url}`,
386
+ src: displayed.url,
387
+ alt: "",
388
+ "data-sc-part": "frame",
389
+ style: frameStyle(displayed)
390
+ })
391
+ );
392
+ }
393
+ if (incoming) {
394
+ children.push(
395
+ createElement("img", {
396
+ key: `incoming-${incoming.url}`,
397
+ src: incoming.url,
398
+ alt: "",
399
+ "data-sc-part": "frame-incoming",
400
+ onLoad: handleIncomingLoad,
401
+ style: { ...frameStyle(incoming), opacity: 0.999 }
402
+ })
403
+ );
404
+ }
405
+ if (!layers.background) {
406
+ children.push(
407
+ createElement(
408
+ "div",
409
+ {
410
+ key: "placeholder",
411
+ "data-sc-part": "placeholder",
412
+ style: {
413
+ position: "absolute",
414
+ inset: 0,
415
+ display: "flex",
416
+ alignItems: "center",
417
+ justifyContent: "center"
418
+ }
419
+ },
420
+ placeholder !== void 0 ? placeholder : createElement("div", {
421
+ style: {
422
+ width: "38%",
423
+ height: "55%",
424
+ borderRadius: 12,
425
+ background: "rgba(127,127,127,0.15)",
426
+ animation: "sc-stage-pulse 1.2s ease-in-out infinite"
427
+ }
428
+ })
429
+ )
430
+ );
431
+ }
432
+ if (stage.isRendering && layers.background) {
433
+ children.push(
434
+ createElement(
435
+ "div",
436
+ {
437
+ key: "rendering",
438
+ "data-sc-part": "rendering-indicator",
439
+ style: { position: "absolute", inset: 0, pointerEvents: "none" }
440
+ },
441
+ renderingIndicator !== void 0 ? renderingIndicator : createElement("div", {
442
+ style: {
443
+ position: "absolute",
444
+ top: 8,
445
+ right: 8,
446
+ width: 8,
447
+ height: 8,
448
+ borderRadius: "50%",
449
+ background: "rgba(127,127,127,0.6)",
450
+ animation: "sc-stage-pulse 0.8s ease-in-out infinite"
451
+ }
452
+ })
453
+ )
454
+ );
455
+ }
456
+ children.push(
457
+ createElement("style", { key: "kf" }, "@keyframes sc-stage-pulse{0%,100%{opacity:.35}50%{opacity:.9}}")
458
+ );
459
+ return createElement(
460
+ "div",
461
+ {
462
+ className,
463
+ style: containerStyle,
464
+ "data-sc-part": "stage",
465
+ "data-sc-status": stage.status,
466
+ "data-sc-rendering": stage.isRendering ? "true" : "false",
467
+ ...stage.error && { "data-sc-error": stage.error.code ?? "error" }
468
+ },
469
+ ...children
470
+ );
471
+ }
139
472
 
140
473
  // src/framework/adapters/react.ts
141
474
  var ReactAdapter = class {
@@ -256,8 +589,10 @@ function useFrameworkAdapter(React) {
256
589
  return new ReactAdapter(React, React);
257
590
  }
258
591
  export {
592
+ MockupStage,
259
593
  ReactAdapter,
260
594
  createReactComponent,
595
+ useMockupStage,
261
596
  useFrameworkAdapter as useReactAdapter,
262
597
  useRealtimeMockup
263
598
  };
package/dist/server.cjs CHANGED
@@ -80,6 +80,7 @@ var PARAMS = {
80
80
  signature: "signature",
81
81
  seal: "seal"
82
82
  };
83
+ var MAX_RENDER_URL_LENGTH = 12 * 1024;
83
84
  var PUBLIC_PARAM_NAMES = [
84
85
  PARAMS.asset,
85
86
  PARAMS.design,
@@ -117,6 +118,7 @@ function canonicalForSig(url) {
117
118
  const rawValue = eq === -1 ? "" : segment.slice(eq + 1);
118
119
  const key = decodeURIComponent(rawKey);
119
120
  if (key === "signature") continue;
121
+ if (key === "debug") continue;
120
122
  pairs.push({ key, raw: rawValue });
121
123
  }
122
124
  }
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  canonicalForSig,
3
3
  signDevSig
4
- } from "./chunk-IL3FXE2X.js";
4
+ } from "./chunk-FPR6ABXM.js";
5
5
 
6
6
  // src/server.ts
7
7
  function json(body, status = 200) {
@@ -248,6 +248,25 @@ interface WebSocketConfig {
248
248
  height: number;
249
249
  }>;
250
250
  }>;
251
+ /**
252
+ * Cropped-overlay delivery: {x,y,w,h} fractions of the OUTPUT frame. Each
253
+ * rendered mockup is cropped server-side to this rect just before AVIF
254
+ * encode, so every realtime frame carries only that region's bytes — the
255
+ * client positions it over a static full-frame render using the same
256
+ * fractions. Full-frame ({x:0,y:0,w:1,h:1}) is a no-op.
257
+ */
258
+ overlayCrop?: {
259
+ x: number;
260
+ y: number;
261
+ w: number;
262
+ h: number;
263
+ } | 'auto';
264
+ /**
265
+ * Operator-only: when this matches the render server's debug secret, every
266
+ * MockupResult carries `serverTiming` — the render's per-stage breakdown.
267
+ * Wrong values fail renders loudly (never pass user input here).
268
+ */
269
+ debugKey?: string;
251
270
  placementSettings?: Record<string, PlacementSettings>;
252
271
  }
253
272
  interface MockupResult {
@@ -269,8 +288,36 @@ interface MockupResult {
269
288
  costUsd?: number;
270
289
  /** Whether the underlying render was served from cache */
271
290
  renderCache?: 'hit' | 'miss';
291
+ /** The rect this payload was cropped with (fractions of the full frame) —
292
+ * present on overlayCrop renders; position the overlay with these numbers. */
293
+ cropRect?: {
294
+ x: number;
295
+ y: number;
296
+ w: number;
297
+ h: number;
298
+ };
299
+ /** Raw Server-Timing header of the render — per-stage breakdown, present
300
+ * only when the session's debugKey matched the server's debug secret. */
301
+ serverTiming?: string;
272
302
  /** Server-side canvas render timing breakdown (present when canvas_state was used) */
273
303
  canvasRenderTiming?: any;
304
+ /**
305
+ * Box-window envelope of this frame in Server-Timing grammar — receive →
306
+ * send on the render node: `rt_total`, `rt_guard`, `rt_canvas` (+
307
+ * `rt_canvas_hop`, `canvas_*`), `rt_coalesce` (desc `superseded N`),
308
+ * `rt_composite`, `rt_store`, `rt_deliver` (desc `sz=<bytes> ws|url`),
309
+ * `rt_box`. Present on every frame from a server that emits it — no
310
+ * debug key needed. `clientRoundTripMs − rt_total` is the round-trip
311
+ * transport (browser ↔ edge ↔ box, both directions).
312
+ */
313
+ rtTiming?: string;
314
+ /** Client-observed edit → frame: the canvas_state send this frame answers
315
+ * → this message's arrival, in ms. Undefined when the frame was not
316
+ * triggered by a send from this client (config re-render, replay). */
317
+ clientRoundTripMs?: number;
318
+ /** How the bytes arrived: pushed down the socket ('ws') or via the
319
+ * imageUrl fetch ('url'). */
320
+ imageDelivery?: 'ws' | 'url';
274
321
  }
275
322
  interface WebSocketMessage {
276
323
  type: string;
@@ -297,6 +344,21 @@ interface WebSocketMessage {
297
344
  costUsd?: number;
298
345
  /** Whether the underlying render was served from cache */
299
346
  renderCache?: 'hit' | 'miss';
347
+ /** Rect the payload was cropped with (overlayCrop renders) */
348
+ cropRect?: {
349
+ x: number;
350
+ y: number;
351
+ w: number;
352
+ h: number;
353
+ };
354
+ /** Raw Server-Timing breakdown (only when the session's debugKey matched) */
355
+ serverTiming?: string;
356
+ /** Box-window envelope of the frame (see MockupResult.rtTiming) */
357
+ rtTiming?: string;
358
+ /** Render node identity, on `connected` */
359
+ box?: string;
360
+ /** 'ws' when the image bytes were pushed as a mockup_frame before this message */
361
+ imageDelivery?: string;
300
362
  /** Server-side canvas render timing (only present when canvas_state was used) */
301
363
  canvasRenderTiming?: {
302
364
  poolAcquireMs: number;
@@ -322,10 +384,21 @@ interface RealtimeRenderError {
322
384
  code: string;
323
385
  /** Human-readable detail (includes specifics such as the blocked asset URL). */
324
386
  message: string;
387
+ /**
388
+ * Set when the error is about ONE mockup, not the session (the others keep
389
+ * streaming); show it as unavailable. Codes: 'E_MOCKUP_NOT_BLESSED' — the
390
+ * scene failed render parity; 'E_MOCKUP_INELIGIBLE' — no compiled scene
391
+ * can express the request (a colour-only or URL-less placement; `message`
392
+ * carries the reason); 'E_MOCKUP_UNRENDERABLE' — any other typed refusal.
393
+ */
394
+ mockupId?: string;
325
395
  }
326
396
  interface RealtimeMockupState {
327
397
  isConnected: boolean;
328
398
  sessionId: string | null;
399
+ /** Render node that answered the handshake (`connected.box`); null until
400
+ * connected or on servers that don't report it. */
401
+ box: string | null;
329
402
  isConfigured: boolean;
330
403
  mockupResults: MockupResult[];
331
404
  status: string;
@@ -342,7 +415,11 @@ interface RealtimeMockupState {
342
415
  renderError: RealtimeRenderError | null;
343
416
  }
344
417
  interface RealtimeMockupCallbacks {
345
- onConnected?: (sessionId: string) => void;
418
+ /** `info.box` names the render node that answered (undefined on servers
419
+ * that don't report it). */
420
+ onConnected?: (sessionId: string, info: {
421
+ box?: string;
422
+ }) => void;
346
423
  onDisconnected?: () => void;
347
424
  onConfigReceived?: () => void;
348
425
  /** Called when server confirms it received a blob for a placement */
@@ -366,6 +443,7 @@ declare class RealtimeMockupService {
366
443
  private config;
367
444
  private configSent;
368
445
  private sessionId;
446
+ private box;
369
447
  private isConfigured;
370
448
  private mockupResults;
371
449
  private status;
@@ -387,6 +465,8 @@ declare class RealtimeMockupService {
387
465
  private latestAcceptedVersionByPlacement;
388
466
  private sendVersionInBlob;
389
467
  private tokenProvider?;
468
+ private pendingFrames;
469
+ private liveObjectUrls;
390
470
  private renewTimer;
391
471
  private isConnecting;
392
472
  private connectAttempt;
@@ -406,6 +486,9 @@ declare class RealtimeMockupService {
406
486
  private renew;
407
487
  private handleMessage;
408
488
  disconnect(): void;
489
+ private handleBinaryFrame;
490
+ /** Swap a ws-delivered frame in for the imageUrl on a render result. */
491
+ private applyBinaryFrame;
409
492
  sendConfig(config: WebSocketConfig): boolean;
410
493
  /**
411
494
  * Update only the mockupIds without changing other config.
@@ -456,6 +539,13 @@ declare class RealtimeMockupService {
456
539
  * Check if there are pending blobs waiting to be sent (in throttle queue)
457
540
  */
458
541
  hasPendingBlobs(): boolean;
542
+ /**
543
+ * Version stamped on the most recent canvas_state send (0 before any).
544
+ * Every frame answers with `requestVersion`, so a caller can tell which
545
+ * send a frame belongs to — the pipeline-depth send policy counts a send
546
+ * as landed when every mockup of its version has arrived.
547
+ */
548
+ getLastSentVersion(): number;
459
549
  sendColorBlob(placement: string, hexColor: string): boolean;
460
550
  createEmptyCanvasBlob(width?: number, height?: number): Promise<Blob>;
461
551
  sendInitialEmptyCanvases(placements: Array<{