@asteby/storefront-react 0.14.0 → 0.15.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.
@@ -9,6 +9,16 @@ var SAFE_AUTH_CAPABILITIES = Object.freeze({
9
9
  otp_channels: Object.freeze([])
10
10
  });
11
11
  var FAILURE_TTL_MS = 5e3;
12
+ var LOG_EVERY_MS = 6e4;
13
+ var lastLogAt = -Infinity;
14
+ function logMisconfigured(scopes) {
15
+ const t = Date.now();
16
+ if (t - lastLogAt < LOG_EVERY_MS) return;
17
+ lastLogAt = t;
18
+ console.error(
19
+ `[@asteby/storefront-react] La credencial de la tienda no tiene permisos${scopes.length ? ` (${scopes.join(", ")})` : ""}; las cuentas de comprador no funcionan hasta repararlo en ${storefront.repairPath()}.`
20
+ );
21
+ }
12
22
  var cache = /* @__PURE__ */ new WeakMap();
13
23
  async function loadAuthCapabilities(sf, options = {}) {
14
24
  const now = options.now ?? Date.now;
@@ -17,14 +27,31 @@ async function loadAuthCapabilities(sf, options = {}) {
17
27
  if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value;
18
28
  try {
19
29
  const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : void 0);
30
+ const missing = Array.isArray(got?.missing_scopes) ? got.missing_scopes.filter((x) => typeof x === "string") : [];
20
31
  const value = {
32
+ // `password: false` (including for a missing scope) is respected: the form never offers what the token cannot do.
21
33
  password: got?.password !== false,
22
34
  email_verification: got?.email_verification === true,
23
- otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : []
35
+ otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],
36
+ ...typeof got?.unavailable_reason === "string" ? { unavailable_reason: got.unavailable_reason } : {},
37
+ ...missing.length ? { missing_scopes: missing } : {}
24
38
  };
39
+ if (value.unavailable_reason === "missing_scope") logMisconfigured(missing);
25
40
  cache.set(sf, { at: now(), ok: true, value });
26
41
  return value;
27
- } catch {
42
+ } catch (err) {
43
+ if (storefront.isStorefrontError(err) && err.code === "insufficient_scope") {
44
+ const value = {
45
+ password: false,
46
+ email_verification: false,
47
+ otp_channels: [],
48
+ unavailable_reason: "missing_scope",
49
+ missing_scopes: err.requiredScopes
50
+ };
51
+ logMisconfigured(err.requiredScopes);
52
+ cache.set(sf, { at: now(), ok: false, value });
53
+ return value;
54
+ }
28
55
  cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES });
29
56
  return SAFE_AUTH_CAPABILITIES;
30
57
  }
@@ -42,6 +69,10 @@ var fail = (code, extra = {}, field) => ({
42
69
  });
43
70
  function toFailure(err, ctx, extra) {
44
71
  if (!storefront.isStorefrontError(err)) return fail("unavailable", extra);
72
+ if (err.code === "insufficient_scope") {
73
+ logMisconfigured(err.requiredScopes);
74
+ return fail("store_misconfigured", extra);
75
+ }
45
76
  switch (err.status) {
46
77
  case 401:
47
78
  return fail(ctx === "credentials" ? "invalid_credentials" : ctx === "code" ? "invalid_code" : "unavailable", extra, ctx === "code" ? "code" : void 0);
@@ -86,16 +117,18 @@ function createAuthAction(options) {
86
117
  if (!email) return fail("validation", carry, "email");
87
118
  const caps = await loadCaps(sf);
88
119
  const passwordOn = caps.password;
120
+ const misconfigured = caps.unavailable_reason === "missing_scope";
121
+ const off = () => fail(misconfigured ? "store_misconfigured" : "unsupported", carry);
89
122
  const otpOn = caps.otp_channels.includes("email");
90
123
  try {
91
124
  switch (intent) {
92
125
  case "login": {
93
- if (!passwordOn) return fail("unsupported", carry);
126
+ if (!passwordOn) return off();
94
127
  if (!password) return fail("validation", carry, "password");
95
128
  return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next);
96
129
  }
97
130
  case "register": {
98
- if (!passwordOn) return fail("unsupported", carry);
131
+ if (!passwordOn) return off();
99
132
  if (!password) return fail("validation", carry, "password");
100
133
  const res = await sf.customer.register(
101
134
  { email, password, ...text("first_name").trim() ? { first_name: text("first_name").trim() } : {}, ...text("last_name").trim() ? { last_name: text("last_name").trim() } : {} },
@@ -108,17 +141,17 @@ function createAuthAction(options) {
108
141
  return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next);
109
142
  }
110
143
  case "otp-request": {
111
- if (!otpOn) return fail("unsupported", carry);
144
+ if (!otpOn) return off();
112
145
  await sf.customer.requestOtp({ email }, w);
113
146
  return { ok: true, step: "otp", email };
114
147
  }
115
148
  case "otp-login": {
116
- if (!otpOn) return fail("unsupported", carry);
149
+ if (!otpOn) return off();
117
150
  if (!code) return fail("validation", carry, "code");
118
151
  return await signedIn(await sf.customer.createSession({ email, code }, w), next);
119
152
  }
120
153
  case "forgot": {
121
- if (!passwordOn || !otpOn) return fail("unsupported", carry);
154
+ if (!passwordOn || !otpOn) return off();
122
155
  try {
123
156
  await sf.customer.requestOtp({ email }, w);
124
157
  } catch (err) {
@@ -127,7 +160,7 @@ function createAuthAction(options) {
127
160
  return { ok: true, step: "reset", email };
128
161
  }
129
162
  case "reset": {
130
- if (!passwordOn) return fail("unsupported", carry);
163
+ if (!passwordOn) return off();
131
164
  if (!code) return fail("validation", carry, "code");
132
165
  if (!password) return fail("validation", carry, "password");
133
166
  await sf.customer.resetPassword({ email, code, password }, w);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/account/server.ts"],"names":["isStorefrontError"],"mappings":";;;;;AAaO,IAAM,sBAAA,GAAyD,OAAO,MAAA,CAAO;AAAA,EAClF,QAAA,EAAU,IAAA;AAAA,EACV,kBAAA,EAAoB,KAAA;AAAA,EACpB,YAAA,EAAc,MAAA,CAAO,MAAA,CAAO,EAAE;AAChC,CAAC;AAED,IAAM,cAAA,GAAiB,GAAA;AACvB,IAAM,KAAA,uBAAY,OAAA,EAA0E;AAe5F,eAAsB,oBAAA,CAAqB,EAAA,EAAsB,OAAA,GAAuC,EAAC,EAAkC;AACzI,EAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,IAAO,IAAA,CAAK,GAAA;AAChC,EAAA,MAAM,GAAA,GAAM,QAAQ,KAAA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AA,CAAS,iBAAA,CAAkB,EAAE,KAAA,EAAO,QAAA,EAAS,EAAG,CAAC,CAAA,EAAG,IAAI,CAAA;AAAA,QACzF;AAAA,QACA;AACE,UAAA,OAAO,IAAA,CAAK,cAAc,KAAK,CAAA;AAAA;AACnC,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAA,GAAO,MAAA,KAAW,QAAA,GAAW,QAAA,GAAW,MAAA,KAAW,WAAA,GAAc,KAAA,GAAQ,MAAA,KAAW,OAAA,IAAW,MAAA,KAAW,QAAA,GAAW,OAAA,GAAU,MAAA;AACrI,MAAA,MAAM,GAAA,GAAM,MAAA,KAAW,OAAA,GAAU,aAAA,GAAgB,OAAO,MAAA,GAAS,OAAA;AACjE,MAAA,OAAO,SAAA,CAAU,GAAA,EAAK,GAAA,EAAK,IAAA,IAAQ,MAAA,KAAW,QAAA,GAAW,EAAE,GAAG,KAAA,EAAO,IAAA,EAAK,GAAI,KAAK,CAAA;AAAA,IACrF;AAAA,EACF,CAAA;AACF","file":"account-server.cjs","sourcesContent":["/**\n * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader\n * and `createAuthAction` for the action. No React, no router: Web `Request`/`Response` only, so any framework mounts it.\n *\n * The browser never talks to OPS. The action signs the buyer in with the store's `sk_` client and keeps the session\n * token in the store's own cookie, which is passed in (`customerCookie`), so name, flags and signing stay the store's.\n */\nimport { isStorefrontError, type CustomerCapabilities, type CustomerSession, type StorefrontClient } from '@asteby/storefront'\nimport type { AuthActionData, AuthErrorCode, AuthIntent } from './types.js'\n\nexport type { AuthActionData, AuthErrorCode, AuthIntent, AuthStep } from './types.js'\n\n/** What is assumed when the store cannot be asked: password sign-in works, nothing else is offered. */\nexport const SAFE_AUTH_CAPABILITIES: Readonly<CustomerCapabilities> = Object.freeze({\n password: true,\n email_verification: false,\n otp_channels: Object.freeze([]) as unknown as CustomerCapabilities['otp_channels'],\n})\n\nconst FAILURE_TTL_MS = 5_000\nconst cache = new WeakMap<object, { at: number; ok: boolean; value: CustomerCapabilities }>()\n\nexport type LoadAuthCapabilitiesOptions = {\n /** How long a good answer is reused per client (default 60 s). `0` disables the cache. */\n ttlMs?: number\n signal?: AbortSignal\n /** Clock, for tests. */\n now?: () => number\n}\n\n/**\n * Asks the store which ways of signing in it offers, with a short cache per client. It NEVER throws: when OPS does not\n * answer (older server, outage, token without scope) it returns `SAFE_AUTH_CAPABILITIES` and retries after a few\n * seconds, so the account screen always renders. Use it as the loader: `loader = () => loadAuthCapabilities(storefront)`.\n */\nexport async function loadAuthCapabilities(sf: StorefrontClient, options: LoadAuthCapabilitiesOptions = {}): Promise<CustomerCapabilities> {\n const now = options.now ?? Date.now\n const ttl = options.ttlMs ?? 60_000\n const hit = cache.get(sf)\n if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value\n try {\n const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : undefined)\n const value: CustomerCapabilities = {\n password: got?.password !== false,\n email_verification: got?.email_verification === true,\n otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],\n }\n cache.set(sf, { at: now(), ok: true, value })\n return value\n } catch {\n cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES })\n return SAFE_AUTH_CAPABILITIES\n }\n}\n\n/** The part of a cookie the action needs. React Router's `createCookie(...)` and Remix's fit as they are. */\nexport type AuthCookie = {\n serialize(value: string, options?: { expires?: Date; maxAge?: number }): string | Promise<string>\n}\n\n/** Allows only a path inside the site (`/account`, `/orders?x=1`); anything else is `fallback`. Blocks `//host` and `/\\host`. */\nexport function safeNextPath(raw: string | null | undefined, fallback = '/account'): string {\n if (typeof raw !== 'string') return fallback\n const v = raw.trim()\n if (!v.startsWith('/') || v.startsWith('//') || v.startsWith('/\\\\') || /[\\u0000-\\u001f\\\\]/.test(v)) return fallback\n return v\n}\n\nexport type CreateAuthActionOptions = {\n storefront: StorefrontClient\n /** The store's cookie for the buyer session token (`createCookie('sf_customer', ...)`). */\n customerCookie: AuthCookie\n /** Validates the `next` field before redirecting (default `safeNextPath`). Return a same-site path. */\n safeNext?: (raw: string | null) => string\n /** Where to go after signing in when there is no `next` (default `/account`). Only used by the default `safeNext`. */\n defaultNext?: string\n /** Shopper IP for the per-shopper rate limit (see `clientIp` of the client). */\n clientIp?: (request: Request) => string | null | undefined\n /** Capabilities source, for tests or a shared cache (default `loadAuthCapabilities`). */\n capabilities?: (sf: StorefrontClient) => Promise<CustomerCapabilities>\n}\n\nexport type AuthActionArgs = { request: Request }\n\nconst fail = (code: AuthErrorCode, extra: Partial<AuthActionData> = {}, field?: string): AuthActionData => ({\n ok: false,\n ...extra,\n error: { code, ...(field ? { field } : {}) },\n})\n\n/** Maps what the SDK threw to the error the form shows. `ctx` tells what a 401 means on this step. */\nfunction toFailure(err: unknown, ctx: 'credentials' | 'code' | 'other', extra: Partial<AuthActionData>): AuthActionData {\n if (!isStorefrontError(err)) return fail('unavailable', extra)\n switch (err.status) {\n case 401:\n return fail(ctx === 'credentials' ? 'invalid_credentials' : ctx === 'code' ? 'invalid_code' : 'unavailable', extra, ctx === 'code' ? 'code' : undefined)\n case 409:\n return fail('email_taken', extra, 'email')\n case 429:\n return fail('rate_limited', extra)\n case 400:\n case 422:\n return fail('validation', extra, err.field)\n case 403:\n case 404:\n return fail('unsupported', extra)\n default:\n return fail('unavailable', extra)\n }\n}\n\n/**\n * The account action: one `POST` form with an `intent` field.\n *\n * | intent | fields | result |\n * | ------------- | ---------------------------------------- | -------------------------------------------------------- |\n * | `login` | email, password | signs in -> redirect |\n * | `register` | email, password, first_name?, last_name? | `step: 'verify'` or, without verification, redirect |\n * | `verify` | email, code | account ready -> redirect |\n * | `otp-request` | email | `step: 'otp'` (code sent) |\n * | `otp-login` | email, code | signs in -> redirect |\n * | `forgot` | email | `step: 'reset'` (always, so it never says who has an account) |\n * | `reset` | email, code, password | new password and signed in -> redirect |\n *\n * Success is a `303` to `next` (validated by `safeNext`) with `Set-Cookie` holding the session token; anything else is\n * an `AuthActionData` to render with `<AccountAuth data={...}>`. Passwords and codes are never echoed back.\n */\nexport function createAuthAction(options: CreateAuthActionOptions) {\n const { storefront: sf, customerCookie } = options\n const safeNext = options.safeNext ?? ((raw: string | null) => safeNextPath(raw, options.defaultNext ?? '/account'))\n const loadCaps = options.capabilities ?? ((client: StorefrontClient) => loadAuthCapabilities(client))\n\n async function signedIn(session: CustomerSession, next: string): Promise<Response> {\n const expires = new Date(session.expires_at)\n const cookie = await customerCookie.serialize(session.token, Number.isNaN(expires.getTime()) ? undefined : { expires })\n return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie } })\n }\n\n return async function authAction({ request }: AuthActionArgs): Promise<Response | AuthActionData> {\n const form = await request.formData().catch(() => null)\n if (!form) return fail('validation')\n const text = (name: string) => {\n const v = form.get(name)\n return typeof v === 'string' ? v : ''\n }\n const intent = text('intent') as AuthIntent\n const email = text('email').trim()\n const password = text('password')\n const code = text('code').replace(/\\s+/g, '')\n const next = safeNext(text('next') || null)\n const ip = options.clientIp?.(request)\n const w = ip ? { clientIp: ip } : undefined\n const carry: Partial<AuthActionData> = { email }\n if (!email) return fail('validation', carry, 'email')\n\n const caps = await loadCaps(sf)\n const passwordOn = caps.password\n const otpOn = caps.otp_channels.includes('email')\n\n try {\n switch (intent) {\n case 'login': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!password) return fail('validation', carry, 'password')\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n case 'register': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!password) return fail('validation', carry, 'password')\n const res = await sf.customer.register(\n { email, password, ...(text('first_name').trim() ? { first_name: text('first_name').trim() } : {}), ...(text('last_name').trim() ? { last_name: text('last_name').trim() } : {}) },\n w,\n )\n return res.status === 'created' ? await signedIn(res.session, next) : { ok: true, step: 'verify', email }\n }\n case 'verify': {\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next)\n }\n case 'otp-request': {\n if (!otpOn) return fail('unsupported', carry)\n await sf.customer.requestOtp({ email }, w)\n return { ok: true, step: 'otp', email }\n }\n case 'otp-login': {\n if (!otpOn) return fail('unsupported', carry)\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.createSession({ email, code }, w), next)\n }\n case 'forgot': {\n if (!passwordOn || !otpOn) return fail('unsupported', carry)\n try {\n await sf.customer.requestOtp({ email }, w)\n } catch (err) {\n // Only throttling and a bad email are told; anything else looks the same as success (no account enumeration).\n if (isStorefrontError(err) && (err.status === 429 || err.status === 400)) throw err\n }\n return { ok: true, step: 'reset', email }\n }\n case 'reset': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!code) return fail('validation', carry, 'code')\n if (!password) return fail('validation', carry, 'password')\n await sf.customer.resetPassword({ email, code, password }, w)\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n default:\n return fail('validation', carry)\n }\n } catch (err) {\n const step = intent === 'verify' ? 'verify' : intent === 'otp-login' ? 'otp' : intent === 'reset' || intent === 'forgot' ? 'reset' : undefined\n const ctx = intent === 'login' ? 'credentials' : step ? 'code' : 'other'\n return toFailure(err, ctx, step && intent !== 'forgot' ? { ...carry, step } : carry)\n }\n }\n}\n\nexport type AuthAction = ReturnType<typeof createAuthAction>\n"]}
1
+ {"version":3,"sources":["../src/account/server.ts"],"names":["repairPath","isStorefrontError"],"mappings":";;;;;AAaO,IAAM,sBAAA,GAAyD,OAAO,MAAA,CAAO;AAAA,EAClF,QAAA,EAAU,IAAA;AAAA,EACV,kBAAA,EAAoB,KAAA;AAAA,EACpB,YAAA,EAAc,MAAA,CAAO,MAAA,CAAO,EAAE;AAChC,CAAC;AAED,IAAM,cAAA,GAAiB,GAAA;AACvB,IAAM,YAAA,GAAe,GAAA;AACrB,IAAI,SAAA,GAAY,CAAA,QAAA;AAGhB,SAAS,iBAAiB,MAAA,EAAiC;AACzD,EAAA,MAAM,CAAA,GAAI,KAAK,GAAA,EA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,EAAM,SAAS,KAAA,EAAM;AAAA,QAC1C;AAAA,QACA,KAAK,OAAA,EAAS;AACZ,UAAA,IAAI,CAAC,UAAA,EAAY,OAAO,GAAA,EAAI;AAC5B,UAAA,IAAI,CAAC,IAAA,EAAM,OAAO,IAAA,CAAK,YAAA,EAAc,OAAO,MAAM,CAAA;AAClD,UAAA,IAAI,CAAC,QAAA,EAAU,OAAO,IAAA,CAAK,YAAA,EAAc,OAAO,UAAU,CAAA;AAC1D,UAAA,MAAM,EAAA,CAAG,SAAS,aAAA,CAAc,EAAE,OAAO,IAAA,EAAM,QAAA,IAAY,CAAC,CAAA;AAC5D,UAAA,OAAO,MAAM,QAAA,CAAS,MAAM,EAAA,CAAG,QAAA,CAAS,iBAAA,CAAkB,EAAE,KAAA,EAAO,QAAA,EAAS,EAAG,CAAC,CAAA,EAAG,IAAI,CAAA;AAAA,QACzF;AAAA,QACA;AACE,UAAA,OAAO,IAAA,CAAK,cAAc,KAAK,CAAA;AAAA;AACnC,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAA,GAAO,MAAA,KAAW,QAAA,GAAW,QAAA,GAAW,MAAA,KAAW,WAAA,GAAc,KAAA,GAAQ,MAAA,KAAW,OAAA,IAAW,MAAA,KAAW,QAAA,GAAW,OAAA,GAAU,MAAA;AACrI,MAAA,MAAM,GAAA,GAAM,MAAA,KAAW,OAAA,GAAU,aAAA,GAAgB,OAAO,MAAA,GAAS,OAAA;AACjE,MAAA,OAAO,SAAA,CAAU,GAAA,EAAK,GAAA,EAAK,IAAA,IAAQ,MAAA,KAAW,QAAA,GAAW,EAAE,GAAG,KAAA,EAAO,IAAA,EAAK,GAAI,KAAK,CAAA;AAAA,IACrF;AAAA,EACF,CAAA;AACF","file":"account-server.cjs","sourcesContent":["/**\n * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader\n * and `createAuthAction` for the action. No React, no router: Web `Request`/`Response` only, so any framework mounts it.\n *\n * The browser never talks to OPS. The action signs the buyer in with the store's `sk_` client and keeps the session\n * token in the store's own cookie, which is passed in (`customerCookie`), so name, flags and signing stay the store's.\n */\nimport { isStorefrontError, repairPath, type CustomerCapabilities, type CustomerSession, type StorefrontClient } from '@asteby/storefront'\nimport type { AuthActionData, AuthErrorCode, AuthIntent } from './types.js'\n\nexport type { AuthActionData, AuthErrorCode, AuthIntent, AuthStep } from './types.js'\n\n/** What is assumed when the store cannot be asked: password sign-in works, nothing else is offered. */\nexport const SAFE_AUTH_CAPABILITIES: Readonly<CustomerCapabilities> = Object.freeze({\n password: true,\n email_verification: false,\n otp_channels: Object.freeze([]) as unknown as CustomerCapabilities['otp_channels'],\n})\n\nconst FAILURE_TTL_MS = 5_000\nconst LOG_EVERY_MS = 60_000\nlet lastLogAt = -Infinity\n\n/** Server log (never the buyer's data): says what is missing and where it is repaired. At most once a minute. */\nfunction logMisconfigured(scopes: readonly string[]): void {\n const t = Date.now()\n if (t - lastLogAt < LOG_EVERY_MS) return\n lastLogAt = t\n console.error(\n `[@asteby/storefront-react] La credencial de la tienda no tiene permisos${scopes.length ? ` (${scopes.join(', ')})` : ''}; ` +\n `las cuentas de comprador no funcionan hasta repararlo en ${repairPath()}.`,\n )\n}\nconst cache = new WeakMap<object, { at: number; ok: boolean; value: CustomerCapabilities }>()\n\nexport type LoadAuthCapabilitiesOptions = {\n /** How long a good answer is reused per client (default 60 s). `0` disables the cache. */\n ttlMs?: number\n signal?: AbortSignal\n /** Clock, for tests. */\n now?: () => number\n}\n\n/**\n * Asks the store which ways of signing in it offers, with a short cache per client. It NEVER throws: when OPS does not\n * answer (older server, outage, token without scope) it returns `SAFE_AUTH_CAPABILITIES` and retries after a few\n * seconds, so the account screen always renders. Use it as the loader: `loader = () => loadAuthCapabilities(storefront)`.\n */\nexport async function loadAuthCapabilities(sf: StorefrontClient, options: LoadAuthCapabilitiesOptions = {}): Promise<CustomerCapabilities> {\n const now = options.now ?? Date.now\n const ttl = options.ttlMs ?? 60_000\n const hit = cache.get(sf)\n if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value\n try {\n const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : undefined)\n const missing = Array.isArray(got?.missing_scopes) ? got.missing_scopes.filter((x): x is string => typeof x === 'string') : []\n const value: CustomerCapabilities = {\n // `password: false` (including for a missing scope) is respected: the form never offers what the token cannot do.\n password: got?.password !== false,\n email_verification: got?.email_verification === true,\n otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],\n ...(typeof got?.unavailable_reason === 'string' ? { unavailable_reason: got.unavailable_reason } : {}),\n ...(missing.length ? { missing_scopes: missing } : {}),\n }\n if (value.unavailable_reason === 'missing_scope') logMisconfigured(missing)\n cache.set(sf, { at: now(), ok: true, value })\n return value\n } catch (err) {\n if (isStorefrontError(err) && err.code === 'insufficient_scope') {\n // The token cannot even read capabilities: do not offer password sign-in it could not complete.\n const value: CustomerCapabilities = {\n password: false,\n email_verification: false,\n otp_channels: [],\n unavailable_reason: 'missing_scope',\n missing_scopes: err.requiredScopes,\n }\n logMisconfigured(err.requiredScopes)\n cache.set(sf, { at: now(), ok: false, value })\n return value\n }\n cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES })\n return SAFE_AUTH_CAPABILITIES\n }\n}\n\n/** The part of a cookie the action needs. React Router's `createCookie(...)` and Remix's fit as they are. */\nexport type AuthCookie = {\n serialize(value: string, options?: { expires?: Date; maxAge?: number }): string | Promise<string>\n}\n\n/** Allows only a path inside the site (`/account`, `/orders?x=1`); anything else is `fallback`. Blocks `//host` and `/\\host`. */\nexport function safeNextPath(raw: string | null | undefined, fallback = '/account'): string {\n if (typeof raw !== 'string') return fallback\n const v = raw.trim()\n if (!v.startsWith('/') || v.startsWith('//') || v.startsWith('/\\\\') || /[\\u0000-\\u001f\\\\]/.test(v)) return fallback\n return v\n}\n\nexport type CreateAuthActionOptions = {\n storefront: StorefrontClient\n /** The store's cookie for the buyer session token (`createCookie('sf_customer', ...)`). */\n customerCookie: AuthCookie\n /** Validates the `next` field before redirecting (default `safeNextPath`). Return a same-site path. */\n safeNext?: (raw: string | null) => string\n /** Where to go after signing in when there is no `next` (default `/account`). Only used by the default `safeNext`. */\n defaultNext?: string\n /** Shopper IP for the per-shopper rate limit (see `clientIp` of the client). */\n clientIp?: (request: Request) => string | null | undefined\n /** Capabilities source, for tests or a shared cache (default `loadAuthCapabilities`). */\n capabilities?: (sf: StorefrontClient) => Promise<CustomerCapabilities>\n}\n\nexport type AuthActionArgs = { request: Request }\n\nconst fail = (code: AuthErrorCode, extra: Partial<AuthActionData> = {}, field?: string): AuthActionData => ({\n ok: false,\n ...extra,\n error: { code, ...(field ? { field } : {}) },\n})\n\n/** Maps what the SDK threw to the error the form shows. `ctx` tells what a 401 means on this step. */\nfunction toFailure(err: unknown, ctx: 'credentials' | 'code' | 'other', extra: Partial<AuthActionData>): AuthActionData {\n if (!isStorefrontError(err)) return fail('unavailable', extra)\n if (err.code === 'insufficient_scope') {\n logMisconfigured(err.requiredScopes)\n return fail('store_misconfigured', extra)\n }\n switch (err.status) {\n case 401:\n return fail(ctx === 'credentials' ? 'invalid_credentials' : ctx === 'code' ? 'invalid_code' : 'unavailable', extra, ctx === 'code' ? 'code' : undefined)\n case 409:\n return fail('email_taken', extra, 'email')\n case 429:\n return fail('rate_limited', extra)\n case 400:\n case 422:\n return fail('validation', extra, err.field)\n case 403:\n case 404:\n return fail('unsupported', extra)\n default:\n return fail('unavailable', extra)\n }\n}\n\n/**\n * The account action: one `POST` form with an `intent` field.\n *\n * | intent | fields | result |\n * | ------------- | ---------------------------------------- | -------------------------------------------------------- |\n * | `login` | email, password | signs in -> redirect |\n * | `register` | email, password, first_name?, last_name? | `step: 'verify'` or, without verification, redirect |\n * | `verify` | email, code | account ready -> redirect |\n * | `otp-request` | email | `step: 'otp'` (code sent) |\n * | `otp-login` | email, code | signs in -> redirect |\n * | `forgot` | email | `step: 'reset'` (always, so it never says who has an account) |\n * | `reset` | email, code, password | new password and signed in -> redirect |\n *\n * Success is a `303` to `next` (validated by `safeNext`) with `Set-Cookie` holding the session token; anything else is\n * an `AuthActionData` to render with `<AccountAuth data={...}>`. Passwords and codes are never echoed back.\n */\nexport function createAuthAction(options: CreateAuthActionOptions) {\n const { storefront: sf, customerCookie } = options\n const safeNext = options.safeNext ?? ((raw: string | null) => safeNextPath(raw, options.defaultNext ?? '/account'))\n const loadCaps = options.capabilities ?? ((client: StorefrontClient) => loadAuthCapabilities(client))\n\n async function signedIn(session: CustomerSession, next: string): Promise<Response> {\n const expires = new Date(session.expires_at)\n const cookie = await customerCookie.serialize(session.token, Number.isNaN(expires.getTime()) ? undefined : { expires })\n return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie } })\n }\n\n return async function authAction({ request }: AuthActionArgs): Promise<Response | AuthActionData> {\n const form = await request.formData().catch(() => null)\n if (!form) return fail('validation')\n const text = (name: string) => {\n const v = form.get(name)\n return typeof v === 'string' ? v : ''\n }\n const intent = text('intent') as AuthIntent\n const email = text('email').trim()\n const password = text('password')\n const code = text('code').replace(/\\s+/g, '')\n const next = safeNext(text('next') || null)\n const ip = options.clientIp?.(request)\n const w = ip ? { clientIp: ip } : undefined\n const carry: Partial<AuthActionData> = { email }\n if (!email) return fail('validation', carry, 'email')\n\n const caps = await loadCaps(sf)\n const passwordOn = caps.password\n // Off because the store's token lacks a scope (not a merchant choice): say so instead of \"not available\".\n const misconfigured = caps.unavailable_reason === 'missing_scope'\n const off = (): AuthActionData => fail(misconfigured ? 'store_misconfigured' : 'unsupported', carry)\n const otpOn = caps.otp_channels.includes('email')\n\n try {\n switch (intent) {\n case 'login': {\n if (!passwordOn) return off()\n if (!password) return fail('validation', carry, 'password')\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n case 'register': {\n if (!passwordOn) return off()\n if (!password) return fail('validation', carry, 'password')\n const res = await sf.customer.register(\n { email, password, ...(text('first_name').trim() ? { first_name: text('first_name').trim() } : {}), ...(text('last_name').trim() ? { last_name: text('last_name').trim() } : {}) },\n w,\n )\n return res.status === 'created' ? await signedIn(res.session, next) : { ok: true, step: 'verify', email }\n }\n case 'verify': {\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next)\n }\n case 'otp-request': {\n if (!otpOn) return off()\n await sf.customer.requestOtp({ email }, w)\n return { ok: true, step: 'otp', email }\n }\n case 'otp-login': {\n if (!otpOn) return off()\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.createSession({ email, code }, w), next)\n }\n case 'forgot': {\n if (!passwordOn || !otpOn) return off()\n try {\n await sf.customer.requestOtp({ email }, w)\n } catch (err) {\n // Only throttling and a bad email are told; anything else looks the same as success (no account enumeration).\n if (isStorefrontError(err) && (err.status === 429 || err.status === 400)) throw err\n }\n return { ok: true, step: 'reset', email }\n }\n case 'reset': {\n if (!passwordOn) return off()\n if (!code) return fail('validation', carry, 'code')\n if (!password) return fail('validation', carry, 'password')\n await sf.customer.resetPassword({ email, code, password }, w)\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n default:\n return fail('validation', carry)\n }\n } catch (err) {\n const step = intent === 'verify' ? 'verify' : intent === 'otp-login' ? 'otp' : intent === 'reset' || intent === 'forgot' ? 'reset' : undefined\n const ctx = intent === 'login' ? 'credentials' : step ? 'code' : 'other'\n return toFailure(err, ctx, step && intent !== 'forgot' ? { ...carry, step } : carry)\n }\n }\n}\n\nexport type AuthAction = ReturnType<typeof createAuthAction>\n"]}
@@ -1,6 +1,6 @@
1
1
  import { StorefrontClient, CustomerCapabilities } from '@asteby/storefront';
2
- import { A as AuthActionData } from './types-HcEUd9hW.cjs';
3
- export { a as AuthErrorCode, b as AuthIntent, c as AuthStep } from './types-HcEUd9hW.cjs';
2
+ import { A as AuthActionData } from './types-D7pVK0GK.cjs';
3
+ export { a as AuthErrorCode, b as AuthIntent, c as AuthStep } from './types-D7pVK0GK.cjs';
4
4
 
5
5
  /**
6
6
  * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader
@@ -1,6 +1,6 @@
1
1
  import { StorefrontClient, CustomerCapabilities } from '@asteby/storefront';
2
- import { A as AuthActionData } from './types-HcEUd9hW.js';
3
- export { a as AuthErrorCode, b as AuthIntent, c as AuthStep } from './types-HcEUd9hW.js';
2
+ import { A as AuthActionData } from './types-D7pVK0GK.js';
3
+ export { a as AuthErrorCode, b as AuthIntent, c as AuthStep } from './types-D7pVK0GK.js';
4
4
 
5
5
  /**
6
6
  * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader
@@ -1,4 +1,4 @@
1
- import { isStorefrontError } from '@asteby/storefront';
1
+ import { isStorefrontError, repairPath } from '@asteby/storefront';
2
2
 
3
3
  // src/account/server.ts
4
4
  var SAFE_AUTH_CAPABILITIES = Object.freeze({
@@ -7,6 +7,16 @@ var SAFE_AUTH_CAPABILITIES = Object.freeze({
7
7
  otp_channels: Object.freeze([])
8
8
  });
9
9
  var FAILURE_TTL_MS = 5e3;
10
+ var LOG_EVERY_MS = 6e4;
11
+ var lastLogAt = -Infinity;
12
+ function logMisconfigured(scopes) {
13
+ const t = Date.now();
14
+ if (t - lastLogAt < LOG_EVERY_MS) return;
15
+ lastLogAt = t;
16
+ console.error(
17
+ `[@asteby/storefront-react] La credencial de la tienda no tiene permisos${scopes.length ? ` (${scopes.join(", ")})` : ""}; las cuentas de comprador no funcionan hasta repararlo en ${repairPath()}.`
18
+ );
19
+ }
10
20
  var cache = /* @__PURE__ */ new WeakMap();
11
21
  async function loadAuthCapabilities(sf, options = {}) {
12
22
  const now = options.now ?? Date.now;
@@ -15,14 +25,31 @@ async function loadAuthCapabilities(sf, options = {}) {
15
25
  if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value;
16
26
  try {
17
27
  const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : void 0);
28
+ const missing = Array.isArray(got?.missing_scopes) ? got.missing_scopes.filter((x) => typeof x === "string") : [];
18
29
  const value = {
30
+ // `password: false` (including for a missing scope) is respected: the form never offers what the token cannot do.
19
31
  password: got?.password !== false,
20
32
  email_verification: got?.email_verification === true,
21
- otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : []
33
+ otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],
34
+ ...typeof got?.unavailable_reason === "string" ? { unavailable_reason: got.unavailable_reason } : {},
35
+ ...missing.length ? { missing_scopes: missing } : {}
22
36
  };
37
+ if (value.unavailable_reason === "missing_scope") logMisconfigured(missing);
23
38
  cache.set(sf, { at: now(), ok: true, value });
24
39
  return value;
25
- } catch {
40
+ } catch (err) {
41
+ if (isStorefrontError(err) && err.code === "insufficient_scope") {
42
+ const value = {
43
+ password: false,
44
+ email_verification: false,
45
+ otp_channels: [],
46
+ unavailable_reason: "missing_scope",
47
+ missing_scopes: err.requiredScopes
48
+ };
49
+ logMisconfigured(err.requiredScopes);
50
+ cache.set(sf, { at: now(), ok: false, value });
51
+ return value;
52
+ }
26
53
  cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES });
27
54
  return SAFE_AUTH_CAPABILITIES;
28
55
  }
