@snowcone-app/sdk 0.10.0 → 0.11.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 +6 -0
- package/dist/index.cjs +84 -0
- package/dist/index.d.cts +101 -1
- package/dist/index.d.ts +101 -1
- package/dist/index.js +80 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#591](https://github.com/snowcone-app/snowcone-monorepo/pull/591) [`f15c421`](https://github.com/snowcone-app/snowcone-monorepo/commit/f15c421f11a793064fc5471f3286760f393ac4d7) Thanks [@kevinsproles](https://github.com/kevinsproles)! - Upload grants (ADR-0084): `uploadAsset`, `mintUploadGrant`, and `fetchUploadGrant` extend the realtime grant pattern to user-image uploads, so a static page can accept a shopper's logo with no proxy backend. `uploadAsset(file, { shop })` mints a short-lived grant (keyless publishable path, or sk\_/`grantUrl` for the server-side path), uploads the image, and returns a URL on the shop's own storage origin — already inside the asset-origin allowlist, ready for `getMockupUrl`/`getBuyUrl`.
|
|
8
|
+
|
|
3
9
|
## 0.10.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
package/dist/index.cjs
CHANGED
|
@@ -42,6 +42,7 @@ __export(index_exports, {
|
|
|
42
42
|
DEFAULT_GRANT_BASE: () => DEFAULT_GRANT_BASE,
|
|
43
43
|
DEFAULT_MOCKUP_BASE: () => DEFAULT_MOCKUP_BASE,
|
|
44
44
|
DEFAULT_PLACEMENT_DIMENSIONS: () => DEFAULT_PLACEMENT_DIMENSIONS,
|
|
45
|
+
DEFAULT_UPLOAD_BASE: () => DEFAULT_UPLOAD_BASE,
|
|
45
46
|
Elements: () => Elements,
|
|
46
47
|
ErrorManager: () => ErrorManager,
|
|
47
48
|
EventDelegator: () => EventDelegator,
|
|
@@ -103,6 +104,7 @@ __export(index_exports, {
|
|
|
103
104
|
describeProductTitle: () => describeProductTitle,
|
|
104
105
|
extractProductId: () => extractProductId,
|
|
105
106
|
fetchRealtimeGrant: () => fetchRealtimeGrant,
|
|
107
|
+
fetchUploadGrant: () => fetchUploadGrant,
|
|
106
108
|
filterImagePlacements: () => filterImagePlacements,
|
|
107
109
|
findBestCombination: () => findBestCombination,
|
|
108
110
|
findClosestSnapPoint: () => findClosestSnapPoint,
|
|
@@ -128,6 +130,7 @@ __export(index_exports, {
|
|
|
128
130
|
isValidTileCount: () => isValidTileCount,
|
|
129
131
|
listProducts: () => listProducts,
|
|
130
132
|
mintRealtimeGrant: () => mintRealtimeGrant,
|
|
133
|
+
mintUploadGrant: () => mintUploadGrant,
|
|
131
134
|
mockupUrl: () => mockupUrl,
|
|
132
135
|
normalizeChoice: () => normalizeChoice,
|
|
133
136
|
prepareOptionRenderData: () => prepareOptionRenderData,
|
|
@@ -139,6 +142,7 @@ __export(index_exports, {
|
|
|
139
142
|
simulateCartOperation: () => simulateCartOperation,
|
|
140
143
|
toCombinations: () => toCombinations,
|
|
141
144
|
toOptionAttributes: () => toOptionAttributes,
|
|
145
|
+
uploadAsset: () => uploadAsset,
|
|
142
146
|
useVueAdapter: () => useFrameworkAdapter,
|
|
143
147
|
validateAlignment: () => validateAlignment,
|
|
144
148
|
validateDesignElement: () => validateDesignElement,
|
|
@@ -6109,6 +6113,82 @@ async function createDesignState(input) {
|
|
|
6109
6113
|
return { stateId: ds.id, stateUrl: ds.stateUrl ?? "", previewUrl: ds.previewUrl ?? "" };
|
|
6110
6114
|
}
|
|
6111
6115
|
|
|
6116
|
+
// src/upload/grant.ts
|
|
6117
|
+
var DEFAULT_UPLOAD_BASE = "https://api.snowcone.app";
|
|
6118
|
+
async function mintUploadGrant(opts) {
|
|
6119
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
6120
|
+
const headers = { "Content-Type": "application/json" };
|
|
6121
|
+
if (opts.apiKey) headers.Authorization = `Bearer ${opts.apiKey}`;
|
|
6122
|
+
const res = await f(`${opts.base ?? DEFAULT_UPLOAD_BASE}/uploads/grant`, {
|
|
6123
|
+
method: "POST",
|
|
6124
|
+
headers,
|
|
6125
|
+
body: JSON.stringify({ shop: opts.shop })
|
|
6126
|
+
});
|
|
6127
|
+
if (!res.ok) {
|
|
6128
|
+
const detail = await res.text().catch(() => "");
|
|
6129
|
+
throw new Error(`upload grant failed: ${res.status}${detail ? ` ${detail}` : ""}`);
|
|
6130
|
+
}
|
|
6131
|
+
return await res.json();
|
|
6132
|
+
}
|
|
6133
|
+
async function fetchUploadGrant(grantUrl, shop, fetchImpl) {
|
|
6134
|
+
const f = fetchImpl ?? globalThis.fetch;
|
|
6135
|
+
const res = await f(grantUrl, {
|
|
6136
|
+
method: "POST",
|
|
6137
|
+
headers: { "Content-Type": "application/json" },
|
|
6138
|
+
body: JSON.stringify({ shop })
|
|
6139
|
+
});
|
|
6140
|
+
if (!res.ok) throw new Error(`upload grant failed: ${res.status}`);
|
|
6141
|
+
return await res.json();
|
|
6142
|
+
}
|
|
6143
|
+
async function toImageDataUrl(image) {
|
|
6144
|
+
if (typeof image === "string") {
|
|
6145
|
+
if (/^data:image\/\w+;base64,/.test(image)) return image;
|
|
6146
|
+
throw new Error(
|
|
6147
|
+
"uploadAsset: a string image must be a data:image/\u2026;base64 URL (pass a Blob/File otherwise)"
|
|
6148
|
+
);
|
|
6149
|
+
}
|
|
6150
|
+
const bytes = new Uint8Array(await image.arrayBuffer());
|
|
6151
|
+
const type = image.type?.startsWith("image/") ? image.type : "image/png";
|
|
6152
|
+
const B = globalThis.Buffer;
|
|
6153
|
+
let base64;
|
|
6154
|
+
if (B) {
|
|
6155
|
+
base64 = B.from(bytes).toString("base64");
|
|
6156
|
+
} else {
|
|
6157
|
+
let bin = "";
|
|
6158
|
+
const CHUNK = 32768;
|
|
6159
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
6160
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
6161
|
+
}
|
|
6162
|
+
base64 = btoa(bin);
|
|
6163
|
+
}
|
|
6164
|
+
return `data:${type};base64,${base64}`;
|
|
6165
|
+
}
|
|
6166
|
+
async function uploadAsset(image, opts) {
|
|
6167
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
6168
|
+
const base = opts.base ?? DEFAULT_UPLOAD_BASE;
|
|
6169
|
+
const base64Image = await toImageDataUrl(image);
|
|
6170
|
+
let token;
|
|
6171
|
+
if (opts.grant) {
|
|
6172
|
+
token = typeof opts.grant === "string" ? opts.grant : opts.grant.token;
|
|
6173
|
+
} else {
|
|
6174
|
+
if (!opts.shop) {
|
|
6175
|
+
throw new Error("uploadAsset: `shop` is required unless a `grant` is given");
|
|
6176
|
+
}
|
|
6177
|
+
const grant = opts.grantUrl ? await fetchUploadGrant(opts.grantUrl, opts.shop, f) : await mintUploadGrant({ apiKey: opts.apiKey, shop: opts.shop, base, fetch: f });
|
|
6178
|
+
token = grant.token;
|
|
6179
|
+
}
|
|
6180
|
+
const res = await f(`${base}/uploads/grant/base64`, {
|
|
6181
|
+
method: "POST",
|
|
6182
|
+
headers: { "Content-Type": "application/json" },
|
|
6183
|
+
body: JSON.stringify({ token, base64Image })
|
|
6184
|
+
});
|
|
6185
|
+
if (!res.ok) {
|
|
6186
|
+
const detail = await res.text().catch(() => "");
|
|
6187
|
+
throw new Error(`upload failed: ${res.status}${detail ? ` ${detail}` : ""}`);
|
|
6188
|
+
}
|
|
6189
|
+
return await res.json();
|
|
6190
|
+
}
|
|
6191
|
+
|
|
6112
6192
|
// src/index.ts
|
|
6113
6193
|
function getFetcher(config) {
|
|
6114
6194
|
return config?.fetcher || globalThis.fetch.bind(globalThis);
|
|
@@ -6205,6 +6285,7 @@ function createClient(config) {
|
|
|
6205
6285
|
DEFAULT_GRANT_BASE,
|
|
6206
6286
|
DEFAULT_MOCKUP_BASE,
|
|
6207
6287
|
DEFAULT_PLACEMENT_DIMENSIONS,
|
|
6288
|
+
DEFAULT_UPLOAD_BASE,
|
|
6208
6289
|
Elements,
|
|
6209
6290
|
ErrorManager,
|
|
6210
6291
|
EventDelegator,
|
|
@@ -6266,6 +6347,7 @@ function createClient(config) {
|
|
|
6266
6347
|
describeProductTitle,
|
|
6267
6348
|
extractProductId,
|
|
6268
6349
|
fetchRealtimeGrant,
|
|
6350
|
+
fetchUploadGrant,
|
|
6269
6351
|
filterImagePlacements,
|
|
6270
6352
|
findBestCombination,
|
|
6271
6353
|
findClosestSnapPoint,
|
|
@@ -6291,6 +6373,7 @@ function createClient(config) {
|
|
|
6291
6373
|
isValidTileCount,
|
|
6292
6374
|
listProducts,
|
|
6293
6375
|
mintRealtimeGrant,
|
|
6376
|
+
mintUploadGrant,
|
|
6294
6377
|
mockupUrl,
|
|
6295
6378
|
normalizeChoice,
|
|
6296
6379
|
prepareOptionRenderData,
|
|
@@ -6302,6 +6385,7 @@ function createClient(config) {
|
|
|
6302
6385
|
simulateCartOperation,
|
|
6303
6386
|
toCombinations,
|
|
6304
6387
|
toOptionAttributes,
|
|
6388
|
+
uploadAsset,
|
|
6305
6389
|
useVueAdapter,
|
|
6306
6390
|
validateAlignment,
|
|
6307
6391
|
validateDesignElement,
|
package/dist/index.d.cts
CHANGED
|
@@ -3061,6 +3061,106 @@ interface CreatedDesignState {
|
|
|
3061
3061
|
*/
|
|
3062
3062
|
declare function createDesignState(input: CreateDesignStateInput): Promise<CreatedDesignState>;
|
|
3063
3063
|
|
|
3064
|
+
/**
|
|
3065
|
+
* Upload grant helpers — the realtime grant pattern (ADR-0079), extended to
|
|
3066
|
+
* asset uploads so the zero-backend story survives the first user-supplied
|
|
3067
|
+
* image. A static page can take a shopper's logo, upload it, and render it on
|
|
3068
|
+
* merchandise without any proxy server.
|
|
3069
|
+
*
|
|
3070
|
+
* A short-lived (5 min) grant token authorizes uploads into the shop's own
|
|
3071
|
+
* storage origin (`{shopId}.storage.snowcone.app`) — which is inside the
|
|
3072
|
+
* shop's asset-origin allowlist, so the returned URL drops straight into
|
|
3073
|
+
* `getMockupUrl` with zero further config. Three ways to get one, mirroring
|
|
3074
|
+
* the realtime grant exactly:
|
|
3075
|
+
*
|
|
3076
|
+
* - {@link mintUploadGrant} — SERVER-SIDE with a secret API key (sk_), or
|
|
3077
|
+
* keyless with just the publishable shop id.
|
|
3078
|
+
* - {@link fetchUploadGrant} — BROWSER, from your own proxy endpoint.
|
|
3079
|
+
* - {@link uploadAsset} — the one-call helper: resolves a grant however you
|
|
3080
|
+
* provide it, uploads the image, returns the hosted URL.
|
|
3081
|
+
*/
|
|
3082
|
+
/** A short-lived upload grant. */
|
|
3083
|
+
interface UploadGrant {
|
|
3084
|
+
/** Opaque token for `POST /uploads/grant/base64`. */
|
|
3085
|
+
token: string;
|
|
3086
|
+
/** Expiry, epoch seconds. Mint a fresh grant after this. */
|
|
3087
|
+
expiresAt: number;
|
|
3088
|
+
}
|
|
3089
|
+
/** Default backend base URL hosting `POST /uploads/grant`. */
|
|
3090
|
+
declare const DEFAULT_UPLOAD_BASE = "https://api.snowcone.app";
|
|
3091
|
+
/**
|
|
3092
|
+
* Mint an upload grant. Mirrors `mintRealtimeGrant`:
|
|
3093
|
+
*
|
|
3094
|
+
* Omit `apiKey` (or pass `undefined`/`null`/`''`) for the **keyless
|
|
3095
|
+
* publishable path** — the grant is authorized by the publishable `shop` id
|
|
3096
|
+
* alone (shops on the L3 signed-URLs rung must use a key or a signed grant
|
|
3097
|
+
* request instead). Pass a secret API key (sk_) with the `uploads:write`
|
|
3098
|
+
* scope to mint server-side; the key's organization must own the shop.
|
|
3099
|
+
*
|
|
3100
|
+
* @example
|
|
3101
|
+
* // keyless, straight from the browser — quick trials & sandbox shops:
|
|
3102
|
+
* const grant = await mintUploadGrant({ shop });
|
|
3103
|
+
*
|
|
3104
|
+
* @example
|
|
3105
|
+
* // your backend route: POST /api/upload/grant
|
|
3106
|
+
* const grant = await mintUploadGrant({ apiKey: process.env.SNOWCONE_API_KEY!, shop });
|
|
3107
|
+
* return Response.json(grant);
|
|
3108
|
+
*/
|
|
3109
|
+
declare function mintUploadGrant(opts: {
|
|
3110
|
+
/**
|
|
3111
|
+
* Secret API key (sk_) with the `uploads:write` scope. Omit (or pass
|
|
3112
|
+
* `undefined`/`null`/`''`) for the keyless publishable path.
|
|
3113
|
+
*/
|
|
3114
|
+
apiKey?: string | null;
|
|
3115
|
+
/** Target shop id (= shop.id). Uploads land in this shop's storage origin. */
|
|
3116
|
+
shop: string;
|
|
3117
|
+
/** Backend base URL. Defaults to {@link DEFAULT_UPLOAD_BASE}. */
|
|
3118
|
+
base?: string;
|
|
3119
|
+
/** Override fetch (e.g. in tests / non-global-fetch runtimes). */
|
|
3120
|
+
fetch?: typeof fetch;
|
|
3121
|
+
}): Promise<UploadGrant>;
|
|
3122
|
+
/**
|
|
3123
|
+
* BROWSER: fetch an upload grant from your own proxy endpoint, which calls
|
|
3124
|
+
* {@link mintUploadGrant} server-side (when you want the sk_ path without
|
|
3125
|
+
* shipping the key). The proxy receives `POST { shop }` and returns
|
|
3126
|
+
* `{ token, expiresAt }`.
|
|
3127
|
+
*/
|
|
3128
|
+
declare function fetchUploadGrant(grantUrl: string, shop: string, fetchImpl?: typeof fetch): Promise<UploadGrant>;
|
|
3129
|
+
/**
|
|
3130
|
+
* Upload an image and get back its hosted URL — ready to pass as `asset` to
|
|
3131
|
+
* `getMockupUrl` / `getBuyUrl` (it lands on the shop's own storage origin, so
|
|
3132
|
+
* it's already on the asset-origin allowlist).
|
|
3133
|
+
*
|
|
3134
|
+
* Provide auth in whichever shape fits:
|
|
3135
|
+
* - `{ shop }` alone — keyless publishable path (mints the grant for you),
|
|
3136
|
+
* - `{ shop, grantUrl }` — exchange via your own proxy endpoint,
|
|
3137
|
+
* - `{ shop, apiKey }` — server-side with an sk_ key,
|
|
3138
|
+
* - `{ grant }` — a grant you already hold (token reusable until it expires).
|
|
3139
|
+
*
|
|
3140
|
+
* @example
|
|
3141
|
+
* // a static page, no backend anywhere:
|
|
3142
|
+
* const { url } = await uploadAsset(fileInput.files[0], { shop });
|
|
3143
|
+
* img.src = getMockupUrl("BEEB77", { shop, asset: url });
|
|
3144
|
+
*/
|
|
3145
|
+
declare function uploadAsset(
|
|
3146
|
+
/** A `Blob`/`File`, or a `data:image/…;base64,` URL. */
|
|
3147
|
+
image: Blob | string, opts: {
|
|
3148
|
+
/** Target shop id. Required unless a pre-fetched `grant` is given. */
|
|
3149
|
+
shop?: string;
|
|
3150
|
+
/** A grant you already hold (or its raw token). Skips minting. */
|
|
3151
|
+
grant?: UploadGrant | string;
|
|
3152
|
+
/** Your own proxy endpoint that returns a grant (see {@link fetchUploadGrant}). */
|
|
3153
|
+
grantUrl?: string;
|
|
3154
|
+
/** Secret API key (sk_, scope `uploads:write`) for server-side minting. */
|
|
3155
|
+
apiKey?: string | null;
|
|
3156
|
+
/** Backend base URL. Defaults to {@link DEFAULT_UPLOAD_BASE}. */
|
|
3157
|
+
base?: string;
|
|
3158
|
+
/** Override fetch. */
|
|
3159
|
+
fetch?: typeof fetch;
|
|
3160
|
+
}): Promise<{
|
|
3161
|
+
url: string;
|
|
3162
|
+
}>;
|
|
3163
|
+
|
|
3064
3164
|
interface ProductPlacement {
|
|
3065
3165
|
label: string;
|
|
3066
3166
|
x: number;
|
|
@@ -3115,4 +3215,4 @@ declare function getProduct(idOrSlug: string, config?: Partial<SdkConfig>): Prom
|
|
|
3115
3215
|
*/
|
|
3116
3216
|
declare function createClient(config: SdkConfig): SnowconeClient;
|
|
3117
3217
|
|
|
3118
|
-
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
|
3218
|
+
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, DEFAULT_UPLOAD_BASE, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UploadGrant, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, fetchUploadGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mintUploadGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, uploadAsset, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
package/dist/index.d.ts
CHANGED
|
@@ -3061,6 +3061,106 @@ interface CreatedDesignState {
|
|
|
3061
3061
|
*/
|
|
3062
3062
|
declare function createDesignState(input: CreateDesignStateInput): Promise<CreatedDesignState>;
|
|
3063
3063
|
|
|
3064
|
+
/**
|
|
3065
|
+
* Upload grant helpers — the realtime grant pattern (ADR-0079), extended to
|
|
3066
|
+
* asset uploads so the zero-backend story survives the first user-supplied
|
|
3067
|
+
* image. A static page can take a shopper's logo, upload it, and render it on
|
|
3068
|
+
* merchandise without any proxy server.
|
|
3069
|
+
*
|
|
3070
|
+
* A short-lived (5 min) grant token authorizes uploads into the shop's own
|
|
3071
|
+
* storage origin (`{shopId}.storage.snowcone.app`) — which is inside the
|
|
3072
|
+
* shop's asset-origin allowlist, so the returned URL drops straight into
|
|
3073
|
+
* `getMockupUrl` with zero further config. Three ways to get one, mirroring
|
|
3074
|
+
* the realtime grant exactly:
|
|
3075
|
+
*
|
|
3076
|
+
* - {@link mintUploadGrant} — SERVER-SIDE with a secret API key (sk_), or
|
|
3077
|
+
* keyless with just the publishable shop id.
|
|
3078
|
+
* - {@link fetchUploadGrant} — BROWSER, from your own proxy endpoint.
|
|
3079
|
+
* - {@link uploadAsset} — the one-call helper: resolves a grant however you
|
|
3080
|
+
* provide it, uploads the image, returns the hosted URL.
|
|
3081
|
+
*/
|
|
3082
|
+
/** A short-lived upload grant. */
|
|
3083
|
+
interface UploadGrant {
|
|
3084
|
+
/** Opaque token for `POST /uploads/grant/base64`. */
|
|
3085
|
+
token: string;
|
|
3086
|
+
/** Expiry, epoch seconds. Mint a fresh grant after this. */
|
|
3087
|
+
expiresAt: number;
|
|
3088
|
+
}
|
|
3089
|
+
/** Default backend base URL hosting `POST /uploads/grant`. */
|
|
3090
|
+
declare const DEFAULT_UPLOAD_BASE = "https://api.snowcone.app";
|
|
3091
|
+
/**
|
|
3092
|
+
* Mint an upload grant. Mirrors `mintRealtimeGrant`:
|
|
3093
|
+
*
|
|
3094
|
+
* Omit `apiKey` (or pass `undefined`/`null`/`''`) for the **keyless
|
|
3095
|
+
* publishable path** — the grant is authorized by the publishable `shop` id
|
|
3096
|
+
* alone (shops on the L3 signed-URLs rung must use a key or a signed grant
|
|
3097
|
+
* request instead). Pass a secret API key (sk_) with the `uploads:write`
|
|
3098
|
+
* scope to mint server-side; the key's organization must own the shop.
|
|
3099
|
+
*
|
|
3100
|
+
* @example
|
|
3101
|
+
* // keyless, straight from the browser — quick trials & sandbox shops:
|
|
3102
|
+
* const grant = await mintUploadGrant({ shop });
|
|
3103
|
+
*
|
|
3104
|
+
* @example
|
|
3105
|
+
* // your backend route: POST /api/upload/grant
|
|
3106
|
+
* const grant = await mintUploadGrant({ apiKey: process.env.SNOWCONE_API_KEY!, shop });
|
|
3107
|
+
* return Response.json(grant);
|
|
3108
|
+
*/
|
|
3109
|
+
declare function mintUploadGrant(opts: {
|
|
3110
|
+
/**
|
|
3111
|
+
* Secret API key (sk_) with the `uploads:write` scope. Omit (or pass
|
|
3112
|
+
* `undefined`/`null`/`''`) for the keyless publishable path.
|
|
3113
|
+
*/
|
|
3114
|
+
apiKey?: string | null;
|
|
3115
|
+
/** Target shop id (= shop.id). Uploads land in this shop's storage origin. */
|
|
3116
|
+
shop: string;
|
|
3117
|
+
/** Backend base URL. Defaults to {@link DEFAULT_UPLOAD_BASE}. */
|
|
3118
|
+
base?: string;
|
|
3119
|
+
/** Override fetch (e.g. in tests / non-global-fetch runtimes). */
|
|
3120
|
+
fetch?: typeof fetch;
|
|
3121
|
+
}): Promise<UploadGrant>;
|
|
3122
|
+
/**
|
|
3123
|
+
* BROWSER: fetch an upload grant from your own proxy endpoint, which calls
|
|
3124
|
+
* {@link mintUploadGrant} server-side (when you want the sk_ path without
|
|
3125
|
+
* shipping the key). The proxy receives `POST { shop }` and returns
|
|
3126
|
+
* `{ token, expiresAt }`.
|
|
3127
|
+
*/
|
|
3128
|
+
declare function fetchUploadGrant(grantUrl: string, shop: string, fetchImpl?: typeof fetch): Promise<UploadGrant>;
|
|
3129
|
+
/**
|
|
3130
|
+
* Upload an image and get back its hosted URL — ready to pass as `asset` to
|
|
3131
|
+
* `getMockupUrl` / `getBuyUrl` (it lands on the shop's own storage origin, so
|
|
3132
|
+
* it's already on the asset-origin allowlist).
|
|
3133
|
+
*
|
|
3134
|
+
* Provide auth in whichever shape fits:
|
|
3135
|
+
* - `{ shop }` alone — keyless publishable path (mints the grant for you),
|
|
3136
|
+
* - `{ shop, grantUrl }` — exchange via your own proxy endpoint,
|
|
3137
|
+
* - `{ shop, apiKey }` — server-side with an sk_ key,
|
|
3138
|
+
* - `{ grant }` — a grant you already hold (token reusable until it expires).
|
|
3139
|
+
*
|
|
3140
|
+
* @example
|
|
3141
|
+
* // a static page, no backend anywhere:
|
|
3142
|
+
* const { url } = await uploadAsset(fileInput.files[0], { shop });
|
|
3143
|
+
* img.src = getMockupUrl("BEEB77", { shop, asset: url });
|
|
3144
|
+
*/
|
|
3145
|
+
declare function uploadAsset(
|
|
3146
|
+
/** A `Blob`/`File`, or a `data:image/…;base64,` URL. */
|
|
3147
|
+
image: Blob | string, opts: {
|
|
3148
|
+
/** Target shop id. Required unless a pre-fetched `grant` is given. */
|
|
3149
|
+
shop?: string;
|
|
3150
|
+
/** A grant you already hold (or its raw token). Skips minting. */
|
|
3151
|
+
grant?: UploadGrant | string;
|
|
3152
|
+
/** Your own proxy endpoint that returns a grant (see {@link fetchUploadGrant}). */
|
|
3153
|
+
grantUrl?: string;
|
|
3154
|
+
/** Secret API key (sk_, scope `uploads:write`) for server-side minting. */
|
|
3155
|
+
apiKey?: string | null;
|
|
3156
|
+
/** Backend base URL. Defaults to {@link DEFAULT_UPLOAD_BASE}. */
|
|
3157
|
+
base?: string;
|
|
3158
|
+
/** Override fetch. */
|
|
3159
|
+
fetch?: typeof fetch;
|
|
3160
|
+
}): Promise<{
|
|
3161
|
+
url: string;
|
|
3162
|
+
}>;
|
|
3163
|
+
|
|
3064
3164
|
interface ProductPlacement {
|
|
3065
3165
|
label: string;
|
|
3066
3166
|
x: number;
|
|
@@ -3115,4 +3215,4 @@ declare function getProduct(idOrSlug: string, config?: Partial<SdkConfig>): Prom
|
|
|
3115
3215
|
*/
|
|
3116
3216
|
declare function createClient(config: SdkConfig): SnowconeClient;
|
|
3117
3217
|
|
|
3118
|
-
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
|
3218
|
+
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, DEFAULT_UPLOAD_BASE, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SignedUrlResponse, type SnowconeClient, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UploadGrant, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchRealtimeGrant, fetchUploadGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, isSelectionComplete, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mintUploadGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolveVariantId, retryOperation, simulateCartOperation, toCombinations, toOptionAttributes, uploadAsset, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
package/dist/index.js
CHANGED
|
@@ -4981,6 +4981,82 @@ async function createDesignState(input) {
|
|
|
4981
4981
|
return { stateId: ds.id, stateUrl: ds.stateUrl ?? "", previewUrl: ds.previewUrl ?? "" };
|
|
4982
4982
|
}
|
|
4983
4983
|
|
|
4984
|
+
// src/upload/grant.ts
|
|
4985
|
+
var DEFAULT_UPLOAD_BASE = "https://api.snowcone.app";
|
|
4986
|
+
async function mintUploadGrant(opts) {
|
|
4987
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
4988
|
+
const headers = { "Content-Type": "application/json" };
|
|
4989
|
+
if (opts.apiKey) headers.Authorization = `Bearer ${opts.apiKey}`;
|
|
4990
|
+
const res = await f(`${opts.base ?? DEFAULT_UPLOAD_BASE}/uploads/grant`, {
|
|
4991
|
+
method: "POST",
|
|
4992
|
+
headers,
|
|
4993
|
+
body: JSON.stringify({ shop: opts.shop })
|
|
4994
|
+
});
|
|
4995
|
+
if (!res.ok) {
|
|
4996
|
+
const detail = await res.text().catch(() => "");
|
|
4997
|
+
throw new Error(`upload grant failed: ${res.status}${detail ? ` ${detail}` : ""}`);
|
|
4998
|
+
}
|
|
4999
|
+
return await res.json();
|
|
5000
|
+
}
|
|
5001
|
+
async function fetchUploadGrant(grantUrl, shop, fetchImpl) {
|
|
5002
|
+
const f = fetchImpl ?? globalThis.fetch;
|
|
5003
|
+
const res = await f(grantUrl, {
|
|
5004
|
+
method: "POST",
|
|
5005
|
+
headers: { "Content-Type": "application/json" },
|
|
5006
|
+
body: JSON.stringify({ shop })
|
|
5007
|
+
});
|
|
5008
|
+
if (!res.ok) throw new Error(`upload grant failed: ${res.status}`);
|
|
5009
|
+
return await res.json();
|
|
5010
|
+
}
|
|
5011
|
+
async function toImageDataUrl(image) {
|
|
5012
|
+
if (typeof image === "string") {
|
|
5013
|
+
if (/^data:image\/\w+;base64,/.test(image)) return image;
|
|
5014
|
+
throw new Error(
|
|
5015
|
+
"uploadAsset: a string image must be a data:image/\u2026;base64 URL (pass a Blob/File otherwise)"
|
|
5016
|
+
);
|
|
5017
|
+
}
|
|
5018
|
+
const bytes = new Uint8Array(await image.arrayBuffer());
|
|
5019
|
+
const type = image.type?.startsWith("image/") ? image.type : "image/png";
|
|
5020
|
+
const B = globalThis.Buffer;
|
|
5021
|
+
let base64;
|
|
5022
|
+
if (B) {
|
|
5023
|
+
base64 = B.from(bytes).toString("base64");
|
|
5024
|
+
} else {
|
|
5025
|
+
let bin = "";
|
|
5026
|
+
const CHUNK = 32768;
|
|
5027
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
5028
|
+
bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
|
|
5029
|
+
}
|
|
5030
|
+
base64 = btoa(bin);
|
|
5031
|
+
}
|
|
5032
|
+
return `data:${type};base64,${base64}`;
|
|
5033
|
+
}
|
|
5034
|
+
async function uploadAsset(image, opts) {
|
|
5035
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
5036
|
+
const base = opts.base ?? DEFAULT_UPLOAD_BASE;
|
|
5037
|
+
const base64Image = await toImageDataUrl(image);
|
|
5038
|
+
let token;
|
|
5039
|
+
if (opts.grant) {
|
|
5040
|
+
token = typeof opts.grant === "string" ? opts.grant : opts.grant.token;
|
|
5041
|
+
} else {
|
|
5042
|
+
if (!opts.shop) {
|
|
5043
|
+
throw new Error("uploadAsset: `shop` is required unless a `grant` is given");
|
|
5044
|
+
}
|
|
5045
|
+
const grant = opts.grantUrl ? await fetchUploadGrant(opts.grantUrl, opts.shop, f) : await mintUploadGrant({ apiKey: opts.apiKey, shop: opts.shop, base, fetch: f });
|
|
5046
|
+
token = grant.token;
|
|
5047
|
+
}
|
|
5048
|
+
const res = await f(`${base}/uploads/grant/base64`, {
|
|
5049
|
+
method: "POST",
|
|
5050
|
+
headers: { "Content-Type": "application/json" },
|
|
5051
|
+
body: JSON.stringify({ token, base64Image })
|
|
5052
|
+
});
|
|
5053
|
+
if (!res.ok) {
|
|
5054
|
+
const detail = await res.text().catch(() => "");
|
|
5055
|
+
throw new Error(`upload failed: ${res.status}${detail ? ` ${detail}` : ""}`);
|
|
5056
|
+
}
|
|
5057
|
+
return await res.json();
|
|
5058
|
+
}
|
|
5059
|
+
|
|
4984
5060
|
// src/index.ts
|
|
4985
5061
|
function getFetcher(config) {
|
|
4986
5062
|
return config?.fetcher || globalThis.fetch.bind(globalThis);
|
|
@@ -5076,6 +5152,7 @@ export {
|
|
|
5076
5152
|
DEFAULT_GRANT_BASE,
|
|
5077
5153
|
DEFAULT_MOCKUP_BASE,
|
|
5078
5154
|
DEFAULT_PLACEMENT_DIMENSIONS,
|
|
5155
|
+
DEFAULT_UPLOAD_BASE,
|
|
5079
5156
|
Elements,
|
|
5080
5157
|
ErrorManager,
|
|
5081
5158
|
EventDelegator,
|
|
@@ -5137,6 +5214,7 @@ export {
|
|
|
5137
5214
|
describeProductTitle,
|
|
5138
5215
|
extractProductId,
|
|
5139
5216
|
fetchRealtimeGrant,
|
|
5217
|
+
fetchUploadGrant,
|
|
5140
5218
|
filterImagePlacements,
|
|
5141
5219
|
findBestCombination,
|
|
5142
5220
|
findClosestSnapPoint,
|
|
@@ -5162,6 +5240,7 @@ export {
|
|
|
5162
5240
|
isValidTileCount,
|
|
5163
5241
|
listProducts,
|
|
5164
5242
|
mintRealtimeGrant,
|
|
5243
|
+
mintUploadGrant,
|
|
5165
5244
|
mockupUrl,
|
|
5166
5245
|
normalizeChoice,
|
|
5167
5246
|
prepareOptionRenderData,
|
|
@@ -5173,6 +5252,7 @@ export {
|
|
|
5173
5252
|
simulateCartOperation,
|
|
5174
5253
|
toCombinations,
|
|
5175
5254
|
toOptionAttributes,
|
|
5255
|
+
uploadAsset,
|
|
5176
5256
|
useFrameworkAdapter as useVueAdapter,
|
|
5177
5257
|
validateAlignment,
|
|
5178
5258
|
validateDesignElement,
|