@eldrajs/sdk 0.3.2 → 0.4.1

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,24 @@ platform repository.
9
9
 
10
10
  ## Unreleased
11
11
 
12
+ - **`installIcelandicIntl()` (new entry `@eldrajs/sdk/format/intl`)** — Icelandic for code that calls
13
+ `Intl` itself (date pickers, vue-i18n, chart libraries). Where the runtime has no Icelandic data,
14
+ it patches `Intl.NumberFormat`, `Intl.DateTimeFormat`, `Number.prototype.toLocaleString` and
15
+ `Date.prototype.toLocale{,Date,Time}String` so Icelandic requests use this package's data; every
16
+ other locale stays with the runtime. Opt-in, nothing runs on import; `{ force: true }` patches
17
+ runtimes that have Icelandic too (use it on both sides of a server render), and the function the
18
+ installing call returns restores the runtime; a repeat call is a no-op. Only dates in a UTC zone
19
+ are patched; a date in another zone, the runtime's default included, stays with the runtime.
20
+
21
+ - **Campaign attribution (WS-546, contract 5.4.0).** `captureCampaignAttribution(url?)` keeps a
22
+ landing URL's `utm_source`, `utm_medium`, `utm_campaign` and `utm_id` (as `campaignId`, only when
23
+ it is a uuid) in `localStorage` for 30 days, replacing an earlier landing whole; nothing else, and
24
+ nothing outside a browser. Each tag loses control characters and is cut to 100 characters; a tag
25
+ holding `@` is dropped, since it may be an email address. `cart.addItem` sends it as `attribution`
26
+ with every add, which needs a gateway on contract 5.4.0 or later. New: `readCampaignAttribution()`,
27
+ `clearCampaignAttribution()`, the `EldraCampaignAttribution` type and the client option
28
+ `campaignAttribution` (`{ storage }`, or `false` to send none). Nothing clears it automatically.
29
+
12
30
  - **Images use the size the API gives them (contract 4.14.0).** `EldraImageSource` accepts the
13
31
  `width` and `height` an image object now carries (its pixels as displayed). `imageSrcset` stops at
14
32
  that width unless `originalWidth` is passed, and `responsiveImage` sets `width`/`height` to the