@@ -40,6 +67,10 @@ var fail = (code, extra = {}, field) => ({
40
67
  });
41
68
  function toFailure(err, ctx, extra) {
42
69
  if (!isStorefrontError(err)) return fail("unavailable", extra);
70
+ if (err.code === "insufficient_scope") {
71
+ logMisconfigured(err.requiredScopes);
72
+ return fail("store_misconfigured", extra);
73
+ }
43
74
  switch (err.status) {
44
75
  case 401:
45
76
  return fail(ctx === "credentials" ? "invalid_credentials" : ctx === "code" ? "invalid_code" : "unavailable", extra, ctx === "code" ? "code" : void 0);
@@ -84,16 +115,18 @@ function createAuthAction(options) {
84
115
  if (!email) return fail("validation", carry, "email");
85
116
  const caps = await loadCaps(sf);
86
117
  const passwordOn = caps.password;
118
+ const misconfigured = caps.unavailable_reason === "missing_scope";
119
+ const off = () => fail(misconfigured ? "store_misconfigured" : "unsupported", carry);
87
120
  const otpOn = caps.otp_channels.includes("email");
88
121
  try {
89
122
  switch (intent) {
90
123
  case "login": {
91
- if (!passwordOn) return fail("unsupported", carry);
124
+ if (!passwordOn) return off();
92
125
  if (!password) return fail("validation", carry, "password");
93
126
  return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next);
94
127
  }
95
128
  case "register": {
96
- if (!passwordOn) return fail("unsupported", carry);
129
+ if (!passwordOn) return off();
97
130
  if (!password) return fail("validation", carry, "password");
98
131
  const res = await sf.customer.register(
99
132
  { email, password, ...text("first_name").trim() ? { first_name: text("first_name").trim() } : {}, ...text("last_name").trim() ? { last_name: text("last_name").trim() } : {} },
@@ -106,17 +139,17 @@ function createAuthAction(options) {
106
139
  return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next);
107
140
  }
108
141
  case "otp-request": {
109
- if (!otpOn) return fail("unsupported", carry);
142
+ if (!otpOn) return off();
110
143
  await sf.customer.requestOtp({ email }, w);
111
144
  return { ok: true, step: "otp", email };
112
145
  }
113
146
  case "otp-login": {
114
- if (!otpOn) return fail("unsupported", carry);
147
+ if (!otpOn) return off();
115
148
  if (!code) return fail("validation", carry, "code");
116
149
  return await signedIn(await sf.customer.createSession({ email, code }, w), next);
117
150
  }
118
151
  case "forgot": {
119
- if (!passwordOn || !otpOn) return fail("unsupported", carry);
152
+ if (!passwordOn || !otpOn) return off();
120
153
  try {
121
154
  await sf.customer.requestOtp({ email }, w);
122
155
  } catch (err) {
@@ -125,7 +158,7 @@ function createAuthAction(options) {
125
158
  return { ok: true, step: "reset", email };
126
159
  }
127
160
  case "reset": {
128
- if (!passwordOn) return fail("unsupported", carry);
161
+ if (!passwordOn) return off();
129
162
  if (!code) return fail("validation", carry, "code");
130
163
  if (!password) return fail("validation", carry, "password");
131
164
  await sf.customer.resetPassword({ email, code, password }, w);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/account/server.ts"],"names":[],"mappings":";;;AAaO,IAAM,sBAAA,G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,EAAS;AACZ,UAAA,IAAI,CAAC,UAAA,EAAY,OAAO,IAAA,CAAK,eAAe,KAAK,CAAA;AACjD,UAAA,IAAI,CAAC,IAAA,EAAM,OAAO,IAAA,CAAK,YAAA,EAAc,OAAO,MAAM,CAAA;AAClD,UAAA,IAAI,CAAC,QAAA,EAAU,OAAO,IAAA,CAAK,YAAA,EAAc,OAAO,UAAU,CAAA;AAC1D,UAAA,MAAM,EAAA,CAAG,SAAS,aAAA,CAAc,EAAE,OAAO,IAAA,EAAM,QAAA,IAAY,CAAC,CAAA;AAC5D,UAAA,OAAO,MAAM,QAAA,CAAS,MAAM,EAAA,CAAG,QAAA,CAAS,iBAAA,CAAkB,EAAE,KAAA,EAAO,QAAA,EAAS,EAAG,CAAC,CAAA,EAAG,IAAI,CAAA;AAAA,QACzF;AAAA,QACA;AACE,UAAA,OAAO,IAAA,CAAK,cAAc,KAAK,CAAA;AAAA;AACnC,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAA,GAAO,MAAA,KAAW,QAAA,GAAW,QAAA,GAAW,MAAA,KAAW,WAAA,GAAc,KAAA,GAAQ,MAAA,KAAW,OAAA,IAAW,MAAA,KAAW,QAAA,GAAW,OAAA,GAAU,MAAA;AACrI,MAAA,MAAM,GAAA,GAAM,MAAA,KAAW,OAAA,GAAU,aAAA,GAAgB,OAAO,MAAA,GAAS,OAAA;AACjE,MAAA,OAAO,SAAA,CAAU,GAAA,EAAK,GAAA,EAAK,IAAA,IAAQ,MAAA,KAAW,QAAA,GAAW,EAAE,GAAG,KAAA,EAAO,IAAA,EAAK,GAAI,KAAK,CAAA;AAAA,IACrF;AAAA,EACF,CAAA;AACF","file":"account-server.js","sourcesContent":["/**\n * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader\n * and `createAuthAction` for the action. No React, no router: Web `Request`/`Response` only, so any framework mounts it.\n *\n * The browser never talks to OPS. The action signs the buyer in with the store's `sk_` client and keeps the session\n * token in the store's own cookie, which is passed in (`customerCookie`), so name, flags and signing stay the store's.\n */\nimport { isStorefrontError, type CustomerCapabilities, type CustomerSession, type StorefrontClient } from '@asteby/storefront'\nimport type { AuthActionData, AuthErrorCode, AuthIntent } from './types.js'\n\nexport type { AuthActionData, AuthErrorCode, AuthIntent, AuthStep } from './types.js'\n\n/** What is assumed when the store cannot be asked: password sign-in works, nothing else is offered. */\nexport const SAFE_AUTH_CAPABILITIES: Readonly<CustomerCapabilities> = Object.freeze({\n password: true,\n email_verification: false,\n otp_channels: Object.freeze([]) as unknown as CustomerCapabilities['otp_channels'],\n})\n\nconst FAILURE_TTL_MS = 5_000\nconst cache = new WeakMap<object, { at: number; ok: boolean; value: CustomerCapabilities }>()\n\nexport type LoadAuthCapabilitiesOptions = {\n /** How long a good answer is reused per client (default 60 s). `0` disables the cache. */\n ttlMs?: number\n signal?: AbortSignal\n /** Clock, for tests. */\n now?: () => number\n}\n\n/**\n * Asks the store which ways of signing in it offers, with a short cache per client. It NEVER throws: when OPS does not\n * answer (older server, outage, token without scope) it returns `SAFE_AUTH_CAPABILITIES` and retries after a few\n * seconds, so the account screen always renders. Use it as the loader: `loader = () => loadAuthCapabilities(storefront)`.\n */\nexport async function loadAuthCapabilities(sf: StorefrontClient, options: LoadAuthCapabilitiesOptions = {}): Promise<CustomerCapabilities> {\n const now = options.now ?? Date.now\n const ttl = options.ttlMs ?? 60_000\n const hit = cache.get(sf)\n if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value\n try {\n const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : undefined)\n const value: CustomerCapabilities = {\n password: got?.password !== false,\n email_verification: got?.email_verification === true,\n otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],\n }\n cache.set(sf, { at: now(), ok: true, value })\n return value\n } catch {\n cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES })\n return SAFE_AUTH_CAPABILITIES\n }\n}\n\n/** The part of a cookie the action needs. React Router's `createCookie(...)` and Remix's fit as they are. */\nexport type AuthCookie = {\n serialize(value: string, options?: { expires?: Date; maxAge?: number }): string | Promise<string>\n}\n\n/** Allows only a path inside the site (`/account`, `/orders?x=1`); anything else is `fallback`. Blocks `//host` and `/\\host`. */\nexport function safeNextPath(raw: string | null | undefined, fallback = '/account'): string {\n if (typeof raw !== 'string') return fallback\n const v = raw.trim()\n if (!v.startsWith('/') || v.startsWith('//') || v.startsWith('/\\\\') || /[\\u0000-\\u001f\\\\]/.test(v)) return fallback\n return v\n}\n\nexport type CreateAuthActionOptions = {\n storefront: StorefrontClient\n /** The store's cookie for the buyer session token (`createCookie('sf_customer', ...)`). */\n customerCookie: AuthCookie\n /** Validates the `next` field before redirecting (default `safeNextPath`). Return a same-site path. */\n safeNext?: (raw: string | null) => string\n /** Where to go after signing in when there is no `next` (default `/account`). Only used by the default `safeNext`. */\n defaultNext?: string\n /** Shopper IP for the per-shopper rate limit (see `clientIp` of the client). */\n clientIp?: (request: Request) => string | null | undefined\n /** Capabilities source, for tests or a shared cache (default `loadAuthCapabilities`). */\n capabilities?: (sf: StorefrontClient) => Promise<CustomerCapabilities>\n}\n\nexport type AuthActionArgs = { request: Request }\n\nconst fail = (code: AuthErrorCode, extra: Partial<AuthActionData> = {}, field?: string): AuthActionData => ({\n ok: false,\n ...extra,\n error: { code, ...(field ? { field } : {}) },\n})\n\n/** Maps what the SDK threw to the error the form shows. `ctx` tells what a 401 means on this step. */\nfunction toFailure(err: unknown, ctx: 'credentials' | 'code' | 'other', extra: Partial<AuthActionData>): AuthActionData {\n if (!isStorefrontError(err)) return fail('unavailable', extra)\n switch (err.status) {\n case 401:\n return fail(ctx === 'credentials' ? 'invalid_credentials' : ctx === 'code' ? 'invalid_code' : 'unavailable', extra, ctx === 'code' ? 'code' : undefined)\n case 409:\n return fail('email_taken', extra, 'email')\n case 429:\n return fail('rate_limited', extra)\n case 400:\n case 422:\n return fail('validation', extra, err.field)\n case 403:\n case 404:\n return fail('unsupported', extra)\n default:\n return fail('unavailable', extra)\n }\n}\n\n/**\n * The account action: one `POST` form with an `intent` field.\n *\n * | intent | fields | result |\n * | ------------- | ---------------------------------------- | -------------------------------------------------------- |\n * | `login` | email, password | signs in -> redirect |\n * | `register` | email, password, first_name?, last_name? | `step: 'verify'` or, without verification, redirect |\n * | `verify` | email, code | account ready -> redirect |\n * | `otp-request` | email | `step: 'otp'` (code sent) |\n * | `otp-login` | email, code | signs in -> redirect |\n * | `forgot` | email | `step: 'reset'` (always, so it never says who has an account) |\n * | `reset` | email, code, password | new password and signed in -> redirect |\n *\n * Success is a `303` to `next` (validated by `safeNext`) with `Set-Cookie` holding the session token; anything else is\n * an `AuthActionData` to render with `<AccountAuth data={...}>`. Passwords and codes are never echoed back.\n */\nexport function createAuthAction(options: CreateAuthActionOptions) {\n const { storefront: sf, customerCookie } = options\n const safeNext = options.safeNext ?? ((raw: string | null) => safeNextPath(raw, options.defaultNext ?? '/account'))\n const loadCaps = options.capabilities ?? ((client: StorefrontClient) => loadAuthCapabilities(client))\n\n async function signedIn(session: CustomerSession, next: string): Promise<Response> {\n const expires = new Date(session.expires_at)\n const cookie = await customerCookie.serialize(session.token, Number.isNaN(expires.getTime()) ? undefined : { expires })\n return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie } })\n }\n\n return async function authAction({ request }: AuthActionArgs): Promise<Response | AuthActionData> {\n const form = await request.formData().catch(() => null)\n if (!form) return fail('validation')\n const text = (name: string) => {\n const v = form.get(name)\n return typeof v === 'string' ? v : ''\n }\n const intent = text('intent') as AuthIntent\n const email = text('email').trim()\n const password = text('password')\n const code = text('code').replace(/\\s+/g, '')\n const next = safeNext(text('next') || null)\n const ip = options.clientIp?.(request)\n const w = ip ? { clientIp: ip } : undefined\n const carry: Partial<AuthActionData> = { email }\n if (!email) return fail('validation', carry, 'email')\n\n const caps = await loadCaps(sf)\n const passwordOn = caps.password\n const otpOn = caps.otp_channels.includes('email')\n\n try {\n switch (intent) {\n case 'login': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!password) return fail('validation', carry, 'password')\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n case 'register': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!password) return fail('validation', carry, 'password')\n const res = await sf.customer.register(\n { email, password, ...(text('first_name').trim() ? { first_name: text('first_name').trim() } : {}), ...(text('last_name').trim() ? { last_name: text('last_name').trim() } : {}) },\n w,\n )\n return res.status === 'created' ? await signedIn(res.session, next) : { ok: true, step: 'verify', email }\n }\n case 'verify': {\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next)\n }\n case 'otp-request': {\n if (!otpOn) return fail('unsupported', carry)\n await sf.customer.requestOtp({ email }, w)\n return { ok: true, step: 'otp', email }\n }\n case 'otp-login': {\n if (!otpOn) return fail('unsupported', carry)\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.createSession({ email, code }, w), next)\n }\n case 'forgot': {\n if (!passwordOn || !otpOn) return fail('unsupported', carry)\n try {\n await sf.customer.requestOtp({ email }, w)\n } catch (err) {\n // Only throttling and a bad email are told; anything else looks the same as success (no account enumeration).\n if (isStorefrontError(err) && (err.status === 429 || err.status === 400)) throw err\n }\n return { ok: true, step: 'reset', email }\n }\n case 'reset': {\n if (!passwordOn) return fail('unsupported', carry)\n if (!code) return fail('validation', carry, 'code')\n if (!password) return fail('validation', carry, 'password')\n await sf.customer.resetPassword({ email, code, password }, w)\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n default:\n return fail('validation', carry)\n }\n } catch (err) {\n const step = intent === 'verify' ? 'verify' : intent === 'otp-login' ? 'otp' : intent === 'reset' || intent === 'forgot' ? 'reset' : undefined\n const ctx = intent === 'login' ? 'credentials' : step ? 'code' : 'other'\n return toFailure(err, ctx, step && intent !== 'forgot' ? { ...carry, step } : carry)\n }\n }\n}\n\nexport type AuthAction = ReturnType<typeof createAuthAction>\n"]}
1
+ {"version":3,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AAA,GAAU,aAAA,GAAgB,OAAO,MAAA,GAAS,OAAA;AACjE,MAAA,OAAO,SAAA,CAAU,GAAA,EAAK,GAAA,EAAK,IAAA,IAAQ,MAAA,KAAW,QAAA,GAAW,EAAE,GAAG,KAAA,EAAO,IAAA,EAAK,GAAI,KAAK,CAAA;AAAA,IACrF;AAAA,EACF,CAAA;AACF","file":"account-server.js","sourcesContent":["/**\n * Server side of the account screen (`@asteby/storefront-react/account/server`): `loadAuthCapabilities` for the loader\n * and `createAuthAction` for the action. No React, no router: Web `Request`/`Response` only, so any framework mounts it.\n *\n * The browser never talks to OPS. The action signs the buyer in with the store's `sk_` client and keeps the session\n * token in the store's own cookie, which is passed in (`customerCookie`), so name, flags and signing stay the store's.\n */\nimport { isStorefrontError, repairPath, type CustomerCapabilities, type CustomerSession, type StorefrontClient } from '@asteby/storefront'\nimport type { AuthActionData, AuthErrorCode, AuthIntent } from './types.js'\n\nexport type { AuthActionData, AuthErrorCode, AuthIntent, AuthStep } from './types.js'\n\n/** What is assumed when the store cannot be asked: password sign-in works, nothing else is offered. */\nexport const SAFE_AUTH_CAPABILITIES: Readonly<CustomerCapabilities> = Object.freeze({\n password: true,\n email_verification: false,\n otp_channels: Object.freeze([]) as unknown as CustomerCapabilities['otp_channels'],\n})\n\nconst FAILURE_TTL_MS = 5_000\nconst LOG_EVERY_MS = 60_000\nlet lastLogAt = -Infinity\n\n/** Server log (never the buyer's data): says what is missing and where it is repaired. At most once a minute. */\nfunction logMisconfigured(scopes: readonly string[]): void {\n const t = Date.now()\n if (t - lastLogAt < LOG_EVERY_MS) return\n lastLogAt = t\n console.error(\n `[@asteby/storefront-react] La credencial de la tienda no tiene permisos${scopes.length ? ` (${scopes.join(', ')})` : ''}; ` +\n `las cuentas de comprador no funcionan hasta repararlo en ${repairPath()}.`,\n )\n}\nconst cache = new WeakMap<object, { at: number; ok: boolean; value: CustomerCapabilities }>()\n\nexport type LoadAuthCapabilitiesOptions = {\n /** How long a good answer is reused per client (default 60 s). `0` disables the cache. */\n ttlMs?: number\n signal?: AbortSignal\n /** Clock, for tests. */\n now?: () => number\n}\n\n/**\n * Asks the store which ways of signing in it offers, with a short cache per client. It NEVER throws: when OPS does not\n * answer (older server, outage, token without scope) it returns `SAFE_AUTH_CAPABILITIES` and retries after a few\n * seconds, so the account screen always renders. Use it as the loader: `loader = () => loadAuthCapabilities(storefront)`.\n */\nexport async function loadAuthCapabilities(sf: StorefrontClient, options: LoadAuthCapabilitiesOptions = {}): Promise<CustomerCapabilities> {\n const now = options.now ?? Date.now\n const ttl = options.ttlMs ?? 60_000\n const hit = cache.get(sf)\n if (hit && now() - hit.at < (hit.ok ? ttl : FAILURE_TTL_MS)) return hit.value\n try {\n const got = await sf.customer.capabilities(options.signal ? { signal: options.signal } : undefined)\n const missing = Array.isArray(got?.missing_scopes) ? got.missing_scopes.filter((x): x is string => typeof x === 'string') : []\n const value: CustomerCapabilities = {\n // `password: false` (including for a missing scope) is respected: the form never offers what the token cannot do.\n password: got?.password !== false,\n email_verification: got?.email_verification === true,\n otp_channels: Array.isArray(got?.otp_channels) ? got.otp_channels : [],\n ...(typeof got?.unavailable_reason === 'string' ? { unavailable_reason: got.unavailable_reason } : {}),\n ...(missing.length ? { missing_scopes: missing } : {}),\n }\n if (value.unavailable_reason === 'missing_scope') logMisconfigured(missing)\n cache.set(sf, { at: now(), ok: true, value })\n return value\n } catch (err) {\n if (isStorefrontError(err) && err.code === 'insufficient_scope') {\n // The token cannot even read capabilities: do not offer password sign-in it could not complete.\n const value: CustomerCapabilities = {\n password: false,\n email_verification: false,\n otp_channels: [],\n unavailable_reason: 'missing_scope',\n missing_scopes: err.requiredScopes,\n }\n logMisconfigured(err.requiredScopes)\n cache.set(sf, { at: now(), ok: false, value })\n return value\n }\n cache.set(sf, { at: now(), ok: false, value: SAFE_AUTH_CAPABILITIES })\n return SAFE_AUTH_CAPABILITIES\n }\n}\n\n/** The part of a cookie the action needs. React Router's `createCookie(...)` and Remix's fit as they are. */\nexport type AuthCookie = {\n serialize(value: string, options?: { expires?: Date; maxAge?: number }): string | Promise<string>\n}\n\n/** Allows only a path inside the site (`/account`, `/orders?x=1`); anything else is `fallback`. Blocks `//host` and `/\\host`. */\nexport function safeNextPath(raw: string | null | undefined, fallback = '/account'): string {\n if (typeof raw !== 'string') return fallback\n const v = raw.trim()\n if (!v.startsWith('/') || v.startsWith('//') || v.startsWith('/\\\\') || /[\\u0000-\\u001f\\\\]/.test(v)) return fallback\n return v\n}\n\nexport type CreateAuthActionOptions = {\n storefront: StorefrontClient\n /** The store's cookie for the buyer session token (`createCookie('sf_customer', ...)`). */\n customerCookie: AuthCookie\n /** Validates the `next` field before redirecting (default `safeNextPath`). Return a same-site path. */\n safeNext?: (raw: string | null) => string\n /** Where to go after signing in when there is no `next` (default `/account`). Only used by the default `safeNext`. */\n defaultNext?: string\n /** Shopper IP for the per-shopper rate limit (see `clientIp` of the client). */\n clientIp?: (request: Request) => string | null | undefined\n /** Capabilities source, for tests or a shared cache (default `loadAuthCapabilities`). */\n capabilities?: (sf: StorefrontClient) => Promise<CustomerCapabilities>\n}\n\nexport type AuthActionArgs = { request: Request }\n\nconst fail = (code: AuthErrorCode, extra: Partial<AuthActionData> = {}, field?: string): AuthActionData => ({\n ok: false,\n ...extra,\n error: { code, ...(field ? { field } : {}) },\n})\n\n/** Maps what the SDK threw to the error the form shows. `ctx` tells what a 401 means on this step. */\nfunction toFailure(err: unknown, ctx: 'credentials' | 'code' | 'other', extra: Partial<AuthActionData>): AuthActionData {\n if (!isStorefrontError(err)) return fail('unavailable', extra)\n if (err.code === 'insufficient_scope') {\n logMisconfigured(err.requiredScopes)\n return fail('store_misconfigured', extra)\n }\n switch (err.status) {\n case 401:\n return fail(ctx === 'credentials' ? 'invalid_credentials' : ctx === 'code' ? 'invalid_code' : 'unavailable', extra, ctx === 'code' ? 'code' : undefined)\n case 409:\n return fail('email_taken', extra, 'email')\n case 429:\n return fail('rate_limited', extra)\n case 400:\n case 422:\n return fail('validation', extra, err.field)\n case 403:\n case 404:\n return fail('unsupported', extra)\n default:\n return fail('unavailable', extra)\n }\n}\n\n/**\n * The account action: one `POST` form with an `intent` field.\n *\n * | intent | fields | result |\n * | ------------- | ---------------------------------------- | -------------------------------------------------------- |\n * | `login` | email, password | signs in -> redirect |\n * | `register` | email, password, first_name?, last_name? | `step: 'verify'` or, without verification, redirect |\n * | `verify` | email, code | account ready -> redirect |\n * | `otp-request` | email | `step: 'otp'` (code sent) |\n * | `otp-login` | email, code | signs in -> redirect |\n * | `forgot` | email | `step: 'reset'` (always, so it never says who has an account) |\n * | `reset` | email, code, password | new password and signed in -> redirect |\n *\n * Success is a `303` to `next` (validated by `safeNext`) with `Set-Cookie` holding the session token; anything else is\n * an `AuthActionData` to render with `<AccountAuth data={...}>`. Passwords and codes are never echoed back.\n */\nexport function createAuthAction(options: CreateAuthActionOptions) {\n const { storefront: sf, customerCookie } = options\n const safeNext = options.safeNext ?? ((raw: string | null) => safeNextPath(raw, options.defaultNext ?? '/account'))\n const loadCaps = options.capabilities ?? ((client: StorefrontClient) => loadAuthCapabilities(client))\n\n async function signedIn(session: CustomerSession, next: string): Promise<Response> {\n const expires = new Date(session.expires_at)\n const cookie = await customerCookie.serialize(session.token, Number.isNaN(expires.getTime()) ? undefined : { expires })\n return new Response(null, { status: 303, headers: { Location: next, 'Set-Cookie': cookie } })\n }\n\n return async function authAction({ request }: AuthActionArgs): Promise<Response | AuthActionData> {\n const form = await request.formData().catch(() => null)\n if (!form) return fail('validation')\n const text = (name: string) => {\n const v = form.get(name)\n return typeof v === 'string' ? v : ''\n }\n const intent = text('intent') as AuthIntent\n const email = text('email').trim()\n const password = text('password')\n const code = text('code').replace(/\\s+/g, '')\n const next = safeNext(text('next') || null)\n const ip = options.clientIp?.(request)\n const w = ip ? { clientIp: ip } : undefined\n const carry: Partial<AuthActionData> = { email }\n if (!email) return fail('validation', carry, 'email')\n\n const caps = await loadCaps(sf)\n const passwordOn = caps.password\n // Off because the store's token lacks a scope (not a merchant choice): say so instead of \"not available\".\n const misconfigured = caps.unavailable_reason === 'missing_scope'\n const off = (): AuthActionData => fail(misconfigured ? 'store_misconfigured' : 'unsupported', carry)\n const otpOn = caps.otp_channels.includes('email')\n\n try {\n switch (intent) {\n case 'login': {\n if (!passwordOn) return off()\n if (!password) return fail('validation', carry, 'password')\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n case 'register': {\n if (!passwordOn) return off()\n if (!password) return fail('validation', carry, 'password')\n const res = await sf.customer.register(\n { email, password, ...(text('first_name').trim() ? { first_name: text('first_name').trim() } : {}), ...(text('last_name').trim() ? { last_name: text('last_name').trim() } : {}) },\n w,\n )\n return res.status === 'created' ? await signedIn(res.session, next) : { ok: true, step: 'verify', email }\n }\n case 'verify': {\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.verifyRegistration({ email, code }, w), next)\n }\n case 'otp-request': {\n if (!otpOn) return off()\n await sf.customer.requestOtp({ email }, w)\n return { ok: true, step: 'otp', email }\n }\n case 'otp-login': {\n if (!otpOn) return off()\n if (!code) return fail('validation', carry, 'code')\n return await signedIn(await sf.customer.createSession({ email, code }, w), next)\n }\n case 'forgot': {\n if (!passwordOn || !otpOn) return off()\n try {\n await sf.customer.requestOtp({ email }, w)\n } catch (err) {\n // Only throttling and a bad email are told; anything else looks the same as success (no account enumeration).\n if (isStorefrontError(err) && (err.status === 429 || err.status === 400)) throw err\n }\n return { ok: true, step: 'reset', email }\n }\n case 'reset': {\n if (!passwordOn) return off()\n if (!code) return fail('validation', carry, 'code')\n if (!password) return fail('validation', carry, 'password')\n await sf.customer.resetPassword({ email, code, password }, w)\n return await signedIn(await sf.customer.loginWithPassword({ email, password }, w), next)\n }\n default:\n return fail('validation', carry)\n }\n } catch (err) {\n const step = intent === 'verify' ? 'verify' : intent === 'otp-login' ? 'otp' : intent === 'reset' || intent === 'forgot' ? 'reset' : undefined\n const ctx = intent === 'login' ? 'credentials' : step ? 'code' : 'other'\n return toFailure(err, ctx, step && intent !== 'forgot' ? { ...carry, step } : carry)\n }\n }\n}\n\nexport type AuthAction = ReturnType<typeof createAuthAction>\n"]}
package/dist/account.cjs CHANGED
@@ -263,6 +263,7 @@ var ES2 = {
263
263
  rate_limited: "Demasiados intentos. Espera unos minutos e int\xE9ntalo de nuevo.",
264
264
  validation: "Revisa los datos e int\xE9ntalo de nuevo.",
265
265
  unsupported: "Esta forma de entrar no est\xE1 disponible en esta tienda.",
266
+ store_misconfigured: "No pudimos crear tu cuenta por un problema de configuraci\xF3n de la tienda. Puedes comprar como invitado; ya avisamos a la tienda.",
266
267
  unavailable: "No pudimos completar la acci\xF3n. Int\xE9ntalo de nuevo en un momento."
267
268
  }
268
269
  };
@@ -307,6 +308,7 @@ var EN2 = {
307
308
  rate_limited: "Too many attempts. Wait a few minutes and try again.",
308
309
  validation: "Check the details and try again.",
309
310
  unsupported: "This way of signing in is not available in this store.",
311
+ store_misconfigured: "We could not create your account because of a store configuration problem. You can check out as a guest; we have already told the store.",
310
312
  unavailable: "We could not complete that. Try again in a moment."
311
313
  }
312
314
  };
@@ -410,7 +412,7 @@ function AccountAuth({ capabilities, data, next, pending = false, initialView, f
410
412
  const showSummary = !data?.error?.field;
411
413
  const title = m.titles[view];
412
414
  if (!available && !passwordOn && !otpOn) {
413
- return /* @__PURE__ */ jsxRuntime.jsx("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": "unavailable", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.notice, role: "status", children: m.nothingAvailable }) });
415
+ return /* @__PURE__ */ jsxRuntime.jsx("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": "unavailable", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: cx.notice, role: "status", children: capabilities.unavailable_reason === "missing_scope" ? m.errors.store_misconfigured : m.nothingAvailable }) });
414
416
  }
