@eldrajs/sdk 0.2.4 → 0.2.6

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
@@ -9,6 +9,12 @@ platform repository.
9
9
 
10
10
  ## Unreleased
11
11
 
12
+ - Responsive images: `responsiveImage` returns `src`, `srcset`, `sizes`, `width` and `height` for
13
+ an `<img>` from any media URL or object the API returns; `imageSrcset`, `imageUrl`,
14
+ `imageVariantFor`, `isEldraImage` and `ELDRA_IMAGE_VARIANT_WIDTHS` are the parts. A bare media
15
+ URL serves 800 px, so a storefront rendering it as-is was soft on wide screens. External URLs
16
+ and formats the host does not resize come back unchanged. See `docs/images.md`.
17
+
12
18
  - `checkout.handoffUrl` defaults to the hosted checkout at `https://checkout.eldra.app` (exported
13
19
  as `DEFAULT_ELDRA_CHECKOUT_URL`) when the client uses the default API base URL, so a production
14
20
  storefront no longer needs a checkout URL setting. `checkoutUrl` and the `ELDRA_CHECKOUT_URL` env
package/README.md CHANGED
@@ -42,6 +42,25 @@ it as `X-Preview-Token`. Configure each separately; the generator never embeds t
42
42
  output. See [preview mode](../../docs/getting-started.md#preview-mode) for examples and header
43
43
  precedence.
44
44
 
45
+ ## Images
46
+
47
+ A media URL from the API serves an 800 px copy. Build a `srcset` over the sizes the media host
48
+ serves (400 to 2560 px) so the browser picks one that is sharp on the screen in front of it:
49
+
50
+ ```ts
51
+ import { responsiveImage } from '@eldrajs/sdk';
52
+
53
+ const image = responsiveImage(product.thumbnail, {
54
+ sizes: '(min-width: 1024px) 25vw, 50vw', // how wide the image is drawn
55
+ aspectRatio: 4 / 5, // reserves the space: width="800" height="1000"
56
+ });
57
+ // spread onto <img>: { src, srcset, sizes, width, height }
58
+ ```
59
+
60
+ `imageSrcset`, `imageUrl(source, 'xl')` and `imageVariantFor(width, density)` are there for the
61
+ parts on their own. Anything that is not an Eldra media asset comes back unchanged. The variants,
62
+ choosing `sizes`, and avoiding layout shift are in [docs/images.md](../../docs/images.md).
63
+
45
64
  ## What is in the client
46
65
 
47
66
  | Group | Methods |
@@ -344,4 +344,4 @@ function isRawBody(body) {
344
344
  return typeof body === "string" || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams || typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer;
345
345
  }
346
346
  //#endregion
347
- export { getEldraClient as a, createEldraClient as i, DEFAULT_ELDRA_CHECKOUT_URL as n, initEldraClient as o, EldraHttpError as r, DEFAULT_ELDRA_API_BASE_URL as t };
347
+ export { getEldraClient as a, resolveOrgId as c, createEldraClient as i, DEFAULT_ELDRA_CHECKOUT_URL as n, initEldraClient as o, EldraHttpError as r, resolveApiBaseUrl as s, DEFAULT_ELDRA_API_BASE_URL as t };
package/dist/index.d.ts CHANGED
@@ -47,4 +47,99 @@ export declare function createCartSession(options?: EldraCartSessionOptions): El
47
47
  */
48
48
  export declare function createOrderAccessTokens(options?: EldraOrderAccessTokenOptions): EldraOrderAccessTokens;
49
49
  //#endregion
50
- export type { EldraAddCartItemInput, EldraCart, EldraCartClient, EldraCartItem, EldraCartSession, EldraCartSessionOptions, EldraCartTotals, EldraCatalogClient, EldraCatalogGetProductOptions, EldraCatalogListProductsOptions, EldraCategory, EldraCheckoutClient, EldraCheckoutHandoffOptions, EldraClient, EldraClientOptions, EldraCmsClient, EldraCmsEntryList, EldraCmsEntryListDisplayMode, EldraCmsEntryListEntry, EldraCmsEntryListFilterCriterion, EldraCmsGetEntryByUniqueFieldOptions, EldraCmsGetOptions, EldraCmsListOptions, EldraCmsResolveEntryListOptions, EldraCmsResolveEntryListResponse, EldraCmsResolvedEntryList, EldraCollection, EldraCollectionList, EldraCollectionListOptions, EldraCollectionProductsOptions, EldraContract, EldraContractBody, EldraContractItem, EldraContractMethod, EldraContractPath, EldraContractPaths, EldraContractProp, EldraContractQuery, EldraContractResponse, EldraDiscountResult, EldraFeature, EldraFeatureCapabilities, EldraFeatureClient, EldraHttpClient, EldraHttpRequest, EldraInventoryClient, EldraKeyValueStorage, EldraLocaleOptions, EldraOrder, EldraOrderAccessTokenOptions, EldraOrderAccessTokens, EldraOrderLine, EldraOrderReadOptions, EldraOrdersClient, EldraOrganizationDetails, EldraOrganizationFeature, EldraOrganizationOptions, EldraPageMeta, EldraPaginated, EldraProductDetails, EldraProductList, EldraProductListItem, EldraProductMediaLink, EldraProductOption, EldraProductOptionValue, EldraProductThumbnail, EldraProductVariant, EldraRecoveredBasket, EldraRecoveredBasketItem, EldraRequestContext, EldraRequestOptions, EldraSearchOptions, EldraSearchResponse, EldraStockAvailability, EldraStockAvailabilityInput, EldraStockAvailabilityItem, RuntimeEnv, RuntimeValue };
50
+ //#region src/tracker.d.ts
51
+ interface EldraTrackerScriptOptions extends Pick<EldraClientOptions, 'apiBaseUrl' | 'orgId' | 'env'> {
52
+ /** Origin that receives events when the script is served through a first-party proxy. */
53
+ eventOrigin?: string;
54
+ }
55
+ /** Attributes of the `<script>` tag that loads the Eldra analytics tracker. */
56
+ interface EldraTrackerScript {
57
+ src: string;
58
+ defer: true;
59
+ crossorigin: 'anonymous';
60
+ 'data-org': string;
61
+ 'data-api'?: string;
62
+ }
63
+ /**
64
+ * Builds the tracker `<script>` attributes from the same configuration the client uses, so the
65
+ * tracker always reports to the gateway the site reads from. Returns `undefined` when no
66
+ * organisation id is configured, which is the case in builds that should not report at all.
67
+ */
68
+ export declare function analyticsTrackerScript(options?: EldraTrackerScriptOptions): EldraTrackerScript | undefined;
69
+ //#endregion
70
+ //#region src/image.d.ts
71
+ /** A size the media host serves by path suffix; `original` is the uploaded file, untransformed. */
72
+ type EldraImageVariant = 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'original';
73
+ /** The variants the media host resizes, narrowest first. */
74
+ type EldraSizedImageVariant = Exclude<EldraImageVariant, 'original'>;
75
+ /**
76
+ * The maximum width in pixels of each resized variant. The host scales down only, so an original
77
+ * narrower than a variant comes back at its own width.
78
+ */
79
+ export declare const ELDRA_IMAGE_VARIANT_WIDTHS: Readonly<Record<EldraSizedImageVariant, number>>;
80
+ /**
81
+ * A media URL as the API returns it, or any object carrying one (`thumbnail`, `mediaLinks[]`, a
82
+ * CMS media item). `contentType`, when present, keeps formats the host does not resize out of
83
+ * `srcset`.
84
+ */
85
+ type EldraImageSource = string | {
86
+ url?: string | null;
87
+ contentType?: string | null;
88
+ } | null | undefined;
89
+ /** Whether the source is an Eldra media asset the host can resize. */
90
+ export declare function isEldraImage(source: EldraImageSource): boolean;
91
+ /**
92
+ * The URL of one variant of an Eldra media asset. A URL that already names a variant is switched
93
+ * to the one asked for. Any other URL — an external image, an SVG, a GIF — comes back unchanged.
94
+ */
95
+ export declare function imageUrl(source: string, variant: EldraImageVariant): string;
96
+ export declare function imageUrl(source: EldraImageSource, variant: EldraImageVariant): string | undefined;
97
+ /**
98
+ * The narrowest variant at least `width` CSS pixels wide at the given pixel density, or `full`
99
+ * when nothing is that wide.
100
+ */
101
+ export declare function imageVariantFor(width: number, density?: number): EldraSizedImageVariant;
102
+ interface EldraImageSrcsetOptions {
103
+ /**
104
+ * The original's width in pixels, when you know it. Variants wider than it would be the same
105
+ * pixels at a new URL, so they are dropped, and the last one is described at its true width.
106
+ */
107
+ originalWidth?: number;
108
+ }
109
+ /**
110
+ * A `srcset` over the resized variants of an Eldra media asset, each described by its width. Returns
111
+ * `undefined` for anything else, so `<img :srcset>` simply drops the attribute.
112
+ */
113
+ export declare function imageSrcset(source: EldraImageSource, options?: EldraImageSrcsetOptions): string | undefined;
114
+ interface EldraResponsiveImageOptions extends EldraImageSrcsetOptions {
115
+ /**
116
+ * How wide the image is laid out, as an `<img sizes>` value: `100vw` for a full-bleed banner,
117
+ * `(min-width: 1024px) 25vw, 50vw` for a four-up grid that is two-up on phones.
118
+ */
119
+ sizes: string;
120
+ /** The variant in `src`, for a browser that ignores `srcset`. Defaults to `md`. */
121
+ variant?: EldraSizedImageVariant;
122
+ /**
123
+ * The width-to-height ratio of the box the image fills, such as `4 / 5`. It becomes `width` and
124
+ * `height` attributes, which reserve the space before the image loads.
125
+ */
126
+ aspectRatio?: number;
127
+ /** Explicit `width` and `height` attributes; they take precedence over `aspectRatio`. */
128
+ width?: number;
129
+ height?: number;
130
+ }
131
+ /** Attributes for an `<img>`; spread them onto the tag. */
132
+ interface EldraResponsiveImage {
133
+ src: string;
134
+ srcset?: string;
135
+ sizes?: string;
136
+ width?: number;
137
+ height?: number;
138
+ }
139
+ /**
140
+ * The `src`, `srcset`, `sizes`, `width` and `height` for one image. An external image gets its URL
141
+ * as `src` and no `srcset`. Returns `undefined` when there is no URL to render.
142
+ */
143
+ export declare function responsiveImage(source: EldraImageSource, options: EldraResponsiveImageOptions): EldraResponsiveImage | undefined;
144
+ //#endregion
145
+ export type { EldraAddCartItemInput, EldraCart, EldraCartClient, EldraCartItem, EldraCartSession, EldraCartSessionOptions, EldraCartTotals, EldraCatalogClient, EldraCatalogGetProductOptions, EldraCatalogListProductsOptions, EldraCategory, EldraCheckoutClient, EldraCheckoutHandoffOptions, EldraClient, EldraClientOptions, EldraCmsClient, EldraCmsEntryList, EldraCmsEntryListDisplayMode, EldraCmsEntryListEntry, EldraCmsEntryListFilterCriterion, EldraCmsGetEntryByUniqueFieldOptions, EldraCmsGetOptions, EldraCmsListOptions, EldraCmsResolveEntryListOptions, EldraCmsResolveEntryListResponse, EldraCmsResolvedEntryList, EldraCollection, EldraCollectionList, EldraCollectionListOptions, EldraCollectionProductsOptions, EldraContract, EldraContractBody, EldraContractItem, EldraContractMethod, EldraContractPath, EldraContractPaths, EldraContractProp, EldraContractQuery, EldraContractResponse, EldraDiscountResult, EldraFeature, EldraFeatureCapabilities, EldraFeatureClient, EldraHttpClient, EldraHttpRequest, EldraImageSource, EldraImageSrcsetOptions, EldraImageVariant, EldraInventoryClient, EldraKeyValueStorage, EldraLocaleOptions, EldraOrder, EldraOrderAccessTokenOptions, EldraOrderAccessTokens, EldraOrderLine, EldraOrderReadOptions, EldraOrdersClient, EldraOrganizationDetails, EldraOrganizationFeature, EldraOrganizationOptions, EldraPageMeta, EldraPaginated, EldraProductDetails, EldraProductList, EldraProductListItem, EldraProductMediaLink, EldraProductOption, EldraProductOptionValue, EldraProductThumbnail, EldraProductVariant, EldraRecoveredBasket, EldraRecoveredBasketItem, EldraRequestContext, EldraRequestOptions, EldraResponsiveImage, EldraResponsiveImageOptions, EldraSearchOptions, EldraSearchResponse, EldraSizedImageVariant, EldraStockAvailability, EldraStockAvailabilityInput, EldraStockAvailabilityItem, EldraTrackerScript, EldraTrackerScriptOptions, RuntimeEnv, RuntimeValue };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as getEldraClient, i as createEldraClient, n as DEFAULT_ELDRA_CHECKOUT_URL, o as initEldraClient, r as EldraHttpError, t as DEFAULT_ELDRA_API_BASE_URL } from "./client-DEKwEhpg.js";
1
+ import { a as getEldraClient, c as resolveOrgId, i as createEldraClient, n as DEFAULT_ELDRA_CHECKOUT_URL, o as initEldraClient, r as EldraHttpError, s as resolveApiBaseUrl, t as DEFAULT_ELDRA_API_BASE_URL } from "./client-DVn7qqKo.js";
2
2
  //#region src/storage.ts
