@eldrajs/sdk 0.2.8 → 0.3.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
@@ -9,6 +9,42 @@ platform repository.
9
9
 
10
10
  ## Unreleased
11
11
 
12
+ - **`EldraFormDefinition.consentText` (WS-386, contract 4.13.0).** A form that subscribes the
13
+ visitor now publishes the consent sentence per locale, with the shop name already filled in
14
+ (`consentText?: EldraFormLocalized`, present only when `kinds` contains `subscribe`). Show it
15
+ beside the submit button as escaped plain text; the platform records it as the proof of consent
16
+ (followed by the labels of any ticked `consent` fields). No new submit field and no checkbox.
17
+
18
+ - **Forms are gated by the `FORMS` feature, and mailed links go to the web gateway (WS-386,
19
+ contract 4.12.0).** `client.forms` no longer needs `PAGE_BUILDER`: the organisation's new `FORMS`
20
+ feature switches on form reads and submissions, so a headless app with no theme or page builder
21
+ can use them (its origin must be a registered storefront origin). The confirm and unsubscribe
22
+ links in form mails now point at the web gateway's own page rather than the storefront's domain;
23
+ nothing changes for `confirm(token)` and `unsubscribe(token)`. No SDK code change.
24
+
25
+ - **`EldraFormFieldType` gains `number` and `url` (WS-386, contract 4.11.0).** The two types Core
26
+ accepts besides the earlier set from contract 4.11.0 on; both carry text the platform validates
27
+ (a finite number, with a decimal comma stored as a point, and an absolute http(s) URL).
28
+
29
+ - **`client.forms.confirm(token)` and `unsubscribe(token)` POST (WS-386, contract 4.10.0).** The
30
+ emailed confirm and unsubscribe links no longer act on a `GET`: Core answers a `GET` with a small
31
+ HTML page whose button posts the token back, so a mail scanner that prefetches the link confirms
32
+ and unsubscribes nobody. The two methods now `POST` the same paths with the token in the query and
33
+ still resolve `{ status }`; confirming or unsubscribing twice is a success. Needs a gateway at
34
+ contract 4.10.0 or later (the `GET` JSON answer of 4.7.0 to 4.9.0, never released, is gone).
35
+ - **`client.forms`: the site-forms API (WS-386).** `get(key)` reads a form definition,
36
+ `submit(key, { values, locale, pagePath, turnstileToken?, hp? })` posts a submission and
37
+ `confirm(token)` / `unsubscribe(token)` finish a subscriber's emailed links. A `422` resolves as
38
+ `{ status: 'invalid', errors, form }` (field-keyed, ready for `apiErrors`) rather than throwing;
39
+ `404`, `413` and `429` reject with `EldraHttpError`. New types `EldraFormDefinition`,
40
+ `EldraFormField`, `EldraFormSubmitInput`, `EldraFormSubmitResult` and friends, hand-written like
41
+ `EldraPlatformConfig`. Needs a gateway at contract 4.4.0 or later.
42
+ - **Icelandic formatting that prints the same on every runtime: `@eldrajs/sdk/format`.**
43
+ `numberFormat`, `formatPrice` and `comparator`/`compareIcelandic`, plus `./format/date`,
44
+ `./format/list`, `./format/relative-time` and `./format/display-names`. Icelandic and English come
45
+ from the package's own CLDR 48.2 data, so Chrome and Cloudflare Workers, which lack it, print what
46
+ Node and Safari do; every other locale goes to the runtime's `Intl`. Dates are UTC. No new
47
+ runtime dependency: the formatjs code is bundled.
12
48
  - **A request that answered `429` or `503` is retried instead of failing.** The gateway rate-limits a
13
49
  client by requests per minute, which a static build of a real catalogue meets routinely. The