415
417
  return /* @__PURE__ */ jsxRuntime.jsxs("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": view, "aria-labelledby": "sf-account-title", children: [
416
418
  header,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/checkout/fields.tsx","../src/account/account-auth.tsx"],"names":["useRef","useState","useEffect","jsxs","jsx","ES","EN","Fragment"],"mappings":";;;;;;AA6BA,IAAM,EAAA,GAAoB;AAAA,EACxB,YAAA,EAAc,sBAAA;AAAA,EACd,aAAA,EAAe,sBAAA;AAAA,EACf,KAAA,EAAO,6DAAA;AAAA,EACP,GAAA,EAAK,mCAAA;AAAA,EACL,OAAA,EAAS,oBAAA;AAAA,EACT,QAAA,EAAU,kCAAA;AAAA,EACV,MAAA,EAAQ,oBAAA;AAAA,EACR,UAAA,EAAY,+BAAA;AAAA,EACZ,WAAA,EAAa,kCAAA;AAAA,EACb,QAAA,EAAU;AACZ,CAAA;AAEA,IAAM,EAAA,GAAoB;AAAA,EACxB,YAAA,EAAc,qBAAA;AAAA,EACd,aAAA,EAAe,mBAAA;AAAA,EACf,KAAA,EAAO,6CAAA;AAAA,EACP,GAAA,EAAK,6BAAA;AAAA,EACL,OAAA,EAAS,mBAAA;AAAA,EACT,QAAA,EAAU,gCAAA;AAAA,EACV,MAAA,EAAQ,mBAAA;AAAA,EACR,UAAA,EAAY,2BAAA;AAAA,EACZ,WAAA,EAAa,8BAAA;AAAA,EACb,QAAA,EAAU;AACZ,CAAA;AAGO,SAAS,aAAA,CAAc,QAAwB,SAAA,EAA0D;AAC9G,EAAA,MAAM,IAAA,GAAA,CAAQ,UAAU,OAAA,EAAS,WAAA,GAAc,UAAA,CAAW,IAAI,IAAI,EAAA,GAAK,EAAA;AACvE,EAAA,OAAO,YAAY,EAAE,GAAG,IAAA,EAAM,GAAG,WAAU,GAAI,IAAA;AACjD;AASA,IAAM,SAAA,GAAY,CAAC,EAAA,KACjB,CAAC,CAAC,EAAA,IAAM,OAAQ,GAAe,OAAA,KAAY,QAAA,IAAY,CAAC,OAAA,EAAS,QAAA,EAAU,UAAU,CAAA,CAAE,QAAA,CAAU,GAAe,OAAO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A,MAC1D,IAAA;AAAA,sBACDA,cAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAW,EAAA,CAAG,OAAA,EACjB,QAAA,kBAAAA,cAAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,IAAA,EAAK,QAAA,EAAS,OAAO,MAAA,EAAQ,QAAA,EAAU,OAAA,EAAS,SAAA,EAAW,EAAA,CAAG,MAAA,EAAQ,wBAAA,EAAsB,IAAA,EAC/G,QAAA,EAAA,CAAA,CAAE,MAAA,CAAO,IAAI,CAAA,EAChB,CAAA,EACF,CAAA;AAAA,sBACAA,eAAC,KAAA,EAAA,EAAI,SAAA,EAAW,GAAG,KAAA,EAAO,uBAAA,EAAqB,MAC5C,QAAA,EAAA,KAAA,EACH;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"account.cjs","sourcesContent":["/**\n * Form fields of a checkout with inline validation: a labelled field that shows its own error under it, a focusable\n * error summary for the submit, and one hook that reads the browser's own constraint validation (`required`, `type`,\n * `pattern`, `minLength`...) so the rules stay in the HTML and the page keeps working without JavaScript (then the\n * browser explains the errors itself).\n *\n * WCAG 2.2: errors are identified in text next to the field (3.3.1), linked with `aria-describedby` and `aria-invalid`,\n * and the summary takes focus and links to every field (3.3.1 / 2.4.3). Validation runs when the buyer leaves a field\n * that has a value, and clears as soon as it is fixed: it never nags while typing.\n */\nimport { useEffect, useRef, useState, type InputHTMLAttributes, type ReactNode, type RefObject, type SelectHTMLAttributes } from 'react'\n\nexport type FieldMessages = {\n valueMissing: string\n /** Required radio group (delivery, payment). */\n choiceMissing: string\n email: string\n tel: string\n pattern: string\n /** `{n}` = minimum length. */\n tooShort: string\n /** A field the server rejected. */\n server: string\n /** Error summary title, `{n}` = number of fields. */\n summaryOne: string\n summaryMany: string\n optional: string\n}\n\nconst ES: FieldMessages = {\n valueMissing: 'Completa este campo.',\n choiceMissing: 'Elige una opción.',\n email: 'Escribe un correo válido, por ejemplo nombre@correo.com.',\n tel: 'Escribe un teléfono válido.',\n pattern: 'Revisa el formato.',\n tooShort: 'Escribe al menos {n} caracteres.',\n server: 'Revisa este campo.',\n summaryOne: 'Revisa 1 campo para continuar',\n summaryMany: 'Revisa {n} campos para continuar',\n optional: '(opcional)',\n}\n\nconst EN: FieldMessages = {\n valueMissing: 'Fill in this field.',\n choiceMissing: 'Choose an option.',\n email: 'Enter a valid email, like name@example.com.',\n tel: 'Enter a valid phone number.',\n pattern: 'Check the format.',\n tooShort: 'Enter at least {n} characters.',\n server: 'Check this field.',\n summaryOne: 'Check 1 field to continue',\n summaryMany: 'Check {n} fields to continue',\n optional: '(optional)',\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides. */\nexport function fieldMessages(locale?: string | null, overrides?: Partial<FieldMessages> | null): FieldMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n return overrides ? { ...base, ...overrides } : base\n}\n\n/** Field name -> error text. */\nexport type FieldErrors = Record<string, string>\n\nexport type ErrorSummaryItem = { name: string; id: string; label: string; message: string }\n\ntype Control = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement\n\nconst isControl = (el: EventTarget | null): el is Control =>\n !!el && typeof (el as Element).tagName === 'string' && ['INPUT', 'SELECT', 'TEXTAREA'].includes((el as Element).tagName) && !!(el as Control).name\n\n/**\n * The error text for a control, from its validity. A control can bring its own text with `data-sf-error` (any\n * failure) or `title` (pattern mismatch, the HTML convention).\n */\nexport function validationMessage(el: Control, m: FieldMessages = ES): string | null {\n const v = el.validity\n if (!v || v.valid) return null\n const own = el.getAttribute('data-sf-error')\n if (own) return own\n if (v.valueMissing) return el instanceof HTMLInputElement && (el.type === 'radio' || el.type === 'checkbox') ? m.choiceMissing : m.valueMissing\n if (v.typeMismatch && el instanceof HTMLInputElement) return el.type === 'email' ? m.email : el.type === 'tel' ? m.tel : m.pattern\n if (v.patternMismatch) return el.getAttribute('title') || (el instanceof HTMLInputElement && el.type === 'tel' ? m.tel : m.pattern)\n if (v.tooShort && el instanceof HTMLInputElement) return m.tooShort.replace('{n}', String(el.minLength))\n return el.validationMessage || m.pattern\n}\n\n/** Visible name of a control: its `<label>`, `aria-label`, or the legend of its group (radios). */\nfunction labelOf(el: Control): string {\n if (el instanceof HTMLInputElement && el.type === 'radio') {\n const legend = el.closest('fieldset')?.querySelector('legend')\n if (legend?.textContent) return legend.textContent.trim()\n }\n const text = el.labels?.[0]?.getAttribute('data-sf-label') ?? el.labels?.[0]?.textContent ?? el.getAttribute('aria-label') ?? el.name\n return text.trim()\n}\n\nexport type UseFieldErrorsOptions = {\n locale?: string\n messages?: Partial<FieldMessages>\n /** Fields the server rejected (e.g. from the action), shown with `serverMessages[name]` or the generic text. */\n serverFields?: Iterable<string> | null\n serverMessages?: Record<string, string> | null\n}\n\nexport type FieldErrorsState = {\n errors: FieldErrors\n /** Non-null after a submit with problems (or with server errors): render it in `<ErrorSummary>`. */\n summary: ErrorSummaryItem[] | null\n /** Changes every time a new summary appears, so `<ErrorSummary>` focuses it again. */\n summaryKey: number\n clear: () => void\n}\n\n/**\n * Inline validation for the page `<form>`. Listens to the form (no wrapping component): leaving a field with a value\n * checks it; typing in a field with an error clears it when fixed; a submit or `reportValidity()` with problems\n * collects them (the browser's bubbles are replaced by the inline texts) for the summary.\n */\nexport function useFieldErrors(formRef: RefObject<HTMLFormElement | null>, options: UseFieldErrorsOptions = {}): FieldErrorsState {\n const m = fieldMessages(options.locale, options.messages)\n const live = useRef(m)\n live.current = m\n const server = [...(options.serverFields ?? [])]\n const serverKey = server.join('|')\n const [errors, setErrors] = useState<FieldErrors>(() => Object.fromEntries(server.map((n) => [n, options.serverMessages?.[n] ?? m.server])))\n const [summary, setSummary] = useState<ErrorSummaryItem[] | null>(null)\n const [summaryKey, setSummaryKey] = useState(0)\n\n // Server errors (a new action result): inline texts plus a summary.\n useEffect(() => {\n if (!server.length) return\n const form = formRef.current\n const items: ErrorSummaryItem[] = []\n const next: FieldErrors = {}\n for (const name of server) {\n const msg = options.serverMessages?.[name] ?? live.current.server\n next[name] = msg\n const el = form?.elements.namedItem(name)\n const ctl = el && 'length' in el && !(el instanceof HTMLSelectElement) ? ((el as RadioNodeList)[0] as Control | undefined) : (el as Control | null)\n if (ctl) items.push({ name, id: ctl.id || name, label: labelOf(ctl), message: msg })\n }\n setErrors((e) => ({ ...e, ...next }))\n if (items.length) {\n setSummary(items)\n setSummaryKey((k) => k + 1)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [serverKey])\n\n useEffect(() => {\n const form = formRef.current\n if (!form) return\n let batch: Control[] | null = null\n const set = (name: string, msg: string | null) =>\n setErrors((e) => {\n if (msg === null) {\n if (!(name in e)) return e\n const { [name]: _gone, ...rest } = e\n return rest\n }\n return e[name] === msg ? e : { ...e, [name]: msg }\n })\n const onBlur = (ev: FocusEvent) => {\n const el = ev.target\n if (!isControl(el) || (el instanceof HTMLInputElement && (el.type === 'radio' || el.type === 'checkbox' || el.type === 'hidden'))) return\n // Leaving an empty field you only tabbed through is not an error yet; it is at submit.\n if (!el.value) return\n set(el.name, validationMessage(el, live.current))\n }\n const onInput = (ev: Event) => {\n const el = ev.target\n if (!isControl(el)) return\n setErrors((e) => {\n if (!(el.name in e)) return e\n const msg = el.validity.valid ? null : validationMessage(el, live.current)\n if (msg !== null) return e // keep the text until the field is fixed (no flicker while typing)\n const { [el.name]: _gone, ...rest } = e\n return rest\n })\n }\n const onInvalid = (ev: Event) => {\n const el = ev.target\n if (!isControl(el)) return\n ev.preventDefault() // the inline text replaces the browser bubble\n if (!batch) {\n batch = []\n queueMicrotask(() => {\n const list = batch ?? []\n batch = null\n const seen = new Set<string>()\n const items: ErrorSummaryItem[] = []\n const next: FieldErrors = {}\n for (const c of list) {\n if (seen.has(c.name)) continue\n seen.add(c.name)\n const msg = validationMessage(c, live.current) ?? live.current.valueMissing\n next[c.name] = msg\n items.push({ name: c.name, id: c.id || c.name, label: labelOf(c), message: msg })\n }\n setErrors((e) => ({ ...e, ...next }))\n setSummary(items)\n setSummaryKey((k) => k + 1)\n })\n }\n batch.push(el)\n }\n form.addEventListener('focusout', onBlur)\n form.addEventListener('input', onInput)\n form.addEventListener('change', onInput)\n form.addEventListener('invalid', onInvalid, true)\n return () => {\n form.removeEventListener('focusout', onBlur)\n form.removeEventListener('input', onInput)\n form.removeEventListener('change', onInput)\n form.removeEventListener('invalid', onInvalid, true)\n }\n }, [formRef])\n\n // The summary follows the fixes: a field fixed after the submit leaves the list.\n const shown = summary ? summary.filter((s) => s.name in errors).map((s) => ({ ...s, message: errors[s.name]! })) : null\n return {\n errors,\n summary: shown && shown.length ? shown : null,\n summaryKey,\n clear: () => {\n setErrors({})\n setSummary(null)\n },\n }\n}\n\nexport type ErrorSummaryProps = {\n items: readonly ErrorSummaryItem[] | null\n /** Changes when a new summary must take focus (`useFieldErrors().summaryKey`). */\n focusKey?: number\n locale?: string\n messages?: Partial<FieldMessages>\n title?: ReactNode\n className?: string\n classNames?: Partial<Record<'title' | 'list' | 'link', string>>\n}\n\n/**\n * The list of problems after a submit, above the form: `role=\"alert\"`, takes focus, one link per field (moves the\n * focus to it). Renders nothing without items.\n */\nexport function ErrorSummary({ items, focusKey, locale, messages, title, className, classNames: cx = {} }: ErrorSummaryProps) {\n const ref = useRef<HTMLDivElement>(null)\n const m = fieldMessages(locale, messages)\n const has = !!items && items.length > 0\n useEffect(() => {\n if (has) ref.current?.focus()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [focusKey])\n if (!has) return null\n const n = items!.length\n return (\n <div ref={ref} role=\"alert\" tabIndex={-1} className={className} data-sf-error-summary aria-labelledby=\"sf-error-summary-title\">\n <p id=\"sf-error-summary-title\" className={cx.title} data-sf-error-summary-title>\n {title ?? (n === 1 ? m.summaryOne : m.summaryMany.replace('{n}', String(n)))}\n </p>\n <ul className={cx.list}>\n {items!.map((it) => (\n <li key={it.name}>\n <a\n href={`#${it.id}`}\n className={cx.link}\n onClick={(e) => {\n const el = document.getElementById(it.id)\n if (!el) return\n e.preventDefault()\n el.focus()\n el.scrollIntoView?.({ block: 'center' })\n }}\n >\n {it.label}: {it.message}\n </a>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n\nexport type CheckoutFieldClassNames = Partial<Record<'root' | 'label' | 'optional' | 'input' | 'hint' | 'error', string>>\n\ntype BaseFieldProps = {\n name: string\n label: string\n /** Field id. Default: the name. */\n id?: string\n /** Error text (from `useFieldErrors().errors[name]` or the server). */\n error?: string | null\n /** Help under the label (\"we only use it for the delivery\"). */\n hint?: ReactNode\n /** Marks the label \"(optional)\" and drops `required`. */\n optional?: boolean\n classNames?: CheckoutFieldClassNames\n locale?: string\n messages?: Partial<FieldMessages>\n}\n\nexport type CheckoutFieldProps = BaseFieldProps & Omit<InputHTMLAttributes<HTMLInputElement>, 'name' | 'id'> & { as?: 'input' }\nexport type CheckoutSelectProps = BaseFieldProps & Omit<SelectHTMLAttributes<HTMLSelectElement>, 'name' | 'id'> & { as: 'select'; children: ReactNode }\n\n/**\n * One labelled field: label (with \"(optional)\"), hint, the control and its error text, wired with `aria-describedby`\n * and `aria-invalid`. Required unless `optional`. `as=\"select\"` renders a `<select>` with the given options.\n */\nexport function CheckoutField(props: CheckoutFieldProps | CheckoutSelectProps) {\n const { name, label, id = name, error, hint, optional = false, classNames: cx = {}, locale, messages, ...rest } = props\n const m = fieldMessages(locale, messages)\n const hintId = hint ? `${id}-hint` : undefined\n const errorId = `${id}-error`\n const describedBy = [hintId, error ? errorId : undefined].filter(Boolean).join(' ') || undefined\n const common = {\n id,\n name,\n required: !optional,\n 'aria-invalid': error ? true : undefined,\n 'aria-describedby': describedBy,\n className: cx.input,\n 'data-sf-field-control': '',\n } as const\n return (\n <div className={cx.root} data-sf-field data-invalid={error ? '' : undefined}>\n <label htmlFor={id} className={cx.label} data-sf-label={label}>\n {label}\n {optional ? (\n <span className={cx.optional} data-sf-field-optional>\n {' '}\n {m.optional}\n </span>\n ) : null}\n </label>\n {hint ? (\n <p id={hintId} className={cx.hint} data-sf-field-hint>\n {hint}\n </p>\n ) : null}\n {rest.as === 'select' ? (\n (() => {\n const { as: _as, children, ...select } = rest\n return (\n <select {...select} {...common}>\n {children}\n </select>\n )\n })()\n ) : (\n (() => {\n const { as: _as, ...input } = rest as CheckoutFieldProps\n return <input {...input} {...common} />\n })()\n )}\n {/* Reserved only when there is an error: the text sits right under its field. */}\n {error ? (\n <p id={errorId} className={cx.error} data-sf-field-error>\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n","/**\n * The account screen: sign in with password, create an account, verify the emailed code, sign in with a code and\n * recover a forgotten password, in one `<form method=\"post\">` driven by `createAuthAction` (`./server`). What the store\n * offers comes from `loadAuthCapabilities`; the form shows only that. Plain HTML: it works without JavaScript for the\n * password sign-in and the steps the action sends back; the view switches (links) need JavaScript.\n *\n * Styling: `data-sf-account-*` attributes and `classNames` slots, fields reuse `CheckoutField` (and `checkout.css`);\n * `account.css` is an optional neutral sheet. Texts are Spanish by default, English with `locale=\"en\"`, any with `messages`.\n */\nimport { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\nimport type { CustomerCapabilities } from '@asteby/storefront'\nimport { CheckoutField, ErrorSummary, useFieldErrors, type CheckoutFieldClassNames } from '../checkout/fields.js'\nimport type { AuthActionData, AuthErrorCode, AuthStep } from './types.js'\n\nexport type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep\n\nexport type AccountAuthMessages = {\n titles: Record<AccountAuthView, string>\n email: string\n password: string\n newPassword: string\n passwordHint: string\n firstName: string\n lastName: string\n code: string\n codeSentTo: string\n submit: Record<AccountAuthView, string>\n resend: string\n forgotLink: string\n registerLink: string\n loginLink: string\n otpLink: string\n backToLogin: string\n nothingAvailable: string\n errors: Record<AuthErrorCode, string>\n}\n\nconst ES: AccountAuthMessages = {\n titles: {\n login: 'Entrar a tu cuenta',\n register: 'Crear una cuenta',\n verify: 'Confirma tu correo',\n 'otp-email': 'Entrar con un código',\n otp: 'Escribe tu código',\n forgot: 'Recuperar contraseña',\n reset: 'Elige una contraseña nueva',\n },\n email: 'Correo electrónico',\n password: 'Contraseña',\n newPassword: 'Contraseña nueva',\n passwordHint: 'Entre 10 y 128 caracteres.',\n firstName: 'Nombre',\n lastName: 'Apellido',\n code: 'Código',\n codeSentTo: 'Enviamos un código a {email}. Puede tardar un minuto.',\n submit: {\n login: 'Entrar',\n register: 'Crear cuenta',\n verify: 'Confirmar',\n 'otp-email': 'Enviarme el código',\n otp: 'Entrar',\n forgot: 'Enviarme el código',\n reset: 'Guardar y entrar',\n },\n resend: 'Reenviar código',\n forgotLink: '¿Olvidaste tu contraseña?',\n registerLink: 'Crear una cuenta',\n loginLink: 'Ya tengo cuenta',\n otpLink: 'Entrar con un código por correo',\n backToLogin: 'Volver a entrar con contraseña',\n nothingAvailable: 'Esta tienda no admite iniciar sesión por ahora.',\n errors: {\n invalid_credentials: 'El correo o la contraseña no coinciden.',\n invalid_code: 'El código no es válido o ya venció.',\n email_taken: 'Ya existe una cuenta con este correo. Entra o recupera tu contraseña.',\n rate_limited: 'Demasiados intentos. Espera unos minutos e inténtalo de nuevo.',\n validation: 'Revisa los datos e inténtalo de nuevo.',\n unsupported: 'Esta forma de entrar no está disponible en esta tienda.',\n unavailable: 'No pudimos completar la acción. Inténtalo de nuevo en un momento.',\n },\n}\n\nconst EN: AccountAuthMessages = {\n titles: {\n login: 'Sign in',\n register: 'Create an account',\n verify: 'Confirm your email',\n 'otp-email': 'Sign in with a code',\n otp: 'Enter your code',\n forgot: 'Reset your password',\n reset: 'Choose a new password',\n },\n email: 'Email',\n password: 'Password',\n newPassword: 'New password',\n passwordHint: 'Between 10 and 128 characters.',\n firstName: 'First name',\n lastName: 'Last name',\n code: 'Code',\n codeSentTo: 'We sent a code to {email}. It can take a minute.',\n submit: {\n login: 'Sign in',\n register: 'Create account',\n verify: 'Confirm',\n 'otp-email': 'Email me the code',\n otp: 'Sign in',\n forgot: 'Email me the code',\n reset: 'Save and sign in',\n },\n resend: 'Resend code',\n forgotLink: 'Forgot your password?',\n registerLink: 'Create an account',\n loginLink: 'I already have an account',\n otpLink: 'Sign in with an emailed code',\n backToLogin: 'Back to password sign-in',\n nothingAvailable: 'This store does not support signing in right now.',\n errors: {\n invalid_credentials: 'The email and password do not match.',\n invalid_code: 'The code is not valid or has expired.',\n email_taken: 'An account with this email already exists. Sign in or reset your password.',\n rate_limited: 'Too many attempts. Wait a few minutes and try again.',\n validation: 'Check the details and try again.',\n unsupported: 'This way of signing in is not available in this store.',\n unavailable: 'We could not complete that. Try again in a moment.',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides (nested `titles`/`submit`/`errors` merge). */\nexport function accountAuthMessages(locale?: string | null, overrides?: DeepPartial<AccountAuthMessages> | null): AccountAuthMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n return {\n ...base,\n ...(overrides as Partial<AccountAuthMessages>),\n titles: { ...base.titles, ...overrides.titles },\n submit: { ...base.submit, ...overrides.submit },\n errors: { ...base.errors, ...overrides.errors },\n }\n}\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, string> ? Partial<T[K]> : T[K] }\n\nexport type AccountAuthClassNames = Partial<Record<'root' | 'title' | 'form' | 'notice' | 'error' | 'actions' | 'submit' | 'links' | 'link', string>> & {\n field?: CheckoutFieldClassNames\n}\n\n/** What `<AccountAuth>` passes to its `form` component: the few props a router `Form` and the HTML `<form>` both accept. */\nexport type AccountFormProps = {\n method?: 'post'\n action?: string\n className?: string\n children?: ReactNode\n /** Loose on purpose: a router `Form` types its ref with its own copy of `@types/react`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ref?: any\n 'data-sf-account-form'?: boolean | string\n}\n\nexport type AccountAuthProps = {\n /** From `loadAuthCapabilities` (the loader). */\n capabilities: CustomerCapabilities\n /** What the action returned (`useActionData()`); drives the next screen and the errors. */\n data?: AuthActionData | null\n /** Where to go after signing in (sent as `next`; the server validates it). */\n next?: string | null\n /** A submit is in flight (`navigation.state !== 'idle'`): disables the buttons. */\n pending?: boolean\n /** First screen. Default `login`, or `otp-email` when the store has no password sign-in. */\n initialView?: AccountAuthView\n /** Form component, e.g. React Router's `Form`, to submit without a reload. It must forward `ref` to the `<form>` (React 19: a prop). Default: the HTML `<form>`. */\n form?: 'form' | ComponentType<AccountFormProps>\n /** `action` of the form (default: the current URL). */\n action?: string\n locale?: string\n messages?: DeepPartial<AccountAuthMessages>\n classNames?: AccountAuthClassNames\n /** Shown above the form (a logo, a welcome text). */\n header?: ReactNode\n}\n\nconst initialOf = (caps: CustomerCapabilities, initialView?: AccountAuthView): AccountAuthView =>\n initialView ?? (caps.password ? 'login' : caps.otp_channels.includes('email') ? 'otp-email' : 'login')\n\n/**\n * The whole account screen. Headless enough to restyle, complete enough to drop in:\n * `export default function Account() { return <AccountAuth capabilities={useLoaderData()} data={useActionData()} form={Form} /> }`.\n */\nexport function AccountAuth({ capabilities, data, next, pending = false, initialView, form: FormTag = 'form', action, locale, messages, classNames: cx = {}, header }: AccountAuthProps) {\n const m = accountAuthMessages(locale, messages)\n const passwordOn = capabilities.password\n const otpOn = capabilities.otp_channels.includes('email')\n const [view, setView] = useState<AccountAuthView>(() => data?.step ?? initialOf(capabilities, initialView))\n const [email, setEmail] = useState(data?.email ?? '')\n const ref = useRef<HTMLFormElement>(null)\n const serverFields = data?.error?.field ? [data.error.field] : null\n const errorText = data?.error ? m.errors[data.error.code] : null\n const v = useFieldErrors(ref, { ...(locale ? { locale } : {}), serverFields, serverMessages: data?.error?.field && errorText ? { [data.error.field]: errorText } : null })\n\n // The action decides the next screen; the email it carries survives it.\n useEffect(() => {\n if (data?.step) setView(data.step)\n if (data?.email) setEmail(data.email)\n }, [data])\n\n const go = (to: AccountAuthView) => {\n v.clear()\n setView(to)\n }\n const fieldProps = { classNames: cx.field, ...(locale ? { locale } : {}) }\n const emailField = (\n <CheckoutField {...fieldProps} name=\"email\" type=\"email\" label={m.email} autoComplete=\"email\" inputMode=\"email\" value={email} onChange={(e) => setEmail(e.currentTarget.value)} error={v.errors.email ?? null} />\n )\n const codeField = (\n <CheckoutField {...fieldProps} name=\"code\" label={m.code} autoComplete=\"one-time-code\" inputMode=\"numeric\" pattern=\"[0-9]*\" error={v.errors.code ?? null} />\n )\n const passwordField = (label: string, autoComplete: string, newPassword: boolean) => (\n <CheckoutField\n {...fieldProps}\n name=\"password\"\n type=\"password\"\n label={label}\n autoComplete={autoComplete}\n error={v.errors.password ?? null}\n {...(newPassword ? { minLength: 10, maxLength: 128, hint: m.passwordHint } : {})}\n />\n )\n const link = (to: AccountAuthView, text: string) => (\n <button type=\"button\" className={cx.link} data-sf-account-link={to} onClick={() => go(to)}>\n {text}\n </button>\n )\n\n let body: ReactNode\n let links: ReactNode = null\n switch (view) {\n case 'register':\n body = (\n <>\n <CheckoutField {...fieldProps} name=\"first_name\" label={m.firstName} autoComplete=\"given-name\" optional />\n <CheckoutField {...fieldProps} name=\"last_name\" label={m.lastName} autoComplete=\"family-name\" optional />\n {emailField}\n {passwordField(m.password, 'new-password', true)}\n </>\n )\n links = link('login', m.loginLink)\n break\n case 'verify':\n case 'otp':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n </>\n )\n links = (\n <>\n {view === 'otp' ? (\n <button type=\"submit\" name=\"intent\" value=\"otp-request\" formNoValidate className={cx.link} data-sf-account-link=\"resend\">\n {m.resend}\n </button>\n ) : null}\n {link('login', m.backToLogin)}\n </>\n )\n break\n case 'otp-email':\n case 'forgot':\n body = emailField\n links = link('login', m.backToLogin)\n break\n case 'reset':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n {passwordField(m.newPassword, 'new-password', true)}\n </>\n )\n links = link('login', m.backToLogin)\n break\n default:\n body = (\n <>\n {emailField}\n {passwordField(m.password, 'current-password', false)}\n </>\n )\n links = (\n <>\n {otpOn ? link('forgot', m.forgotLink) : null}\n {link('register', m.registerLink)}\n {otpOn ? link('otp-email', m.otpLink) : null}\n </>\n )\n }\n\n const intent = { login: 'login', register: 'register', verify: 'verify', 'otp-email': 'otp-request', otp: 'otp-login', forgot: 'forgot', reset: 'reset' }[view]\n // Without password accounts the password views do not exist; only the code sign-in does.\n const available = view === 'login' || view === 'register' || view === 'forgot' || view === 'reset' || view === 'verify' ? passwordOn : otpOn\n const showSummary = !data?.error?.field\n const title = m.titles[view]\n if (!available && !passwordOn && !otpOn) {\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view=\"unavailable\">\n <p className={cx.notice} role=\"status\">\n {m.nothingAvailable}\n </p>\n </section>\n )\n }\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view={view} aria-labelledby=\"sf-account-title\">\n {header}\n <h1 id=\"sf-account-title\" className={cx.title}>\n {title}\n </h1>\n <FormTag ref={ref as never} method=\"post\" {...(action ? { action } : {})} className={cx.form} data-sf-account-form>\n <ErrorSummary items={v.summary} focusKey={v.summaryKey} {...(locale ? { locale } : {})} />\n {errorText && showSummary ? (\n <p role=\"alert\" className={cx.error} data-sf-account-error={data!.error!.code}>\n {errorText}\n </p>\n ) : null}\n {next ? <input type=\"hidden\" name=\"next\" value={next} /> : null}\n {body}\n <div className={cx.actions}>\n <button type=\"submit\" name=\"intent\" value={intent} disabled={pending} className={cx.submit} data-sf-account-submit>\n {m.submit[view]}\n </button>\n </div>\n <div className={cx.links} data-sf-account-links>\n {links}\n </div>\n </FormTag>\n </section>\n )\n}\n"]}
1
+ {"version":3,"sources":["../src/checkout/fields.tsx","../src/account/account-auth.tsx"],"names":["useRef","useState","useEffect","jsxs","jsx","ES","EN","Fragment"],"mappings":";;;;;;AA6BA,IAAM,EAAA,GAAoB;AAAA,EACxB,YAAA,EAAc,sBAAA;AAAA,EACd,aAAA,EAAe,sBAAA;AA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SAAA,EAAW,EAAA,CAAG,OAAA,EACjB,QAAA,kBAAAA,cAAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,IAAA,EAAK,QAAA,EAAS,OAAO,MAAA,EAAQ,QAAA,EAAU,OAAA,EAAS,SAAA,EAAW,EAAA,CAAG,MAAA,EAAQ,wBAAA,EAAsB,IAAA,EAC/G,QAAA,EAAA,CAAA,CAAE,MAAA,CAAO,IAAI,CAAA,EAChB,CAAA,EACF,CAAA;AAAA,sBACAA,eAAC,KAAA,EAAA,EAAI,SAAA,EAAW,GAAG,KAAA,EAAO,uBAAA,EAAqB,MAC5C,QAAA,EAAA,KAAA,EACH;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"account.cjs","sourcesContent":["/**\n * Form fields of a checkout with inline validation: a labelled field that shows its own error under it, a focusable\n * error summary for the submit, and one hook that reads the browser's own constraint validation (`required`, `type`,\n * `pattern`, `minLength`...) so the rules stay in the HTML and the page keeps working without JavaScript (then the\n * browser explains the errors itself).\n *\n * WCAG 2.2: errors are identified in text next to the field (3.3.1), linked with `aria-describedby` and `aria-invalid`,\n * and the summary takes focus and links to every field (3.3.1 / 2.4.3). Validation runs when the buyer leaves a field\n * that has a value, and clears as soon as it is fixed: it never nags while typing.\n */\nimport { useEffect, useRef, useState, type InputHTMLAttributes, type ReactNode, type RefObject, type SelectHTMLAttributes } from 'react'\n\nexport type FieldMessages = {\n valueMissing: string\n /** Required radio group (delivery, payment). */\n choiceMissing: string\n email: string\n tel: string\n pattern: string\n /** `{n}` = minimum length. */\n tooShort: string\n /** A field the server rejected. */\n server: string\n /** Error summary title, `{n}` = number of fields. */\n summaryOne: string\n summaryMany: string\n optional: string\n}\n\nconst ES: FieldMessages = {\n valueMissing: 'Completa este campo.',\n choiceMissing: 'Elige una opción.',\n email: 'Escribe un correo válido, por ejemplo nombre@correo.com.',\n tel: 'Escribe un teléfono válido.',\n pattern: 'Revisa el formato.',\n tooShort: 'Escribe al menos {n} caracteres.',\n server: 'Revisa este campo.',\n summaryOne: 'Revisa 1 campo para continuar',\n summaryMany: 'Revisa {n} campos para continuar',\n optional: '(opcional)',\n}\n\nconst EN: FieldMessages = {\n valueMissing: 'Fill in this field.',\n choiceMissing: 'Choose an option.',\n email: 'Enter a valid email, like name@example.com.',\n tel: 'Enter a valid phone number.',\n pattern: 'Check the format.',\n tooShort: 'Enter at least {n} characters.',\n server: 'Check this field.',\n summaryOne: 'Check 1 field to continue',\n summaryMany: 'Check {n} fields to continue',\n optional: '(optional)',\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides. */\nexport function fieldMessages(locale?: string | null, overrides?: Partial<FieldMessages> | null): FieldMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n return overrides ? { ...base, ...overrides } : base\n}\n\n/** Field name -> error text. */\nexport type FieldErrors = Record<string, string>\n\nexport type ErrorSummaryItem = { name: string; id: string; label: string; message: string }\n\ntype Control = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement\n\nconst isControl = (el: EventTarget | null): el is Control =>\n !!el && typeof (el as Element).tagName === 'string' && ['INPUT', 'SELECT', 'TEXTAREA'].includes((el as Element).tagName) && !!(el as Control).name\n\n/**\n * The error text for a control, from its validity. A control can bring its own text with `data-sf-error` (any\n * failure) or `title` (pattern mismatch, the HTML convention).\n */\nexport function validationMessage(el: Control, m: FieldMessages = ES): string | null {\n const v = el.validity\n if (!v || v.valid) return null\n const own = el.getAttribute('data-sf-error')\n if (own) return own\n if (v.valueMissing) return el instanceof HTMLInputElement && (el.type === 'radio' || el.type === 'checkbox') ? m.choiceMissing : m.valueMissing\n if (v.typeMismatch && el instanceof HTMLInputElement) return el.type === 'email' ? m.email : el.type === 'tel' ? m.tel : m.pattern\n if (v.patternMismatch) return el.getAttribute('title') || (el instanceof HTMLInputElement && el.type === 'tel' ? m.tel : m.pattern)\n if (v.tooShort && el instanceof HTMLInputElement) return m.tooShort.replace('{n}', String(el.minLength))\n return el.validationMessage || m.pattern\n}\n\n/** Visible name of a control: its `<label>`, `aria-label`, or the legend of its group (radios). */\nfunction labelOf(el: Control): string {\n if (el instanceof HTMLInputElement && el.type === 'radio') {\n const legend = el.closest('fieldset')?.querySelector('legend')\n if (legend?.textContent) return legend.textContent.trim()\n }\n const text = el.labels?.[0]?.getAttribute('data-sf-label') ?? el.labels?.[0]?.textContent ?? el.getAttribute('aria-label') ?? el.name\n return text.trim()\n}\n\nexport type UseFieldErrorsOptions = {\n locale?: string\n messages?: Partial<FieldMessages>\n /** Fields the server rejected (e.g. from the action), shown with `serverMessages[name]` or the generic text. */\n serverFields?: Iterable<string> | null\n serverMessages?: Record<string, string> | null\n}\n\nexport type FieldErrorsState = {\n errors: FieldErrors\n /** Non-null after a submit with problems (or with server errors): render it in `<ErrorSummary>`. */\n summary: ErrorSummaryItem[] | null\n /** Changes every time a new summary appears, so `<ErrorSummary>` focuses it again. */\n summaryKey: number\n clear: () => void\n}\n\n/**\n * Inline validation for the page `<form>`. Listens to the form (no wrapping component): leaving a field with a value\n * checks it; typing in a field with an error clears it when fixed; a submit or `reportValidity()` with problems\n * collects them (the browser's bubbles are replaced by the inline texts) for the summary.\n */\nexport function useFieldErrors(formRef: RefObject<HTMLFormElement | null>, options: UseFieldErrorsOptions = {}): FieldErrorsState {\n const m = fieldMessages(options.locale, options.messages)\n const live = useRef(m)\n live.current = m\n const server = [...(options.serverFields ?? [])]\n const serverKey = server.join('|')\n const [errors, setErrors] = useState<FieldErrors>(() => Object.fromEntries(server.map((n) => [n, options.serverMessages?.[n] ?? m.server])))\n const [summary, setSummary] = useState<ErrorSummaryItem[] | null>(null)\n const [summaryKey, setSummaryKey] = useState(0)\n\n // Server errors (a new action result): inline texts plus a summary.\n useEffect(() => {\n if (!server.length) return\n const form = formRef.current\n const items: ErrorSummaryItem[] = []\n const next: FieldErrors = {}\n for (const name of server) {\n const msg = options.serverMessages?.[name] ?? live.current.server\n next[name] = msg\n const el = form?.elements.namedItem(name)\n const ctl = el && 'length' in el && !(el instanceof HTMLSelectElement) ? ((el as RadioNodeList)[0] as Control | undefined) : (el as Control | null)\n if (ctl) items.push({ name, id: ctl.id || name, label: labelOf(ctl), message: msg })\n }\n setErrors((e) => ({ ...e, ...next }))\n if (items.length) {\n setSummary(items)\n setSummaryKey((k) => k + 1)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [serverKey])\n\n useEffect(() => {\n const form = formRef.current\n if (!form) return\n let batch: Control[] | null = null\n const set = (name: string, msg: string | null) =>\n setErrors((e) => {\n if (msg === null) {\n if (!(name in e)) return e\n const { [name]: _gone, ...rest } = e\n return rest\n }\n return e[name] === msg ? e : { ...e, [name]: msg }\n })\n const onBlur = (ev: FocusEvent) => {\n const el = ev.target\n if (!isControl(el) || (el instanceof HTMLInputElement && (el.type === 'radio' || el.type === 'checkbox' || el.type === 'hidden'))) return\n // Leaving an empty field you only tabbed through is not an error yet; it is at submit.\n if (!el.value) return\n set(el.name, validationMessage(el, live.current))\n }\n const onInput = (ev: Event) => {\n const el = ev.target\n if (!isControl(el)) return\n setErrors((e) => {\n if (!(el.name in e)) return e\n const msg = el.validity.valid ? null : validationMessage(el, live.current)\n if (msg !== null) return e // keep the text until the field is fixed (no flicker while typing)\n const { [el.name]: _gone, ...rest } = e\n return rest\n })\n }\n const onInvalid = (ev: Event) => {\n const el = ev.target\n if (!isControl(el)) return\n ev.preventDefault() // the inline text replaces the browser bubble\n if (!batch) {\n batch = []\n queueMicrotask(() => {\n const list = batch ?? []\n batch = null\n const seen = new Set<string>()\n const items: ErrorSummaryItem[] = []\n const next: FieldErrors = {}\n for (const c of list) {\n if (seen.has(c.name)) continue\n seen.add(c.name)\n const msg = validationMessage(c, live.current) ?? live.current.valueMissing\n next[c.name] = msg\n items.push({ name: c.name, id: c.id || c.name, label: labelOf(c), message: msg })\n }\n setErrors((e) => ({ ...e, ...next }))\n setSummary(items)\n setSummaryKey((k) => k + 1)\n })\n }\n batch.push(el)\n }\n form.addEventListener('focusout', onBlur)\n form.addEventListener('input', onInput)\n form.addEventListener('change', onInput)\n form.addEventListener('invalid', onInvalid, true)\n return () => {\n form.removeEventListener('focusout', onBlur)\n form.removeEventListener('input', onInput)\n form.removeEventListener('change', onInput)\n form.removeEventListener('invalid', onInvalid, true)\n }\n }, [formRef])\n\n // The summary follows the fixes: a field fixed after the submit leaves the list.\n const shown = summary ? summary.filter((s) => s.name in errors).map((s) => ({ ...s, message: errors[s.name]! })) : null\n return {\n errors,\n summary: shown && shown.length ? shown : null,\n summaryKey,\n clear: () => {\n setErrors({})\n setSummary(null)\n },\n }\n}\n\nexport type ErrorSummaryProps = {\n items: readonly ErrorSummaryItem[] | null\n /** Changes when a new summary must take focus (`useFieldErrors().summaryKey`). */\n focusKey?: number\n locale?: string\n messages?: Partial<FieldMessages>\n title?: ReactNode\n className?: string\n classNames?: Partial<Record<'title' | 'list' | 'link', string>>\n}\n\n/**\n * The list of problems after a submit, above the form: `role=\"alert\"`, takes focus, one link per field (moves the\n * focus to it). Renders nothing without items.\n */\nexport function ErrorSummary({ items, focusKey, locale, messages, title, className, classNames: cx = {} }: ErrorSummaryProps) {\n const ref = useRef<HTMLDivElement>(null)\n const m = fieldMessages(locale, messages)\n const has = !!items && items.length > 0\n useEffect(() => {\n if (has) ref.current?.focus()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [focusKey])\n if (!has) return null\n const n = items!.length\n return (\n <div ref={ref} role=\"alert\" tabIndex={-1} className={className} data-sf-error-summary aria-labelledby=\"sf-error-summary-title\">\n <p id=\"sf-error-summary-title\" className={cx.title} data-sf-error-summary-title>\n {title ?? (n === 1 ? m.summaryOne : m.summaryMany.replace('{n}', String(n)))}\n </p>\n <ul className={cx.list}>\n {items!.map((it) => (\n <li key={it.name}>\n <a\n href={`#${it.id}`}\n className={cx.link}\n onClick={(e) => {\n const el = document.getElementById(it.id)\n if (!el) return\n e.preventDefault()\n el.focus()\n el.scrollIntoView?.({ block: 'center' })\n }}\n >\n {it.label}: {it.message}\n </a>\n </li>\n ))}\n </ul>\n </div>\n )\n}\n\nexport type CheckoutFieldClassNames = Partial<Record<'root' | 'label' | 'optional' | 'input' | 'hint' | 'error', string>>\n\ntype BaseFieldProps = {\n name: string\n label: string\n /** Field id. Default: the name. */\n id?: string\n /** Error text (from `useFieldErrors().errors[name]` or the server). */\n error?: string | null\n /** Help under the label (\"we only use it for the delivery\"). */\n hint?: ReactNode\n /** Marks the label \"(optional)\" and drops `required`. */\n optional?: boolean\n classNames?: CheckoutFieldClassNames\n locale?: string\n messages?: Partial<FieldMessages>\n}\n\nexport type CheckoutFieldProps = BaseFieldProps & Omit<InputHTMLAttributes<HTMLInputElement>, 'name' | 'id'> & { as?: 'input' }\nexport type CheckoutSelectProps = BaseFieldProps & Omit<SelectHTMLAttributes<HTMLSelectElement>, 'name' | 'id'> & { as: 'select'; children: ReactNode }\n\n/**\n * One labelled field: label (with \"(optional)\"), hint, the control and its error text, wired with `aria-describedby`\n * and `aria-invalid`. Required unless `optional`. `as=\"select\"` renders a `<select>` with the given options.\n */\nexport function CheckoutField(props: CheckoutFieldProps | CheckoutSelectProps) {\n const { name, label, id = name, error, hint, optional = false, classNames: cx = {}, locale, messages, ...rest } = props\n const m = fieldMessages(locale, messages)\n const hintId = hint ? `${id}-hint` : undefined\n const errorId = `${id}-error`\n const describedBy = [hintId, error ? errorId : undefined].filter(Boolean).join(' ') || undefined\n const common = {\n id,\n name,\n required: !optional,\n 'aria-invalid': error ? true : undefined,\n 'aria-describedby': describedBy,\n className: cx.input,\n 'data-sf-field-control': '',\n } as const\n return (\n <div className={cx.root} data-sf-field data-invalid={error ? '' : undefined}>\n <label htmlFor={id} className={cx.label} data-sf-label={label}>\n {label}\n {optional ? (\n <span className={cx.optional} data-sf-field-optional>\n {' '}\n {m.optional}\n </span>\n ) : null}\n </label>\n {hint ? (\n <p id={hintId} className={cx.hint} data-sf-field-hint>\n {hint}\n </p>\n ) : null}\n {rest.as === 'select' ? (\n (() => {\n const { as: _as, children, ...select } = rest\n return (\n <select {...select} {...common}>\n {children}\n </select>\n )\n })()\n ) : (\n (() => {\n const { as: _as, ...input } = rest as CheckoutFieldProps\n return <input {...input} {...common} />\n })()\n )}\n {/* Reserved only when there is an error: the text sits right under its field. */}\n {error ? (\n <p id={errorId} className={cx.error} data-sf-field-error>\n {error}\n </p>\n ) : null}\n </div>\n )\n}\n","/**\n * The account screen: sign in with password, create an account, verify the emailed code, sign in with a code and\n * recover a forgotten password, in one `<form method=\"post\">` driven by `createAuthAction` (`./server`). What the store\n * offers comes from `loadAuthCapabilities`; the form shows only that. Plain HTML: it works without JavaScript for the\n * password sign-in and the steps the action sends back; the view switches (links) need JavaScript.\n *\n * Styling: `data-sf-account-*` attributes and `classNames` slots, fields reuse `CheckoutField` (and `checkout.css`);\n * `account.css` is an optional neutral sheet. Texts are Spanish by default, English with `locale=\"en\"`, any with `messages`.\n */\nimport { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\nimport type { CustomerCapabilities } from '@asteby/storefront'\nimport { CheckoutField, ErrorSummary, useFieldErrors, type CheckoutFieldClassNames } from '../checkout/fields.js'\nimport type { AuthActionData, AuthErrorCode, AuthStep } from './types.js'\n\nexport type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep\n\nexport type AccountAuthMessages = {\n titles: Record<AccountAuthView, string>\n email: string\n password: string\n newPassword: string\n passwordHint: string\n firstName: string\n lastName: string\n code: string\n codeSentTo: string\n submit: Record<AccountAuthView, string>\n resend: string\n forgotLink: string\n registerLink: string\n loginLink: string\n otpLink: string\n backToLogin: string\n nothingAvailable: string\n errors: Record<AuthErrorCode, string>\n}\n\nconst ES: AccountAuthMessages = {\n titles: {\n login: 'Entrar a tu cuenta',\n register: 'Crear una cuenta',\n verify: 'Confirma tu correo',\n 'otp-email': 'Entrar con un código',\n otp: 'Escribe tu código',\n forgot: 'Recuperar contraseña',\n reset: 'Elige una contraseña nueva',\n },\n email: 'Correo electrónico',\n password: 'Contraseña',\n newPassword: 'Contraseña nueva',\n passwordHint: 'Entre 10 y 128 caracteres.',\n firstName: 'Nombre',\n lastName: 'Apellido',\n code: 'Código',\n codeSentTo: 'Enviamos un código a {email}. Puede tardar un minuto.',\n submit: {\n login: 'Entrar',\n register: 'Crear cuenta',\n verify: 'Confirmar',\n 'otp-email': 'Enviarme el código',\n otp: 'Entrar',\n forgot: 'Enviarme el código',\n reset: 'Guardar y entrar',\n },\n resend: 'Reenviar código',\n forgotLink: '¿Olvidaste tu contraseña?',\n registerLink: 'Crear una cuenta',\n loginLink: 'Ya tengo cuenta',\n otpLink: 'Entrar con un código por correo',\n backToLogin: 'Volver a entrar con contraseña',\n nothingAvailable: 'Esta tienda no admite iniciar sesión por ahora.',\n errors: {\n invalid_credentials: 'El correo o la contraseña no coinciden.',\n invalid_code: 'El código no es válido o ya venció.',\n email_taken: 'Ya existe una cuenta con este correo. Entra o recupera tu contraseña.',\n rate_limited: 'Demasiados intentos. Espera unos minutos e inténtalo de nuevo.',\n validation: 'Revisa los datos e inténtalo de nuevo.',\n unsupported: 'Esta forma de entrar no está disponible en esta tienda.',\n store_misconfigured: 'No pudimos crear tu cuenta por un problema de configuración de la tienda. Puedes comprar como invitado; ya avisamos a la tienda.',\n unavailable: 'No pudimos completar la acción. Inténtalo de nuevo en un momento.',\n },\n}\n\nconst EN: AccountAuthMessages = {\n titles: {\n login: 'Sign in',\n register: 'Create an account',\n verify: 'Confirm your email',\n 'otp-email': 'Sign in with a code',\n otp: 'Enter your code',\n forgot: 'Reset your password',\n reset: 'Choose a new password',\n },\n email: 'Email',\n password: 'Password',\n newPassword: 'New password',\n passwordHint: 'Between 10 and 128 characters.',\n firstName: 'First name',\n lastName: 'Last name',\n code: 'Code',\n codeSentTo: 'We sent a code to {email}. It can take a minute.',\n submit: {\n login: 'Sign in',\n register: 'Create account',\n verify: 'Confirm',\n 'otp-email': 'Email me the code',\n otp: 'Sign in',\n forgot: 'Email me the code',\n reset: 'Save and sign in',\n },\n resend: 'Resend code',\n forgotLink: 'Forgot your password?',\n registerLink: 'Create an account',\n loginLink: 'I already have an account',\n otpLink: 'Sign in with an emailed code',\n backToLogin: 'Back to password sign-in',\n nothingAvailable: 'This store does not support signing in right now.',\n errors: {\n invalid_credentials: 'The email and password do not match.',\n invalid_code: 'The code is not valid or has expired.',\n email_taken: 'An account with this email already exists. Sign in or reset your password.',\n rate_limited: 'Too many attempts. Wait a few minutes and try again.',\n validation: 'Check the details and try again.',\n unsupported: 'This way of signing in is not available in this store.',\n store_misconfigured: 'We could not create your account because of a store configuration problem. You can check out as a guest; we have already told the store.',\n unavailable: 'We could not complete that. Try again in a moment.',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides (nested `titles`/`submit`/`errors` merge). */\nexport function accountAuthMessages(locale?: string | null, overrides?: DeepPartial<AccountAuthMessages> | null): AccountAuthMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n return {\n ...base,\n ...(overrides as Partial<AccountAuthMessages>),\n titles: { ...base.titles, ...overrides.titles },\n submit: { ...base.submit, ...overrides.submit },\n errors: { ...base.errors, ...overrides.errors },\n }\n}\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, string> ? Partial<T[K]> : T[K] }\n\nexport type AccountAuthClassNames = Partial<Record<'root' | 'title' | 'form' | 'notice' | 'error' | 'actions' | 'submit' | 'links' | 'link', string>> & {\n field?: CheckoutFieldClassNames\n}\n\n/** What `<AccountAuth>` passes to its `form` component: the few props a router `Form` and the HTML `<form>` both accept. */\nexport type AccountFormProps = {\n method?: 'post'\n action?: string\n className?: string\n children?: ReactNode\n /** Loose on purpose: a router `Form` types its ref with its own copy of `@types/react`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ref?: any\n 'data-sf-account-form'?: boolean | string\n}\n\nexport type AccountAuthProps = {\n /** From `loadAuthCapabilities` (the loader). */\n capabilities: CustomerCapabilities\n /** What the action returned (`useActionData()`); drives the next screen and the errors. */\n data?: AuthActionData | null\n /** Where to go after signing in (sent as `next`; the server validates it). */\n next?: string | null\n /** A submit is in flight (`navigation.state !== 'idle'`): disables the buttons. */\n pending?: boolean\n /** First screen. Default `login`, or `otp-email` when the store has no password sign-in. */\n initialView?: AccountAuthView\n /** Form component, e.g. React Router's `Form`, to submit without a reload. It must forward `ref` to the `<form>` (React 19: a prop). Default: the HTML `<form>`. */\n form?: 'form' | ComponentType<AccountFormProps>\n /** `action` of the form (default: the current URL). */\n action?: string\n locale?: string\n messages?: DeepPartial<AccountAuthMessages>\n classNames?: AccountAuthClassNames\n /** Shown above the form (a logo, a welcome text). */\n header?: ReactNode\n}\n\nconst initialOf = (caps: CustomerCapabilities, initialView?: AccountAuthView): AccountAuthView =>\n initialView ?? (caps.password ? 'login' : caps.otp_channels.includes('email') ? 'otp-email' : 'login')\n\n/**\n * The whole account screen. Headless enough to restyle, complete enough to drop in:\n * `export default function Account() { return <AccountAuth capabilities={useLoaderData()} data={useActionData()} form={Form} /> }`.\n */\nexport function AccountAuth({ capabilities, data, next, pending = false, initialView, form: FormTag = 'form', action, locale, messages, classNames: cx = {}, header }: AccountAuthProps) {\n const m = accountAuthMessages(locale, messages)\n const passwordOn = capabilities.password\n const otpOn = capabilities.otp_channels.includes('email')\n const [view, setView] = useState<AccountAuthView>(() => data?.step ?? initialOf(capabilities, initialView))\n const [email, setEmail] = useState(data?.email ?? '')\n const ref = useRef<HTMLFormElement>(null)\n const serverFields = data?.error?.field ? [data.error.field] : null\n const errorText = data?.error ? m.errors[data.error.code] : null\n const v = useFieldErrors(ref, { ...(locale ? { locale } : {}), serverFields, serverMessages: data?.error?.field && errorText ? { [data.error.field]: errorText } : null })\n\n // The action decides the next screen; the email it carries survives it.\n useEffect(() => {\n if (data?.step) setView(data.step)\n if (data?.email) setEmail(data.email)\n }, [data])\n\n const go = (to: AccountAuthView) => {\n v.clear()\n setView(to)\n }\n const fieldProps = { classNames: cx.field, ...(locale ? { locale } : {}) }\n const emailField = (\n <CheckoutField {...fieldProps} name=\"email\" type=\"email\" label={m.email} autoComplete=\"email\" inputMode=\"email\" value={email} onChange={(e) => setEmail(e.currentTarget.value)} error={v.errors.email ?? null} />\n )\n const codeField = (\n <CheckoutField {...fieldProps} name=\"code\" label={m.code} autoComplete=\"one-time-code\" inputMode=\"numeric\" pattern=\"[0-9]*\" error={v.errors.code ?? null} />\n )\n const passwordField = (label: string, autoComplete: string, newPassword: boolean) => (\n <CheckoutField\n {...fieldProps}\n name=\"password\"\n type=\"password\"\n label={label}\n autoComplete={autoComplete}\n error={v.errors.password ?? null}\n {...(newPassword ? { minLength: 10, maxLength: 128, hint: m.passwordHint } : {})}\n />\n )\n const link = (to: AccountAuthView, text: string) => (\n <button type=\"button\" className={cx.link} data-sf-account-link={to} onClick={() => go(to)}>\n {text}\n </button>\n )\n\n let body: ReactNode\n let links: ReactNode = null\n switch (view) {\n case 'register':\n body = (\n <>\n <CheckoutField {...fieldProps} name=\"first_name\" label={m.firstName} autoComplete=\"given-name\" optional />\n <CheckoutField {...fieldProps} name=\"last_name\" label={m.lastName} autoComplete=\"family-name\" optional />\n {emailField}\n {passwordField(m.password, 'new-password', true)}\n </>\n )\n links = link('login', m.loginLink)\n break\n case 'verify':\n case 'otp':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n </>\n )\n links = (\n <>\n {view === 'otp' ? (\n <button type=\"submit\" name=\"intent\" value=\"otp-request\" formNoValidate className={cx.link} data-sf-account-link=\"resend\">\n {m.resend}\n </button>\n ) : null}\n {link('login', m.backToLogin)}\n </>\n )\n break\n case 'otp-email':\n case 'forgot':\n body = emailField\n links = link('login', m.backToLogin)\n break\n case 'reset':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n {passwordField(m.newPassword, 'new-password', true)}\n </>\n )\n links = link('login', m.backToLogin)\n break\n default:\n body = (\n <>\n {emailField}\n {passwordField(m.password, 'current-password', false)}\n </>\n )\n links = (\n <>\n {otpOn ? link('forgot', m.forgotLink) : null}\n {link('register', m.registerLink)}\n {otpOn ? link('otp-email', m.otpLink) : null}\n </>\n )\n }\n\n const intent = { login: 'login', register: 'register', verify: 'verify', 'otp-email': 'otp-request', otp: 'otp-login', forgot: 'forgot', reset: 'reset' }[view]\n // Without password accounts the password views do not exist; only the code sign-in does.\n const available = view === 'login' || view === 'register' || view === 'forgot' || view === 'reset' || view === 'verify' ? passwordOn : otpOn\n const showSummary = !data?.error?.field\n const title = m.titles[view]\n if (!available && !passwordOn && !otpOn) {\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view=\"unavailable\">\n <p className={cx.notice} role=\"status\">\n {capabilities.unavailable_reason === 'missing_scope' ? m.errors.store_misconfigured : m.nothingAvailable}\n </p>\n </section>\n )\n }\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view={view} aria-labelledby=\"sf-account-title\">\n {header}\n <h1 id=\"sf-account-title\" className={cx.title}>\n {title}\n </h1>\n <FormTag ref={ref as never} method=\"post\" {...(action ? { action } : {})} className={cx.form} data-sf-account-form>\n <ErrorSummary items={v.summary} focusKey={v.summaryKey} {...(locale ? { locale } : {})} />\n {errorText && showSummary ? (\n <p role=\"alert\" className={cx.error} data-sf-account-error={data!.error!.code}>\n {errorText}\n </p>\n ) : null}\n {next ? <input type=\"hidden\" name=\"next\" value={next} /> : null}\n {body}\n <div className={cx.actions}>\n <button type=\"submit\" name=\"intent\" value={intent} disabled={pending} className={cx.submit} data-sf-account-submit>\n {m.submit[view]}\n </button>\n </div>\n <div className={cx.links} data-sf-account-links>\n {links}\n </div>\n </FormTag>\n </section>\n )\n}\n"]}
@@ -2,8 +2,8 @@ import * as react from 'react';
2
2
  import { ComponentType, ReactNode } from 'react';
3
3
  import { CustomerCapabilities } from '@asteby/storefront';
4
4
  import { a as CheckoutFieldClassNames } from './fields-vnMUi2HB.cjs';
5
- import { A as AuthActionData, c as AuthStep, a as AuthErrorCode } from './types-HcEUd9hW.cjs';
6
- export { b as AuthIntent } from './types-HcEUd9hW.cjs';
5
+ import { A as AuthActionData, c as AuthStep, a as AuthErrorCode } from './types-D7pVK0GK.cjs';
6
+ export { b as AuthIntent } from './types-D7pVK0GK.cjs';
7
7
 
8
8
  type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep;
9
9
  type AccountAuthMessages = {
package/dist/account.d.ts CHANGED
@@ -2,8 +2,8 @@ import * as react from 'react';
2
2
  import { ComponentType, ReactNode } from 'react';
3
3
  import { CustomerCapabilities } from '@asteby/storefront';
4
4
  import { a as CheckoutFieldClassNames } from './fields-vnMUi2HB.js';
5
- import { A as AuthActionData, c as AuthStep, a as AuthErrorCode } from './types-HcEUd9hW.js';
6
- export { b as AuthIntent } from './types-HcEUd9hW.js';
5
+ import { A as AuthActionData, c as AuthStep, a as AuthErrorCode } from './types-D7pVK0GK.js';
6
+ export { b as AuthIntent } from './types-D7pVK0GK.js';
7
7
 
8
8
  type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep;
9
9
  type AccountAuthMessages = {
package/dist/account.js CHANGED
@@ -43,6 +43,7 @@ var ES = {
43
43
  rate_limited: "Demasiados intentos. Espera unos minutos e int\xE9ntalo de nuevo.",
44
44
  validation: "Revisa los datos e int\xE9ntalo de nuevo.",
45
45
  unsupported: "Esta forma de entrar no est\xE1 disponible en esta tienda.",
46
+ store_misconfigured: "No pudimos crear tu cuenta por un problema de configuraci\xF3n de la tienda. Puedes comprar como invitado; ya avisamos a la tienda.",
46
47
  unavailable: "No pudimos completar la acci\xF3n. Int\xE9ntalo de nuevo en un momento."
47
48
  }
48
49
  };
@@ -87,6 +88,7 @@ var EN = {
87
88
  rate_limited: "Too many attempts. Wait a few minutes and try again.",
88
89
  validation: "Check the details and try again.",
89
90
  unsupported: "This way of signing in is not available in this store.",
91
+ store_misconfigured: "We could not create your account because of a store configuration problem. You can check out as a guest; we have already told the store.",
90
92
  unavailable: "We could not complete that. Try again in a moment."
91
93
  }
92
94
  };
@@ -190,7 +192,7 @@ function AccountAuth({ capabilities, data, next, pending = false, initialView, f
190
192
  const showSummary = !data?.error?.field;
191
193
  const title = m.titles[view];
192
194
  if (!available && !passwordOn && !otpOn) {
193
- return /* @__PURE__ */ jsx("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": "unavailable", children: /* @__PURE__ */ jsx("p", { className: cx.notice, role: "status", children: m.nothingAvailable }) });
195
+ return /* @__PURE__ */ jsx("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": "unavailable", children: /* @__PURE__ */ jsx("p", { className: cx.notice, role: "status", children: capabilities.unavailable_reason === "missing_scope" ? m.errors.store_misconfigured : m.nothingAvailable }) });
194
196
  }
195
197
  return /* @__PURE__ */ jsxs("section", { className: cx.root, "data-sf-account-auth": true, "data-sf-account-view": view, "aria-labelledby": "sf-account-title", children: [
196
198
  header,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/account/account-auth.tsx"],"names":[],"mappings":";;;;AAqCA,IAAM,EAAA,GAA0B;AAAA,EAC9B,MAAA,EAAQ;AAAA,IACN,KAAA,EAAO,oBAAA;AAAA,IACP,QAAA,EAAU,kBAAA;AAAA,IACV,MAAA,EAAQ,oBAAA;AAAA,IACR,WAAA,EAAa,yBAAA;AAAA,IACb,GAAA,EAAK,sBAAA;AAAA,IACL,MAAA,EAAQ,yBAAA;AAAA,IACR,KAAA,EAAO;AAAA,GACT;AAAA,EACA,KAAA,EAAO,uBAAA;AAAA,EACP,QAAA,EAAU,eAAA;AAAA,EACV,WAAA,EAAa,qBAAA;AAAA,EACb,YAAA,EAAc,4BAAA;AAAA,EACd,SAAA,EAAW,QAAA;AAAA,EACX,QAAA,EAAU,UAAA;AAAA,EACV,IAAA,EAAM,WAAA;AAAA,EACN,UAAA,EAAY,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SAAA,IAAa,WAAA,mBACZ,GAAA,CAAC,GAAA,EAAA,EAAE,MAAK,OAAA,EAAQ,SAAA,EAAW,EAAA,CAAG,KAAA,EAAO,uBAAA,EAAuB,IAAA,CAAM,KAAA,CAAO,IAAA,EACtE,qBACH,CAAA,GACE,IAAA;AAAA,MACH,IAAA,uBAAQ,OAAA,EAAA,EAAM,IAAA,EAAK,UAAS,IAAA,EAAK,MAAA,EAAO,KAAA,EAAO,IAAA,EAAM,CAAA,GAAK,IAAA;AAAA,MAC1D,IAAA;AAAA,sBACD,GAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAW,EAAA,CAAG,OAAA,EACjB,8BAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,IAAA,EAAK,QAAA,EAAS,KAAA,EAAO,QAAQ,QAAA,EAAU,OAAA,EAAS,SAAA,EAAW,EAAA,CAAG,MAAA,EAAQ,wBAAA,EAAsB,MAC/G,QAAA,EAAA,CAAA,CAAE,MAAA,CAAO,IAAI,CAAA,EAChB,CAAA,EACF,CAAA;AAAA,0BACC,KAAA,EAAA,EAAI,SAAA,EAAW,GAAG,KAAA,EAAO,uBAAA,EAAqB,MAC5C,QAAA,EAAA,KAAA,EACH;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"account.js","sourcesContent":["/**\n * The account screen: sign in with password, create an account, verify the emailed code, sign in with a code and\n * recover a forgotten password, in one `<form method=\"post\">` driven by `createAuthAction` (`./server`). What the store\n * offers comes from `loadAuthCapabilities`; the form shows only that. Plain HTML: it works without JavaScript for the\n * password sign-in and the steps the action sends back; the view switches (links) need JavaScript.\n *\n * Styling: `data-sf-account-*` attributes and `classNames` slots, fields reuse `CheckoutField` (and `checkout.css`);\n * `account.css` is an optional neutral sheet. Texts are Spanish by default, English with `locale=\"en\"`, any with `messages`.\n */\nimport { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\nimport type { CustomerCapabilities } from '@asteby/storefront'\nimport { CheckoutField, ErrorSummary, useFieldErrors, type CheckoutFieldClassNames } from '../checkout/fields.js'\nimport type { AuthActionData, AuthErrorCode, AuthStep } from './types.js'\n\nexport type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep\n\nexport type AccountAuthMessages = {\n titles: Record<AccountAuthView, string>\n email: string\n password: string\n newPassword: string\n passwordHint: string\n firstName: string\n lastName: string\n code: string\n codeSentTo: string\n submit: Record<AccountAuthView, string>\n resend: string\n forgotLink: string\n registerLink: string\n loginLink: string\n otpLink: string\n backToLogin: string\n nothingAvailable: string\n errors: Record<AuthErrorCode, string>\n}\n\nconst ES: AccountAuthMessages = {\n titles: {\n login: 'Entrar a tu cuenta',\n register: 'Crear una cuenta',\n verify: 'Confirma tu correo',\n 'otp-email': 'Entrar con un código',\n otp: 'Escribe tu código',\n forgot: 'Recuperar contraseña',\n reset: 'Elige una contraseña nueva',\n },\n email: 'Correo electrónico',\n password: 'Contraseña',\n newPassword: 'Contraseña nueva',\n passwordHint: 'Entre 10 y 128 caracteres.',\n firstName: 'Nombre',\n lastName: 'Apellido',\n code: 'Código',\n codeSentTo: 'Enviamos un código a {email}. Puede tardar un minuto.',\n submit: {\n login: 'Entrar',\n register: 'Crear cuenta',\n verify: 'Confirmar',\n 'otp-email': 'Enviarme el código',\n otp: 'Entrar',\n forgot: 'Enviarme el código',\n reset: 'Guardar y entrar',\n },\n resend: 'Reenviar código',\n forgotLink: '¿Olvidaste tu contraseña?',\n registerLink: 'Crear una cuenta',\n loginLink: 'Ya tengo cuenta',\n otpLink: 'Entrar con un código por correo',\n backToLogin: 'Volver a entrar con contraseña',\n nothingAvailable: 'Esta tienda no admite iniciar sesión por ahora.',\n errors: {\n invalid_credentials: 'El correo o la contraseña no coinciden.',\n invalid_code: 'El código no es válido o ya venció.',\n email_taken: 'Ya existe una cuenta con este correo. Entra o recupera tu contraseña.',\n rate_limited: 'Demasiados intentos. Espera unos minutos e inténtalo de nuevo.',\n validation: 'Revisa los datos e inténtalo de nuevo.',\n unsupported: 'Esta forma de entrar no está disponible en esta tienda.',\n unavailable: 'No pudimos completar la acción. Inténtalo de nuevo en un momento.',\n },\n}\n\nconst EN: AccountAuthMessages = {\n titles: {\n login: 'Sign in',\n register: 'Create an account',\n verify: 'Confirm your email',\n 'otp-email': 'Sign in with a code',\n otp: 'Enter your code',\n forgot: 'Reset your password',\n reset: 'Choose a new password',\n },\n email: 'Email',\n password: 'Password',\n newPassword: 'New password',\n passwordHint: 'Between 10 and 128 characters.',\n firstName: 'First name',\n lastName: 'Last name',\n code: 'Code',\n codeSentTo: 'We sent a code to {email}. It can take a minute.',\n submit: {\n login: 'Sign in',\n register: 'Create account',\n verify: 'Confirm',\n 'otp-email': 'Email me the code',\n otp: 'Sign in',\n forgot: 'Email me the code',\n reset: 'Save and sign in',\n },\n resend: 'Resend code',\n forgotLink: 'Forgot your password?',\n registerLink: 'Create an account',\n loginLink: 'I already have an account',\n otpLink: 'Sign in with an emailed code',\n backToLogin: 'Back to password sign-in',\n nothingAvailable: 'This store does not support signing in right now.',\n errors: {\n invalid_credentials: 'The email and password do not match.',\n invalid_code: 'The code is not valid or has expired.',\n email_taken: 'An account with this email already exists. Sign in or reset your password.',\n rate_limited: 'Too many attempts. Wait a few minutes and try again.',\n validation: 'Check the details and try again.',\n unsupported: 'This way of signing in is not available in this store.',\n unavailable: 'We could not complete that. Try again in a moment.',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides (nested `titles`/`submit`/`errors` merge). */\nexport function accountAuthMessages(locale?: string | null, overrides?: DeepPartial<AccountAuthMessages> | null): AccountAuthMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n return {\n ...base,\n ...(overrides as Partial<AccountAuthMessages>),\n titles: { ...base.titles, ...overrides.titles },\n submit: { ...base.submit, ...overrides.submit },\n errors: { ...base.errors, ...overrides.errors },\n }\n}\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, string> ? Partial<T[K]> : T[K] }\n\nexport type AccountAuthClassNames = Partial<Record<'root' | 'title' | 'form' | 'notice' | 'error' | 'actions' | 'submit' | 'links' | 'link', string>> & {\n field?: CheckoutFieldClassNames\n}\n\n/** What `<AccountAuth>` passes to its `form` component: the few props a router `Form` and the HTML `<form>` both accept. */\nexport type AccountFormProps = {\n method?: 'post'\n action?: string\n className?: string\n children?: ReactNode\n /** Loose on purpose: a router `Form` types its ref with its own copy of `@types/react`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ref?: any\n 'data-sf-account-form'?: boolean | string\n}\n\nexport type AccountAuthProps = {\n /** From `loadAuthCapabilities` (the loader). */\n capabilities: CustomerCapabilities\n /** What the action returned (`useActionData()`); drives the next screen and the errors. */\n data?: AuthActionData | null\n /** Where to go after signing in (sent as `next`; the server validates it). */\n next?: string | null\n /** A submit is in flight (`navigation.state !== 'idle'`): disables the buttons. */\n pending?: boolean\n /** First screen. Default `login`, or `otp-email` when the store has no password sign-in. */\n initialView?: AccountAuthView\n /** Form component, e.g. React Router's `Form`, to submit without a reload. It must forward `ref` to the `<form>` (React 19: a prop). Default: the HTML `<form>`. */\n form?: 'form' | ComponentType<AccountFormProps>\n /** `action` of the form (default: the current URL). */\n action?: string\n locale?: string\n messages?: DeepPartial<AccountAuthMessages>\n classNames?: AccountAuthClassNames\n /** Shown above the form (a logo, a welcome text). */\n header?: ReactNode\n}\n\nconst initialOf = (caps: CustomerCapabilities, initialView?: AccountAuthView): AccountAuthView =>\n initialView ?? (caps.password ? 'login' : caps.otp_channels.includes('email') ? 'otp-email' : 'login')\n\n/**\n * The whole account screen. Headless enough to restyle, complete enough to drop in:\n * `export default function Account() { return <AccountAuth capabilities={useLoaderData()} data={useActionData()} form={Form} /> }`.\n */\nexport function AccountAuth({ capabilities, data, next, pending = false, initialView, form: FormTag = 'form', action, locale, messages, classNames: cx = {}, header }: AccountAuthProps) {\n const m = accountAuthMessages(locale, messages)\n const passwordOn = capabilities.password\n const otpOn = capabilities.otp_channels.includes('email')\n const [view, setView] = useState<AccountAuthView>(() => data?.step ?? initialOf(capabilities, initialView))\n const [email, setEmail] = useState(data?.email ?? '')\n const ref = useRef<HTMLFormElement>(null)\n const serverFields = data?.error?.field ? [data.error.field] : null\n const errorText = data?.error ? m.errors[data.error.code] : null\n const v = useFieldErrors(ref, { ...(locale ? { locale } : {}), serverFields, serverMessages: data?.error?.field && errorText ? { [data.error.field]: errorText } : null })\n\n // The action decides the next screen; the email it carries survives it.\n useEffect(() => {\n if (data?.step) setView(data.step)\n if (data?.email) setEmail(data.email)\n }, [data])\n\n const go = (to: AccountAuthView) => {\n v.clear()\n setView(to)\n }\n const fieldProps = { classNames: cx.field, ...(locale ? { locale } : {}) }\n const emailField = (\n <CheckoutField {...fieldProps} name=\"email\" type=\"email\" label={m.email} autoComplete=\"email\" inputMode=\"email\" value={email} onChange={(e) => setEmail(e.currentTarget.value)} error={v.errors.email ?? null} />\n )\n const codeField = (\n <CheckoutField {...fieldProps} name=\"code\" label={m.code} autoComplete=\"one-time-code\" inputMode=\"numeric\" pattern=\"[0-9]*\" error={v.errors.code ?? null} />\n )\n const passwordField = (label: string, autoComplete: string, newPassword: boolean) => (\n <CheckoutField\n {...fieldProps}\n name=\"password\"\n type=\"password\"\n label={label}\n autoComplete={autoComplete}\n error={v.errors.password ?? null}\n {...(newPassword ? { minLength: 10, maxLength: 128, hint: m.passwordHint } : {})}\n />\n )\n const link = (to: AccountAuthView, text: string) => (\n <button type=\"button\" className={cx.link} data-sf-account-link={to} onClick={() => go(to)}>\n {text}\n </button>\n )\n\n let body: ReactNode\n let links: ReactNode = null\n switch (view) {\n case 'register':\n body = (\n <>\n <CheckoutField {...fieldProps} name=\"first_name\" label={m.firstName} autoComplete=\"given-name\" optional />\n <CheckoutField {...fieldProps} name=\"last_name\" label={m.lastName} autoComplete=\"family-name\" optional />\n {emailField}\n {passwordField(m.password, 'new-password', true)}\n </>\n )\n links = link('login', m.loginLink)\n break\n case 'verify':\n case 'otp':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n </>\n )\n links = (\n <>\n {view === 'otp' ? (\n <button type=\"submit\" name=\"intent\" value=\"otp-request\" formNoValidate className={cx.link} data-sf-account-link=\"resend\">\n {m.resend}\n </button>\n ) : null}\n {link('login', m.backToLogin)}\n </>\n )\n break\n case 'otp-email':\n case 'forgot':\n body = emailField\n links = link('login', m.backToLogin)\n break\n case 'reset':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n {passwordField(m.newPassword, 'new-password', true)}\n </>\n )\n links = link('login', m.backToLogin)\n break\n default:\n body = (\n <>\n {emailField}\n {passwordField(m.password, 'current-password', false)}\n </>\n )\n links = (\n <>\n {otpOn ? link('forgot', m.forgotLink) : null}\n {link('register', m.registerLink)}\n {otpOn ? link('otp-email', m.otpLink) : null}\n </>\n )\n }\n\n const intent = { login: 'login', register: 'register', verify: 'verify', 'otp-email': 'otp-request', otp: 'otp-login', forgot: 'forgot', reset: 'reset' }[view]\n // Without password accounts the password views do not exist; only the code sign-in does.\n const available = view === 'login' || view === 'register' || view === 'forgot' || view === 'reset' || view === 'verify' ? passwordOn : otpOn\n const showSummary = !data?.error?.field\n const title = m.titles[view]\n if (!available && !passwordOn && !otpOn) {\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view=\"unavailable\">\n <p className={cx.notice} role=\"status\">\n {m.nothingAvailable}\n </p>\n </section>\n )\n }\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view={view} aria-labelledby=\"sf-account-title\">\n {header}\n <h1 id=\"sf-account-title\" className={cx.title}>\n {title}\n </h1>\n <FormTag ref={ref as never} method=\"post\" {...(action ? { action } : {})} className={cx.form} data-sf-account-form>\n <ErrorSummary items={v.summary} focusKey={v.summaryKey} {...(locale ? { locale } : {})} />\n {errorText && showSummary ? (\n <p role=\"alert\" className={cx.error} data-sf-account-error={data!.error!.code}>\n {errorText}\n </p>\n ) : null}\n {next ? <input type=\"hidden\" name=\"next\" value={next} /> : null}\n {body}\n <div className={cx.actions}>\n <button type=\"submit\" name=\"intent\" value={intent} disabled={pending} className={cx.submit} data-sf-account-submit>\n {m.submit[view]}\n </button>\n </div>\n <div className={cx.links} data-sf-account-links>\n {links}\n </div>\n </FormTag>\n </section>\n )\n}\n"]}
1
+ {"version":3,"sources":["../src/account/account-auth.tsx"],"names":[],"mappings":";;;;AAqCA,IAAM,EAAA,GAA0B;AAAA,EAC9B,MAAA,EAAQ;AAAA,IACN,KAAA,EAAO,oBAAA;AAAA,IACP,QAAA,EAAU,kBAAA;AAAA,IACV,MAAA,EAAQ,oBAAA;AAAA,IACR,WAAA,EAAa,yBAAA;AAAA,IACb,GAAA,EAAK,sBAAA;AAAA,IACL,MAAA,EAAQ,yBAAA;AAAA,IACR,KAAA,EAAO;AAAA,GACT;AAAA,EACA,KAAA,EAAO,uBAAA;AAAA,EACP,QAAA,EAAU,eAAA;AAAA,EACV,WAAA,EAAa,qBAAA;AAAA,EACb,YAAA,EAAc,4BAAA;AAAA,EACd,SAAA,EAAW,QAAA;AAAA,EACX,QAAA,EAAU,UAAA;AAAA,EACV,IAAA,EAAM,WAAA;AAAA,EACN,UAAA,EAAY,0DAAA;AAAA,EACZ,MAAA,EAAQ;AAAA,IACN,KAAA,EAAO,QAAA;AAAA,IACP,QAAA,EAAU,cAAA;AAAA,IACV,MAAA,EAAQ,WAAA;AAAA,IACR,WAAA,EAAa,uBAAA;AAAA,IACb,GAAA,EAAK,QAAA;AAAA,IACL,MAAA,EAAQ,uBAAA;AAAA,IACR,KAAA,EAAO;AAAA,GACT;AAAA,EACA,MAAA,EAAQ,oBAAA;AAAA,EACR,UAAA,EAAY,iCAAA;AAAA,EACZ,YAAA,EAAc,kBAAA;AAAA,EACd,SAAA,EAAW,iBA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ACH,IAAA,uBAAQ,OAAA,EAAA,EAAM,IAAA,EAAK,UAAS,IAAA,EAAK,MAAA,EAAO,KAAA,EAAO,IAAA,EAAM,CAAA,GAAK,IAAA;AAAA,MAC1D,IAAA;AAAA,sBACD,GAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAW,EAAA,CAAG,OAAA,EACjB,8BAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,IAAA,EAAK,QAAA,EAAS,KAAA,EAAO,QAAQ,QAAA,EAAU,OAAA,EAAS,SAAA,EAAW,EAAA,CAAG,MAAA,EAAQ,wBAAA,EAAsB,MAC/G,QAAA,EAAA,CAAA,CAAE,MAAA,CAAO,IAAI,CAAA,EAChB,CAAA,EACF,CAAA;AAAA,0BACC,KAAA,EAAA,EAAI,SAAA,EAAW,GAAG,KAAA,EAAO,uBAAA,EAAqB,MAC5C,QAAA,EAAA,KAAA,EACH;AAAA,KAAA,EACF;AAAA,GAAA,EACF,CAAA;AAEJ","file":"account.js","sourcesContent":["/**\n * The account screen: sign in with password, create an account, verify the emailed code, sign in with a code and\n * recover a forgotten password, in one `<form method=\"post\">` driven by `createAuthAction` (`./server`). What the store\n * offers comes from `loadAuthCapabilities`; the form shows only that. Plain HTML: it works without JavaScript for the\n * password sign-in and the steps the action sends back; the view switches (links) need JavaScript.\n *\n * Styling: `data-sf-account-*` attributes and `classNames` slots, fields reuse `CheckoutField` (and `checkout.css`);\n * `account.css` is an optional neutral sheet. Texts are Spanish by default, English with `locale=\"en\"`, any with `messages`.\n */\nimport { useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\nimport type { CustomerCapabilities } from '@asteby/storefront'\nimport { CheckoutField, ErrorSummary, useFieldErrors, type CheckoutFieldClassNames } from '../checkout/fields.js'\nimport type { AuthActionData, AuthErrorCode, AuthStep } from './types.js'\n\nexport type AccountAuthView = 'login' | 'register' | 'otp-email' | 'forgot' | AuthStep\n\nexport type AccountAuthMessages = {\n titles: Record<AccountAuthView, string>\n email: string\n password: string\n newPassword: string\n passwordHint: string\n firstName: string\n lastName: string\n code: string\n codeSentTo: string\n submit: Record<AccountAuthView, string>\n resend: string\n forgotLink: string\n registerLink: string\n loginLink: string\n otpLink: string\n backToLogin: string\n nothingAvailable: string\n errors: Record<AuthErrorCode, string>\n}\n\nconst ES: AccountAuthMessages = {\n titles: {\n login: 'Entrar a tu cuenta',\n register: 'Crear una cuenta',\n verify: 'Confirma tu correo',\n 'otp-email': 'Entrar con un código',\n otp: 'Escribe tu código',\n forgot: 'Recuperar contraseña',\n reset: 'Elige una contraseña nueva',\n },\n email: 'Correo electrónico',\n password: 'Contraseña',\n newPassword: 'Contraseña nueva',\n passwordHint: 'Entre 10 y 128 caracteres.',\n firstName: 'Nombre',\n lastName: 'Apellido',\n code: 'Código',\n codeSentTo: 'Enviamos un código a {email}. Puede tardar un minuto.',\n submit: {\n login: 'Entrar',\n register: 'Crear cuenta',\n verify: 'Confirmar',\n 'otp-email': 'Enviarme el código',\n otp: 'Entrar',\n forgot: 'Enviarme el código',\n reset: 'Guardar y entrar',\n },\n resend: 'Reenviar código',\n forgotLink: '¿Olvidaste tu contraseña?',\n registerLink: 'Crear una cuenta',\n loginLink: 'Ya tengo cuenta',\n otpLink: 'Entrar con un código por correo',\n backToLogin: 'Volver a entrar con contraseña',\n nothingAvailable: 'Esta tienda no admite iniciar sesión por ahora.',\n errors: {\n invalid_credentials: 'El correo o la contraseña no coinciden.',\n invalid_code: 'El código no es válido o ya venció.',\n email_taken: 'Ya existe una cuenta con este correo. Entra o recupera tu contraseña.',\n rate_limited: 'Demasiados intentos. Espera unos minutos e inténtalo de nuevo.',\n validation: 'Revisa los datos e inténtalo de nuevo.',\n unsupported: 'Esta forma de entrar no está disponible en esta tienda.',\n store_misconfigured: 'No pudimos crear tu cuenta por un problema de configuración de la tienda. Puedes comprar como invitado; ya avisamos a la tienda.',\n unavailable: 'No pudimos completar la acción. Inténtalo de nuevo en un momento.',\n },\n}\n\nconst EN: AccountAuthMessages = {\n titles: {\n login: 'Sign in',\n register: 'Create an account',\n verify: 'Confirm your email',\n 'otp-email': 'Sign in with a code',\n otp: 'Enter your code',\n forgot: 'Reset your password',\n reset: 'Choose a new password',\n },\n email: 'Email',\n password: 'Password',\n newPassword: 'New password',\n passwordHint: 'Between 10 and 128 characters.',\n firstName: 'First name',\n lastName: 'Last name',\n code: 'Code',\n codeSentTo: 'We sent a code to {email}. It can take a minute.',\n submit: {\n login: 'Sign in',\n register: 'Create account',\n verify: 'Confirm',\n 'otp-email': 'Email me the code',\n otp: 'Sign in',\n forgot: 'Email me the code',\n reset: 'Save and sign in',\n },\n resend: 'Resend code',\n forgotLink: 'Forgot your password?',\n registerLink: 'Create an account',\n loginLink: 'I already have an account',\n otpLink: 'Sign in with an emailed code',\n backToLogin: 'Back to password sign-in',\n nothingAvailable: 'This store does not support signing in right now.',\n errors: {\n invalid_credentials: 'The email and password do not match.',\n invalid_code: 'The code is not valid or has expired.',\n email_taken: 'An account with this email already exists. Sign in or reset your password.',\n rate_limited: 'Too many attempts. Wait a few minutes and try again.',\n validation: 'Check the details and try again.',\n unsupported: 'This way of signing in is not available in this store.',\n store_misconfigured: 'We could not create your account because of a store configuration problem. You can check out as a guest; we have already told the store.',\n unavailable: 'We could not complete that. Try again in a moment.',\n },\n}\n\n/** Messages for a locale (`es*` default, `en*`), with optional overrides (nested `titles`/`submit`/`errors` merge). */\nexport function accountAuthMessages(locale?: string | null, overrides?: DeepPartial<AccountAuthMessages> | null): AccountAuthMessages {\n const base = (locale ?? 'es-MX').toLowerCase().startsWith('en') ? EN : ES\n if (!overrides) return base\n return {\n ...base,\n ...(overrides as Partial<AccountAuthMessages>),\n titles: { ...base.titles, ...overrides.titles },\n submit: { ...base.submit, ...overrides.submit },\n errors: { ...base.errors, ...overrides.errors },\n }\n}\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends Record<string, string> ? Partial<T[K]> : T[K] }\n\nexport type AccountAuthClassNames = Partial<Record<'root' | 'title' | 'form' | 'notice' | 'error' | 'actions' | 'submit' | 'links' | 'link', string>> & {\n field?: CheckoutFieldClassNames\n}\n\n/** What `<AccountAuth>` passes to its `form` component: the few props a router `Form` and the HTML `<form>` both accept. */\nexport type AccountFormProps = {\n method?: 'post'\n action?: string\n className?: string\n children?: ReactNode\n /** Loose on purpose: a router `Form` types its ref with its own copy of `@types/react`. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ref?: any\n 'data-sf-account-form'?: boolean | string\n}\n\nexport type AccountAuthProps = {\n /** From `loadAuthCapabilities` (the loader). */\n capabilities: CustomerCapabilities\n /** What the action returned (`useActionData()`); drives the next screen and the errors. */\n data?: AuthActionData | null\n /** Where to go after signing in (sent as `next`; the server validates it). */\n next?: string | null\n /** A submit is in flight (`navigation.state !== 'idle'`): disables the buttons. */\n pending?: boolean\n /** First screen. Default `login`, or `otp-email` when the store has no password sign-in. */\n initialView?: AccountAuthView\n /** Form component, e.g. React Router's `Form`, to submit without a reload. It must forward `ref` to the `<form>` (React 19: a prop). Default: the HTML `<form>`. */\n form?: 'form' | ComponentType<AccountFormProps>\n /** `action` of the form (default: the current URL). */\n action?: string\n locale?: string\n messages?: DeepPartial<AccountAuthMessages>\n classNames?: AccountAuthClassNames\n /** Shown above the form (a logo, a welcome text). */\n header?: ReactNode\n}\n\nconst initialOf = (caps: CustomerCapabilities, initialView?: AccountAuthView): AccountAuthView =>\n initialView ?? (caps.password ? 'login' : caps.otp_channels.includes('email') ? 'otp-email' : 'login')\n\n/**\n * The whole account screen. Headless enough to restyle, complete enough to drop in:\n * `export default function Account() { return <AccountAuth capabilities={useLoaderData()} data={useActionData()} form={Form} /> }`.\n */\nexport function AccountAuth({ capabilities, data, next, pending = false, initialView, form: FormTag = 'form', action, locale, messages, classNames: cx = {}, header }: AccountAuthProps) {\n const m = accountAuthMessages(locale, messages)\n const passwordOn = capabilities.password\n const otpOn = capabilities.otp_channels.includes('email')\n const [view, setView] = useState<AccountAuthView>(() => data?.step ?? initialOf(capabilities, initialView))\n const [email, setEmail] = useState(data?.email ?? '')\n const ref = useRef<HTMLFormElement>(null)\n const serverFields = data?.error?.field ? [data.error.field] : null\n const errorText = data?.error ? m.errors[data.error.code] : null\n const v = useFieldErrors(ref, { ...(locale ? { locale } : {}), serverFields, serverMessages: data?.error?.field && errorText ? { [data.error.field]: errorText } : null })\n\n // The action decides the next screen; the email it carries survives it.\n useEffect(() => {\n if (data?.step) setView(data.step)\n if (data?.email) setEmail(data.email)\n }, [data])\n\n const go = (to: AccountAuthView) => {\n v.clear()\n setView(to)\n }\n const fieldProps = { classNames: cx.field, ...(locale ? { locale } : {}) }\n const emailField = (\n <CheckoutField {...fieldProps} name=\"email\" type=\"email\" label={m.email} autoComplete=\"email\" inputMode=\"email\" value={email} onChange={(e) => setEmail(e.currentTarget.value)} error={v.errors.email ?? null} />\n )\n const codeField = (\n <CheckoutField {...fieldProps} name=\"code\" label={m.code} autoComplete=\"one-time-code\" inputMode=\"numeric\" pattern=\"[0-9]*\" error={v.errors.code ?? null} />\n )\n const passwordField = (label: string, autoComplete: string, newPassword: boolean) => (\n <CheckoutField\n {...fieldProps}\n name=\"password\"\n type=\"password\"\n label={label}\n autoComplete={autoComplete}\n error={v.errors.password ?? null}\n {...(newPassword ? { minLength: 10, maxLength: 128, hint: m.passwordHint } : {})}\n />\n )\n const link = (to: AccountAuthView, text: string) => (\n <button type=\"button\" className={cx.link} data-sf-account-link={to} onClick={() => go(to)}>\n {text}\n </button>\n )\n\n let body: ReactNode\n let links: ReactNode = null\n switch (view) {\n case 'register':\n body = (\n <>\n <CheckoutField {...fieldProps} name=\"first_name\" label={m.firstName} autoComplete=\"given-name\" optional />\n <CheckoutField {...fieldProps} name=\"last_name\" label={m.lastName} autoComplete=\"family-name\" optional />\n {emailField}\n {passwordField(m.password, 'new-password', true)}\n </>\n )\n links = link('login', m.loginLink)\n break\n case 'verify':\n case 'otp':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n </>\n )\n links = (\n <>\n {view === 'otp' ? (\n <button type=\"submit\" name=\"intent\" value=\"otp-request\" formNoValidate className={cx.link} data-sf-account-link=\"resend\">\n {m.resend}\n </button>\n ) : null}\n {link('login', m.backToLogin)}\n </>\n )\n break\n case 'otp-email':\n case 'forgot':\n body = emailField\n links = link('login', m.backToLogin)\n break\n case 'reset':\n body = (\n <>\n <p className={cx.notice} data-sf-account-notice>\n {m.codeSentTo.replace('{email}', email)}\n </p>\n <input type=\"hidden\" name=\"email\" value={email} />\n {codeField}\n {passwordField(m.newPassword, 'new-password', true)}\n </>\n )\n links = link('login', m.backToLogin)\n break\n default:\n body = (\n <>\n {emailField}\n {passwordField(m.password, 'current-password', false)}\n </>\n )\n links = (\n <>\n {otpOn ? link('forgot', m.forgotLink) : null}\n {link('register', m.registerLink)}\n {otpOn ? link('otp-email', m.otpLink) : null}\n </>\n )\n }\n\n const intent = { login: 'login', register: 'register', verify: 'verify', 'otp-email': 'otp-request', otp: 'otp-login', forgot: 'forgot', reset: 'reset' }[view]\n // Without password accounts the password views do not exist; only the code sign-in does.\n const available = view === 'login' || view === 'register' || view === 'forgot' || view === 'reset' || view === 'verify' ? passwordOn : otpOn\n const showSummary = !data?.error?.field\n const title = m.titles[view]\n if (!available && !passwordOn && !otpOn) {\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view=\"unavailable\">\n <p className={cx.notice} role=\"status\">\n {capabilities.unavailable_reason === 'missing_scope' ? m.errors.store_misconfigured : m.nothingAvailable}\n </p>\n </section>\n )\n }\n return (\n <section className={cx.root} data-sf-account-auth data-sf-account-view={view} aria-labelledby=\"sf-account-title\">\n {header}\n <h1 id=\"sf-account-title\" className={cx.title}>\n {title}\n </h1>\n <FormTag ref={ref as never} method=\"post\" {...(action ? { action } : {})} className={cx.form} data-sf-account-form>\n <ErrorSummary items={v.summary} focusKey={v.summaryKey} {...(locale ? { locale } : {})} />\n {errorText && showSummary ? (\n <p role=\"alert\" className={cx.error} data-sf-account-error={data!.error!.code}>\n {errorText}\n </p>\n ) : null}\n {next ? <input type=\"hidden\" name=\"next\" value={next} /> : null}\n {body}\n <div className={cx.actions}>\n <button type=\"submit\" name=\"intent\" value={intent} disabled={pending} className={cx.submit} data-sf-account-submit>\n {m.submit[view]}\n </button>\n </div>\n <div className={cx.links} data-sf-account-links>\n {links}\n </div>\n </FormTag>\n </section>\n )\n}\n"]}
@@ -16,6 +16,11 @@ type AuthErrorCode =
16
16
  | 'validation'
17
17
  /** The store does not offer this way of signing in. */
18
18
  | 'unsupported'
19
+ /**
20
+ * The store's own credential lacks a permission (`403 insufficient_scope`): the shop is misconfigured, not the
21
+ * buyer's data. The buyer can still check out as a guest; the server already logged how to repair it.
22
+ */
23
+ | 'store_misconfigured'
19
24
  /** Anything else (network, server). */
20
25
  | 'unavailable';
21
26
  /** What the action returns when it does not redirect. Texts are NOT here: `<AccountAuth>` writes them (i18n). */
@@ -16,6 +16,11 @@ type AuthErrorCode =
16
16
  | 'validation'
17
17
  /** The store does not offer this way of signing in. */
18
18
  | 'unsupported'
19
+ /**
20
+ * The store's own credential lacks a permission (`403 insufficient_scope`): the shop is misconfigured, not the
21
+ * buyer's data. The buyer can still check out as a guest; the server already logged how to repair it.
22
+ */
23
+ | 'store_misconfigured'
19
24
  /** Anything else (network, server). */
20
25
  | 'unavailable';
21
26
  /** What the action returns when it does not redirect. Texts are NOT here: `<AccountAuth>` writes them (i18n). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asteby/storefront-react",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "React bindings for @asteby/storefront — SSR-safe provider, optimistic cart, Money, responsive Image, prices, variant selection, SEO meta and JSON-LD, section registry and server-rendered theme CSS.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -142,7 +142,7 @@
142
142
  "react": "^19.0.0"
143
143
  },
144
144
  "dependencies": {
145
- "@asteby/storefront": "0.10.0"
145
+ "@asteby/storefront": "0.11.0"
146
146
  },
147
147
  "devDependencies": {
148
148
  "@testing-library/react": "^16.3.2",