create-nymbal-app 0.6.0 → 0.8.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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +9 -0
  3. package/dist/index.d.ts +13 -2
  4. package/dist/index.js +45 -12
  5. package/dist/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/scaffold/templates/astro/README.md +49 -15
  8. package/scaffold/templates/astro/_dot.env.example +3 -1
  9. package/scaffold/templates/astro/astro.config.mjs +3 -0
  10. package/scaffold/templates/astro/package.json +25 -25
  11. package/scaffold/templates/astro/src/layouts/AccountLayout.astro +3 -6
  12. package/scaffold/templates/astro/src/layouts/BaseLayout.astro +5 -2
  13. package/scaffold/templates/astro/src/lib/api.ts +119 -13
  14. package/scaffold/templates/astro/src/lib/client.ts +9 -3
  15. package/scaffold/templates/astro/src/lib/page-policy.ts +24 -0
  16. package/scaffold/templates/astro/src/lib/reviews.ts +6 -0
  17. package/scaffold/templates/astro/src/lib/seo.ts +14 -1
  18. package/scaffold/templates/astro/src/lib/submit-once.ts +15 -2
  19. package/scaffold/templates/astro/src/middleware.ts +19 -10
  20. package/scaffold/templates/astro/src/pages/account/index.astro +1 -0
  21. package/scaffold/templates/astro/src/pages/account/orders/[orderNumber].astro +1 -1
  22. package/scaffold/templates/astro/src/pages/alerts/confirm.astro +3 -2
  23. package/scaffold/templates/astro/src/pages/alerts/unsubscribe.astro +3 -2
  24. package/scaffold/templates/astro/src/pages/cart.astro +18 -4
  25. package/scaffold/templates/astro/src/pages/checkout.astro +9 -2
  26. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +186 -60
  27. package/scaffold/templates/astro/src/pages/product/[slug].astro +10 -4
  28. package/scaffold/templates/astro/src/pages/products/index.astro +2 -1
  29. package/scaffold/templates/astro/src/scripts/order-access.ts +181 -0
  30. package/scaffold/templates/astro/src/scripts/pdp.ts +1 -0
  31. package/scaffold/templates/astro/src/scripts/plp.ts +1 -0
  32. package/scaffold/templates/astro/src/scripts/search.ts +1 -0
  33. package/scaffold/templates/astro/src/scripts/signed-in-redirect.ts +14 -1
  34. package/scaffold/templates/astro/src/styles/global.css +3 -0
  35. package/scaffold/templates/astro/src/styles/pages/pdp.css +7 -4
  36. package/scaffold/templates/nextjs/README.md +49 -15
  37. package/scaffold/templates/nextjs/_dot.env.example +3 -1
  38. package/scaffold/templates/nextjs/app/(catalog)/home/[key]/page.tsx +2 -2
  39. package/scaffold/templates/nextjs/app/(catalog)/product/[slug]/page.tsx +24 -20
  40. package/scaffold/templates/nextjs/app/(catalog)/products/page.tsx +8 -5
  41. package/scaffold/templates/nextjs/app/(catalog)/search/SearchView.tsx +1 -1
  42. package/scaffold/templates/nextjs/app/(shopper)/account/login/LoginView.tsx +4 -4
  43. package/scaffold/templates/nextjs/app/(shopper)/account/login/page.tsx +3 -1
  44. package/scaffold/templates/nextjs/app/(shopper)/alerts/actions.ts +6 -3
  45. package/scaffold/templates/nextjs/app/(shopper)/cart/page.tsx +21 -5
  46. package/scaffold/templates/nextjs/app/(shopper)/checkout/CheckoutView.tsx +6 -2
  47. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderDetails.tsx +23 -0
  48. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderEmailPrompt.tsx +112 -0
  49. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderLinkForm.tsx +89 -0
  50. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderNotFound.tsx +30 -0
  51. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderView.tsx +140 -0
  52. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OwnerRedirect.tsx +48 -0
  53. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/actions.ts +56 -0
  54. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/not-found.tsx +6 -0
  55. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/page.tsx +9 -137
  56. package/scaffold/templates/nextjs/app/error.tsx +9 -3
  57. package/scaffold/templates/nextjs/app/globals.css +3 -0
  58. package/scaffold/templates/nextjs/components/client/AuthGuard.tsx +2 -2
  59. package/scaffold/templates/nextjs/components/client/NymbalSetup.tsx +1 -2
  60. package/scaffold/templates/nextjs/components/server/Header.tsx +5 -2
  61. package/scaffold/templates/nextjs/lib/api.ts +118 -12
  62. package/scaffold/templates/nextjs/lib/chrome.ts +9 -5
  63. package/scaffold/templates/nextjs/lib/client.ts +5 -7
  64. package/scaffold/templates/nextjs/lib/header.ts +15 -0
  65. package/scaffold/templates/nextjs/lib/page-policy.mjs +24 -0
  66. package/scaffold/templates/nextjs/lib/reviews.ts +6 -0
  67. package/scaffold/templates/nextjs/lib/seo.ts +19 -15
  68. package/scaffold/templates/nextjs/lib/signed-in-target.ts +11 -0
  69. package/scaffold/templates/nextjs/next.config.mjs +10 -1
  70. package/scaffold/templates/nextjs/package.json +26 -26
  71. package/scaffold/templates/astro/src/scripts/account-guard.ts +0 -22