14
50
  default `fetch` transport now repeats an **idempotent** request (`GET`/`HEAD`/`OPTIONS` — never a
package/README.md CHANGED
@@ -61,6 +61,27 @@ const image = responsiveImage(product.thumbnail, {
61
61
  parts on their own. Anything that is not an Eldra media asset comes back unchanged. The variants,
62
62
  choosing `sizes`, and avoiding layout shift are in [docs/images.md](../../docs/images.md).
63
63
 
64
+ ## Icelandic formatting
65
+
66
+ Chrome, Edge and Cloudflare Workers ship without Icelandic locale data, and `Intl` then prints
67
+ English without an error (`ISK 1,234,567` for `1.234.567 kr.`), which also breaks hydration. The
68
+ `./format` entries print Icelandic and English the same on every runtime:
69
+
70
+ ```ts
71
+ import { comparator, formatPrice, numberFormat } from '@eldrajs/sdk/format';
72
+ import { dateTimeFormat } from '@eldrajs/sdk/format/date';
73
+
74
+ formatPrice(12900, 'ISK', 'is-IS'); // "12.900 kr."
75
+ formatPrice(12900, 'ISK', 'en-US'); // "ISK 12,900"
76
+ dateTimeFormat('is-IS', { dateStyle: 'long' }).format(date); // "12. október 2026"
77
+ towns.sort(comparator('is-IS')); // Akureyri, Ísafjörður, Þórshöfn, Ölfus
78
+ ```
79
+
80
+ Each takes the options of the `Intl` constructor it is named after and returns an object with the
81
+ same methods. `./format/list`, `./format/relative-time` and `./format/display-names` cover the rest.
82
+ Import only the entries you use; each carries its own data. The rules and what it costs are in
83
+ [docs/icelandic-formatting.md](../../docs/icelandic-formatting.md).
84
+
64
85
  ## What is in the client
65
86
 
66
87
  | Group | Methods |
@@ -73,6 +94,34 @@ choosing `sizes`, and avoiding layout shift are in [docs/images.md](../../docs/i
73
94
  | `inventory` | `availability` |
74
95
  | `features` | `getOrganization`, `list`, `isEnabled`, `getCapabilities`, `getCommerce` |
75
96
  | `platform` | `config` |
97
+ | `forms` | `get`, `submit`, `confirm`, `unsubscribe` |
98
+
99
+ `forms` is the site-forms API: `get(key)` reads a form's definition (fields with a label per locale,
100
+ the honeypot field's name, the Turnstile site key, the success message), and `submit(key, { values,
101
+ locale, pagePath, turnstileToken?, hp? })` posts a submission. A `422` is an answer, not a failure:
102
+ `submit` resolves `{ status: 'invalid', errors, form }` with the field-keyed messages a form shows
103
+ inline (`errors` is the shape `@eldrajs/ui`'s `apiErrors` takes), and `{ status: 'ok', pending }` on
104
+ success, where `pending` means a double opt-in email is on its way. A `404` (unknown form), `413`
105
+ (oversize) and `429` (rate limited) reject with `EldraHttpError`. `confirm(token)` and
106
+ `unsubscribe(token)` finish the subscriber's emailed links; those links point at the web gateway's
107
+ own page, so an app needs no route of its own for them. Forms need the organisation's `FORMS`
108
+ feature (not `PAGE_BUILDER`) and work with no theme: the app's origin must be registered as a
109
+ storefront origin in Studio, and when the definition has a Turnstile site key the app renders the
110
+ widget itself and sends the token as `turnstileToken`. The form types are hand-written, like
111
+ `EldraPlatformConfig`: the SDK ships no response types.
112
+
113
+ **Proof of consent.** For a form that subscribes the visitor, the platform records what they agreed
114
+ to, and that wording is always real: the definition's `consentText` (a sentence per locale, with the
115
+ shop name already filled in; present only when `kinds` contains `subscribe`). Show it next to the
116
+ submit button as escaped plain text; submitting is the consent, so there is no extra checkbox and
117
+ nothing extra to send. The platform stores the sentence in the visitor's `locale`, followed by the
118
+ label of each `consent` field they ticked, taken from the form definition on the server, never from
119
+ the client. `pagePath` is stored as the page the submission came from, so send the real
120
+ `location.pathname`; it is client-supplied and informational. IP addresses and user agents are not
121
+ stored.
122
+
123
+ Subscribers and this record are owned by the platform's marketing service; `confirm` and
124
+ `unsubscribe` keep calling the same `/site/v1/forms/subscriptions/*` paths, so nothing changes in an app.
76
125
 
77
126
  `checkout.url({ cartId, locale })` is where a storefront sends the shopper. The platform hosts the
78
127
  checkout page, so the client asks the platform where (`platform.config()`, a public read cached per
@@ -0,0 +1,18 @@
1
+ # Third-party notices
2
+
3
+ The `./format` entries bundle code from [formatjs](https://github.com/formatjs/formatjs) (`@formatjs/intl-numberformat`, `-datetimeformat`, `-listformat`, `-relativetimeformat`, `-displaynames`, `@formatjs/bigdecimal`, `@formatjs/intl-localematcher`, `@formatjs/fast-memoize`) and locale data derived from the Unicode CLDR. formatjs is distributed under this licence:
4
+
5
+ ```
6
+ MIT License
7
+
8
+ Copyright (c) 2023 FormatJS
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
15
+ ```
16
+
17
+ The locale data is derived from the Unicode Common Locale Data Repository, under the
18
+ [Unicode License v3](https://www.unicode.org/license.txt).
@@ -439,6 +439,41 @@ function createEldraClient(options) {
439
439
  })
440
440
  },
441
441
  platform: { config: (readOptions) => readPlatformConfig(readOptions) },
442
+ forms: {
443
+ get: (key, context) => request({
444
+ ...context,
445
+ path: `/site/v1/forms/${encodeURIComponent(key)}`
446
+ }),
447
+ submit: async (key, input, context) => {
448
+ try {
449
+ const answer = await request({
450
+ ...context,
451
+ method: "POST",
452
+ path: `/site/v1/forms/${encodeURIComponent(key)}/submissions`,
453
+ body: input
454
+ });
455
+ return {
456
+ status: "ok",
457
+ pending: typeof answer === "object" && answer !== null && "pending" in answer ? answer.pending === true : false
458
+ };
459
+ } catch (error) {
460
+ if (error instanceof EldraHttpError && error.status === 422) return toFormInvalid(error.body);
461
+ throw error;
462
+ }
463
+ },
464
+ confirm: (token, context) => request({
465
+ ...context,
466
+ method: "POST",
467
+ path: "/site/v1/forms/subscriptions/confirm",
468
+ query: { token }
469
+ }),
470
+ unsubscribe: (token, context) => request({
471
+ ...context,
472
+ method: "POST",
473
+ path: "/site/v1/forms/subscriptions/unsubscribe",
474
+ query: { token }
475
+ })
476
+ },
442
477
  checkout: { url: async (handoff, readOptions) => {
443
478
  let checkoutUrl = null;
444
479
  let cause;
@@ -579,6 +614,26 @@ function resolveEntryListBody(entryList) {
579
614
  pageSize: entryList.pageSize
580
615
  };
581
616
  }
617
+ /**
618
+ * A `422` body, narrowed to the field-keyed shape. Anything that is not a string array under a key
619
+ * is dropped rather than guessed at, so a malformed body still reads as "invalid" with no messages
620
+ * (the caller shows its own generic line) instead of throwing a TypeError at the visitor.
621
+ */
622
+ function toFormInvalid(body) {
623
+ const record = typeof body === "object" && body !== null ? body : {};
624
+ const strings = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
625
+ const errors = {};
626
+ const rawErrors = record.errors;
627
+ if (typeof rawErrors === "object" && rawErrors !== null && !Array.isArray(rawErrors)) for (const [field, messages] of Object.entries(rawErrors)) {
628
+ const list = strings(messages);
629
+ if (list.length > 0) errors[field] = list;
630
+ }
631
+ return {
632
+ status: "invalid",
633
+ errors,
634
+ form: strings(record.form)
635
+ };
636
+ }
582
637
  function createHttpRequest(clientOptions, requestOptions) {
583
638
  const method = requestOptions.method ?? (requestOptions.body === void 0 ? "GET" : "POST");
584
639
  const headers = mergeHeaders(resolveRuntimeValue(clientOptions.headers), requestOptions.headers);
@@ -0,0 +1,4 @@
1
+ //#region src/format/date.d.ts
2
+ /** `new Intl.DateTimeFormat(locale, options)` with the same text everywhere; the time zone defaults to UTC, Iceland's. */
3
+ export declare function dateTimeFormat(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat;
4
+ //#endregion