@snowcone-app/sdk 0.29.0 → 0.30.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.30.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#2973](https://github.com/snowcone-app/snowcone-monorepo/pull/2973) [`6910bc9`](https://github.com/snowcone-app/snowcone-monorepo/commit/6910bc9c88dbdcc5974d45ee93d2b2e17fff3bcf) Thanks [@kevinsproles](https://github.com/kevinsproles)! - The SDK owns Snowcone's hostnames. New `SNOWCONE_HOSTS` export (`api`, `img`, `buy`, `search`, `cdn`, `sign`, `raws`, `docs`) and `SNOWCONE_REALTIME_WS_URL` — every default host in the SDK, MCP server, canvas, and ui now reads from this one registry, so a host move ships as a version bump instead of breaking integrations. For an endpoint the SDK doesn't wrap, build the URL from `SNOWCONE_HOSTS.api` rather than hardcoding `https://api.snowcone.app`.
8
+
9
+ ## 0.29.1
10
+
11
+ ### Patch Changes
12
+
13
+ - [#4643](https://github.com/snowcone-app/snowcone-monorepo/pull/4643) [`af17a28`](https://github.com/snowcone-app/snowcone-monorepo/commit/af17a28ff9a11fa6e59efb83aff3c8dae863a082) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Realtime frame flow control: an `all_mockups_rendered` summary that arrives before its frames (they wait behind the ack window) no longer replaces the frame a picture still has to draw. It was lost, never drawn or acked, and the box waited out its 5 s ack timeout (`E_RT_ACK_TIMEOUT`) on every picture of the gallery. A frame dropped by the per-picture bound (`E_BLOB_PICTURE_BOUND`) is now acked too.
14
+
3
15
  ## 0.29.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -101,7 +101,7 @@ const url = getMockupUrl(productCode: string, opts: {
101
101
  design?: Design; // Multi-placement: { [placementKey]: Fill } — takes precedence over `asset`
102
102
  options?: Record<string, string>; // Variant picks: { size: "m" } → opt.size=m
103
103
  secret?: string; // Optional: per-shop secret → appends a signed &signature (server only)
104
- base?: string; // Optional: override the host (default img.snowcone.app)
104
+ base?: string; // Optional: override the host (default SNOWCONE_HOSTS.img — leave unset in prod)
105
105
  width?: number; // Optional: display width
106
106
  view?: string; // Optional: camera view / mockup scene (alias: `mockup`)
107
107
  variant?: string; // Optional: specific resolved variant (gvid)
@@ -228,6 +228,24 @@ React apps can use the lower-level `useRealtimeMockup({ getToken })` hook from
228
228
  `@snowcone-app/sdk/react` instead. Full walkthrough:
229
229
  [Realtime server-side render](https://developers.snowcone.app/realtime).
230
230
 
231
+ ## Hosts: let the SDK own them
232
+
233
+ Don't write `https://api.snowcone.app` (or any Snowcone host) into your code.
234
+ The helpers above pick the host; for an endpoint the SDK doesn't wrap, read it
235
+ from `SNOWCONE_HOSTS`:
236
+
237
+ ```typescript
238
+ import { SNOWCONE_HOSTS } from '@snowcone-app/sdk';
239
+
240
+ await fetch(`${SNOWCONE_HOSTS.api}/orders`, { method: 'POST', headers, body });
241
+ // roles: api, img, buy, search, cdn, sign, raws, docs
242
+ ```
243
+
244
+ Hostnames live in one place in this package. If one has to move, you upgrade
245
+ the SDK; nothing you wrote changes. Store inputs (product, asset, options), not
246
+ built URLs — `getMockupUrl` is pure and sync, so rebuild at render time.
247
+ More: [Keep hosts out of your code](https://developers.snowcone.app/sdk#hosts).
248
+
231
249
  ## TypeScript Support
232
250
 
233
251
  Full TypeScript definitions are included. Import types:
@@ -1,4 +1,23 @@
1
1
  // ../mockup-url/src/index.ts
2
+ var SNOWCONE_HOSTS = {
3
+ /** REST API: shops, orders, AI generation, realtime grants. */
4
+ api: "https://api.snowcone.app",
5
+ /** Public mockup-image resolver (`/{productCode}?shop=…&asset=…`). */
6
+ img: "https://img.snowcone.app",
7
+ /** Hosted buy page (same grammar as `img`, opens checkout). */
8
+ buy: "https://buy.snowcone.app",
9
+ /** Public product / designs catalog (Meilisearch-compatible). */
10
+ search: "https://search.snowcone.app",
11
+ /** Render CDN — signed render URLs and the realtime socket. */
12
+ cdn: "https://cdn.snowcone.app",
13
+ /** Legacy URL signer. */
14
+ sign: "https://s.snowcone.app",
15
+ /** Content-addressed artwork store (ingest handles). */
16
+ raws: "https://raws.snowcone.app",
17
+ /** Developer docs. */
18
+ docs: "https://developers.snowcone.app"
19
+ };
20
+ var SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, "ws")}/realtime`;
2
21
  var PARAMS = {
3
22
  shop: "shop",
4
23
  asset: "asset",
@@ -86,6 +105,7 @@ var ALLOWED_WIDTHS = [
86
105
  4e3
87
106
  ];
88
107
  var MAX_RENDER_URL_LENGTH = 12 * 1024;
108
+ var INGEST_HANDLE_BASE = `${SNOWCONE_HOSTS.raws}/art-ingest/`;
89
109
  function normalizeWidth(width) {
90
110
  for (let i = ALLOWED_WIDTHS.length - 1; i >= 0; i--) {
91
111
  if (ALLOWED_WIDTHS[i] <= width) return ALLOWED_WIDTHS[i];
@@ -170,7 +190,7 @@ var PARAM_PREFIX = {
170
190
  /** ADR-0099 bundles: `pick.<role>=<productCode>` — which alternative fills a slot. */
171
191
  pick: "pick."
172
192
  };
173
- var DEFAULT_PUBLIC_BASE_URL = "https://img.snowcone.app";
193
+ var DEFAULT_PUBLIC_BASE_URL = SNOWCONE_HOSTS.img;
174
194
  function buildPublicMockupUrl(options, cfg = {}) {
175
195
  const base = (cfg.baseUrl ?? DEFAULT_PUBLIC_BASE_URL).replace(/\/+$/, "");
176
196
  const path = `/${encodeURIComponent(options.productCode)}`;
@@ -296,6 +316,8 @@ async function signDevSig(canonical, secret) {
296
316
  }
297
317
 
298
318
  export {
319
+ SNOWCONE_HOSTS,
320
+ SNOWCONE_REALTIME_WS_URL,
299
321
  normalizeWidth,
300
322
  normalizeDesignElements,
301
323
  buildMockupUrl,
@@ -1,5 +1,9 @@
1
+ import {
2
+ SNOWCONE_REALTIME_WS_URL
3
+ } from "./chunk-5HX26XOJ.js";
4
+
1
5
  // src/realtime/constants.ts
2
- var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
6
+ var REALTIME_WS_URL = SNOWCONE_REALTIME_WS_URL;
3
7
 
4
8
  // src/realtime/websocket.ts
5
9
  function pruneUndefined(obj) {
@@ -370,17 +374,23 @@ var RealtimeMockupService = class {
370
374
  }
371
375
  return true;
372
376
  });
373
- const batch = freshMockups.map((mockup) => {
377
+ const batch = freshMockups.flatMap((mockup) => {
374
378
  const existing = this.mockupResults.find(
375
379
  (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
376
380
  );
377
- if (!existing) return mockup;
381
+ if (!existing) {
382
+ if (!mockup.imageUrl) {
383
+ const held = this.mockupResults.find((m) => m.mockupId === mockup.mockupId && m.imageUrl);
384
+ return held ? [held] : [];
385
+ }
386
+ return [mockup];
387
+ }
378
388
  const merged = { ...existing, ...pruneUndefined(mockup) };
379
389
  if (existing.imageUrl.startsWith("blob:")) {
380
390
  merged.imageUrl = existing.imageUrl;
381
391
  merged.renderUrl = existing.renderUrl;
382
392
  }
383
- return merged;
393
+ return [merged];
384
394
  });
385
395
  const batchById = new Map(batch.map((m) => [m.mockupId, m]));
386
396
  this.mockupResults = [
package/dist/index.cjs CHANGED
@@ -58,6 +58,8 @@ __export(src_exports, {
58
58
  RealtimeMockupService: () => RealtimeMockupService,
59
59
  RenderSession: () => RenderSession,
60
60
  SIZE_PICTURE: () => SIZE_PICTURE,
61
+ SNOWCONE_HOSTS: () => SNOWCONE_HOSTS,
62
+ SNOWCONE_REALTIME_WS_URL: () => SNOWCONE_REALTIME_WS_URL,
61
63
  SnowconeSdkError: () => SnowconeSdkError,
62
64
  StandardComponents: () => StandardComponents,
63
65
  StandardEvents: () => StandardEvents,
@@ -258,242 +260,26 @@ var CatalogProductSchema = import_zod.z.object({
258
260
  defaultGvid: import_zod.z.string().optional()
259
261
  });
260
262
 
261
- // src/mockup/cache.ts
262
- var SignatureCache = class {
263
- memoryCache = /* @__PURE__ */ new Map();
264
- maxMemoryEntries;
265
- maxLocalStorageEntries;
266
- localStorageKey = "snowcone_signature_cache";
267
- localStorageAvailable;
268
- constructor(maxMemoryEntries = 500, maxLocalStorageEntries = 100) {
269
- this.maxMemoryEntries = maxMemoryEntries;
270
- this.maxLocalStorageEntries = maxLocalStorageEntries;
271
- this.localStorageAvailable = this.checkLocalStorageAvailability();
272
- if (this.localStorageAvailable) {
273
- this.loadFromLocalStorage();
274
- }
275
- }
276
- checkLocalStorageAvailability() {
277
- try {
278
- const test = "__storage_test__";
279
- localStorage.setItem(test, test);
280
- localStorage.removeItem(test);
281
- return true;
282
- } catch {
283
- return false;
284
- }
285
- }
286
- loadFromLocalStorage() {
287
- try {
288
- const stored = localStorage.getItem(this.localStorageKey);
289
- if (stored) {
290
- const parsed = JSON.parse(stored);
291
- if (Array.isArray(parsed)) {
292
- parsed.forEach(([key, value]) => {
293
- if (this.memoryCache.size < this.maxMemoryEntries) {
294
- this.memoryCache.set(key, value);
295
- }
296
- });
297
- }
298
- }
299
- } catch (error) {
300
- console.warn("Failed to load signature cache from localStorage:", error);
301
- }
302
- }
303
- saveToLocalStorage() {
304
- if (!this.localStorageAvailable) return;
305
- try {
306
- const entries = Array.from(this.memoryCache.entries()).sort((a, b) => b[1].timestamp - a[1].timestamp).slice(0, this.maxLocalStorageEntries);
307
- localStorage.setItem(this.localStorageKey, JSON.stringify(entries));
308
- } catch (error) {
309
- console.warn("Failed to save signature cache to localStorage:", error);
310
- this.localStorageAvailable = false;
311
- }
312
- }
313
- get(key) {
314
- const entry = this.memoryCache.get(key);
315
- if (entry) {
316
- entry.timestamp = Date.now();
317
- this.memoryCache.delete(key);
318
- this.memoryCache.set(key, entry);
319
- return entry.url;
320
- }
321
- return null;
322
- }
323
- set(key, url) {
324
- if (this.memoryCache.size >= this.maxMemoryEntries) {
325
- const oldestKey = this.findOldestKey();
326
- if (oldestKey) {
327
- this.memoryCache.delete(oldestKey);
328
- }
329
- }
330
- this.memoryCache.set(key, {
331
- url,
332
- timestamp: Date.now()
333
- });
334
- this.saveToLocalStorage();
335
- }
336
- findOldestKey() {
337
- let oldestKey = null;
338
- let oldestTime = Infinity;
339
- for (const [key, entry] of this.memoryCache.entries()) {
340
- if (entry.timestamp < oldestTime) {
341
- oldestTime = entry.timestamp;
342
- oldestKey = key;
343
- }
344
- }
345
- return oldestKey;
346
- }
347
- clear() {
348
- this.memoryCache.clear();
349
- if (this.localStorageAvailable) {
350
- try {
351
- localStorage.removeItem(this.localStorageKey);
352
- } catch (error) {
353
- console.warn("Failed to clear localStorage cache:", error);
354
- }
355
- }
356
- }
357
- size() {
358
- return this.memoryCache.size;
359
- }
360
- };
361
-
362
- // src/mockup/service.ts
363
- var DEFAULT_IMAGE_URL = typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || "https://cdn.snowcone.app";
364
- var DEFAULT_SIGNER_URL = typeof process !== "undefined" && process.env?.SNOWCONE_SIGNER_URL || "https://s.snowcone.app/sign";
365
- var RATE_LIMIT_PER_MINUTE = 450;
366
- var RATE_LIMIT_PER_SECOND = 20;
367
- var MockupServiceImpl = class {
368
- config;
369
- cache;
370
- rateLimitState;
371
- fetch;
372
- constructor(config, customFetch) {
373
- this.config = {
374
- imageUrl: config.imageUrl || DEFAULT_IMAGE_URL,
375
- signerUrl: config.signerUrl || DEFAULT_SIGNER_URL,
376
- shop: config.shop || typeof process !== "undefined" && process.env?.SNOWCONE_SHOP_ID || ""
377
- };
378
- this.cache = new SignatureCache();
379
- this.fetch = customFetch || fetch.bind(globalThis);
380
- this.rateLimitState = {
381
- perMinute: { count: 0, resetTime: Date.now() + 6e4 },
382
- perSecond: { count: 0, resetTime: Date.now() + 1e3 }
383
- };
384
- }
385
- async getMockupUrl(options) {
386
- if (!options.design || !options.product) {
387
- throw new Error("Missing required options: design and product are required");
388
- }
389
- if (!this.config.shop) {
390
- throw new Error("Shop ID is required for mockup generation");
391
- }
392
- for (const element of options.design) {
393
- if (element.type === "image" && element.imageUrl) {
394
- if (element.imageUrl.startsWith("blob:")) {
395
- throw new Error(
396
- `[snowcone-sdk] Cannot generate mockup: design element for placement "${element.placement}" uses a blob URL ("${element.imageUrl.slice(0, 60)}..."). Blob URLs are local to this browser tab and cannot be downloaded by the mockup rendering server. Upload the image to a publicly accessible URL or convert it to a data URL before requesting a mockup.`
397
- );
398
- }
399
- }
400
- }
401
- this.checkRateLimits();
402
- const relativeUrl = this.buildMockupUrlWithParams(options);
403
- const cacheKey = `${relativeUrl}:${this.config.shop}`;
404
- const cachedUrl = this.cache.get(cacheKey);
405
- if (cachedUrl) {
406
- return cachedUrl;
407
- }
408
- const signedUrl = await this.getSignedUrl(relativeUrl);
409
- this.cache.set(cacheKey, signedUrl);
410
- this.incrementRateLimitCounters();
411
- return signedUrl;
412
- }
413
- buildMockupUrlWithParams(options) {
414
- const { design, product, effects, ar } = options;
415
- const designBase64 = typeof window !== "undefined" && window.btoa ? window.btoa(JSON.stringify(design)) : Buffer.from(JSON.stringify(design)).toString("base64");
416
- const encodedDesign = encodeURIComponent(designBase64);
417
- let url = `/mockup?productId=${encodeURIComponent(product.productId)}`;
418
- url += `&mockupId=${encodeURIComponent(product.mockupId)}`;
419
- url += `&variantId=${encodeURIComponent(product.variantId)}`;
420
- url += `&design=${encodedDesign}`;
421
- url += `&width=${product.width}`;
422
- if (effects?.grain) {
423
- url += `&grain=${effects.grain}`;
424
- }
425
- if (ar && ar !== "16:9") {
426
- url += `&ar=${encodeURIComponent(ar)}`;
427
- }
428
- if (product.optionSelections && Object.keys(product.optionSelections).length > 0) {
429
- const optionSelectionsBase64 = typeof window !== "undefined" && window.btoa ? window.btoa(JSON.stringify(product.optionSelections)) : Buffer.from(JSON.stringify(product.optionSelections)).toString("base64");
430
- url += `&optionSelections=${encodeURIComponent(optionSelectionsBase64)}`;
431
- }
432
- return url;
433
- }
434
- async getSignedUrl(relativeUrl) {
435
- const urlWithAccountId = relativeUrl + (relativeUrl.includes("?") ? "&" : "?") + `shop=${encodeURIComponent(this.config.shop)}`;
436
- const cacheKey = urlWithAccountId;
437
- const cachedUrl = this.cache.get(cacheKey);
438
- if (cachedUrl) {
439
- return cachedUrl;
440
- }
441
- const signerUrl = new URL(this.config.signerUrl);
442
- signerUrl.searchParams.set("url", urlWithAccountId);
443
- try {
444
- const response = await this.fetch(signerUrl.toString(), {
445
- method: "GET",
446
- headers: {
447
- "Accept": "application/json"
448
- }
449
- });
450
- if (!response.ok) {
451
- throw new Error(`Failed to sign URL: ${response.statusText}`);
452
- }
453
- const data = await response.json();
454
- const signedUrl = this.config.imageUrl + (data.urlWithSignature || data.url);
455
- this.cache.set(cacheKey, signedUrl);
456
- return signedUrl;
457
- } catch (error) {
458
- throw new Error(`Failed to get signed URL: ${error}`);
459
- }
460
- }
461
- checkRateLimits() {
462
- const now = Date.now();
463
- if (now >= this.rateLimitState.perMinute.resetTime) {
464
- this.rateLimitState.perMinute.count = 0;
465
- this.rateLimitState.perMinute.resetTime = now + 6e4;
466
- }
467
- if (now >= this.rateLimitState.perSecond.resetTime) {
468
- this.rateLimitState.perSecond.count = 0;
469
- this.rateLimitState.perSecond.resetTime = now + 1e3;
470
- }
471
- if (this.rateLimitState.perMinute.count >= RATE_LIMIT_PER_MINUTE) {
472
- throw new Error("Rate limit exceeded: Too many requests per minute");
473
- }
474
- if (this.rateLimitState.perSecond.count >= RATE_LIMIT_PER_SECOND) {
475
- throw new Error("Rate limit exceeded: Too many requests per second");
476
- }
477
- }
478
- incrementRateLimitCounters() {
479
- this.rateLimitState.perMinute.count++;
480
- this.rateLimitState.perSecond.count++;
481
- }
482
- getConfig() {
483
- return { ...this.config };
484
- }
485
- };
486
-
487
- // src/dev-fetcher.ts
488
- function createDevFetcher(baseUrl) {
489
- return async function devFetch(input, init) {
490
- const url = input.startsWith("http") ? input : `${baseUrl}${input}`;
491
- const res = await fetch(url, init);
492
- return res;
493
- };
494
- }
495
-
496
263
  // ../mockup-url/src/index.ts
264
+ var SNOWCONE_HOSTS = {
265
+ /** REST API: shops, orders, AI generation, realtime grants. */
266
+ api: "https://api.snowcone.app",
267
+ /** Public mockup-image resolver (`/{productCode}?shop=…&asset=…`). */
268
+ img: "https://img.snowcone.app",
269
+ /** Hosted buy page (same grammar as `img`, opens checkout). */
270
+ buy: "https://buy.snowcone.app",
271
+ /** Public product / designs catalog (Meilisearch-compatible). */
272
+ search: "https://search.snowcone.app",
273
+ /** Render CDN — signed render URLs and the realtime socket. */
274
+ cdn: "https://cdn.snowcone.app",
275
+ /** Legacy URL signer. */
276
+ sign: "https://s.snowcone.app",
277
+ /** Content-addressed artwork store (ingest handles). */
278
+ raws: "https://raws.snowcone.app",
279
+ /** Developer docs. */
280
+ docs: "https://developers.snowcone.app"
281
+ };
282
+ var SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, "ws")}/realtime`;
497
283
  var PARAMS = {
498
284
  shop: "shop",
499
285
  asset: "asset",
@@ -581,6 +367,7 @@ var ALLOWED_WIDTHS = [
581
367
  4e3
582
368
  ];
583
369
  var MAX_RENDER_URL_LENGTH = 12 * 1024;
370
+ var INGEST_HANDLE_BASE = `${SNOWCONE_HOSTS.raws}/art-ingest/`;
584
371
  function normalizeWidth(width) {
585
372
  for (let i = ALLOWED_WIDTHS.length - 1; i >= 0; i--) {
586
373
  if (ALLOWED_WIDTHS[i] <= width) return ALLOWED_WIDTHS[i];
@@ -665,7 +452,7 @@ var PARAM_PREFIX = {
665
452
  /** ADR-0099 bundles: `pick.<role>=<productCode>` — which alternative fills a slot. */
666
453
  pick: "pick."
667
454
  };
668
- var DEFAULT_PUBLIC_BASE_URL = "https://img.snowcone.app";
455
+ var DEFAULT_PUBLIC_BASE_URL = SNOWCONE_HOSTS.img;
669
456
  function buildPublicMockupUrl(options, cfg = {}) {
670
457
  const base = (cfg.baseUrl ?? DEFAULT_PUBLIC_BASE_URL).replace(/\/+$/, "");
671
458
  const path = `/${encodeURIComponent(options.productCode)}`;
@@ -771,6 +558,241 @@ function canonicalForSig(url) {
771
558
  return `${pathname}?${canonicalQuery}`;
772
559
  }
773
560
 
561
+ // src/mockup/cache.ts
562
+ var SignatureCache = class {
563
+ memoryCache = /* @__PURE__ */ new Map();
564
+ maxMemoryEntries;
565
+ maxLocalStorageEntries;
566
+ localStorageKey = "snowcone_signature_cache";
567
+ localStorageAvailable;
568
+ constructor(maxMemoryEntries = 500, maxLocalStorageEntries = 100) {
569
+ this.maxMemoryEntries = maxMemoryEntries;
570
+ this.maxLocalStorageEntries = maxLocalStorageEntries;
571
+ this.localStorageAvailable = this.checkLocalStorageAvailability();
572
+ if (this.localStorageAvailable) {
573
+ this.loadFromLocalStorage();
574
+ }
575
+ }
576
+ checkLocalStorageAvailability() {
577
+ try {
578
+ const test = "__storage_test__";
579
+ localStorage.setItem(test, test);
580
+ localStorage.removeItem(test);
581
+ return true;
582
+ } catch {
583
+ return false;
584
+ }
585
+ }
586
+ loadFromLocalStorage() {
587
+ try {
588
+ const stored = localStorage.getItem(this.localStorageKey);
589
+ if (stored) {
590
+ const parsed = JSON.parse(stored);
591
+ if (Array.isArray(parsed)) {
592
+ parsed.forEach(([key, value]) => {
593
+ if (this.memoryCache.size < this.maxMemoryEntries) {
594
+ this.memoryCache.set(key, value);
595
+ }
596
+ });
597
+ }
598
+ }
599
+ } catch (error) {
600
+ console.warn("Failed to load signature cache from localStorage:", error);
601
+ }
602
+ }
603
+ saveToLocalStorage() {
604
+ if (!this.localStorageAvailable) return;
605
+ try {
606
+ const entries = Array.from(this.memoryCache.entries()).sort((a, b) => b[1].timestamp - a[1].timestamp).slice(0, this.maxLocalStorageEntries);
607
+ localStorage.setItem(this.localStorageKey, JSON.stringify(entries));
608
+ } catch (error) {
609
+ console.warn("Failed to save signature cache to localStorage:", error);
610
+ this.localStorageAvailable = false;
611
+ }
612
+ }
613
+ get(key) {
614
+ const entry = this.memoryCache.get(key);
615
+ if (entry) {
616
+ entry.timestamp = Date.now();
617
+ this.memoryCache.delete(key);
618
+ this.memoryCache.set(key, entry);
619
+ return entry.url;
620
+ }
621
+ return null;
622
+ }
623
+ set(key, url) {
624
+ if (this.memoryCache.size >= this.maxMemoryEntries) {
625
+ const oldestKey = this.findOldestKey();
626
+ if (oldestKey) {
627
+ this.memoryCache.delete(oldestKey);
628
+ }
629
+ }
630
+ this.memoryCache.set(key, {
631
+ url,
632
+ timestamp: Date.now()
633
+ });
634
+ this.saveToLocalStorage();
635
+ }
636
+ findOldestKey() {
637
+ let oldestKey = null;
638
+ let oldestTime = Infinity;
639
+ for (const [key, entry] of this.memoryCache.entries()) {
640
+ if (entry.timestamp < oldestTime) {
641
+ oldestTime = entry.timestamp;
642
+ oldestKey = key;
643
+ }
644
+ }
645
+ return oldestKey;
646
+ }
647
+ clear() {
648
+ this.memoryCache.clear();
649
+ if (this.localStorageAvailable) {
650
+ try {
651
+ localStorage.removeItem(this.localStorageKey);
652
+ } catch (error) {
653
+ console.warn("Failed to clear localStorage cache:", error);
654
+ }
655
+ }
656
+ }
657
+ size() {
658
+ return this.memoryCache.size;
659
+ }
660
+ };
661
+
662
+ // src/mockup/service.ts
663
+ var DEFAULT_IMAGE_URL = typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || SNOWCONE_HOSTS.cdn;
664
+ var DEFAULT_SIGNER_URL = typeof process !== "undefined" && process.env?.SNOWCONE_SIGNER_URL || `${SNOWCONE_HOSTS.sign}/sign`;
665
+ var RATE_LIMIT_PER_MINUTE = 450;
666
+ var RATE_LIMIT_PER_SECOND = 20;
667
+ var MockupServiceImpl = class {
668
+ config;
669
+ cache;
670
+ rateLimitState;
671
+ fetch;
672
+ constructor(config, customFetch) {
673
+ this.config = {
674
+ imageUrl: config.imageUrl || DEFAULT_IMAGE_URL,
675
+ signerUrl: config.signerUrl || DEFAULT_SIGNER_URL,
676
+ shop: config.shop || typeof process !== "undefined" && process.env?.SNOWCONE_SHOP_ID || ""
677
+ };
678
+ this.cache = new SignatureCache();
679
+ this.fetch = customFetch || fetch.bind(globalThis);
680
+ this.rateLimitState = {
681
+ perMinute: { count: 0, resetTime: Date.now() + 6e4 },
682
+ perSecond: { count: 0, resetTime: Date.now() + 1e3 }
683
+ };
684
+ }
685
+ async getMockupUrl(options) {
686
+ if (!options.design || !options.product) {
687
+ throw new Error("Missing required options: design and product are required");
688
+ }
689
+ if (!this.config.shop) {
690
+ throw new Error("Shop ID is required for mockup generation");
691
+ }
692
+ for (const element of options.design) {
693
+ if (element.type === "image" && element.imageUrl) {
694
+ if (element.imageUrl.startsWith("blob:")) {
695
+ throw new Error(
696
+ `[snowcone-sdk] Cannot generate mockup: design element for placement "${element.placement}" uses a blob URL ("${element.imageUrl.slice(0, 60)}..."). Blob URLs are local to this browser tab and cannot be downloaded by the mockup rendering server. Upload the image to a publicly accessible URL or convert it to a data URL before requesting a mockup.`
697
+ );
698
+ }
699
+ }
700
+ }
701
+ this.checkRateLimits();
702
+ const relativeUrl = this.buildMockupUrlWithParams(options);
703
+ const cacheKey = `${relativeUrl}:${this.config.shop}`;
704
+ const cachedUrl = this.cache.get(cacheKey);
705
+ if (cachedUrl) {
706
+ return cachedUrl;
707
+ }
708
+ const signedUrl = await this.getSignedUrl(relativeUrl);
709
+ this.cache.set(cacheKey, signedUrl);
710
+ this.incrementRateLimitCounters();
711
+ return signedUrl;
712
+ }
713
+ buildMockupUrlWithParams(options) {
714
+ const { design, product, effects, ar } = options;
715
+ const designBase64 = typeof window !== "undefined" && window.btoa ? window.btoa(JSON.stringify(design)) : Buffer.from(JSON.stringify(design)).toString("base64");
716
+ const encodedDesign = encodeURIComponent(designBase64);
717
+ let url = `/mockup?productId=${encodeURIComponent(product.productId)}`;
718
+ url += `&mockupId=${encodeURIComponent(product.mockupId)}`;
719
+ url += `&variantId=${encodeURIComponent(product.variantId)}`;
720
+ url += `&design=${encodedDesign}`;
721
+ url += `&width=${product.width}`;
722
+ if (effects?.grain) {
723
+ url += `&grain=${effects.grain}`;
724
+ }
725
+ if (ar && ar !== "16:9") {
726
+ url += `&ar=${encodeURIComponent(ar)}`;
727
+ }
728
+ if (product.optionSelections && Object.keys(product.optionSelections).length > 0) {
729
+ const optionSelectionsBase64 = typeof window !== "undefined" && window.btoa ? window.btoa(JSON.stringify(product.optionSelections)) : Buffer.from(JSON.stringify(product.optionSelections)).toString("base64");
730
+ url += `&optionSelections=${encodeURIComponent(optionSelectionsBase64)}`;
731
+ }
732
+ return url;
733
+ }
734
+ async getSignedUrl(relativeUrl) {
735
+ const urlWithAccountId = relativeUrl + (relativeUrl.includes("?") ? "&" : "?") + `shop=${encodeURIComponent(this.config.shop)}`;
736
+ const cacheKey = urlWithAccountId;
737
+ const cachedUrl = this.cache.get(cacheKey);
738
+ if (cachedUrl) {
739
+ return cachedUrl;
740
+ }
741
+ const signerUrl = new URL(this.config.signerUrl);
742
+ signerUrl.searchParams.set("url", urlWithAccountId);
743
+ try {
744
+ const response = await this.fetch(signerUrl.toString(), {
745
+ method: "GET",
746
+ headers: {
747
+ "Accept": "application/json"
748
+ }
749
+ });
750
+ if (!response.ok) {
751
+ throw new Error(`Failed to sign URL: ${response.statusText}`);
752
+ }
753
+ const data = await response.json();
754
+ const signedUrl = this.config.imageUrl + (data.urlWithSignature || data.url);
755
+ this.cache.set(cacheKey, signedUrl);
756
+ return signedUrl;
757
+ } catch (error) {
758
+ throw new Error(`Failed to get signed URL: ${error}`);
759
+ }
760
+ }
761
+ checkRateLimits() {
762
+ const now = Date.now();
763
+ if (now >= this.rateLimitState.perMinute.resetTime) {
764
+ this.rateLimitState.perMinute.count = 0;
765
+ this.rateLimitState.perMinute.resetTime = now + 6e4;
766
+ }
767
+ if (now >= this.rateLimitState.perSecond.resetTime) {
768
+ this.rateLimitState.perSecond.count = 0;
769
+ this.rateLimitState.perSecond.resetTime = now + 1e3;
770
+ }
771
+ if (this.rateLimitState.perMinute.count >= RATE_LIMIT_PER_MINUTE) {
772
+ throw new Error("Rate limit exceeded: Too many requests per minute");
773
+ }
774
+ if (this.rateLimitState.perSecond.count >= RATE_LIMIT_PER_SECOND) {
775
+ throw new Error("Rate limit exceeded: Too many requests per second");
776
+ }
777
+ }
778
+ incrementRateLimitCounters() {
779
+ this.rateLimitState.perMinute.count++;
780
+ this.rateLimitState.perSecond.count++;
781
+ }
782
+ getConfig() {
783
+ return { ...this.config };
784
+ }
785
+ };
786
+
787
+ // src/dev-fetcher.ts
788
+ function createDevFetcher(baseUrl) {
789
+ return async function devFetch(input, init) {
790
+ const url = input.startsWith("http") ? input : `${baseUrl}${input}`;
791
+ const res = await fetch(url, init);
792
+ return res;
793
+ };
794
+ }
795
+
774
796
  // src/mockup/hmac.ts
775
797
  var K = new Uint32Array([
776
798
  1116352408,
@@ -982,7 +1004,7 @@ function hmacSha256Hex(secret, message) {
982
1004
  }
983
1005
 
984
1006
  // src/mockup/getMockupUrl.ts
985
- var DEFAULT_MOCKUP_BASE = "https://img.snowcone.app";
1007
+ var DEFAULT_MOCKUP_BASE = SNOWCONE_HOSTS.img;
986
1008
  function getMockupUrl(a, b, c) {
987
1009
  let productCode;
988
1010
  let opts;
@@ -1022,7 +1044,7 @@ function getMockupUrl(a, b, c) {
1022
1044
  const signature = hmacSha256Hex(opts.secret, canonicalForSig(url)).slice(0, 16);
1023
1045
  return `${url}&signature=${signature}`;
1024
1046
  }
1025
- var DEFAULT_BUY_BASE = "https://buy.snowcone.app";
1047
+ var DEFAULT_BUY_BASE = SNOWCONE_HOSTS.buy;
1026
1048
  function getBuyUrl(productCode, opts) {
1027
1049
  return getMockupUrl(productCode, {
1028
1050
  ...opts,
@@ -1937,7 +1959,7 @@ function buildMockupUrl2(options, cfg) {
1937
1959
  }
1938
1960
  function resolveMockupBaseUrl() {
1939
1961
  const winConfig = typeof window !== "undefined" && window.snowcone || {};
1940
- return winConfig.resolver || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MOCKUP_RESOLVER_URL || typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || "https://img.snowcone.app";
1962
+ return winConfig.resolver || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MOCKUP_RESOLVER_URL || typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || SNOWCONE_HOSTS.img;
1941
1963
  }
1942
1964
  function resolveShop() {
1943
1965
  const winConfig = typeof window !== "undefined" && window.snowcone || {};
@@ -5072,7 +5094,7 @@ function createSvelteComponent(descriptor, svelte) {
5072
5094
  }
5073
5095
 
5074
5096
  // src/realtime/constants.ts
5075
- var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
5097
+ var REALTIME_WS_URL = SNOWCONE_REALTIME_WS_URL;
5076
5098
 
5077
5099
  // src/realtime/websocket.ts
5078
5100
  function pruneUndefined(obj) {
@@ -5443,17 +5465,23 @@ var RealtimeMockupService = class {
5443
5465
  }
5444
5466
  return true;
5445
5467
  });
5446
- const batch = freshMockups.map((mockup) => {
5468
+ const batch = freshMockups.flatMap((mockup) => {
5447
5469
  const existing = this.mockupResults.find(
5448
5470
  (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
5449
5471
  );
5450
- if (!existing) return mockup;
5472
+ if (!existing) {
5473
+ if (!mockup.imageUrl) {
5474
+ const held = this.mockupResults.find((m) => m.mockupId === mockup.mockupId && m.imageUrl);
5475
+ return held ? [held] : [];
5476
+ }
5477
+ return [mockup];
5478
+ }
5451
5479
  const merged = { ...existing, ...pruneUndefined(mockup) };
5452
5480
  if (existing.imageUrl.startsWith("blob:")) {
5453
5481
  merged.imageUrl = existing.imageUrl;
5454
5482
  merged.renderUrl = existing.renderUrl;
5455
5483
  }
5456
- return merged;
5484
+ return [merged];
5457
5485
  });
5458
5486
  const batchById = new Map(batch.map((m) => [m.mockupId, m]));
5459
5487
  this.mockupResults = [
@@ -6057,7 +6085,7 @@ ${versionToSend}
6057
6085
  };
6058
6086
 
6059
6087
  // src/realtime/grant.ts
6060
- var DEFAULT_GRANT_BASE = "https://api.snowcone.app";
6088
+ var DEFAULT_GRANT_BASE = SNOWCONE_HOSTS.api;
6061
6089
  async function mintRealtimeGrant(opts) {
6062
6090
  const f = opts.fetch ?? globalThis.fetch;
6063
6091
  const headers = { "Content-Type": "application/json" };
@@ -6541,7 +6569,7 @@ function validateProductLoose(product) {
6541
6569
  }
6542
6570
  async function listProducts(config) {
6543
6571
  const f = getFetcher(config);
6544
- const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
6572
+ const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
6545
6573
  const meilisearchApiKey = config?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
6546
6574
  const meilisearchIndex = config?.meilisearch?.index || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_INDEX || "snowcone";
6547
6575
  const headers = {
@@ -6567,7 +6595,7 @@ async function listProducts(config) {
6567
6595
  }
6568
6596
  async function getProduct(idOrSlug, config) {
6569
6597
  const f = getFetcher(config);
6570
- const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
6598
+ const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
6571
6599
  const meilisearchApiKey = config?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
6572
6600
  const meilisearchIndex = config?.meilisearch?.index || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_INDEX || "snowcone";
6573
6601
  const headers = {
@@ -6591,7 +6619,7 @@ async function getProduct(idOrSlug, config) {
6591
6619
  }
6592
6620
  async function searchDesigns(query = "", options) {
6593
6621
  const f = getFetcher(options);
6594
- const meilisearchHost = options?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
6622
+ const meilisearchHost = options?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
6595
6623
  const meilisearchApiKey = options?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
6596
6624
  const designsIndex = options?.meilisearch?.designsIndex || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_DESIGNS_INDEX || "snowcone-designs";
6597
6625
  const headers = {
@@ -6678,6 +6706,8 @@ function createClient(config) {
6678
6706
  RealtimeMockupService,
6679
6707
  RenderSession,
6680
6708
  SIZE_PICTURE,
6709
+ SNOWCONE_HOSTS,
6710
+ SNOWCONE_REALTIME_WS_URL,
6681
6711
  SnowconeSdkError,
6682
6712
  StandardComponents,
6683
6713
  StandardEvents,
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { createDevFetcher } from './dev-fetcher.cjs';
2
2
  import { PublicDesign, PublicFill, PublicOptions } from '@snowcone-app/mockup-url';
3
+ export { SNOWCONE_HOSTS, SNOWCONE_REALTIME_WS_URL, SnowconeHostRole } from '@snowcone-app/mockup-url';
3
4
  export { GalleryReason, GalleryStanding, MockupRole, OrdinaryMockups, PDP_GALLERY_LIMIT, SIZE_PICTURE, gallerySizePicture, galleryStanding, mockupRole, ordinaryMockups, pictureForVariant, primaryMockup } from './mockup-role.cjs';
4
5
  import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-CvN0UU2j.cjs';
5
6
  export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-CvN0UU2j.cjs';
@@ -297,7 +298,7 @@ interface RateLimitState {
297
298
  }
298
299
 
299
300
  /** Default public host for the image-CDN model (ADR-0076). */
300
- declare const DEFAULT_MOCKUP_BASE = "https://img.snowcone.app";
301
+ declare const DEFAULT_MOCKUP_BASE: string;
301
302
  /**
302
303
  * What fills one placement, re-exported from `@snowcone-app/mockup-url`:
303
304
  * - a bare `string` → an image URL (shorthand for `{ src }`),
@@ -364,7 +365,7 @@ interface GetMockupUrlOptions {
364
365
  * verifies it.
365
366
  */
366
367
  secret?: string;
367
- /** Override the public host. Default: `https://img.snowcone.app`. */
368
+ /** Override the public host. Default: `SNOWCONE_HOSTS.img`. */
368
369
  base?: string;
369
370
  /**
370
371
  * Render width in px. Snaps DOWN to the nearest allowed size
@@ -417,7 +418,7 @@ interface GetMockupUrlOptions {
417
418
  declare function getMockupUrl(productCode: string, opts: GetMockupUrlOptions): string;
418
419
  declare function getMockupUrl(assetUrl: string, productCode: string, opts: GetMockupUrlOptions): string;
419
420
  /** Default public host for the hosted buy page. */
420
- declare const DEFAULT_BUY_BASE = "https://buy.snowcone.app";
421
+ declare const DEFAULT_BUY_BASE: string;
421
422
  /**
422
423
  * Build the hosted buy-page URL — the checkout counterpart of
423
424
  * {@link getMockupUrl}. Same wire grammar, same options shape, different host:
@@ -1023,7 +1024,7 @@ type UserSelection = Record<string, string>;
1023
1024
  * Config for the pure URL builder: the two things not on MockupGenerationOptions.
1024
1025
  */
1025
1026
  interface BuildMockupUrlConfig {
1026
- /** Base of the public-image RESOLVER, e.g. https://img.snowcone.app (it
1027
+ /** Base of the public-image RESOLVER, e.g. `SNOWCONE_HOSTS.img` (it
1027
1028
  * seals the URL and 302s to the renderer). NOT the renderer host. */
1028
1029
  mockupBaseUrl: string;
1029
1030
  /** The shop's public Shop ID (= shop.id). */
@@ -2802,7 +2803,7 @@ declare function createSvelteComponent(descriptor: ComponentDescriptor, svelte:
2802
2803
  * `wss://WS_URL_NOT_CONFIGURED.invalid/realtime` placeholder so a 3rd party
2803
2804
  * can find the endpoint from the package alone (ADR-0079, Phase 2).
2804
2805
  */
2805
- declare const REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
2806
+ declare const REALTIME_WS_URL: string;
2806
2807
 
2807
2808
  /**
2808
2809
  * Realtime grant helpers (ADR-0079, Phase 2).
@@ -2824,7 +2825,7 @@ interface RealtimeGrant {
2824
2825
  expiresAt: number;
2825
2826
  }
2826
2827
  /** Default backend base URL hosting `POST /realtime/grant`. */
2827
- declare const DEFAULT_GRANT_BASE = "https://api.snowcone.app";
2828
+ declare const DEFAULT_GRANT_BASE: string;
2828
2829
  /**
2829
2830
  * SERVER-SIDE: mint a realtime grant with a secret API key (sk_). Call this
2830
2831
  * from YOUR backend — never the browser; the API key must stay secret. The key
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { createDevFetcher } from './dev-fetcher.js';
2
2
  import { PublicDesign, PublicFill, PublicOptions } from '@snowcone-app/mockup-url';
3
+ export { SNOWCONE_HOSTS, SNOWCONE_REALTIME_WS_URL, SnowconeHostRole } from '@snowcone-app/mockup-url';
3
4
  export { GalleryReason, GalleryStanding, MockupRole, OrdinaryMockups, PDP_GALLERY_LIMIT, SIZE_PICTURE, gallerySizePicture, galleryStanding, mockupRole, ordinaryMockups, pictureForVariant, primaryMockup } from './mockup-role.js';
4
5
  import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-CvN0UU2j.js';
5
6
  export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-CvN0UU2j.js';
@@ -297,7 +298,7 @@ interface RateLimitState {
297
298
  }
298
299
 
299
300
  /** Default public host for the image-CDN model (ADR-0076). */
300
- declare const DEFAULT_MOCKUP_BASE = "https://img.snowcone.app";
301
+ declare const DEFAULT_MOCKUP_BASE: string;
301
302
  /**
302
303
  * What fills one placement, re-exported from `@snowcone-app/mockup-url`:
303
304
  * - a bare `string` → an image URL (shorthand for `{ src }`),
@@ -364,7 +365,7 @@ interface GetMockupUrlOptions {
364
365
  * verifies it.
365
366
  */
366
367
  secret?: string;
367
- /** Override the public host. Default: `https://img.snowcone.app`. */
368
+ /** Override the public host. Default: `SNOWCONE_HOSTS.img`. */
368
369
  base?: string;
369
370
  /**
370
371
  * Render width in px. Snaps DOWN to the nearest allowed size
@@ -417,7 +418,7 @@ interface GetMockupUrlOptions {
417
418
  declare function getMockupUrl(productCode: string, opts: GetMockupUrlOptions): string;
418
419
  declare function getMockupUrl(assetUrl: string, productCode: string, opts: GetMockupUrlOptions): string;
419
420
  /** Default public host for the hosted buy page. */
420
- declare const DEFAULT_BUY_BASE = "https://buy.snowcone.app";
421
+ declare const DEFAULT_BUY_BASE: string;
421
422
  /**
422
423
  * Build the hosted buy-page URL — the checkout counterpart of
423
424
  * {@link getMockupUrl}. Same wire grammar, same options shape, different host:
@@ -1023,7 +1024,7 @@ type UserSelection = Record<string, string>;
1023
1024
  * Config for the pure URL builder: the two things not on MockupGenerationOptions.
1024
1025
  */
1025
1026
  interface BuildMockupUrlConfig {
1026
- /** Base of the public-image RESOLVER, e.g. https://img.snowcone.app (it
1027
+ /** Base of the public-image RESOLVER, e.g. `SNOWCONE_HOSTS.img` (it
1027
1028
  * seals the URL and 302s to the renderer). NOT the renderer host. */
1028
1029
  mockupBaseUrl: string;
1029
1030
  /** The shop's public Shop ID (= shop.id). */
@@ -2802,7 +2803,7 @@ declare function createSvelteComponent(descriptor: ComponentDescriptor, svelte:
2802
2803
  * `wss://WS_URL_NOT_CONFIGURED.invalid/realtime` placeholder so a 3rd party
2803
2804
  * can find the endpoint from the package alone (ADR-0079, Phase 2).
2804
2805
  */
2805
- declare const REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
2806
+ declare const REALTIME_WS_URL: string;
2806
2807
 
2807
2808
  /**
2808
2809
  * Realtime grant helpers (ADR-0079, Phase 2).
@@ -2824,7 +2825,7 @@ interface RealtimeGrant {
2824
2825
  expiresAt: number;
2825
2826
  }
2826
2827
  /** Default backend base URL hosting `POST /realtime/grant`. */
2827
- declare const DEFAULT_GRANT_BASE = "https://api.snowcone.app";
2828
+ declare const DEFAULT_GRANT_BASE: string;
2828
2829
  /**
2829
2830
  * SERVER-SIDE: mint a realtime grant with a secret API key (sk_). Call this
2830
2831
  * from YOUR backend — never the browser; the API key must stay secret. The key
package/dist/index.js CHANGED
@@ -1,17 +1,19 @@
1
1
  import {
2
2
  REALTIME_WS_URL,
3
3
  RealtimeMockupService
4
- } from "./chunk-IW7DXXGY.js";
4
+ } from "./chunk-ATN2PYRL.js";
5
5
  import {
6
6
  createDevFetcher
7
7
  } from "./chunk-7VO4EL2V.js";
8
8
  import {
9
+ SNOWCONE_HOSTS,
10
+ SNOWCONE_REALTIME_WS_URL,
9
11
  buildMockupUrl,
10
12
  buildPublicMockupUrl,
11
13
  canonicalForSig,
12
14
  normalizeDesignElements,
13
15
  normalizeWidth
14
- } from "./chunk-ZBJBBIH3.js";
16
+ } from "./chunk-5HX26XOJ.js";
15
17
  import {
16
18
  PDP_GALLERY_LIMIT,
17
19
  SIZE_PICTURE,
@@ -213,8 +215,8 @@ var SignatureCache = class {
213
215
  };
214
216
 
215
217
  // src/mockup/service.ts
216
- var DEFAULT_IMAGE_URL = typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || "https://cdn.snowcone.app";
217
- var DEFAULT_SIGNER_URL = typeof process !== "undefined" && process.env?.SNOWCONE_SIGNER_URL || "https://s.snowcone.app/sign";
218
+ var DEFAULT_IMAGE_URL = typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || SNOWCONE_HOSTS.cdn;
219
+ var DEFAULT_SIGNER_URL = typeof process !== "undefined" && process.env?.SNOWCONE_SIGNER_URL || `${SNOWCONE_HOSTS.sign}/sign`;
218
220
  var RATE_LIMIT_PER_MINUTE = 450;
219
221
  var RATE_LIMIT_PER_SECOND = 20;
220
222
  var MockupServiceImpl = class {
@@ -548,7 +550,7 @@ function hmacSha256Hex(secret, message) {
548
550
  }
549
551
 
550
552
  // src/mockup/getMockupUrl.ts
551
- var DEFAULT_MOCKUP_BASE = "https://img.snowcone.app";
553
+ var DEFAULT_MOCKUP_BASE = SNOWCONE_HOSTS.img;
552
554
  function getMockupUrl(a, b, c) {
553
555
  let productCode;
554
556
  let opts;
@@ -588,7 +590,7 @@ function getMockupUrl(a, b, c) {
588
590
  const signature = hmacSha256Hex(opts.secret, canonicalForSig(url)).slice(0, 16);
589
591
  return `${url}&signature=${signature}`;
590
592
  }
591
- var DEFAULT_BUY_BASE = "https://buy.snowcone.app";
593
+ var DEFAULT_BUY_BASE = SNOWCONE_HOSTS.buy;
592
594
  function getBuyUrl(productCode, opts) {
593
595
  return getMockupUrl(productCode, {
594
596
  ...opts,
@@ -1464,7 +1466,7 @@ function buildMockupUrl2(options, cfg) {
1464
1466
  }
1465
1467
  function resolveMockupBaseUrl() {
1466
1468
  const winConfig = typeof window !== "undefined" && window.snowcone || {};
1467
- return winConfig.resolver || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MOCKUP_RESOLVER_URL || typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || "https://img.snowcone.app";
1469
+ return winConfig.resolver || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MOCKUP_RESOLVER_URL || typeof process !== "undefined" && process.env?.SNOWCONE_IMAGE_URL || SNOWCONE_HOSTS.img;
1468
1470
  }
1469
1471
  function resolveShop() {
1470
1472
  const winConfig = typeof window !== "undefined" && window.snowcone || {};
@@ -4599,7 +4601,7 @@ function createSvelteComponent(descriptor, svelte) {
4599
4601
  }
4600
4602
 
4601
4603
  // src/realtime/grant.ts
4602
- var DEFAULT_GRANT_BASE = "https://api.snowcone.app";
4604
+ var DEFAULT_GRANT_BASE = SNOWCONE_HOSTS.api;
4603
4605
  async function mintRealtimeGrant(opts) {
4604
4606
  const f = opts.fetch ?? globalThis.fetch;
4605
4607
  const headers = { "Content-Type": "application/json" };
@@ -5083,7 +5085,7 @@ function validateProductLoose(product) {
5083
5085
  }
5084
5086
  async function listProducts(config) {
5085
5087
  const f = getFetcher(config);
5086
- const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
5088
+ const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
5087
5089
  const meilisearchApiKey = config?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
5088
5090
  const meilisearchIndex = config?.meilisearch?.index || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_INDEX || "snowcone";
5089
5091
  const headers = {
@@ -5109,7 +5111,7 @@ async function listProducts(config) {
5109
5111
  }
5110
5112
  async function getProduct(idOrSlug, config) {
5111
5113
  const f = getFetcher(config);
5112
- const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
5114
+ const meilisearchHost = config?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
5113
5115
  const meilisearchApiKey = config?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
5114
5116
  const meilisearchIndex = config?.meilisearch?.index || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_INDEX || "snowcone";
5115
5117
  const headers = {
@@ -5133,7 +5135,7 @@ async function getProduct(idOrSlug, config) {
5133
5135
  }
5134
5136
  async function searchDesigns(query = "", options) {
5135
5137
  const f = getFetcher(options);
5136
- const meilisearchHost = options?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || "https://search.snowcone.app";
5138
+ const meilisearchHost = options?.meilisearch?.host || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_HOST || SNOWCONE_HOSTS.search;
5137
5139
  const meilisearchApiKey = options?.meilisearch?.apiKey || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_API_KEY || "73f573ead9be75531c56ee89d104caa49d79154db387f119a013d33eccfe654b";
5138
5140
  const designsIndex = options?.meilisearch?.designsIndex || typeof process !== "undefined" && process.env?.NEXT_PUBLIC_MEILISEARCH_DESIGNS_INDEX || "snowcone-designs";
5139
5141
  const headers = {
@@ -5219,6 +5221,8 @@ export {
5219
5221
  RealtimeMockupService,
5220
5222
  RenderSession,
5221
5223
  SIZE_PICTURE,
5224
+ SNOWCONE_HOSTS,
5225
+ SNOWCONE_REALTIME_WS_URL,
5222
5226
  SnowconeSdkError,
5223
5227
  StandardComponents,
5224
5228
  StandardEvents,
package/dist/react.cjs CHANGED
@@ -32,8 +32,93 @@ module.exports = __toCommonJS(react_exports);
32
32
  // src/realtime/react.ts
33
33
  var import_react = require("react");
34
34
 
35
+ // ../mockup-url/src/index.ts
36
+ var SNOWCONE_HOSTS = {
37
+ /** REST API: shops, orders, AI generation, realtime grants. */
38
+ api: "https://api.snowcone.app",
39
+ /** Public mockup-image resolver (`/{productCode}?shop=…&asset=…`). */
40
+ img: "https://img.snowcone.app",
41
+ /** Hosted buy page (same grammar as `img`, opens checkout). */
42
+ buy: "https://buy.snowcone.app",
43
+ /** Public product / designs catalog (Meilisearch-compatible). */
44
+ search: "https://search.snowcone.app",
45
+ /** Render CDN — signed render URLs and the realtime socket. */
46
+ cdn: "https://cdn.snowcone.app",
47
+ /** Legacy URL signer. */
48
+ sign: "https://s.snowcone.app",
49
+ /** Content-addressed artwork store (ingest handles). */
50
+ raws: "https://raws.snowcone.app",
51
+ /** Developer docs. */
52
+ docs: "https://developers.snowcone.app"
53
+ };
54
+ var SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, "ws")}/realtime`;
55
+ var PARAMS = {
56
+ shop: "shop",
57
+ asset: "asset",
58
+ assets: "assets",
59
+ /**
60
+ * Render a catalog design by reference (ADR-0086): `design=<pairingId|slug>`.
61
+ * The resolver looks the design up in the public `snowcone-designs` index
62
+ * (membership = license) and injects its asset components server-side, so no
63
+ * raw asset URL crosses the wire and no origin allowlisting is involved.
64
+ * Catalog renders are FREE — mutually exclusive with `asset`/`asset.<key>`/
65
+ * `color.<key>` (free = the design as published).
66
+ */
67
+ design: "design",
68
+ placement: "placement",
69
+ /**
70
+ * Album page selector (ADR-0086 §5): `page=N` (positive integer) picks which
71
+ * page/spread of an album product a mockup renders. Only valid on products
72
+ * whose catalog entry carries an `album` block — the edge resolver maps page
73
+ * N onto the repeating page placement (`page_N` → the geometry of
74
+ * `album.pagePlacement`); the catalog never enumerates `page_1…page_100` and
75
+ * the render server is unchanged.
76
+ */
77
+ page: "page",
78
+ variant: "variant",
79
+ mockup: "mockup",
80
+ width: "width",
81
+ grain: "grain",
82
+ aspect: "aspect",
83
+ /**
84
+ * Background color (6-hex, no '#') painted behind the mockup — visible only
85
+ * where the mockup itself has transparency (studio-cutout shots) — or the
86
+ * reserved `transparent` token, which suppresses the shop default for this
87
+ * one render. Absent = the shop's configured default, else transparent.
88
+ */
89
+ bg: "bg",
90
+ /** Live preview/calibration mask overrides (not cached). */
91
+ maskOverrides: "maskOverrides",
92
+ /**
93
+ * Render-only option picks (the `affectsCombinations:false` attributes), as a
94
+ * base64 JSON map `{ attributeName: choiceLabel }`. The render server already parses
95
+ * this and resolves per-choice underlays from it; the builder emits it so the
96
+ * edge resolver can forward render-only picks (e.g. a cap's Crown/Strap color)
97
+ * without changing the server grammar.
98
+ */
99
+ optionSelections: "optionSelections",
100
+ signature: "signature",
101
+ seal: "seal"
102
+ };
103
+ var MAX_RENDER_URL_LENGTH = 12 * 1024;
104
+ var INGEST_HANDLE_BASE = `${SNOWCONE_HOSTS.raws}/art-ingest/`;
105
+ var DEFAULT_PUBLIC_BASE_URL = SNOWCONE_HOSTS.img;
106
+ var PUBLIC_PARAM_NAMES = [
107
+ PARAMS.asset,
108
+ PARAMS.design,
109
+ PARAMS.shop,
110
+ PARAMS.placement,
111
+ PARAMS.page,
112
+ PARAMS.variant,
113
+ PARAMS.mockup,
114
+ PARAMS.width,
115
+ PARAMS.aspect,
116
+ PARAMS.bg,
117
+ PARAMS.signature
118
+ ];
119
+
35
120
  // src/realtime/constants.ts
36
- var REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
121
+ var REALTIME_WS_URL = SNOWCONE_REALTIME_WS_URL;
37
122
 
38
123
  // src/realtime/websocket.ts
39
124
  function pruneUndefined(obj) {
@@ -404,17 +489,23 @@ var RealtimeMockupService = class {
404
489
  }
405
490
  return true;
406
491
  });
407
- const batch = freshMockups.map((mockup) => {
492
+ const batch = freshMockups.flatMap((mockup) => {
408
493
  const existing = this.mockupResults.find(
409
494
  (m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
410
495
  );
411
- if (!existing) return mockup;
496
+ if (!existing) {
497
+ if (!mockup.imageUrl) {
498
+ const held = this.mockupResults.find((m) => m.mockupId === mockup.mockupId && m.imageUrl);
499
+ return held ? [held] : [];
500
+ }
501
+ return [mockup];
502
+ }
412
503
  const merged = { ...existing, ...pruneUndefined(mockup) };
413
504
  if (existing.imageUrl.startsWith("blob:")) {
414
505
  merged.imageUrl = existing.imageUrl;
415
506
  merged.renderUrl = existing.renderUrl;
416
507
  }
417
- return merged;
508
+ return [merged];
418
509
  });
419
510
  const batchById = new Map(batch.map((m) => [m.mockupId, m]));
420
511
  this.mockupResults = [
@@ -1018,7 +1109,7 @@ ${versionToSend}
1018
1109
  };
1019
1110
 
1020
1111
  // src/realtime/react.ts
1021
- var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
1112
+ var DEFAULT_REALTIME_WS_URL = REALTIME_WS_URL;
1022
1113
  function useRealtimeMockup(options = {}) {
1023
1114
  const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
1024
1115
  const serviceRef = (0, import_react.useRef)(null);
package/dist/react.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import {
2
+ REALTIME_WS_URL,
2
3
  RealtimeMockupService
3
- } from "./chunk-IW7DXXGY.js";
4
+ } from "./chunk-ATN2PYRL.js";
5
+ import "./chunk-5HX26XOJ.js";
4
6
 
5
7
  // src/realtime/react.ts
6
8
  import { useCallback, useEffect, useRef, useState } from "react";
7
- var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
9
+ var DEFAULT_REALTIME_WS_URL = REALTIME_WS_URL;
8
10
  function useRealtimeMockup(options = {}) {
9
11
  const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
10
12
  const serviceRef = useRef(null);
package/dist/server.cjs CHANGED
@@ -32,6 +32,25 @@ __export(server_exports, {
32
32
  module.exports = __toCommonJS(server_exports);
33
33
 
34
34
  // ../mockup-url/src/index.ts
35
+ var SNOWCONE_HOSTS = {
36
+ /** REST API: shops, orders, AI generation, realtime grants. */
37
+ api: "https://api.snowcone.app",
38
+ /** Public mockup-image resolver (`/{productCode}?shop=…&asset=…`). */
39
+ img: "https://img.snowcone.app",
40
+ /** Hosted buy page (same grammar as `img`, opens checkout). */
41
+ buy: "https://buy.snowcone.app",
42
+ /** Public product / designs catalog (Meilisearch-compatible). */
43
+ search: "https://search.snowcone.app",
44
+ /** Render CDN — signed render URLs and the realtime socket. */
45
+ cdn: "https://cdn.snowcone.app",
46
+ /** Legacy URL signer. */
47
+ sign: "https://s.snowcone.app",
48
+ /** Content-addressed artwork store (ingest handles). */
49
+ raws: "https://raws.snowcone.app",
50
+ /** Developer docs. */
51
+ docs: "https://developers.snowcone.app"
52
+ };
53
+ var SNOWCONE_REALTIME_WS_URL = `${SNOWCONE_HOSTS.cdn.replace(/^http/, "ws")}/realtime`;
35
54
  var PARAMS = {
36
55
  shop: "shop",
37
56
  asset: "asset",
@@ -81,6 +100,8 @@ var PARAMS = {
81
100
  seal: "seal"
82
101
  };
83
102
  var MAX_RENDER_URL_LENGTH = 12 * 1024;
103
+ var INGEST_HANDLE_BASE = `${SNOWCONE_HOSTS.raws}/art-ingest/`;
104
+ var DEFAULT_PUBLIC_BASE_URL = SNOWCONE_HOSTS.img;
84
105
  var PUBLIC_PARAM_NAMES = [
85
106
  PARAMS.asset,
86
107
  PARAMS.design,
@@ -202,7 +223,7 @@ async function signGrantRequest(shop, secret) {
202
223
  return { shop, ts, signature };
203
224
  }
204
225
  function createRealtimeGrantHandler(opts) {
205
- const base = opts.base ?? "https://api.snowcone.app";
226
+ const base = opts.base ?? SNOWCONE_HOSTS.api;
206
227
  return async function POST(req) {
207
228
  if (opts.gate) {
208
229
  const result = await opts.gate(req);
@@ -422,7 +443,7 @@ function createImageSearchHandler(opts) {
422
443
  }
423
444
  var BG_REMOVE_MAX_URL_LENGTH = 2048;
424
445
  function createBgRemoveHandler(opts) {
425
- const base = opts.base ?? "https://api.snowcone.app";
446
+ const base = opts.base ?? SNOWCONE_HOSTS.api;
426
447
  return async function POST(req) {
427
448
  if (opts.gate) {
428
449
  const result = await opts.gate(req);
package/dist/server.d.cts CHANGED
@@ -78,7 +78,7 @@ interface RealtimeGrantHandlerOptions {
78
78
  secret: string;
79
79
  /** The shop to mint grants for (= shop.id). */
80
80
  shop: string;
81
- /** Backend base URL hosting `POST /realtime/grant`. Default api.snowcone.app. */
81
+ /** Backend base URL hosting `POST /realtime/grant`. Default `SNOWCONE_HOSTS.api`. */
82
82
  base?: string;
83
83
  /** Optional gate (auth / rate-limit) run before minting. */
84
84
  gate?: SignGate;
@@ -174,7 +174,7 @@ interface BgRemoveHandlerOptions {
174
174
  * Server-only — the browser only ever sees this route. Required.
175
175
  */
176
176
  shopKey: string;
177
- /** Backend base URL hosting `POST /ai-generations/remove-background`. Default api.snowcone.app. */
177
+ /** Backend base URL hosting `POST /ai-generations/remove-background`. Default `SNOWCONE_HOSTS.api`. */
178
178
  base?: string;
179
179
  /** Optional auth / rate-limit / bot check, same SignGate type as the other handlers. */
180
180
  gate?: SignGate;
package/dist/server.d.ts CHANGED
@@ -78,7 +78,7 @@ interface RealtimeGrantHandlerOptions {
78
78
  secret: string;
79
79
  /** The shop to mint grants for (= shop.id). */
80
80
  shop: string;
81
- /** Backend base URL hosting `POST /realtime/grant`. Default api.snowcone.app. */
81
+ /** Backend base URL hosting `POST /realtime/grant`. Default `SNOWCONE_HOSTS.api`. */
82
82
  base?: string;
83
83
  /** Optional gate (auth / rate-limit) run before minting. */
84
84
  gate?: SignGate;
@@ -174,7 +174,7 @@ interface BgRemoveHandlerOptions {
174
174
  * Server-only — the browser only ever sees this route. Required.
175
175
  */
176
176
  shopKey: string;
177
- /** Backend base URL hosting `POST /ai-generations/remove-background`. Default api.snowcone.app. */
177
+ /** Backend base URL hosting `POST /ai-generations/remove-background`. Default `SNOWCONE_HOSTS.api`. */
178
178
  base?: string;
179
179
  /** Optional auth / rate-limit / bot check, same SignGate type as the other handlers. */
180
180
  gate?: SignGate;
package/dist/server.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
+ SNOWCONE_HOSTS,
2
3
  canonicalForSig,
3
4
  signDevSig
4
- } from "./chunk-ZBJBBIH3.js";
5
+ } from "./chunk-5HX26XOJ.js";
5
6
 
6
7
  // src/server.ts
7
8
  function json(body, status = 200) {
@@ -59,7 +60,7 @@ async function signGrantRequest(shop, secret) {
59
60
  return { shop, ts, signature };
60
61
  }
61
62
  function createRealtimeGrantHandler(opts) {
62
- const base = opts.base ?? "https://api.snowcone.app";
63
+ const base = opts.base ?? SNOWCONE_HOSTS.api;
63
64
  return async function POST(req) {
64
65
  if (opts.gate) {
65
66
  const result = await opts.gate(req);
@@ -279,7 +280,7 @@ function createImageSearchHandler(opts) {
279
280
  }
280
281
  var BG_REMOVE_MAX_URL_LENGTH = 2048;
281
282
  function createBgRemoveHandler(opts) {
282
- const base = opts.base ?? "https://api.snowcone.app";
283
+ const base = opts.base ?? SNOWCONE_HOSTS.api;
283
284
  return async function POST(req) {
284
285
  if (opts.gate) {
285
286
  const result = await opts.gate(req);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/sdk",
3
- "version": "0.29.0",
3
+ "version": "0.30.0",
4
4
  "description": "Snowcone SDK for product mockups and print-on-demand",
5
5
  "keywords": [
6
6
  "merch",