@@ -4,7 +4,13 @@ import type {
4
4
  ProductSearchResult,
5
5
  ReviewsListResult,
6
6
  } from '@nymbalhq/sdk'
7
- import { DEFAULT_PRODUCT_SORT, ORDER_KEY_HEADER, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
7
+ import {
8
+ DEFAULT_PRODUCT_SORT,
9
+ ORDER_EMAIL_HEADER,
10
+ ORDER_KEY_HEADER,
11
+ PRODUCT_SORT_KEYS,
12
+ SHOPPER_ATTESTATION_HEADER,
13
+ } from '@nymbalhq/types'
8
14
  import type {
9
15
  AlertKind,
10
16
  Cart,
@@ -14,7 +20,9 @@ import type {
14
20
  StoreCapabilities,
15
21
  } from '@nymbalhq/types'
16
22
 
17
- const API_URL = import.meta.env.NYMBAL_API_URL ?? 'http://localhost:3001'
23
+ // Read at run time first: `nymbal start` gives the API's address when it starts the built storefront.
24
+ const API_URL =
25
+ process.env.NYMBAL_API_URL ?? import.meta.env.NYMBAL_API_URL ?? 'http://localhost:3001'
18
26
 
19
27
  export async function fetchProducts(params?: {
20
28
  limit?: number
@@ -106,22 +114,92 @@ export async function fetchCategories(): Promise<Category[]> {
106
114
  }
107
115
 
108
116
  /**
109
- * The order its key opens, `key` being the confirmation URL's `?key=`. Null on a 404, which the API answers alike for
110
- * an unknown number and for an order read without its key; rejects when the API fails, so a failed read is a 500 and
111
- * never a not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
117
+ * The order its key opens, `key` being the confirmation URL's `?key=`. `'expired'` when the API says the key has
118
+ * expired, so the page can ask for the order's email. Null on any other 404, which the API answers alike for an
119
+ * unknown number and an order read without its key; rejects when the API fails, so a failed read is a 500 and never a
120
+ * not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
112
121
  */
113
- export async function fetchOrder(orderNumber: string, key?: string): Promise<ShopperOrder | null> {
122
+ export async function fetchOrder(
123
+ orderNumber: string,
124
+ key?: string,
125
+ ): Promise<ShopperOrder | 'expired' | null> {
114
126
  const path = `/api/orders/${encodeURIComponent(orderNumber)}`
115
127
  const res = await fetch(`${API_URL}${path}`, {
116
128
  headers: key ? { [ORDER_KEY_HEADER]: key } : {},
117
129
  })
118
- if (res.status === 404) return null
130
+ if (res.status === 404) {
131
+ const refusal = (await res.json().catch(() => null)) as { error?: { code?: string } } | null
132
+ return refusal?.error?.code === 'orders.key_expired' ? 'expired' : null
133
+ }
134
+ if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
135
+ const envelope = (await res.json()) as { data?: ShopperOrder | null }
136
+ if (!envelope.data) throw new ApiUnavailableError(`GET ${path} answered no data`)
137
+ return envelope.data
138
+ }
139
+
140
+ // The two calls below serve the order page's forms only when its script did not run. From this server they count
141
+ // against the shopper's address only when they echo the attestation the API sent with the page (`shopperHeaders`).
142
+
143
+ /** The page request's `x-nymbal-shopper`, set by the API that forwarded it; `{}` when no API forwarded it. */
144
+ export function shopperHeaders(headers: Headers): Record<string, string> {
145
+ const value = headers.get(SHOPPER_ATTESTATION_HEADER)
146
+ return value === null ? {} : { [SHOPPER_ATTESTATION_HEADER]: value }
147
+ }
148
+
149
+ /**
150
+ * The order its expired key opens beside the order's email; `'not-found'` when the email does not open it (the API's
151
+ * unknown-number 404), `'limited'` on the API's 429; rejects on any other failure. The email goes in a header.
152
+ */
153
+ export async function openExpiredOrder(
154
+ orderNumber: string,
155
+ key: string,
156
+ email: string,
157
+ forwarded: Record<string, string> = {},
158
+ ): Promise<ShopperOrder | 'not-found' | 'limited'> {
159
+ const path = `/api/orders/${encodeURIComponent(orderNumber)}`
160
+ const res = await fetch(`${API_URL}${path}`, {
161
+ headers: { ...forwarded, [ORDER_KEY_HEADER]: key, [ORDER_EMAIL_HEADER]: email },
162
+ })
163
+ if (res.status === 404) return 'not-found'
164
+ if (res.status === 429) return 'limited'
119
165
  if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
120
166
  const envelope = (await res.json()) as { data?: ShopperOrder | null }
121
167
  if (!envelope.data) throw new ApiUnavailableError(`GET ${path} answered no data`)
122
168
  return envelope.data
123
169
  }
124
170
 
171
+ const CSRF_COOKIE = 'nymbal.csrf'
172
+ const CSRF_HEADER = 'x-csrf-token'
173
+
174
+ /**
175
+ * Asks the API to mail the order's link to the order's email; `'sent'` whatever matched (the API answers alike),
176
+ * `'limited'` on its 429; rejects on any other failure. The route is CSRF-checked, so the token `GET /api/csrf` gives
177
+ * goes back as both its cookie and its header.
178
+ */
179
+ export async function requestOrderLink(
180
+ orderNumber: string,
181
+ email: string,
182
+ forwarded: Record<string, string> = {},
183
+ ): Promise<'sent' | 'limited'> {
184
+ const issued = await fetch(`${API_URL}/api/csrf`, { headers: forwarded })
185
+ if (!issued.ok) throw new ApiUnavailableError(`GET /api/csrf answered ${issued.status}`)
186
+ const { token } = ((await issued.json()) as { data: { token: string } }).data
187
+ const res = await fetch(`${API_URL}/api/orders/link`, {
188
+ method: 'POST',
189
+ headers: {
190
+ ...forwarded,
191
+ 'content-type': 'application/json',
192
+ accept: 'application/json',
193
+ cookie: `${CSRF_COOKIE}=${token}`,
194
+ [CSRF_HEADER]: token,
195
+ },
196
+ body: JSON.stringify({ orderNumber, email }),
197
+ })
198
+ if (res.status === 202) return 'sent'
199
+ if (res.status === 429) return 'limited'
200
+ throw new ApiUnavailableError(`POST /api/orders/link answered ${res.status}`)
201
+ }
202
+
125
203
  export async function fetchReviews(productId: string): Promise<ReviewsListResult> {
126
204
  try {
127
205
  const res = await fetch(`${API_URL}/api/products/${encodeURIComponent(productId)}/reviews`)
@@ -179,6 +257,20 @@ export async function fetchCart(cookie: string | null): Promise<CartProjection |
179
257
  }
180
258
  }
181
259
 
260
+ /** Whether a request's Cookie header carries the shopper's `nymbal.cart` cookie. */
261
+ export function hasCartCookie(cookie: string | null): boolean {
262
+ return cartToken(cookie) !== null
263
+ }
264
+
265
+ /**
266
+ * The cart the cart page renders from: the empty cart without a `nymbal.cart` cookie, since the cart lives behind it,
267
+ * else `fetchCart`'s answer, where null (a failed read) is an unknown cart and never shown as empty.
268
+ */
269
+ export async function cartPageCart(cookie: string | null): Promise<CartProjection | null> {
270
+ if (!hasCartCookie(cookie)) return { items: [], subtotalMinor: 0, currency: '', itemCount: 0 }
271
+ return fetchCart(cookie)
272
+ }
273
+
182
274
  /** The search the search page shows for `q` (and its category), as the search store would hold it. */
183
275
  export async function fetchSearch(
184
276
  q: string,
@@ -198,10 +290,14 @@ export async function fetchSearch(
198
290
  }
199
291
 
200
292
  /** An alert link's token posted to the API from this server; null when the API refuses the link (404, or 400). */
201
- async function postAlertToken<T>(path: string, token: string): Promise<T | null> {
293
+ async function postAlertToken<T>(
294
+ path: string,
295
+ token: string,
296
+ forwarded: Record<string, string>,
297
+ ): Promise<T | null> {
202
298
  const res = await fetch(`${API_URL}${path}`, {
203
299
  method: 'POST',
204
- headers: { 'content-type': 'application/json', accept: 'application/json' },
300
+ headers: { ...forwarded, 'content-type': 'application/json', accept: 'application/json' },
205
301
  body: JSON.stringify({ token }),
206
302
  })
207
303
  if (res.status === 404 || res.status === 400) return null
@@ -215,13 +311,23 @@ export interface AlertConfirmation {
215
311
  }
216
312
 
217
313
  /** Confirms the alert a confirmation email's link names; null when the link is not valid; rejects when the API fails. */
218
- export function confirmAlert(token: string): Promise<AlertConfirmation | null> {
219
- return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token)
314
+ export function confirmAlert(
315
+ token: string,
316
+ forwarded: Record<string, string> = {},
317
+ ): Promise<AlertConfirmation | null> {
318
+ return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token, forwarded)
220
319
  }
221
320
 
222
321
  /** Stops the alert an email's unsubscribe link names; false when the link is not valid; rejects when the API fails. */
223
- export async function unsubscribeAlert(token: string): Promise<boolean> {
322
+ export async function unsubscribeAlert(
323
+ token: string,
324
+ forwarded: Record<string, string> = {},
325
+ ): Promise<boolean> {
224
326
  return (
225
- (await postAlertToken<{ status: 'unsubscribed' }>('/api/alerts/unsubscribe', token)) !== null
327
+ (await postAlertToken<{ status: 'unsubscribed' }>(
328
+ '/api/alerts/unsubscribe',
329
+ token,
330
+ forwarded,
331
+ )) !== null
226
332
  )
227
333
  }
@@ -1,15 +1,21 @@
1
1
  import '../elements/index.js'
2
- import { createNymbalClient } from '@nymbalhq/sdk'
2
+ import { createNymbalClient, resumeSession } from '@nymbalhq/sdk/core'
3
+ import '@nymbalhq/sdk/ns/cart'
4
+ // Every page's layout has the search bar: its store ships with the client, not in a chunk of its own.
5
+ import '@nymbalhq/sdk/ns/search'
3
6
  import { registerClient } from '@nymbalhq/web-components'
4
7
 
5
8
  const client = createNymbalClient({
6
9
  baseUrl: import.meta.env.PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
7
- tokenStorage: 'localStorage',
8
10
  })
9
11
 
12
+ // Before any element connects: every request the page sends while the session comes back waits for it, so none goes
13
+ // as a guest's. The auth store is not loaded for it: what reads the profile (the account pages, the review form)
14
+ // calls client.auth.restore(), which shares this refresh.
15
+ void resumeSession(client)
10
16
  registerClient(client)
11
17
  // A payment driver of the project's own goes here, before any element is defined: registerPaymentDriver(name, driver)
12
- // from @nymbalhq/sdk, named by the driver of the payments adapter's client half.
18
+ // from @nymbalhq/sdk/core, named by the driver of the payments adapter's client half.
13
19
  client.cart.load()
14
20
 
15
21
  export { client }
@@ -0,0 +1,24 @@
1
+ import { PAYMENT_SOURCES as PAY } from '@nymbalhq/web-components/payment-sources'
2
+
3
+ /**
4
+ * The content security policy every page answers. A script, style, font, frame or browser-side call from anywhere
5
+ * else (analytics, chat, a web font) is refused until it is named here; the payment step's come with its drivers.
6
+ * Scripts stay 'unsafe-inline': escaping is the defence against an injected inline script. `apiUrl` empty is the API
7
+ * on the page's own origin. `dev` adds nothing: the dev server loads nothing this refuses.
8
+ */
9
+ export function pagePolicy({ apiUrl }: { apiUrl: string; dev: boolean }): string {
10
+ const api = apiUrl === '' ? '' : ` ${new URL(apiUrl).origin}`
11
+ return [
12
+ "default-src 'self'",
13
+ `script-src 'self' 'unsafe-inline' ${PAY.script.join(' ')}`,
14
+ "style-src 'self' 'unsafe-inline'",
15
+ `img-src 'self'${api} data: blob: https:`,
16
+ "font-src 'self' data:",
17
+ `connect-src 'self'${api} ${PAY.connect.join(' ')}`,
18
+ `frame-src ${PAY.frame.join(' ')}`,
19
+ "frame-ancestors 'none'",
20
+ "base-uri 'self'",
21
+ "form-action 'self'",
22
+ "object-src 'none'",
23
+ ].join('; ')
24
+ }
@@ -0,0 +1,6 @@
1
+ import type { StoreCapabilities } from '@nymbalhq/sdk'
2
+
3
+ /** The review form only where the store's reviews adapter takes reviews on the site (`submit`). */
4
+ export function acceptsReviews(capabilities: StoreCapabilities | null | undefined): boolean {
5
+ return capabilities?.reviews?.capabilities.includes('submit') === true
6
+ }
@@ -1,4 +1,7 @@
1
1
  import type { DenormalisedProduct } from '@nymbalhq/sdk'
2
+ import { descriptionText } from '@nymbalhq/web-components/ssr'
3
+
4
+ export { descriptionText, serializeJsonLd } from '@nymbalhq/web-components/ssr'
2
5
 
3
6
  export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
4
7
  // The SDK types `media` as unknown: the projection stores either URLs or `{ url }` objects.
@@ -22,7 +25,7 @@ export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
22
25
  '@context': 'https://schema.org',
23
26
  '@type': 'Product',
24
27
  name: product.name,
25
- description: product.description,
28
+ description: descriptionText(product.description),
26
29
  image: images,
27
30
  sku,
28
31
  url: `${baseUrl}/product/${product.slug}`,
@@ -36,6 +39,16 @@ export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
36
39
  : 'https://schema.org/OutOfStock',
37
40
  offerCount: product.variants?.length ?? 1,
38
41
  },
42
+ // None without an approved review: a zero-count aggregateRating is invalid structured data.
43
+ ...(product.rating?.count && {
44
+ aggregateRating: {
45
+ '@type': 'AggregateRating',
46
+ ratingValue: product.rating.average,
47
+ reviewCount: product.rating.count,
48
+ bestRating: 5,
49
+ worstRating: 1,
50
+ },
51
+ }),
39
52
  }
40
53
  }
41
54
 
@@ -1,4 +1,7 @@
1
- /** What a handler resolves when it has sent the browser elsewhere (`location.href = …`): the form stays locked. */
1
+ /**
2
+ * What a handler resolves when it has sent the browser elsewhere (`location.href = …`): the form stays locked until the
3
+ * browser restores the page from its back/forward cache.
4
+ */
2
5
  export type SubmitOutcome = void | 'leaving'
3
6
 
4
7
  export type SubmitHandler = (event: SubmitEvent) => Promise<SubmitOutcome> | SubmitOutcome
@@ -15,6 +18,15 @@ function submitButtonOf(event: SubmitEvent, form: HTMLFormElement): HTMLButtonEl
15
18
  export function submitOnce(form: HTMLFormElement | null, handler: SubmitHandler): void {
16
19
  if (form === null) return
17
20
  let inFlight = false
21
+ /** Releases the lock a `'leaving'` resolve left; null while no such lock is held. */
22
+ let releaseLeaving: (() => void) | null = null
23
+
24
+ // Back to a page the browser kept in its back/forward cache: the navigation that locked the form left that page.
25
+ window.addEventListener('pageshow', (event) => {
26
+ if ((event as PageTransitionEvent).persisted !== true || releaseLeaving === null) return
27
+ releaseLeaving()
28
+ releaseLeaving = null
29
+ })
18
30
 
19
31
  form.addEventListener('submit', (event) => {
20
32
  event.preventDefault()
@@ -33,7 +45,8 @@ export function submitOnce(form: HTMLFormElement | null, handler: SubmitHandler)
33
45
  .then(() => handler(event as SubmitEvent))
34
46
  .then(
35
47
  (outcome) => {
36
- if (outcome !== 'leaving') release()
48
+ if (outcome === 'leaving') releaseLeaving = release
49
+ else release()
37
50
  },
38
51
  (reason: unknown) => {
39
52
  release()
@@ -1,4 +1,10 @@
1
1
  import { defineMiddleware } from 'astro:middleware'
2
+ import { pagePolicy } from './lib/page-policy'
3
+
4
+ const POLICY = pagePolicy({
5
+ apiUrl: import.meta.env.PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
6
+ dev: import.meta.env.DEV,
7
+ })
2
8
 
3
9
  /** Whether an `Accept-Encoding` value accepts gzip: a `gzip` entry (or, without one, `*`) with a q-value above 0. */
4
10
  function acceptsGzip(header: string): boolean {
@@ -13,21 +19,24 @@ function acceptsGzip(header: string): boolean {
13
19
  return star
14
20
  }
15
21
 
16
- // The standalone Node adapter compresses nothing, so a page's HTML (its styles inlined) went over the wire whole.
17
- // An HTML response is gzipped as a stream when the client accepts it; everything else passes through unchanged, and a
18
- // proxy that compresses sees the encoding and passes it on. Every HTML response varies on Accept-Encoding, the
19
- // uncompressed one included, so a cache keeps both forms apart.
22
+ // Every HTML response carries the page policy. The standalone Node adapter compresses nothing, so a page's HTML (its
23
+ // styles inlined) went over the wire whole. An HTML response is gzipped as a stream when the client accepts it;
24
+ // everything else passes through unchanged, and a proxy that compresses sees the encoding and passes it on. Every HTML
25
+ // response varies on Accept-Encoding, the uncompressed one included, so a cache keeps both forms apart.
20
26
  export const onRequest = defineMiddleware(async (context, next) => {
21
27
  const response = await next()
22
28
  const type = response.headers.get('content-type') ?? ''
23
- if (!type.startsWith('text/html') || response.headers.has('content-encoding')) return response
29
+ if (!type.startsWith('text/html')) return response
24
30
  const headers = new Headers(response.headers)
25
- headers.append('vary', 'Accept-Encoding')
31
+ headers.set('content-security-policy', POLICY)
26
32
  let body = response.body
27
- if (body !== null && acceptsGzip(context.request.headers.get('accept-encoding') ?? '')) {
28
- headers.set('content-encoding', 'gzip')
29
- headers.delete('content-length')
30
- body = body.pipeThrough(new CompressionStream('gzip'))
33
+ if (!response.headers.has('content-encoding')) {
34
+ headers.append('vary', 'Accept-Encoding')
35
+ if (body !== null && acceptsGzip(context.request.headers.get('accept-encoding') ?? '')) {
36
+ headers.set('content-encoding', 'gzip')
37
+ headers.delete('content-length')
38
+ body = body.pipeThrough(new CompressionStream('gzip'))
39
+ }
31
40
  }
32
41
  return new Response(body, {
33
42
  status: response.status,
@@ -41,6 +41,7 @@ import AccountLayout from '../../layouts/AccountLayout.astro'
41
41
  </AccountLayout>
42
42
 
43
43
  <script>
44
+ import '@nymbalhq/sdk/ns/auth'
44
45
  import { client } from '../../lib/client.js'
45
46
  import { formatDate } from '../../lib/format.js'
46
47
 
@@ -13,7 +13,7 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
13
13
  </AccountLayout>
14
14
 
15
15
  <script>
16
- import { NymbalApiError } from '@nymbalhq/sdk'
16
+ import { NymbalApiError } from '@nymbalhq/sdk/core'
17
17
  import { client } from '../../../lib/client.js'
18
18
  import { escapeHtml, formatPrice, formatDate } from '../../../lib/format.js'
19
19
  import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  import '../../styles/pages/error.css'
3
3
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
- import { confirmAlert } from '../../lib/api'
4
+ import { confirmAlert, shopperHeaders } from '../../lib/api'
5
5
 
6
6
  // Opening the link only shows the button, so a mail scanner that fetches it confirms nothing. The press posts the
7
7
  // token back here, and this server posts it on to the API, so the browser needs no CSRF cookie.
@@ -9,7 +9,8 @@ const pressed = Astro.request.method === 'POST'
9
9
  const token = pressed
10
10
  ? String((await Astro.request.formData()).get('token') ?? '')
11
11
  : (Astro.url.searchParams.get('token') ?? '')
12
- const confirmed = pressed && token !== '' ? await confirmAlert(token) : null
12
+ const confirmed =
13
+ pressed && token !== '' ? await confirmAlert(token, shopperHeaders(Astro.request.headers)) : null
13
14
  ---
14
15
 
15
16
  <BaseLayout title="Email alert | Nymbal" description="Confirm your email alert.">
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  import '../../styles/pages/error.css'
3
3
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
- import { unsubscribeAlert } from '../../lib/api'
4
+ import { shopperHeaders, unsubscribeAlert } from '../../lib/api'
5
5
 
6
6
  // Opening the link only shows the button, so a mail scanner that fetches it stops nothing. The press posts the token
7
7
  // back here, and this server posts it on to the API, which holds no CSRF cookie.
@@ -9,7 +9,8 @@ const pressed = Astro.request.method === 'POST'
9
9
  const token = pressed
10
10
  ? String((await Astro.request.formData()).get('token') ?? '')
11
11
  : (Astro.url.searchParams.get('token') ?? '')
12
- const stopped = pressed && token !== '' ? await unsubscribeAlert(token) : false
12
+ const stopped =
13
+ pressed && token !== '' ? await unsubscribeAlert(token, shopperHeaders(Astro.request.headers)) : false
13
14
  ---
14
15
 
15
16
  <BaseLayout title="Back-in-stock alert | Nymbal" description="Stop a back-in-stock alert.">
@@ -1,17 +1,31 @@
1
1
  ---
2
2
  import NymbalElement from '@nymbalhq/web-components/astro'
3
3
  import BaseLayout from '../layouts/BaseLayout.astro'
4
- import { fetchCart } from '../lib/api'
4
+ import { cartPageCart, hasCartCookie } from '../lib/api'
5
5
 
6
- const cart = await fetchCart(Astro.request.headers.get('cookie'))
6
+ // The shopper's own cart: no shared cache may keep it for the next visitor.
7
+ Astro.response.headers.set('Cache-Control', 'no-store')
8
+
9
+ const cookie = Astro.request.headers.get('cookie')
10
+ const cart = await cartPageCart(cookie)
11
+ // Without the cookie this server cannot tell an empty cart from one the browser holds for an API on another host, so
12
+ // the empty cart is for a browser without JavaScript; with it, the element's own read decides.
13
+ const noCookie = !hasCartCookie(cookie)
14
+ const shown = noCookie ? null : cart
7
15
  ---
8
16
 
9
- <BaseLayout title="Your Cart | Nymbal" description="Review the items in your cart." cart={cart}>
17
+ <BaseLayout title="Your Cart | Nymbal" description="Review the items in your cart." cart={shown}>
10
18
  <div class="container section" data-testid="cart-page">
11
19
  <NymbalElement
12
20
  tag="nymbal-cart-page"
13
- attributes={cart === null ? {} : { cart: JSON.stringify(cart) }}
21
+ attributes={shown === null ? {} : { cart: JSON.stringify(shown) }}
14
22
  />
23
+ {noCookie && (
24
+ <noscript>
25
+ <style is:inline>nymbal-cart-page:not([cart]) { display: none; }</style>
26
+ <NymbalElement tag="nymbal-cart-page" attributes={{ cart: JSON.stringify(cart) }} />
27
+ </noscript>
28
+ )}
15
29
  </div>
16
30
  </BaseLayout>
17
31
 
@@ -3,6 +3,9 @@ import NymbalElement from '@nymbalhq/web-components/astro'
3
3
  import BaseLayout from '../layouts/BaseLayout.astro'
4
4
  import { fetchCapabilities, fetchCart } from '../lib/api'
5
5
 
6
+ // The shopper's own cart and checkout: no shared cache may keep them for the next visitor.
7
+ Astro.response.headers.set('Cache-Control', 'no-store')
8
+
6
9
  const [capabilities, cart] = await Promise.all([
7
10
  fetchCapabilities(),
8
11
  fetchCart(Astro.request.headers.get('cookie')),
@@ -36,9 +39,13 @@ const paymentElement = `<nymbal-payment-element slot="payment" data-testid="paym
36
39
  NymbalPaymentElement.define()
37
40
  NymbalCheckout.define()
38
41
 
39
- // The element places the order; the page only goes to it.
42
+ // The element places the order; the page only goes to it. A guest's order opens with its key; a signed-in
43
+ // shopper's checkout answers none, and their account is the order's home.
40
44
  document.addEventListener('nymbal:checkout:placed', (event) => {
41
45
  const { orderNumber, orderKey } = (event as CustomEvent<{ orderNumber: string; orderKey?: string }>).detail
42
- window.location.href = `/order/${encodeURIComponent(orderNumber)}${orderKey ? `?key=${encodeURIComponent(orderKey)}` : ''}`
46
+ const number = encodeURIComponent(orderNumber)
47
+ window.location.href = orderKey
48
+ ? `/order/${number}?key=${encodeURIComponent(orderKey)}`
49
+ : `/account/orders/${number}`
43
50
  })
44
51
  </script>