package/README.md CHANGED
@@ -83,6 +83,27 @@ same methods. `./format/list`, `./format/relative-time` and `./format/display-na
83
83
  Import only the entries you use; each carries its own data. The rules and what it costs are in
84
84
  [docs/icelandic-formatting.md](../../docs/icelandic-formatting.md).
85
85
 
86
+ ### Code that calls `Intl` itself
87
+
88
+ A date picker, vue-i18n's `n()`/`d()` or a chart library formats with `Intl` directly. Opt in to
89
+ Icelandic there with one call, before anything formats:
90
+
91
+ ```ts
92
+ import { installIcelandicIntl } from '@eldrajs/sdk/format/intl';
93
+
94
+ installIcelandicIntl();
95
+ ```
96
+
97
+ Where the runtime has no Icelandic, it patches `Intl.NumberFormat`, `Intl.DateTimeFormat`,
98
+ `Number.prototype.toLocaleString` and `Date.prototype.toLocale{,Date,Time}String` so a request for
99
+ Icelandic is formatted from this package's data. Every other locale goes to the runtime untouched,
100
+ so a browser on `en-GB` keeps `12/10/2026`. Where the runtime has Icelandic (Node, Safari, Firefox)
101
+ it does nothing, unless `{ force: true }`; a server render installs it with `force` on both sides so
102
+ the two match. The call that installs it returns a function that restores the runtime's `Intl`; a
103
+ later call while it is installed returns one that does nothing. Dates in a zone other than UTC, the
104
+ runtime's default included, stay with the runtime and can print in English; pass `timeZone: 'UTC'`.
105
+ Lists, relative times, names and sorting are not patched; use the functions above.
106
+
86
107
  ## What is in the client
87
108
 
88
109
  | Group | Methods |
@@ -140,6 +161,75 @@ number rather than under a currency symbol nobody chose. It reads the same organ
140
161
  rest of the group reads, so a caller already holding an `EldraOrganizationDetails` should take
141
162
  `commerce` off it instead of asking again.
142
163
 
164
+ ## Campaign attribution
165
+
166
+ A merchant's campaign mails link to the storefront with `utm_source`, `utm_medium`, `utm_campaign`
167
+ and `utm_id` (the campaign's id). Call `captureCampaignAttribution()` in the browser on the first
168
+ page and after every navigation. When the URL carries any of the four, the kit notes them with the
169
+ time. **It keeps them only once the visitor agrees.** Keeping them in the browser to credit a sale is
170
+ not something the shop needs in order to work, so in Iceland it needs consent (88. gr. 2. mgr. laga
171
+ 70/2022 as Fjarskiptastofa reads it, ákvörðun 14/2024). Your consent tool answers with one call each:
172
+
173
+ ```ts
174
+ import {
175
+ captureCampaignAttribution,
176
+ grantCampaignAttributionConsent,
177
+ withdrawCampaignAttributionConsent,
178
+ } from '@eldrajs/sdk';
179
+
180
+ captureCampaignAttribution(); // reads location.href
181
+ router.afterEach((to, _from, failure) => {
182
+ if (!failure) captureCampaignAttribution(to.fullPath);
183
+ });
184
+ consentTool.onChange((choice) =>
185
+ choice.marketing ? grantCampaignAttributionConsent() : withdrawCampaignAttributionConsent()
186
+ );
187
+ ```
188
+
189
+ - **Before consent** the landing is held in memory for this page load only, and `cart.addItem`
190
+ sends nothing.
191
+ - **On consent** the landing of this page load is kept in `localStorage` (key
192
+ `eldra.campaignAttribution`) for 30 days from when the visitor landed. Later landings are kept as
193
+ they come, a later one replacing the earlier whole. From then on `cart.addItem` sends them as
194
+ `attribution` with every add, and the platform credits the order made from that cart to the
195
+ campaign.
196
+ - **Consent is not stored by the kit.** Call `grantCampaignAttributionConsent()` on every page load
197
+ where it stands, as consent tools report a stored choice on load.
198
+ - **On withdrawal** the kept value is removed, and later carts carry none.
199
+ - A value kept before this version, without consent, is removed at the next capture and never sent.
200
+ - A site with no consent tool keeps nothing. Its orders are still credited by the platform's email
201
+ match, "Orders from recipients" in Studio.
202
+
203
+ A Nuxt theme on `@eldrajs/theme-nuxt` captures by itself and takes the consent answer from the
204
+ window ([Campaign attribution](../../docs/themes.md#campaign-attribution)).
205
+
206
+ **It stores no personal data.** It keeps those four campaign-level tags and nothing else: no click id
207
+ (`gclid`, `fbclid`), no referrer, no visitor id, nothing about the person. `utm_id` is kept as
208
+ `campaignId` only when it is a uuid, as Eldra's campaign ids are. A tag loses its control characters
209
+ and is cut to 100 characters, as the gateway does, and a tag holding an `@` is dropped, since it may be
210
+ an email address. Outside a browser nothing is held, kept or read: a server's `localStorage` (Node's,
211
+ when enabled) is shared by every visitor it serves, so the default there is no storage at all.
212
+
213
+ **Clearing it.** The kit clears it only on withdrawal. Checkout is the platform's, so a storefront
214
+ has no "order placed" moment of its own, and a second order inside the 30 days is still that
215
+ campaign's result. `clearCampaignAttribution()` forgets it, for a storefront that wants one order per
216
+ landing; `readCampaignAttribution()` returns what is kept, or `null` once it has expired or while
217
+ there is no consent.
218
+
219
+ **Options.** `captureCampaignAttribution(url, { storage, maxAgeMs })` takes any
220
+ `getItem`/`setItem`/`removeItem` storage (`null` keeps nothing) and a shorter or longer window in
221
+ milliseconds (one that is not finite keeps the 30 days). Give the consent calls and the client the
222
+ same storage, as `grantCampaignAttributionConsent({ storage })` and
223
+ `createEldraClient({ campaignAttribution: { storage } })`, or
224
+ `campaignAttribution: false` to send none. An `addItem` input that names `attribution` itself is sent
225
+ exactly as given.
226
+
227
+ **Gateway contract 5.4.0 or later.** `attribution` joins the add-items body in public contract 5.4.0;
228
+ an older gateway refuses a body that carries it (`422`), so a client against one passes
229
+ `campaignAttribution: false`. Your generated `EldraAddCartItemInput` names `attribution` once
230
+ `.eldra/web-studio/contract.ts` is regenerated against a 5.4.0 gateway; the SDK adds the field
231
+ itself, so no code changes before or after.
232
+
143
233
  ## Retrying what the gateway refused for now
144
234
 
145
235
  The gateway rate-limits a client by requests per minute, so a static build of a real catalogue —
@@ -1,3 +1,169 @@
1
+ // src/storage.ts
2
+ const DEFAULT_CART_KEY = "eldra.cartId";
3
+ const DEFAULT_ORDER_TOKEN_PREFIX = "eldra.orderAccessToken.";
4
+ function browserStorage(name) {
5
+ try {
6
+ return globalThis[name] ?? null;
7
+ } catch {
8
+ return null;
9
+ }
10
+ }
11
+ function safeRead(storage, key) {
12
+ try {
13
+ return storage?.getItem(key) ?? null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ function safeWrite(storage, key, value) {
19
+ try {
20
+ if (value === null) storage?.removeItem(key);
21
+ else storage?.setItem(key, value);
22
+ } catch {}
23
+ }
24
+ /** The cart id a browser holds between visits. Lives in localStorage so the basket survives a closed tab. */
25
+ function createCartSession(options = {}) {
26
+ const storage = options.storage === void 0 ? browserStorage("localStorage") : options.storage;
27
+ const key = options.key ?? DEFAULT_CART_KEY;
28
+ return {
29
+ read: () => safeRead(storage, key),
30
+ remember: (cartId) => safeWrite(storage, key, cartId),
31
+ forget: () => safeWrite(storage, key, null)
32
+ };
33
+ }
34
+ /**
35
+ * The one-time order access token, kept in sessionStorage rather than the return URL so it
36
+ * survives the payment provider's redirect without landing in a URL, a log or a Referer.
37
+ */
38
+ function createOrderAccessTokens(options = {}) {
39
+ const storage = options.storage === void 0 ? browserStorage("sessionStorage") : options.storage;
40
+ const prefix = options.keyPrefix ?? DEFAULT_ORDER_TOKEN_PREFIX;
41
+ return {
42
+ remember: (orderId, token) => {
43
+ if (token) safeWrite(storage, prefix + orderId, token);
44
+ },
45
+ read: (orderId) => safeRead(storage, prefix + orderId)
46
+ };
47
+ }
48
+ // src/attribution.ts
49
+ const STORAGE_KEY = "eldra.campaignAttribution";
50
+ const DEFAULT_MAX_AGE_MS = 2592e6;
51
+ const MAX_TAG_LENGTH = 100;
52
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
53
+ let consented = false;
54
+ let pending = null;
55
+ /**
56
+ * Notes the campaign tags `url` (default `location.href`) carries, replacing any earlier landing; `null` when none.
57
+ * The landing stays in memory until the visitor agrees (`grantCampaignAttributionConsent`), and is kept in storage
58
+ * only from then on.
59
+ */
60
+ function captureCampaignAttribution(url, options = {}) {
61
+ const storage = storageOf(options);
62
+ if (!consented) dropUnconsented(storage);
63
+ const params = searchParamsOf(url ?? currentHref());
64
+ if (params === null) return null;
65
+ const attribution = toAttribution({
66
+ campaignId: params.get("utm_id"),
67
+ utmSource: params.get("utm_source"),
68
+ utmMedium: params.get("utm_medium"),
69
+ utmCampaign: params.get("utm_campaign")
70
+ });
71
+ if (attribution === null) return null;
72
+ const capturedAt = Date.now();
73
+ const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
74
+ const landing = {
75
+ ...attribution,
76
+ capturedAt,
77
+ expiresAt: capturedAt + (Number.isFinite(maxAgeMs) ? maxAgeMs : DEFAULT_MAX_AGE_MS)
78
+ };
79
+ if (storage === null) return attribution;
80
+ pending = landing;
81
+ if (consented) keep(storage, landing);
82
+ return attribution;
83
+ }
84
+ /**
85
+ * The visitor agreed, through the site's consent tool, to the campaign tags being kept: the landing noted in this
86
+ * page load is kept now, and later landings as they come. Call it on every page load where consent stands.
87
+ */
88
+ function grantCampaignAttributionConsent(options = {}) {
89
+ consented = true;
90
+ const storage = storageOf(options);
91
+ if (pending !== null && Date.now() < pending.expiresAt) keep(storage, pending);
92
+ }
93
+ /** The visitor withdrew or refused consent: the kept landing is removed and carts carry none. */
94
+ function withdrawCampaignAttributionConsent(options = {}) {
95
+ consented = false;
96
+ pending = null;
97
+ safeWrite(storageOf(options), STORAGE_KEY, null);
98
+ }
99
+ function keep(storage, landing) {
100
+ safeWrite(storage, STORAGE_KEY, JSON.stringify({
101
+ ...landing,
102
+ consented: true
103
+ }));
104
+ }
105
+ /** Removes a value kept before the kit asked for consent, so nothing kept without it outlives this release. */
106
+ function dropUnconsented(storage) {
107
+ const raw = safeRead(storage, STORAGE_KEY);
108
+ if (raw !== null && parseStored(raw)?.consented !== true) safeWrite(storage, STORAGE_KEY, null);
109
+ }
110
+ /** The kept landing while the visitor's consent stands, or `null` when there is none, it expired or no consent. */
111
+ function readCampaignAttribution(options = {}) {
112
+ if (!consented) return null;
113
+ const storage = storageOf(options);
114
+ const raw = safeRead(storage, STORAGE_KEY);
115
+ if (raw === null) return null;
116
+ const stored = parseStored(raw);
117
+ const attribution = stored !== null && stored.consented === true && typeof stored.expiresAt === "number" && Date.now() < stored.expiresAt ? toAttribution(stored) : null;
118
+ if (attribution === null) safeWrite(storage, STORAGE_KEY, null);
119
+ return attribution;
120
+ }
121
+ /** Forgets the landing, so later carts carry none until the next tagged landing; consent is unchanged. */
122
+ function clearCampaignAttribution(options = {}) {
123
+ pending = null;
124
+ safeWrite(storageOf(options), STORAGE_KEY, null);
125
+ }
126
+ function storageOf(options) {
127
+ if (options.storage !== void 0) return options.storage;
128
+ return typeof globalThis.document === "undefined" ? null : browserStorage("localStorage");
129
+ }
130
+ function currentHref() {
131
+ const href = globalThis.location?.href;
132
+ return typeof href === "string" ? href : void 0;
133
+ }
134
+ function searchParamsOf(url) {
135
+ if (url === void 0) return null;
136
+ try {
137
+ return new URL(String(url), "http://localhost").searchParams;
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+ function parseStored(raw) {
143
+ try {
144
+ const value = JSON.parse(raw);
145
+ return typeof value === "object" && value !== null ? value : null;
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ function toAttribution(raw) {
151
+ const campaignId = tag(raw.campaignId);
152
+ const attribution = {
153
+ campaignId: campaignId !== void 0 && UUID.test(campaignId) ? campaignId.toLowerCase() : void 0,
154
+ utmSource: tag(raw.utmSource),
155
+ utmMedium: tag(raw.utmMedium),
156
+ utmCampaign: tag(raw.utmCampaign)
157
+ };
158
+ const present = Object.entries(attribution).filter(([, value]) => value !== void 0);
159
+ return present.length === 0 ? null : Object.fromEntries(present);
160
+ }
161
+ function tag(value) {
162
+ if (typeof value !== "string") return void 0;
163
+ const cleaned = value.replace(/\p{Cc}/gu, "").trim();
164
+ if (cleaned === "" || cleaned.includes("@")) return void 0;
165
+ return Array.from(cleaned).slice(0, MAX_TAG_LENGTH).join("").trim();
166
+ }
1
167
  /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
2
168
  const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
3
169
  /**
@@ -191,8 +357,7 @@ function abortReason$1(signal) {
191
357
  if (reason !== void 0) return reason;
192
358
  return new DOMException("This operation was aborted", "AbortError");
193
359
  }
194
- //#endregion
195
- //#region src/client.ts
360
+ // src/client.ts
196
361
  const apiBaseUrlEnvKeys = [
197
362
  "ELDRA_API_BASE_URL",
198
363
  "VITE_ELDRA_API_BASE_URL",
@@ -381,12 +546,18 @@ function createEldraClient(options) {
381
546
  })
382
547
  },
383
548
  cart: {
384
- addItem: (input, context) => request({
385
- ...context,
386
- method: "POST",
387
- path: "/shopping-cart/v1/cart/items",
388
- body: input
389
- }),
549
+ addItem: (input, context) => {
550
+ const attribution = options.campaignAttribution === false || "attribution" in input ? null : readCampaignAttribution(options.campaignAttribution);
551
+ return request({
552
+ ...context,
553
+ method: "POST",
554
+ path: "/shopping-cart/v1/cart/items",
555
+ body: attribution === null ? input : {
556
+ ...input,
557
+ attribution
558
+ }
559
+ });
560
+ },
390
561
  get: (cartId, localeOptions, context) => request({
391
562
  ...context,
392
563
  path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}`,
@@ -746,5 +917,4 @@ function appendQueryValue(searchParams, key, value) {
746
917
  function isRawBody(body) {
747
918
  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;
748
919
  }
749
- //#endregion
750
- export { initEldraClient as a, getEldraClient as i, EldraHttpError as n, resolveApiBaseUrl as o, createEldraClient as r, resolveOrgId as s, DEFAULT_ELDRA_API_BASE_URL as t };
920
+ export { initEldraClient as a, captureCampaignAttribution as c, readCampaignAttribution as d, withdrawCampaignAttributionConsent as f, getEldraClient as i, clearCampaignAttribution as l, createOrderAccessTokens as m, EldraHttpError as n, resolveApiBaseUrl as o, createCartSession as p, createEldraClient as r, resolveOrgId as s, DEFAULT_ELDRA_API_BASE_URL as t, grantCampaignAttributionConsent as u };