@thorprovider/storefront 0.4.0-mvp.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -13
- package/assets/templates/app/app/[[...slug]]/page.tsx +32 -1
- package/assets/templates/app/app/[[...slug]]/renderer.tsx +43 -12
- package/assets/templates/app/lib/__STOREFRONT__/account-boundary.client.tsx +76 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +461 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-mutation.client.ts +46 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +103 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-reconcile.client.ts +465 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +177 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-session.ts +44 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +65 -0
- package/assets/templates/app/lib/__STOREFRONT__/actions.ts +76 -27
- package/assets/templates/app/lib/__STOREFRONT__/catalog.ts +4 -4
- package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +0 -10
- package/assets/templates/app/lib/__STOREFRONT__/composition.ts +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +3 -3
- package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +17 -18
- package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +209 -0
- package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.ts +247 -0
- package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +60 -29
- package/assets/templates/app/lib/__STOREFRONT__/schema.ts +83 -15
- package/assets/templates/app/lib/__STOREFRONT__/section-sources.ts +3 -5
- package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +25 -0
- package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +7 -10
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.client.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.client.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/logoCloud.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/pricing.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.client.tsx +16 -16
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.products.ts +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/statistics.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/testimonials.tsx +26 -19
- package/assets/templates/features/checkout/state.ts +0 -5
- package/assets/templates/features/customer-auth/handlers.ts +19 -23
- package/assets/templates/features/customer-auth/state.ts +21 -0
- package/assets/templates/views/account/index.tsx +19 -7
- package/assets/templates/views/account/registry.tsx +263 -155
- package/assets/templates/views/account/schema.ts +1 -1
- package/assets/templates/views/cart/data.ts +7 -7
- package/assets/templates/views/cart/registry.tsx +4 -3
- package/assets/templates/views/category/assembly/assembly.json +2 -2
- package/assets/templates/views/category/assembly/index.skeleton.tsx +11 -7
- package/assets/templates/views/category/assembly/registry.skeleton.tsx +9 -9
- package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/binding.json +1 -1
- package/assets/templates/views/category/assembly/slots/filter/CategoryListing/catalog.part +5 -0
- package/assets/templates/views/category/assembly/slots/filter/{CategoryFilter2 → CategoryListing}/element.part +5 -3
- package/assets/templates/views/category/assembly/slots/filter/{CategoryFilter2 → CategoryListing}/registry.part +9 -5
- package/assets/templates/views/category/content.ts +2 -1
- package/assets/templates/views/category/index.tsx +19 -13
- package/assets/templates/views/category/props.ts +1 -1
- package/assets/templates/views/category/registry.tsx +19 -15
- package/assets/templates/views/category/schema.ts +48 -21
- package/assets/templates/views/checkout/content.ts +60 -0
- package/assets/templates/views/checkout/props.ts +4 -5
- package/assets/templates/views/checkout/registry.tsx +12 -10
- package/assets/templates/views/checkout/schema.ts +10 -16
- package/assets/templates/views/home/assembly/assembly.json +4 -4
- package/assets/templates/views/home/assembly/index.skeleton.tsx +2 -3
- package/assets/templates/views/home/assembly/registry.skeleton.tsx +4 -1
- package/assets/templates/views/home/assembly/slots/benefits/cards/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/benefits/cards/registry.part +17 -0
- package/assets/templates/views/home/assembly/slots/benefits/split/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → split}/registry.part +6 -2
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/catalog.part +8 -0
- package/assets/templates/views/home/assembly/slots/categories/{ProductCategory2 → CategoryGrid}/element.part +1 -1
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/registry.part +31 -0
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/catalog.part +4 -0
- package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/registry.part +3 -1
- package/assets/templates/views/home/content.ts +22 -0
- package/assets/templates/views/home/index.tsx +11 -8
- package/assets/templates/views/home/props.ts +1 -0
- package/assets/templates/views/home/registry.tsx +39 -15
- package/assets/templates/views/home/schema.ts +141 -24
- package/assets/templates/views/product/data.ts +1 -1
- package/assets/templates/views/product/registry.tsx +10 -6
- package/assets/templates/views/product/schema.ts +36 -1
- package/examples/merchandising/category-led.json +1 -1
- package/examples/merchandising/collection-led.json +1 -1
- package/package.json +4 -5
- package/recipes/archetypes.json +39 -43
- package/recipes/catalog.json +212 -202
- package/recipes/catalog.mjs +10 -0
- package/recipes/catalog.schema.json +4 -0
- package/recipes/features.json +5 -5
- package/recipes/recipes.json +137 -43
- package/recipes/sections.json +4 -4
- package/recipes/validate.mjs +21 -4
- package/scripts/candidate.mjs +2 -2
- package/scripts/composers.mjs +2 -2
- package/scripts/file-classes.mjs +10 -0
- package/scripts/logical-controls.mjs +4 -4
- package/scripts/operation-registry.mjs +1 -1
- package/scripts/ownership-conflict.mjs +5 -2
- package/scripts/view-assembly.mjs +12 -4
- package/scripts/view-selection.mjs +1 -1
- package/skills/sf-view-gen/assets/recipes/archetypes.json +39 -43
- package/skills/sf-view-gen/assets/recipes/catalog.json +212 -202
- package/skills/sf-view-gen/assets/recipes/catalog.schema.json +4 -0
- package/skills/sf-view-gen/assets/recipes/features.json +5 -5
- package/skills/sf-view-gen/assets/recipes/recipes.json +137 -43
- package/skills/sf-view-gen/assets/recipes/sections.json +4 -4
- package/skills/sf-view-gen/assets/templates/views/sections/cta.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/faq.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/pricing.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/products.client.tsx +16 -16
- package/skills/sf-view-gen/assets/templates/views/sections/schema.products.ts +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/schema.testimonials.ts +21 -11
- package/skills/sf-view-gen/assets/templates/views/sections/statistics.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/testimonials.client.tsx +2 -8
- package/skills/sf-view-gen/scripts/catalog.mjs +10 -0
- package/skills/sf-view-gen/scripts/validate.mjs +21 -4
- package/assets/templates/views/category/assembly/slots/filter/CategoryFilter2/catalog.part +0 -5
- package/assets/templates/views/home/assembly/slots/benefits/Feature1/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/benefits/Feature2/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/benefits/Feature2/registry.part +0 -10
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/catalog.part +0 -4
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/registry.part +0 -16
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/catalog.part +0 -4
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/catalog.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/element.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/catalog.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/element.part +0 -0
- /package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/element.part +0 -0
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-reconcile.client.ts)
|
|
4
|
+
//
|
|
5
|
+
// The cross-tab auth-invalidation TRANSPORT (task 4.1) and RECEIVER (task 4.2).
|
|
6
|
+
// After a successful authoritative login/register/logout the shared account
|
|
7
|
+
// lifecycle emits the mutation kind on the `account-mutation.client` seam; this
|
|
8
|
+
// module subscribes to that seam and PUBLISHES a non-secret, store-scoped
|
|
9
|
+
// invalidation signal so other same-store tabs know to reconcile. The RECEIVER
|
|
10
|
+
// (`createAuthReconcileReceiver`, task 4.2) consumes `subscribeAuthInvalidations`
|
|
11
|
+
// — plus foreground/resume transitions — and re-resolves authoritatively through
|
|
12
|
+
// the shared lifecycle's `retryResolution` (never a new fetch/direct HTTP).
|
|
13
|
+
// Unavailable-retry + full listener cleanup is task 4.3.
|
|
14
|
+
//
|
|
15
|
+
// Store scope — the decision (and why):
|
|
16
|
+
// The real store id (`THOR_STORE_ID`, see `store-context.ts`) is SERVER-only;
|
|
17
|
+
// there is no `NEXT_PUBLIC_*` store id, and reading server env on the client is
|
|
18
|
+
// forbidden. The storefront NAME is a non-secret, build-time CLI substitution
|
|
19
|
+
// (`__STOREFRONT__`, the same placeholder that names this module's directory and
|
|
20
|
+
// is rendered into every generated file by `scripts/render-templates.mjs`). It is
|
|
21
|
+
// stable across tabs of one generated storefront and unique per storefront, so it
|
|
22
|
+
// scopes both the channel name and the payload. BroadcastChannel is already
|
|
23
|
+
// origin-scoped; this token additionally isolates multi-store-on-one-origin. It
|
|
24
|
+
// is NOT the store id and NOT a secret — it is a topic discriminator only.
|
|
25
|
+
//
|
|
26
|
+
// Never an identity authority: messages and storage entries carry ONLY the mutation
|
|
27
|
+
// kind, the store scope token, a unique event id, and an optional timestamp. No
|
|
28
|
+
// identity, email, name, orders, counts, credentials, or tokens ever pass through.
|
|
29
|
+
// A received payload is rebuilt from the allowlisted keys, so even a forged message
|
|
30
|
+
// cannot smuggle extra fields into a handler.
|
|
31
|
+
|
|
32
|
+
import type { AuthMutationKind } from './account-mutation.client'
|
|
33
|
+
|
|
34
|
+
/** The non-secret, store-scoped invalidation payload — the only wire shape. */
|
|
35
|
+
export interface AuthInvalidationPayload {
|
|
36
|
+
/** The authoritative mutation that happened. */
|
|
37
|
+
kind: AuthMutationKind
|
|
38
|
+
/** The non-secret store scope token; a foreign store's payload is ignored. */
|
|
39
|
+
scope: string
|
|
40
|
+
/** A unique id used to deduplicate a signal that arrives more than once. */
|
|
41
|
+
id: string
|
|
42
|
+
/** An optional non-secret timestamp (ms). */
|
|
43
|
+
at?: number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One delivery medium carrying the same payload. The BroadcastChannel transport
|
|
48
|
+
* and the `localStorage`/`storage`-event transport both implement it, so the bus
|
|
49
|
+
* is transport-agnostic and unit-testable with injected fakes.
|
|
50
|
+
*/
|
|
51
|
+
export interface AuthInvalidationTransport {
|
|
52
|
+
/** Send the payload to other same-store tabs. Must never throw. */
|
|
53
|
+
post(payload: AuthInvalidationPayload): void
|
|
54
|
+
/**
|
|
55
|
+
* Receive raw payloads from other tabs. The handler gets the UNVALIDATED wire
|
|
56
|
+
* value; the bus validates and normalizes it. Returns an unsubscribe that
|
|
57
|
+
* removes the listener and releases the underlying channel.
|
|
58
|
+
*/
|
|
59
|
+
listen(handler: (payload: unknown) => void): () => void
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Injectable seams for the bus; every field has a real-global default. */
|
|
63
|
+
export interface AuthReconcileDeps {
|
|
64
|
+
/** Non-secret topic token; defaults to the build-time storefront name. */
|
|
65
|
+
scope?: string
|
|
66
|
+
/** Transports carrying the same payload; defaults to broadcast + storage. */
|
|
67
|
+
transports?: AuthInvalidationTransport[]
|
|
68
|
+
/** Clock for the optional timestamp. */
|
|
69
|
+
now?: () => number
|
|
70
|
+
/** Unique-id factory for deduplication. */
|
|
71
|
+
newId?: () => string
|
|
72
|
+
/** How many recent event ids to retain for deduplication. */
|
|
73
|
+
dedupeLimit?: number
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The transport bus: publish a mutation, subscribe to received invalidations. */
|
|
77
|
+
export interface AuthReconcileBus {
|
|
78
|
+
/** Build and post a non-secret payload for `kind`; returns the payload sent. */
|
|
79
|
+
publish(kind: AuthMutationKind): AuthInvalidationPayload
|
|
80
|
+
/**
|
|
81
|
+
* Subscribe to received invalidations. The handler is called at most once per
|
|
82
|
+
* event id, across both transports, and only for this store's scope. Returns an
|
|
83
|
+
* unsubscribe that releases the transports once the last subscriber leaves.
|
|
84
|
+
*/
|
|
85
|
+
subscribe(handler: (payload: AuthInvalidationPayload) => void): () => void
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// The build-time storefront name the CLI substitutes into this module (see the
|
|
89
|
+
// header). It scopes the channel name AND the payload.
|
|
90
|
+
const STORE_SCOPE = '__STOREFRONT__'
|
|
91
|
+
// A distinct namespace so this transport can never collide with unrelated
|
|
92
|
+
// browser messaging/storage on the same origin.
|
|
93
|
+
const TOPIC_PREFIX = 'thor.storefront.auth-reconcile:'
|
|
94
|
+
|
|
95
|
+
const AUTH_MUTATION_KINDS: readonly AuthMutationKind[] = ['login', 'register', 'logout']
|
|
96
|
+
|
|
97
|
+
function isAuthMutationKind(value: unknown): value is AuthMutationKind {
|
|
98
|
+
return typeof value === 'string' && (AUTH_MUTATION_KINDS as readonly string[]).includes(value)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Rebuild a payload from ONLY the allowlisted keys, or `null` when the value is
|
|
103
|
+
* not a well-formed, in-scope invalidation. Dropping unknown keys is deliberate:
|
|
104
|
+
* a handler can never receive identity/orders/tokens even from a forged message.
|
|
105
|
+
*/
|
|
106
|
+
function parsePayload(raw: unknown): AuthInvalidationPayload | null {
|
|
107
|
+
if (typeof raw !== 'object' || raw === null) return null
|
|
108
|
+
const candidate = raw as Record<string, unknown>
|
|
109
|
+
if (!isAuthMutationKind(candidate.kind)) return null
|
|
110
|
+
if (typeof candidate.scope !== 'string' || candidate.scope === '') return null
|
|
111
|
+
if (typeof candidate.id !== 'string' || candidate.id === '') return null
|
|
112
|
+
const payload: AuthInvalidationPayload = {
|
|
113
|
+
kind: candidate.kind,
|
|
114
|
+
scope: candidate.scope,
|
|
115
|
+
id: candidate.id,
|
|
116
|
+
}
|
|
117
|
+
if (typeof candidate.at === 'number') payload.at = candidate.at
|
|
118
|
+
return payload
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A BroadcastChannel transport, or `null` when the API is unavailable. */
|
|
122
|
+
function createBroadcastTransport(scope: string): AuthInvalidationTransport | null {
|
|
123
|
+
if (typeof BroadcastChannel === 'undefined') return null
|
|
124
|
+
const name = `${TOPIC_PREFIX}${scope}`
|
|
125
|
+
return {
|
|
126
|
+
post(payload) {
|
|
127
|
+
// A short-lived channel posts and closes immediately, so a tab that only
|
|
128
|
+
// publishes never retains an open channel (the "inert on mount" contract).
|
|
129
|
+
try {
|
|
130
|
+
const channel = new BroadcastChannel(name)
|
|
131
|
+
channel.postMessage(payload)
|
|
132
|
+
channel.close()
|
|
133
|
+
} catch {
|
|
134
|
+
// A closed/unsupported channel must never break the mutation flow.
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
listen(handler) {
|
|
138
|
+
const channel = new BroadcastChannel(name)
|
|
139
|
+
const listener = (event: MessageEvent) => handler(event.data)
|
|
140
|
+
channel.addEventListener('message', listener)
|
|
141
|
+
return () => {
|
|
142
|
+
channel.removeEventListener('message', listener)
|
|
143
|
+
channel.close()
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A `localStorage` + `storage`-event transport, or `null` when unavailable. */
|
|
150
|
+
function createStorageTransport(scope: string): AuthInvalidationTransport | null {
|
|
151
|
+
if (typeof window === 'undefined' || typeof localStorage === 'undefined') return null
|
|
152
|
+
const key = `${TOPIC_PREFIX}${scope}`
|
|
153
|
+
let storage: Storage
|
|
154
|
+
try {
|
|
155
|
+
storage = localStorage
|
|
156
|
+
} catch {
|
|
157
|
+
// Access can throw in a locked-down/private context; degrade to no storage.
|
|
158
|
+
return null
|
|
159
|
+
}
|
|
160
|
+
// Whether THIS transport instance wrote the non-secret token, so its release
|
|
161
|
+
// removes exactly the entry it created and never a key another writer owns.
|
|
162
|
+
let wrote = false
|
|
163
|
+
return {
|
|
164
|
+
post(payload) {
|
|
165
|
+
try {
|
|
166
|
+
// A unique id per event guarantees the value changes, so other tabs
|
|
167
|
+
// receive a `storage` event (the sender's own window never does).
|
|
168
|
+
storage.setItem(key, JSON.stringify(payload))
|
|
169
|
+
wrote = true
|
|
170
|
+
} catch {
|
|
171
|
+
// Quota/private-mode failures must never break the mutation flow.
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
listen(handler) {
|
|
175
|
+
const listener = (event: StorageEvent) => {
|
|
176
|
+
if (event.key !== key) return
|
|
177
|
+
if (typeof event.newValue !== 'string') return
|
|
178
|
+
try {
|
|
179
|
+
handler(JSON.parse(event.newValue))
|
|
180
|
+
} catch {
|
|
181
|
+
// Ignore a malformed storage entry rather than throwing in a listener.
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
window.addEventListener('storage', listener)
|
|
185
|
+
return () => {
|
|
186
|
+
window.removeEventListener('storage', listener)
|
|
187
|
+
// Release the non-secret token this instance wrote (task 4.3): a
|
|
188
|
+
// capability removal/unmount must leave no invalidation entry behind.
|
|
189
|
+
// Never throws in a locked-down/private context.
|
|
190
|
+
if (wrote) {
|
|
191
|
+
wrote = false
|
|
192
|
+
try {
|
|
193
|
+
storage.removeItem(key)
|
|
194
|
+
} catch {
|
|
195
|
+
// A read-only/full storage area must not break teardown.
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The real transports for `scope`, feature-detected against the globals. */
|
|
204
|
+
function defaultTransports(scope: string): AuthInvalidationTransport[] {
|
|
205
|
+
const transports: AuthInvalidationTransport[] = []
|
|
206
|
+
const broadcast = createBroadcastTransport(scope)
|
|
207
|
+
if (broadcast) transports.push(broadcast)
|
|
208
|
+
const storage = createStorageTransport(scope)
|
|
209
|
+
if (storage) transports.push(storage)
|
|
210
|
+
return transports
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function defaultId(): string {
|
|
214
|
+
// `crypto.randomUUID` exists in modern browsers and Node; fall back to a
|
|
215
|
+
// time+random token where it does not. The id is non-secret either way.
|
|
216
|
+
const cryptoApi = (globalThis as { crypto?: Crypto }).crypto
|
|
217
|
+
if (cryptoApi && typeof cryptoApi.randomUUID === 'function') return cryptoApi.randomUUID()
|
|
218
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Create an isolated transport bus. Tests inject fake transports; production
|
|
223
|
+
* uses the defaults (real BroadcastChannel + real `storage`), resolved lazily so
|
|
224
|
+
* importing the module opens nothing.
|
|
225
|
+
*/
|
|
226
|
+
export function createAuthReconcileBus(deps: AuthReconcileDeps = {}): AuthReconcileBus {
|
|
227
|
+
const scope = deps.scope ?? STORE_SCOPE
|
|
228
|
+
const transports = deps.transports ?? defaultTransports(scope)
|
|
229
|
+
const now = deps.now ?? (() => Date.now())
|
|
230
|
+
const newId = deps.newId ?? defaultId
|
|
231
|
+
const dedupeLimit = deps.dedupeLimit ?? 256
|
|
232
|
+
|
|
233
|
+
const handlers = new Set<(payload: AuthInvalidationPayload) => void>()
|
|
234
|
+
// Insertion-ordered seen set: dedupe at most `dedupeLimit` recent event ids.
|
|
235
|
+
const seen = new Set<string>()
|
|
236
|
+
let unlisteners: Array<() => void> | null = null
|
|
237
|
+
|
|
238
|
+
const remember = (id: string) => {
|
|
239
|
+
seen.add(id)
|
|
240
|
+
if (seen.size > dedupeLimit) {
|
|
241
|
+
const oldest = seen.values().next().value
|
|
242
|
+
if (oldest !== undefined) seen.delete(oldest)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const receive = (raw: unknown) => {
|
|
247
|
+
const payload = parsePayload(raw)
|
|
248
|
+
if (!payload) return
|
|
249
|
+
if (payload.scope !== scope) return
|
|
250
|
+
if (seen.has(payload.id)) return
|
|
251
|
+
remember(payload.id)
|
|
252
|
+
for (const handler of [...handlers]) handler(payload)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const open = () => {
|
|
256
|
+
if (unlisteners) return
|
|
257
|
+
unlisteners = transports.map((transport) => transport.listen(receive))
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const close = () => {
|
|
261
|
+
if (!unlisteners) return
|
|
262
|
+
for (const unlisten of unlisteners) unlisten()
|
|
263
|
+
unlisteners = null
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return {
|
|
267
|
+
publish(kind) {
|
|
268
|
+
const payload: AuthInvalidationPayload = { kind, scope, id: newId(), at: now() }
|
|
269
|
+
for (const transport of transports) transport.post(payload)
|
|
270
|
+
return payload
|
|
271
|
+
},
|
|
272
|
+
subscribe(handler) {
|
|
273
|
+
handlers.add(handler)
|
|
274
|
+
open()
|
|
275
|
+
return () => {
|
|
276
|
+
handlers.delete(handler)
|
|
277
|
+
if (handlers.size === 0) close()
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// The per-tab default bus, created on first use so importing this module is
|
|
284
|
+
// inert (no channel opened, no storage written) until a publish/subscribe call.
|
|
285
|
+
let defaultBus: AuthReconcileBus | null = null
|
|
286
|
+
|
|
287
|
+
function getDefaultBus(): AuthReconcileBus {
|
|
288
|
+
if (!defaultBus) defaultBus = createAuthReconcileBus()
|
|
289
|
+
return defaultBus
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Publish a non-secret, store-scoped auth invalidation. Safe to call with no
|
|
294
|
+
* subscriber: the payload still reaches other tabs. Publishing itself opens no
|
|
295
|
+
* receive channel; a mounted tab opens one through the receiver
|
|
296
|
+
* (`createAuthReconcileReceiver`). Returns the payload sent (including its
|
|
297
|
+
* unique id) so a tab that BOTH publishes and receives can recognize its own
|
|
298
|
+
* broadcast echo and skip a redundant re-resolution (task 4.2).
|
|
299
|
+
*/
|
|
300
|
+
export function publishAuthInvalidation(kind: AuthMutationKind): AuthInvalidationPayload {
|
|
301
|
+
return getDefaultBus().publish(kind)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Subscribe to received auth invalidations for THIS store (task 4.2 consumes
|
|
306
|
+
* this to re-resolve). Returns an unsubscribe that releases the transports when
|
|
307
|
+
* the last subscriber leaves.
|
|
308
|
+
*/
|
|
309
|
+
export function subscribeAuthInvalidations(
|
|
310
|
+
handler: (payload: AuthInvalidationPayload) => void,
|
|
311
|
+
): () => void {
|
|
312
|
+
return getDefaultBus().subscribe(handler)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Injectable seams for the receiver; every field has a real-global default. */
|
|
316
|
+
export interface AuthReconcileReceiverDeps {
|
|
317
|
+
/** The bus to receive on; defaults to the per-tab default bus. */
|
|
318
|
+
bus?: AuthReconcileBus
|
|
319
|
+
/**
|
|
320
|
+
* The authoritative re-resolution — the shared lifecycle's
|
|
321
|
+
* `retryResolution`, which re-resolves through the allowlisted Server Action
|
|
322
|
+
* and claims the result (or the unavailable outcome) under a generation
|
|
323
|
+
* guard. The receiver never issues a fetch or direct HTTP itself.
|
|
324
|
+
*/
|
|
325
|
+
retryResolution: () => void | Promise<void>
|
|
326
|
+
/**
|
|
327
|
+
* Probe the shared per-tab auth-mutation gate. A reconciliation is skipped
|
|
328
|
+
* while a local login/logout/retry holds it, so a received signal cannot race
|
|
329
|
+
* a local auth mutation. Defaults to "never pending".
|
|
330
|
+
*/
|
|
331
|
+
isAuthMutationPending?: () => boolean
|
|
332
|
+
/**
|
|
333
|
+
* True when `payload` is this tab's own published signal. A tab that both
|
|
334
|
+
* publishes and receives sees its own broadcast echo (the listen channel is a
|
|
335
|
+
* different object from the short-lived sender), so it must not re-resolve
|
|
336
|
+
* redundantly. Defaults to "never own".
|
|
337
|
+
*/
|
|
338
|
+
isOwnSignal?: (payload: AuthInvalidationPayload) => boolean
|
|
339
|
+
/**
|
|
340
|
+
* Foreground/resume subscription; defaults to the real DOM listeners
|
|
341
|
+
* (`visibilitychange` to visible, `focus` after blur, `pageshow` from bfcache).
|
|
342
|
+
*/
|
|
343
|
+
subscribeResume?: (handler: () => void) => () => void
|
|
344
|
+
/**
|
|
345
|
+
* Notified when a reconciliation begins (`true`) and when the authoritative
|
|
346
|
+
* re-resolution settles (`false`, including an unavailable/error outcome), so
|
|
347
|
+
* a consumer can present a neutral pending surface instead of previously held
|
|
348
|
+
* private account data while the server round-trip is in flight. It never
|
|
349
|
+
* toggles for a skipped (gate-held) or own-echo signal, and a superseded
|
|
350
|
+
* reconciliation cannot clear a newer one's flag.
|
|
351
|
+
*/
|
|
352
|
+
onReconcileChange?: (reconciling: boolean) => void
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Subscribe to foreground/resume transitions: `visibilitychange` → visible,
|
|
357
|
+
* `focus` after the window was unfocused, and `pageshow` restored from the
|
|
358
|
+
* back/forward cache. The FIRST observation of each is never treated as a
|
|
359
|
+
* transition, so attaching the receiver performs no work on mount (no fetch on
|
|
360
|
+
* mount/navigation); only a genuine hidden→visible / blur→focus / bfcache
|
|
361
|
+
* restore resumes.
|
|
362
|
+
*/
|
|
363
|
+
function subscribeForegroundResume(handler: () => void): () => void {
|
|
364
|
+
if (typeof document === 'undefined' || typeof window === 'undefined') return () => {}
|
|
365
|
+
let hidden = document.visibilityState === 'hidden'
|
|
366
|
+
let focused = typeof document.hasFocus === 'function' ? document.hasFocus() : true
|
|
367
|
+
const onVisibility = () => {
|
|
368
|
+
const nowHidden = document.visibilityState === 'hidden'
|
|
369
|
+
if (hidden && !nowHidden) handler()
|
|
370
|
+
hidden = nowHidden
|
|
371
|
+
}
|
|
372
|
+
const onFocus = () => {
|
|
373
|
+
if (!focused) handler()
|
|
374
|
+
focused = true
|
|
375
|
+
}
|
|
376
|
+
const onBlur = () => {
|
|
377
|
+
focused = false
|
|
378
|
+
}
|
|
379
|
+
const onPageShow = (event: PageTransitionEvent) => {
|
|
380
|
+
// A bfcache restore is a resume; the initial load's pageshow is not.
|
|
381
|
+
if (event.persisted) handler()
|
|
382
|
+
}
|
|
383
|
+
document.addEventListener('visibilitychange', onVisibility)
|
|
384
|
+
window.addEventListener('focus', onFocus)
|
|
385
|
+
window.addEventListener('blur', onBlur)
|
|
386
|
+
window.addEventListener('pageshow', onPageShow)
|
|
387
|
+
return () => {
|
|
388
|
+
document.removeEventListener('visibilitychange', onVisibility)
|
|
389
|
+
window.removeEventListener('focus', onFocus)
|
|
390
|
+
window.removeEventListener('blur', onBlur)
|
|
391
|
+
window.removeEventListener('pageshow', onPageShow)
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Attach the cross-tab RECEIVER (task 4.2): on a same-store invalidation, or a
|
|
397
|
+
* foreground/resume transition, re-resolve the session authoritatively through
|
|
398
|
+
* `retryResolution`. It stays inert until a signal/resume (no fetch on mount or
|
|
399
|
+
* navigation), never re-publishes on receipt (no event loop), ignores this
|
|
400
|
+
* tab's own echo, and skips a reconciliation while a local auth mutation holds
|
|
401
|
+
* the shared per-tab gate. It reports the pending window via
|
|
402
|
+
* `onReconcileChange` so a consumer never presents previously held private
|
|
403
|
+
* account data as current during the round-trip. Returns an unsubscribe that
|
|
404
|
+
* releases the bus subscription and every resume listener.
|
|
405
|
+
*/
|
|
406
|
+
export function createAuthReconcileReceiver(deps: AuthReconcileReceiverDeps): () => void {
|
|
407
|
+
const isAuthMutationPending = deps.isAuthMutationPending ?? (() => false)
|
|
408
|
+
const isOwnSignal = deps.isOwnSignal ?? (() => false)
|
|
409
|
+
const subscribeResume = deps.subscribeResume ?? subscribeForegroundResume
|
|
410
|
+
const onReconcileChange = deps.onReconcileChange ?? (() => {})
|
|
411
|
+
|
|
412
|
+
// Monotonic generation so a superseded reconciliation cannot clear the flag of
|
|
413
|
+
// a newer one. The shared gate already single-flights the request; this guards
|
|
414
|
+
// the flag across the brief window between a settle and the next accept.
|
|
415
|
+
let reconcileGeneration = 0
|
|
416
|
+
|
|
417
|
+
const settle = (generation: number) => {
|
|
418
|
+
if (generation === reconcileGeneration) onReconcileChange(false)
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const reconcile = () => {
|
|
422
|
+
// Never race a local auth mutation: the shared per-tab gate (owned by
|
|
423
|
+
// `retryResolution`) is the single-flight guard, and the explicit check
|
|
424
|
+
// drops the signal instead of issuing a request. A later signal or a resume
|
|
425
|
+
// recovers a missed change.
|
|
426
|
+
if (isAuthMutationPending()) return
|
|
427
|
+
const generation = (reconcileGeneration += 1)
|
|
428
|
+
// Mark pending BEFORE the request so a consumer hides previously held
|
|
429
|
+
// private data for the whole round-trip, not only once the async claim lands.
|
|
430
|
+
onReconcileChange(true)
|
|
431
|
+
const run = deps.retryResolution()
|
|
432
|
+
Promise.resolve(run).then(
|
|
433
|
+
() => settle(generation),
|
|
434
|
+
(error) => {
|
|
435
|
+
// `retryResolution` owns its own error handling and never rejects; a
|
|
436
|
+
// rejection here is unexpected, so surface it (never swallow) and still
|
|
437
|
+
// settle the flag so the pending surface cannot get stuck.
|
|
438
|
+
console.error(
|
|
439
|
+
'[storefront/account] reconciliation failed',
|
|
440
|
+
error instanceof Error ? error.message : error,
|
|
441
|
+
)
|
|
442
|
+
settle(generation)
|
|
443
|
+
},
|
|
444
|
+
)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const onSignal = (payload: AuthInvalidationPayload) => {
|
|
448
|
+
if (isOwnSignal(payload)) return
|
|
449
|
+
reconcile()
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Prefer the named seam in production; an injected bus keeps the unit tests
|
|
453
|
+
// isolated. Both resolve the SAME per-tab default bus.
|
|
454
|
+
const unsubscribeBus = deps.bus
|
|
455
|
+
? deps.bus.subscribe(onSignal)
|
|
456
|
+
: subscribeAuthInvalidations(onSignal)
|
|
457
|
+
const unsubscribeResume = subscribeResume(reconcile)
|
|
458
|
+
let active = true
|
|
459
|
+
return () => {
|
|
460
|
+
if (!active) return
|
|
461
|
+
active = false
|
|
462
|
+
unsubscribeBus()
|
|
463
|
+
unsubscribeResume()
|
|
464
|
+
}
|
|
465
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-session.core.ts)
|
|
2
|
+
//
|
|
3
|
+
// Pure, framework-free core of the host account-session reader. Given the two
|
|
4
|
+
// boundary reads (the verified auth-cookie token and the backend customer
|
|
5
|
+
// resolve) it returns one truthful, serializable outcome:
|
|
6
|
+
//
|
|
7
|
+
// authenticated -> the allowlisted display identity only
|
|
8
|
+
// anonymous -> no trusted session (absent / invalid / expired cookie)
|
|
9
|
+
// unavailable -> the session could not be resolved (backend/transport
|
|
10
|
+
// failure or an untrustworthy identity), NEVER a fake sign-out
|
|
11
|
+
//
|
|
12
|
+
// Zod validates the untrusted backend customer and, by stripping unknown keys,
|
|
13
|
+
// permits only the display fields the navbar/panel need. No token, phone,
|
|
14
|
+
// metadata, or other customer field can therefore enter projected state. This
|
|
15
|
+
// module imports no Next.js/React and calls no backend: `./account-session`
|
|
16
|
+
// binds it to the request cookie and the commerce boundary.
|
|
17
|
+
|
|
18
|
+
import { z } from 'zod'
|
|
19
|
+
import type { Customer } from '@thorprovider/types'
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The display allowlist. Zod strips unknown keys on parse, so a backend
|
|
23
|
+
* customer projects to exactly these four fields. An absent optional name is
|
|
24
|
+
* normalized to null (never undefined) so the projection is stable to
|
|
25
|
+
* serialize.
|
|
26
|
+
*/
|
|
27
|
+
export const accountIdentitySchema = z.object({
|
|
28
|
+
id: z.string().min(1),
|
|
29
|
+
email: z.string().min(1),
|
|
30
|
+
firstName: z.string().nullish().transform((value) => value ?? null),
|
|
31
|
+
lastName: z.string().nullish().transform((value) => value ?? null),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
/** The only customer fields permitted in projected/serialized account state. */
|
|
35
|
+
export type AccountIdentity = z.infer<typeof accountIdentitySchema>
|
|
36
|
+
|
|
37
|
+
/** A truthful, serializable account-session outcome. Carries no token. */
|
|
38
|
+
export type AccountSession =
|
|
39
|
+
| { status: 'authenticated'; identity: AccountIdentity }
|
|
40
|
+
| { status: 'anonymous' }
|
|
41
|
+
| { status: 'unavailable'; error: string }
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The account state keys the catch-all server render seeds before the shell
|
|
45
|
+
* renders. `accountResolution` is the explicit status downstream consumers
|
|
46
|
+
* (the shell chrome and the shared lifecycle, tasks 2.3/3.x) read to tell a
|
|
47
|
+
* resolved anonymous shopper from an unresolved/unavailable session, so an
|
|
48
|
+
* outage never renders as a fake signed-out surface.
|
|
49
|
+
*/
|
|
50
|
+
export type AccountResolution = 'authenticated' | 'anonymous' | 'unavailable'
|
|
51
|
+
|
|
52
|
+
/** The request-scoped account slice seeded into the json-render initial state. */
|
|
53
|
+
export interface AccountInitialState {
|
|
54
|
+
/** The allowlisted display identity, or null when not authenticated. */
|
|
55
|
+
accountCustomer: AccountIdentity | null
|
|
56
|
+
/** True only for a resolved authenticated session. */
|
|
57
|
+
accountAuthenticated: boolean
|
|
58
|
+
/** The truthful resolution status; never carries a token or metadata. */
|
|
59
|
+
accountResolution: AccountResolution
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Project one resolved `AccountSession` into the serializable account state the
|
|
64
|
+
* catch-all render seeds. `unavailable` seeds `accountAuthenticated: false` but
|
|
65
|
+
* keeps its distinct `accountResolution`, so the UI can offer retry instead of
|
|
66
|
+
* asserting a sign-out. No token, phone, or metadata can enter the projection.
|
|
67
|
+
*/
|
|
68
|
+
export function toAccountInitialState(session: AccountSession): AccountInitialState {
|
|
69
|
+
switch (session.status) {
|
|
70
|
+
case 'authenticated':
|
|
71
|
+
return {
|
|
72
|
+
accountCustomer: session.identity,
|
|
73
|
+
accountAuthenticated: true,
|
|
74
|
+
accountResolution: 'authenticated',
|
|
75
|
+
}
|
|
76
|
+
case 'anonymous':
|
|
77
|
+
return { accountCustomer: null, accountAuthenticated: false, accountResolution: 'anonymous' }
|
|
78
|
+
case 'unavailable':
|
|
79
|
+
return {
|
|
80
|
+
accountCustomer: null,
|
|
81
|
+
accountAuthenticated: false,
|
|
82
|
+
accountResolution: 'unavailable',
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The serializable account projection the shared client lifecycle reads and
|
|
89
|
+
* writes: the same three keys the catch-all render seeds. Kept as an alias so
|
|
90
|
+
* the seed and every mutation/reconciliation path type against one shape.
|
|
91
|
+
*/
|
|
92
|
+
export type AccountProjection = AccountInitialState
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Project an allowlisted identity (or null) into the account slice, keeping the
|
|
96
|
+
* three keys in lockstep: a non-null identity IS an authenticated session, and a
|
|
97
|
+
* null identity is a confirmed anonymous one. The shared lifecycle uses this for
|
|
98
|
+
* authoritative action results, so `accountResolution` can never contradict
|
|
99
|
+
* `accountAuthenticated`/`accountCustomer`.
|
|
100
|
+
*/
|
|
101
|
+
export function accountProjectionFromIdentity(identity: AccountIdentity | null): AccountProjection {
|
|
102
|
+
return identity
|
|
103
|
+
? { accountCustomer: identity, accountAuthenticated: true, accountResolution: 'authenticated' }
|
|
104
|
+
: { accountCustomer: null, accountAuthenticated: false, accountResolution: 'anonymous' }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The retryable unavailable projection: no identity and no authentication, but a
|
|
109
|
+
* distinct `accountResolution` so the UI offers retry instead of asserting a
|
|
110
|
+
* sign-out. Never carries a token or metadata.
|
|
111
|
+
*/
|
|
112
|
+
export function unavailableAccountProjection(): AccountProjection {
|
|
113
|
+
return { accountCustomer: null, accountAuthenticated: false, accountResolution: 'unavailable' }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* True when the three account keys agree: only `authenticated` carries a
|
|
118
|
+
* non-null identity, and anonymous/unavailable carry neither. The seed and the
|
|
119
|
+
* lifecycle's write path only ever produce consistent projections.
|
|
120
|
+
*/
|
|
121
|
+
export function isAccountProjectionConsistent(projection: AccountInitialState): boolean {
|
|
122
|
+
if (projection.accountResolution === 'authenticated') {
|
|
123
|
+
return projection.accountAuthenticated === true && projection.accountCustomer !== null
|
|
124
|
+
}
|
|
125
|
+
return projection.accountAuthenticated === false && projection.accountCustomer === null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The boundary reads the core depends on; injected so the logic is testable. */
|
|
129
|
+
export interface AccountSessionDeps {
|
|
130
|
+
/** The verified auth-cookie token, or null when there is no trusted session. */
|
|
131
|
+
readToken: () => Promise<string | null>
|
|
132
|
+
/** Resolve the backend customer for the token; null means confirmed anonymous. */
|
|
133
|
+
loadCustomer: (token: string) => Promise<Customer | null>
|
|
134
|
+
/** Optional non-secret failure sink; never receives a token or customer. */
|
|
135
|
+
onError?: (error: unknown) => void
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function message(error: unknown, fallback: string): string {
|
|
139
|
+
return error instanceof Error && error.message.trim() !== '' ? error.message : fallback
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Resolve one account-session outcome from the cookie/customer boundary.
|
|
144
|
+
*
|
|
145
|
+
* A null token (absent, tampered, expired, or wrong-store cookie) or a null
|
|
146
|
+
* customer (confirmed unauthenticated) is anonymous and performs no further
|
|
147
|
+
* read. Any thrown read is unavailable, never anonymous. A customer that fails
|
|
148
|
+
* the display allowlist is unavailable rather than a fabricated sign-out.
|
|
149
|
+
*/
|
|
150
|
+
export async function resolveAccountSession(
|
|
151
|
+
deps: AccountSessionDeps,
|
|
152
|
+
): Promise<AccountSession> {
|
|
153
|
+
let token: string | null
|
|
154
|
+
try {
|
|
155
|
+
token = await deps.readToken()
|
|
156
|
+
} catch (error) {
|
|
157
|
+
deps.onError?.(error)
|
|
158
|
+
return { status: 'unavailable', error: message(error, 'No se pudo leer la sesión.') }
|
|
159
|
+
}
|
|
160
|
+
if (!token) return { status: 'anonymous' }
|
|
161
|
+
|
|
162
|
+
let customer: Customer | null
|
|
163
|
+
try {
|
|
164
|
+
customer = await deps.loadCustomer(token)
|
|
165
|
+
} catch (error) {
|
|
166
|
+
deps.onError?.(error)
|
|
167
|
+
return { status: 'unavailable', error: message(error, 'No se pudo verificar la sesión.') }
|
|
168
|
+
}
|
|
169
|
+
if (!customer) return { status: 'anonymous' }
|
|
170
|
+
|
|
171
|
+
const parsed = accountIdentitySchema.safeParse(customer)
|
|
172
|
+
if (!parsed.success) {
|
|
173
|
+
deps.onError?.(parsed.error)
|
|
174
|
+
return { status: 'unavailable', error: 'La identidad de la cuenta no es válida.' }
|
|
175
|
+
}
|
|
176
|
+
return { status: 'authenticated', identity: parsed.data }
|
|
177
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-session.ts)
|
|
2
|
+
//
|
|
3
|
+
// READ-ONLY host account-session reader — safe during a Server Component render
|
|
4
|
+
// and reused by the account Server Action. It shares exactly the cookie/customer
|
|
5
|
+
// resolution the account actions use (`readAuthToken` + `loadCustomer`), never
|
|
6
|
+
// mutates a cookie, never creates a session, and performs no backend read when
|
|
7
|
+
// the auth cookie is absent. The pure projection lives in
|
|
8
|
+
// `./account-session.core`; this module only binds it to the request context.
|
|
9
|
+
//
|
|
10
|
+
// Server-only and Next-bound (it reads cookies through `./session`). A
|
|
11
|
+
// request-scoped context is resolved on every call, so no customer result is
|
|
12
|
+
// ever shared between requests or store contexts.
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
resolveAccountSession,
|
|
16
|
+
type AccountSession,
|
|
17
|
+
} from './account-session.core'
|
|
18
|
+
import { loadCustomer } from './commerce'
|
|
19
|
+
import { readAuthToken } from './session'
|
|
20
|
+
import { getStoreContext } from './store-context'
|
|
21
|
+
|
|
22
|
+
/** Log a non-secret context line for a failed resolution; never a token. */
|
|
23
|
+
function logAccountSessionError(error: unknown): void {
|
|
24
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
25
|
+
console.error('[storefront/account-session] resolution failed', { message })
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the current shopper's account session from the verified auth cookie.
|
|
30
|
+
*
|
|
31
|
+
* Render-safe: it reads the cookie and resolves the customer but never writes or
|
|
32
|
+
* creates one. Invalid/expired cookies are anonymous; a backend/transport
|
|
33
|
+
* failure is unavailable so the UI can offer retry instead of a false sign-out.
|
|
34
|
+
*/
|
|
35
|
+
export async function readAccountSession(): Promise<AccountSession> {
|
|
36
|
+
return resolveAccountSession({
|
|
37
|
+
readToken: async () => {
|
|
38
|
+
const context = getStoreContext()
|
|
39
|
+
return readAuthToken(context)
|
|
40
|
+
},
|
|
41
|
+
loadCustomer: (token) => loadCustomer(token),
|
|
42
|
+
onError: logAccountSessionError,
|
|
43
|
+
})
|
|
44
|
+
}
|