3
3
  const DEFAULT_CART_KEY = "eldra.cartId";
4
4
  const DEFAULT_ORDER_TOKEN_PREFIX = "eldra.orderAccessToken.";
@@ -47,4 +47,117 @@ function createOrderAccessTokens(options = {}) {
47
47
  };
48
48
  }
49
49
  //#endregion
50
- export { DEFAULT_ELDRA_API_BASE_URL, DEFAULT_ELDRA_CHECKOUT_URL, EldraHttpError, createCartSession, createEldraClient, createOrderAccessTokens, getEldraClient, initEldraClient };
50
+ //#region src/tracker.ts
51
+ /**
52
+ * Builds the tracker `<script>` attributes from the same configuration the client uses, so the
53
+ * tracker always reports to the gateway the site reads from. Returns `undefined` when no
54
+ * organisation id is configured, which is the case in builds that should not report at all.
55
+ */
56
+ function analyticsTrackerScript(options = {}) {
57
+ const orgId = resolveOrgId(options);
58
+ if (!orgId) return;
59
+ const script = {
60
+ src: `${new URL(resolveApiBaseUrl(options)).origin}/js/script.js`,
61
+ defer: true,
62
+ crossorigin: "anonymous",
63
+ "data-org": orgId
64
+ };
65
+ if (options.eventOrigin) script["data-api"] = options.eventOrigin;
66
+ return script;
67
+ }
68
+ //#endregion
69
+ //#region src/image.ts
70
+ /**
71
+ * The maximum width in pixels of each resized variant. The host scales down only, so an original
72
+ * narrower than a variant comes back at its own width.
73
+ */
74
+ const ELDRA_IMAGE_VARIANT_WIDTHS = {
75
+ sm: 400,
76
+ md: 800,
77
+ lg: 1200,
78
+ xl: 1920,
79
+ full: 2560
80
+ };
81
+ const SIZED_VARIANTS = Object.keys(ELDRA_IMAGE_VARIANT_WIDTHS);
82
+ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
83
+ const ELDRA_ASSET_URL = new RegExp(`^((?:(?:https?:)?//[^/\\s,?#]+)?(?:/[^\\s,?#]*)?/public/${UUID}/assets/${UUID})(?:/(?:sm|md|lg|xl|full|original))?/?$`, "i");
84
+ const RESIZABLE_CONTENT_TYPES = /* @__PURE__ */ new Set([
85
+ "image/jpeg",
86
+ "image/png",
87
+ "image/webp",
88
+ "image/avif",
89
+ "image/heic",
90
+ "image/heif"
91
+ ]);
92
+ function sourceUrl(source) {
93
+ const url = typeof source === "string" ? source : source?.url;
94
+ return url ? url : void 0;
95
+ }
96
+ function resizableAssetBase(source) {
97
+ const url = sourceUrl(source);
98
+ if (!url) return void 0;
99
+ const contentType = typeof source === "object" ? source?.contentType : void 0;
100
+ if (contentType && !RESIZABLE_CONTENT_TYPES.has(contentType.toLowerCase())) return void 0;
101
+ return ELDRA_ASSET_URL.exec(url)?.[1];
102
+ }
103
+ /** Whether the source is an Eldra media asset the host can resize. */
104
+ function isEldraImage(source) {
105
+ return resizableAssetBase(source) !== void 0;
106
+ }
107
+ function imageUrl(source, variant) {
108
+ const base = resizableAssetBase(source);
109
+ return base ? `${base}/${variant}` : sourceUrl(source);
110
+ }
111
+ /**
112
+ * The narrowest variant at least `width` CSS pixels wide at the given pixel density, or `full`
113
+ * when nothing is that wide.
114
+ */
115
+ function imageVariantFor(width, density = 1) {
116
+ const needed = width * density;
117
+ if (!Number.isFinite(needed) || needed <= 0) throw new RangeError(`imageVariantFor needs a positive width, got ${width} at ${density}x`);
118
+ return SIZED_VARIANTS.find((variant) => ELDRA_IMAGE_VARIANT_WIDTHS[variant] >= needed) ?? "full";
119
+ }
120
+ /**
121
+ * A `srcset` over the resized variants of an Eldra media asset, each described by its width. Returns
122
+ * `undefined` for anything else, so `<img :srcset>` simply drops the attribute.
123
+ */
124
+ function imageSrcset(source, options = {}) {
125
+ const base = resizableAssetBase(source);
126
+ if (!base) return void 0;
127
+ const { originalWidth } = options;
128
+ const candidates = [];
129
+ for (const variant of SIZED_VARIANTS) {
130
+ const width = ELDRA_IMAGE_VARIANT_WIDTHS[variant];
131
+ if (originalWidth !== void 0 && originalWidth > 0 && width >= originalWidth) {
132
+ candidates.push(`${base}/${variant} ${Math.round(originalWidth)}w`);
133
+ break;
134
+ }
135
+ candidates.push(`${base}/${variant} ${width}w`);
136
+ }
137
+ return candidates.join(", ");
138
+ }
139
+ /**
140
+ * The `src`, `srcset`, `sizes`, `width` and `height` for one image. An external image gets its URL
141
+ * as `src` and no `srcset`. Returns `undefined` when there is no URL to render.
142
+ */
143
+ function responsiveImage(source, options) {
144
+ const variant = options.variant ?? "md";
145
+ const src = imageUrl(source, variant);
146
+ if (!src) return void 0;
147
+ const image = { src };
148
+ const srcset = imageSrcset(source, options);
149
+ if (srcset) {
150
+ image.srcset = srcset;
151
+ image.sizes = options.sizes;
152
+ }
153
+ if (options.width !== void 0 && options.height !== void 0) {
154
+ image.width = options.width;
155
+ image.height = options.height;
156
+ } else if (options.aspectRatio !== void 0 && options.aspectRatio > 0) {
157
+ image.width = ELDRA_IMAGE_VARIANT_WIDTHS[variant];
158
+ image.height = Math.round(image.width / options.aspectRatio);
159
+ }
160
+ return image;
161
+ }
162
+ //#endregion
163
+ export { DEFAULT_ELDRA_API_BASE_URL, DEFAULT_ELDRA_CHECKOUT_URL, ELDRA_IMAGE_VARIANT_WIDTHS, EldraHttpError, analyticsTrackerScript, createCartSession, createEldraClient, createOrderAccessTokens, getEldraClient, imageSrcset, imageUrl, imageVariantFor, initEldraClient, isEldraImage, responsiveImage };
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./client-DEKwEhpg.js";
1
+ import "./client-DVn7qqKo.js";
2
2
  import { access, mkdir, writeFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import openapiTS, { astToString } from "openapi-typescript";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/sdk",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Framework-free client for the Eldra Web Studio public storefront API: CMS, catalog, cart, checkout handoff, orders, inventory. Types generated from your gateway's OpenAPI document and CMS schemas at build time.",
5
5
  "keywords": [
6
6
  "cms",