create-nymbal-app 0.7.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 (60) 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 +40 -10
  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/package.json +25 -25
  10. package/scaffold/templates/astro/src/layouts/AccountLayout.astro +2 -6
  11. package/scaffold/templates/astro/src/layouts/BaseLayout.astro +2 -1
  12. package/scaffold/templates/astro/src/lib/api.ts +107 -11
  13. package/scaffold/templates/astro/src/lib/client.ts +5 -2
  14. package/scaffold/templates/astro/src/lib/page-policy.ts +24 -0
  15. package/scaffold/templates/astro/src/lib/reviews.ts +6 -0
  16. package/scaffold/templates/astro/src/lib/seo.ts +14 -1
  17. package/scaffold/templates/astro/src/lib/submit-once.ts +15 -2
  18. package/scaffold/templates/astro/src/middleware.ts +19 -10
  19. package/scaffold/templates/astro/src/pages/alerts/confirm.astro +3 -2
  20. package/scaffold/templates/astro/src/pages/alerts/unsubscribe.astro +3 -2
  21. package/scaffold/templates/astro/src/pages/cart.astro +15 -4
  22. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +41 -8
  23. package/scaffold/templates/astro/src/pages/product/[slug].astro +10 -4
  24. package/scaffold/templates/astro/src/pages/products/index.astro +2 -1
  25. package/scaffold/templates/astro/src/scripts/order-access.ts +28 -1
  26. package/scaffold/templates/astro/src/scripts/signed-in-redirect.ts +14 -1
  27. package/scaffold/templates/astro/src/styles/global.css +3 -0
  28. package/scaffold/templates/astro/src/styles/pages/pdp.css +7 -4
  29. package/scaffold/templates/nextjs/README.md +49 -15
  30. package/scaffold/templates/nextjs/_dot.env.example +3 -1
  31. package/scaffold/templates/nextjs/app/(catalog)/home/[key]/page.tsx +2 -2
  32. package/scaffold/templates/nextjs/app/(catalog)/product/[slug]/page.tsx +24 -20
  33. package/scaffold/templates/nextjs/app/(catalog)/products/page.tsx +8 -5
  34. package/scaffold/templates/nextjs/app/(catalog)/search/SearchView.tsx +1 -1
  35. package/scaffold/templates/nextjs/app/(shopper)/account/login/LoginView.tsx +4 -4
  36. package/scaffold/templates/nextjs/app/(shopper)/account/login/page.tsx +3 -1
  37. package/scaffold/templates/nextjs/app/(shopper)/alerts/actions.ts +6 -3
  38. package/scaffold/templates/nextjs/app/(shopper)/cart/page.tsx +21 -5
  39. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderEmailPrompt.tsx +27 -5
  40. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderLinkForm.tsx +20 -4
  41. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderNotFound.tsx +9 -4
  42. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OwnerRedirect.tsx +48 -0
  43. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/actions.ts +56 -0
  44. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/page.tsx +3 -3
  45. package/scaffold/templates/nextjs/app/error.tsx +9 -3
  46. package/scaffold/templates/nextjs/app/globals.css +3 -0
  47. package/scaffold/templates/nextjs/components/client/AuthGuard.tsx +2 -2
  48. package/scaffold/templates/nextjs/components/client/NymbalSetup.tsx +1 -2
  49. package/scaffold/templates/nextjs/components/server/Header.tsx +5 -2
  50. package/scaffold/templates/nextjs/lib/api.ts +109 -11
  51. package/scaffold/templates/nextjs/lib/chrome.ts +9 -5
  52. package/scaffold/templates/nextjs/lib/client.ts +5 -7
  53. package/scaffold/templates/nextjs/lib/header.ts +15 -0
  54. package/scaffold/templates/nextjs/lib/page-policy.mjs +24 -0
  55. package/scaffold/templates/nextjs/lib/reviews.ts +6 -0
  56. package/scaffold/templates/nextjs/lib/seo.ts +19 -15
  57. package/scaffold/templates/nextjs/lib/signed-in-target.ts +11 -0
  58. package/scaffold/templates/nextjs/next.config.mjs +10 -1
  59. package/scaffold/templates/nextjs/package.json +26 -26
  60. package/scaffold/templates/astro/src/scripts/account-guard.ts +0 -23
@@ -9,13 +9,13 @@ interface OrderPageProps {
9
9
  searchParams: Promise<{ key?: string | string[] }>
10
10
  }
11
11
 
12
- // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: the meta
13
- // tag here, and the header next.config.mjs sets on every /order/<n> response, the not-found render's too.
12
+ // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told more than its origin:
13
+ // the meta tag here, and the header next.config.mjs sets on every /order/<n> response, the not-found render's too.
14
14
  export async function generateMetadata({ params }: OrderPageProps): Promise<Metadata> {
15
15
  const { orderNumber } = await params
16
16
  return {
17
17
  title: `Order ${orderNumber}`,
18
- referrer: 'no-referrer',
18
+ referrer: 'strict-origin',
19
19
  }
20
20
  }
21
21
 
@@ -5,10 +5,11 @@ import styles from '@/styles/pages/error.module.css'
5
5
 
6
6
  interface ErrorProps {
7
7
  error: Error & { digest?: string }
8
- reset: () => void
8
+ /** Fetches the failed segment again and renders it; `reset` would render the failed payload again. */
9
+ retry: () => void
9
10
  }
10
11
 
11
- export default function ErrorPage({ error: _error, reset }: ErrorProps) {
12
+ export default function ErrorPage({ error: _error, retry }: ErrorProps) {
12
13
  return (
13
14
  <main id="main" className={styles.page}>
14
15
  <div className={styles.wrapper}>
@@ -35,7 +36,12 @@ export default function ErrorPage({ error: _error, reset }: ErrorProps) {
35
36
  <Link href="/" className={styles.homeLink}>
36
37
  Go Home
37
38
  </Link>
38
- <button type="button" className={styles.retryButton} onClick={reset}>
39
+ <button
40
+ type="button"
41
+ className={styles.retryButton}
42
+ onClick={() => retry()}
43
+ data-testid="error-retry"
44
+ >
39
45
  Try Again
40
46
  </button>
41
47
  </div>
@@ -18,6 +18,9 @@ html {
18
18
  -moz-text-size-adjust: 100%;
19
19
  text-size-adjust: 100%;
20
20
  scroll-behavior: smooth;
21
+ /* What is scrolled to the top edge (a fragment, scrollIntoView, keyboard focus) lands below the sticky site header:
22
+ at least its height at every width, with room for a phone header that also holds the mini-cart. */
23
+ scroll-padding-top: 5.5rem;
21
24
  }
22
25
 
23
26
  body {
@@ -11,8 +11,8 @@ export function AuthGuard({ children }: { children: ReactNode }) {
11
11
  const { isAuthenticated, loading } = useAuth()
12
12
  const router = useRouter()
13
13
  const pathname = usePathname()
14
- // A stored token is only known to be valid once its profile has loaded; redirecting before that would sign a
15
- // reloading shopper out.
14
+ // The shopper is only known to be signed out once the page load's session restore has settled; redirecting before
15
+ // that would sign a reloading shopper out.
16
16
  const [restored, setRestored] = useState(false)
17
17
 
18
18
  const isPublicAuthPath = PUBLIC_AUTH_PATHS.includes(pathname)
@@ -10,7 +10,7 @@ import { NymbalMiniCart } from '@nymbalhq/web-components/elements/nymbal-mini-ca
10
10
  import { NymbalSearchBar } from '@nymbalhq/web-components/elements/nymbal-search-bar'
11
11
  import { NymbalSiteFooter } from '@nymbalhq/web-components/elements/nymbal-site-footer'
12
12
  import { NymbalSiteHeader } from '@nymbalhq/web-components/elements/nymbal-site-header'
13
- import { getNymbalClient, restoreSession } from '@/lib/client'
13
+ import { getNymbalClient } from '@/lib/client'
14
14
 
15
15
  export function NymbalSetup({ children }: { children: ReactNode }) {
16
16
  const client = getNymbalClient()
@@ -29,7 +29,6 @@ export function NymbalSetup({ children }: { children: ReactNode }) {
29
29
  NymbalSearchBar.define()
30
30
  NymbalMiniCart.define()
31
31
  NymbalCartDrawer.define()
32
- void restoreSession()
33
32
  initialized.current = true
34
33
  }
35
34
  }, [client])
@@ -2,7 +2,7 @@ import { headers } from 'next/headers'
2
2
  import { SiteHeader } from '@/components/client/elements'
3
3
  import { fetchCart } from '@/lib/api'
4
4
  import { HEADER } from '@/lib/chrome'
5
- import { canSearch, siteHeader } from '@/lib/header'
5
+ import { canSearch, shopperCanSearch, siteHeader } from '@/lib/header'
6
6
  import { renderNymbal } from '@/lib/render'
7
7
 
8
8
  function HeaderElement({ header }: { header: ReturnType<typeof siteHeader> }) {
@@ -24,7 +24,10 @@ function HeaderElement({ header }: { header: ReturnType<typeof siteHeader> }) {
24
24
  */
25
25
  export async function Header({ shopper = false }: { shopper?: boolean }) {
26
26
  const cookie = shopper ? (await headers()).get('cookie') : null
27
- const [search, cart] = await Promise.all([canSearch(), shopper ? fetchCart(cookie) : null])
27
+ const [search, cart] = await Promise.all([
28
+ shopper ? shopperCanSearch() : canSearch(),
29
+ shopper ? fetchCart(cookie) : null,
30
+ ])
28
31
  return <HeaderElement header={siteHeader(search, cart?.itemCount)} />
29
32
  }
30
33
 
@@ -6,7 +6,13 @@ import type {
6
6
  ProductSearchResult,
7
7
  ReviewsListResult,
8
8
  } from '@nymbalhq/sdk'
9
- import { DEFAULT_PRODUCT_SORT, ORDER_KEY_HEADER, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
9
+ import {
10
+ DEFAULT_PRODUCT_SORT,
11
+ ORDER_EMAIL_HEADER,
12
+ ORDER_KEY_HEADER,
13
+ PRODUCT_SORT_KEYS,
14
+ SHOPPER_ATTESTATION_HEADER,
15
+ } from '@nymbalhq/types'
10
16
  import type {
11
17
  AlertKind,
12
18
  Cart,
@@ -121,10 +127,9 @@ export async function fetchCategories(): Promise<Category[]> {
121
127
 
122
128
  /**
123
129
  * The order its key opens, `key` being the confirmation URL's `?key=`. `'expired'` when the API says the key has
124
- * expired, so the page can ask for the order's email, which the browser sends itself: a read from this server would
125
- * count every shopper's tries under the server's one address. Null on any other 404, which the API answers alike for
126
- * an unknown number and an order read without its key; rejects when the API fails, so the order page's failed read is
127
- * a 500 and never a not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
130
+ * expired, so the page can ask for the order's email. Null on any other 404, which the API answers alike for an
131
+ * unknown number and an order read without its key; rejects when the API fails, so the order page's failed read is a
132
+ * 500 and never a not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
128
133
  */
129
134
  export async function loadOrder(
130
135
  orderNumber: string,
@@ -145,6 +150,71 @@ export async function loadOrder(
145
150
  return envelope.data
146
151
  }
147
152
 
153
+ // The two calls below serve the order page's forms only when its script did not run. From this server they count
154
+ // against the shopper's address only when they echo the attestation the API sent with the page (`shopperHeaders`).
155
+
156
+ /** The page request's `x-nymbal-shopper`, set by the API that forwarded it; `{}` when no API forwarded it. */
157
+ export function shopperHeaders(headers: Headers): Record<string, string> {
158
+ const value = headers.get(SHOPPER_ATTESTATION_HEADER)
159
+ return value === null ? {} : { [SHOPPER_ATTESTATION_HEADER]: value }
160
+ }
161
+
162
+ /**
163
+ * The order its expired key opens beside the order's email; `'not-found'` when the email does not open it (the API's
164
+ * unknown-number 404), `'limited'` on the API's 429; rejects on any other failure. The email goes in a header.
165
+ */
166
+ export async function openExpiredOrder(
167
+ orderNumber: string,
168
+ key: string,
169
+ email: string,
170
+ forwarded: Record<string, string> = {},
171
+ ): Promise<ShopperOrder | 'not-found' | 'limited'> {
172
+ const url = `${API_URL}/api/orders/${encodeURIComponent(orderNumber)}`
173
+ const res = await fetch(url, {
174
+ cache: 'no-store',
175
+ headers: { ...forwarded, [ORDER_KEY_HEADER]: key, [ORDER_EMAIL_HEADER]: email },
176
+ })
177
+ if (res.status === 404) return 'not-found'
178
+ if (res.status === 429) return 'limited'
179
+ if (!res.ok) throw new Error(`[api] GET ${url} answered ${res.status}`)
180
+ const envelope = (await res.json()) as { data?: ShopperOrder | null }
181
+ if (!envelope.data) throw new Error(`[api] GET ${url} answered no data`)
182
+ return envelope.data
183
+ }
184
+
185
+ const CSRF_COOKIE = 'nymbal.csrf'
186
+ const CSRF_HEADER = 'x-csrf-token'
187
+
188
+ /**
189
+ * Asks the API to mail the order's link to the order's email; `'sent'` whatever matched (the API answers alike),
190
+ * `'limited'` on its 429; rejects on any other failure. The route is CSRF-checked, so the token `GET /api/csrf` gives
191
+ * goes back as both its cookie and its header.
192
+ */
193
+ export async function requestOrderLink(
194
+ orderNumber: string,
195
+ email: string,
196
+ forwarded: Record<string, string> = {},
197
+ ): Promise<'sent' | 'limited'> {
198
+ const issued = await fetch(`${API_URL}/api/csrf`, { cache: 'no-store', headers: forwarded })
199
+ if (!issued.ok) throw new Error(`[api] GET /api/csrf answered ${issued.status}`)
200
+ const { token } = ((await issued.json()) as { data: { token: string } }).data
201
+ const res = await fetch(`${API_URL}/api/orders/link`, {
202
+ method: 'POST',
203
+ headers: {
204
+ ...forwarded,
205
+ 'content-type': 'application/json',
206
+ accept: 'application/json',
207
+ cookie: `${CSRF_COOKIE}=${token}`,
208
+ [CSRF_HEADER]: token,
209
+ },
210
+ body: JSON.stringify({ orderNumber, email }),
211
+ cache: 'no-store',
212
+ })
213
+ if (res.status === 202) return 'sent'
214
+ if (res.status === 429) return 'limited'
215
+ throw new Error(`[api] POST /api/orders/link answered ${res.status}`)
216
+ }
217
+
148
218
  export async function fetchReviews(productId: string): Promise<ReviewsListResult> {
149
219
  const res = await catalogFetch(
150
220
  `${API_URL}/api/products/${encodeURIComponent(productId)}/reviews`,
@@ -203,6 +273,20 @@ export const fetchCart = cache(async (cookie: string | null): Promise<CartProjec
203
273
  }
204
274
  })
205
275
 
276
+ /** Whether a request's Cookie header carries the shopper's `nymbal.cart` cookie. */
277
+ export function hasCartCookie(cookie: string | null): boolean {
278
+ return cartToken(cookie) !== null
279
+ }
280
+
281
+ /**
282
+ * The cart the cart page renders from: the empty cart without a `nymbal.cart` cookie, since the cart lives behind it,
283
+ * else `fetchCart`'s answer, where null (a failed read) is an unknown cart and never shown as empty.
284
+ */
285
+ export async function cartPageCart(cookie: string | null): Promise<CartProjection | null> {
286
+ if (!hasCartCookie(cookie)) return { items: [], subtotalMinor: 0, currency: '', itemCount: 0 }
287
+ return fetchCart(cookie)
288
+ }
289
+
206
290
  /** The search the search page shows for `q` (and its category), as the search store would hold it. */
207
291
  export async function fetchSearch(
208
292
  q: string,
@@ -223,10 +307,14 @@ export async function fetchSearch(
223
307
  }
224
308
 
225
309
  /** An alert link's token posted to the API from this server; null when the API refuses the link (404, or 400). */
226
- async function postAlertToken<T>(path: string, token: string): Promise<T | null> {
310
+ async function postAlertToken<T>(
311
+ path: string,
312
+ token: string,
313
+ forwarded: Record<string, string>,
314
+ ): Promise<T | null> {
227
315
  const res = await fetch(`${API_URL}${path}`, {
228
316
  method: 'POST',
229
- headers: { 'content-type': 'application/json', accept: 'application/json' },
317
+ headers: { ...forwarded, 'content-type': 'application/json', accept: 'application/json' },
230
318
  body: JSON.stringify({ token }),
231
319
  cache: 'no-store',
232
320
  })
@@ -241,13 +329,23 @@ export interface AlertConfirmation {
241
329
  }
242
330
 
243
331
  /** Confirms the alert a confirmation email's link names; null when the link is not valid; rejects when the API fails. */
244
- export function confirmAlert(token: string): Promise<AlertConfirmation | null> {
245
- return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token)
332
+ export function confirmAlert(
333
+ token: string,
334
+ forwarded: Record<string, string> = {},
335
+ ): Promise<AlertConfirmation | null> {
336
+ return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token, forwarded)
246
337
  }
247
338
 
248
339
  /** Stops the alert an email's unsubscribe link names; false when the link is not valid; rejects when the API fails. */
249
- export async function unsubscribeAlert(token: string): Promise<boolean> {
340
+ export async function unsubscribeAlert(
341
+ token: string,
342
+ forwarded: Record<string, string> = {},
343
+ ): Promise<boolean> {
250
344
  return (
251
- (await postAlertToken<{ status: 'unsubscribed' }>('/api/alerts/unsubscribe', token)) !== null
345
+ (await postAlertToken<{ status: 'unsubscribed' }>(
346
+ '/api/alerts/unsubscribe',
347
+ token,
348
+ forwarded,
349
+ )) !== null
252
350
  )
253
351
  }
@@ -4,9 +4,11 @@ export const HEADER = {
4
4
  logo: 'Nymbal',
5
5
  accountHref: '/account',
6
6
  links: [
7
- { href: '/products', label: 'Shop' },
8
- { href: '/products?category=new', label: 'New Arrivals' },
9
- { href: '/products?category=sale', label: 'Sale' },
7
+ { href: '/category/apparel', label: 'Apparel' },
8
+ { href: '/category/home', label: 'Home' },
9
+ { href: '/category/electronics', label: 'Electronics' },
10
+ { href: '/category/books', label: 'Books' },
11
+ { href: '/products', label: 'All Products' },
10
12
  ],
11
13
  }
12
14
 
@@ -15,8 +17,10 @@ export const FOOTER_COLUMNS = [
15
17
  heading: 'Shop',
16
18
  links: [
17
19
  { href: '/products', label: 'All Products' },
18
- { href: '/products?category=new', label: 'New Arrivals' },
19
- { href: '/products?category=sale', label: 'Sale' },
20
+ { href: '/category/apparel', label: 'Apparel' },
21
+ { href: '/category/home', label: 'Home' },
22
+ { href: '/category/electronics', label: 'Electronics' },
23
+ { href: '/category/books', label: 'Books' },
20
24
  ],
21
25
  },
22
26
  {
@@ -4,23 +4,21 @@ import { createNymbalClient, type NymbalClient } from '@nymbalhq/sdk'
4
4
  // registerPaymentDriver(name, driver) from @nymbalhq/sdk, named by the driver of the payments adapter's client half.
5
5
 
6
6
  let instance: NymbalClient | null = null
7
- let restoring: Promise<void> | null = null
7
+ let restoring: Promise<void> = Promise.resolve()
8
8
 
9
+ /** In the browser, the first call starts restoring the session: requests sent meanwhile wait for it. */
9
10
  export function getNymbalClient(): NymbalClient {
10
11
  if (!instance) {
11
12
  instance = createNymbalClient({
12
13
  baseUrl: process.env.NEXT_PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
13
- tokenStorage: 'localStorage',
14
14
  })
15
+ if (typeof window !== 'undefined') restoring = instance.auth.restore()
15
16
  }
16
17
  return instance
17
18
  }
18
19
 
19
- /**
20
- * Loads the profile for a stored token once per page load, so a reload keeps a signed-in shopper signed in.
21
- * The account guard awaits the same promise before deciding to redirect.
22
- */
20
+ /** The page load's session restore, which the account guard awaits before deciding to redirect. */
23
21
  export function restoreSession(): Promise<void> {
24
- restoring ??= getNymbalClient().auth.loadProfile()
22
+ getNymbalClient()
25
23
  return restoring
26
24
  }
@@ -1,3 +1,4 @@
1
+ import { unstable_rethrow } from 'next/navigation'
1
2
  import { fetchCapabilities } from '@/lib/api'
2
3
  import { HEADER } from '@/lib/chrome'
3
4
  import { renderElement } from '@/lib/render'
@@ -37,3 +38,17 @@ export async function canSearch(): Promise<boolean> {
37
38
  const capabilities = await fetchCapabilities()
38
39
  return capabilities?.search.capabilities.includes('search') ?? false
39
40
  }
41
+
42
+ /**
43
+ * Whether a shopper's page shows the search bar: no bar when the capabilities read fails. A shopper's page renders per
44
+ * request, so the fallback is never cached; a catalog page's header uses `canSearch`, which rejects instead.
45
+ */
46
+ export async function shopperCanSearch(): Promise<boolean> {
47
+ try {
48
+ return await canSearch()
49
+ } catch (err) {
50
+ unstable_rethrow(err)
51
+ console.error('[header] capabilities read failed; no search bar', err)
52
+ return false
53
+ }
54
+ }
@@ -0,0 +1,24 @@
1
+ import { PAYMENT_SOURCES as PAY } from '@nymbalhq/web-components/payment-sources'
2
+
3
+ /**
4
+ * Every page's content security policy: a script, style, frame or call from elsewhere is refused until it is named here
5
+ * (the payment step's come with its drivers). Scripts keep 'unsafe-inline', as `/` and the product page are cached
6
+ * whole. `apiUrl` empty is the API on the page's own origin; `dev` adds the 'unsafe-eval' React's dev build needs.
7
+ * @param {{ apiUrl: string; dev: boolean }} options
8
+ */
9
+ export function pagePolicy({ apiUrl, dev }) {
10
+ const api = apiUrl === '' ? '' : ` ${new URL(apiUrl).origin}`
11
+ return [
12
+ "default-src 'self'",
13
+ `script-src 'self' 'unsafe-inline' ${PAY.script.join(' ')}${dev ? " 'unsafe-eval'" : ''}`,
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 interface BreadcrumbItem {
4
7
  name: string
@@ -9,8 +12,9 @@ export function productJsonLd(
9
12
  product: DenormalisedProduct,
10
13
  baseUrl: string,
11
14
  ): Record<string, unknown> {
12
- const url = `${baseUrl}/products/${product.slug}`
15
+ const url = `${baseUrl}/product/${product.slug}`
13
16
  const priceCurrency = product.currency ?? 'GBP'
17
+ const availability = `https://schema.org/${product.inStock ? 'InStock' : 'OutOfStock'}`
14
18
 
15
19
  const offers: Record<string, unknown> =
16
20
  product.variants.length > 1 && product.priceRange
@@ -20,17 +24,13 @@ export function productJsonLd(
20
24
  highPrice: (product.priceRange.maxMinor / 100).toFixed(2),
21
25
  priceCurrency,
22
26
  offerCount: product.variants.length,
23
- availability: product.inStock
24
- ? 'https://schema.org/InStock'
25
- : 'https://schema.org/OutOfStock',
27
+ availability,
26
28
  }
27
29
  : {
28
30
  '@type': 'Offer',
29
31
  price: ((product.priceMinor ?? 0) / 100).toFixed(2),
30
32
  priceCurrency,
31
- availability: product.inStock
32
- ? 'https://schema.org/InStock'
33
- : 'https://schema.org/OutOfStock',
33
+ availability,
34
34
  url,
35
35
  }
36
36
 
@@ -38,16 +38,23 @@ export function productJsonLd(
38
38
  '@context': 'https://schema.org',
39
39
  '@type': 'Product',
40
40
  name: product.name,
41
- description: product.description,
41
+ description: descriptionText(product.description),
42
42
  url,
43
43
  sku: product.variants[0]?.sku ?? product.id,
44
44
  offers,
45
+ ...(product.rating?.count && {
46
+ aggregateRating: {
47
+ '@type': 'AggregateRating',
48
+ ratingValue: product.rating.average,
49
+ reviewCount: product.rating.count,
50
+ bestRating: 5,
51
+ worstRating: 1,
52
+ },
53
+ }),
45
54
  }
46
55
  }
47
56
 
48
- export function breadcrumbJsonLd(
49
- items: BreadcrumbItem[],
50
- ): Record<string, unknown> {
57
+ export function breadcrumbJsonLd(items: BreadcrumbItem[]): Record<string, unknown> {
51
58
  return {
52
59
  '@context': 'https://schema.org',
53
60
  '@type': 'BreadcrumbList',
@@ -60,10 +67,7 @@ export function breadcrumbJsonLd(
60
67
  }
61
68
  }
62
69
 
63
- export function organizationJsonLd(
64
- storeName: string,
65
- url: string,
66
- ): Record<string, unknown> {
70
+ export function organizationJsonLd(storeName: string, url: string): Record<string, unknown> {
67
71
  return {
68
72
  '@context': 'https://schema.org',
69
73
  '@type': 'Organization',
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Where to go once signed in: the decoded `redirect` as the URL parser reads it against `origin`, if both are a path
3
+ * on `origin` (one leading `/`, and `/.//host` reads as `//host`) with no control character; else /account.
4
+ */
5
+ export function signedInTarget(redirect: string | null, origin: string): string {
6
+ if (redirect === null || !/^\/(?![/\\])/.test(redirect)) return '/account'
7
+ if ([...redirect].some((c) => c < ' ' || c === '\x7f')) return '/account'
8
+ const url = new URL(redirect, origin)
9
+ const target = url.pathname + url.search + url.hash
10
+ return /^\/(?![/\\])/.test(target) && url.origin === new URL(origin).origin ? target : '/account'
11
+ }
@@ -1,5 +1,6 @@
1
1
  import { relative } from 'node:path'
2
2
  import { fileURLToPath } from 'node:url'
3
+ import { pagePolicy } from './lib/page-policy.mjs'
3
4
 
4
5
  // NYMBAL_ELEMENTS_ENTRY (an absolute path) is the store's elements entry in place of elements/index.ts, on the server
5
6
  // and in the browser (the E2E override fixture).
@@ -32,11 +33,19 @@ const nextConfig = {
32
33
  }
33
34
  },
34
35
  // The order page's URL carries the order's key; no request from it, nor from its not-found render, may refer it on.
36
+ // `strict-origin` sends the origin alone: a form posted to the page's server action keeps its Origin, which Next
37
+ // checks, where `no-referrer` would send `Origin: null` and the action would be refused.
35
38
  async headers() {
39
+ const policy = pagePolicy({
40
+ apiUrl: process.env.NEXT_PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
41
+ dev: process.env.NODE_ENV !== 'production',
42
+ })
36
43
  return [
44
+ // Only the policy: a Referrer-Policy here would replace the order page's.
45
+ { source: '/:path*', headers: [{ key: 'Content-Security-Policy', value: policy }] },
37
46
  {
38
47
  source: '/order/:orderNumber',
39
- headers: [{ key: 'Referrer-Policy', value: 'no-referrer' }],
48
+ headers: [{ key: 'Referrer-Policy', value: 'strict-origin' }],
40
49
  },
41
50
  ]
42
51
  },
@@ -17,17 +17,17 @@
17
17
  "seed": "nymbal seed"
18
18
  },
19
19
  "dependencies": {
20
- "nymbal": "1.5.0",
21
- "@nymbalhq/config": "1.5.0",
22
- "@nymbalhq/platform": "1.5.0",
23
- "@nymbalhq/stack": "1.5.0",
20
+ "nymbal": "1.6.0",
21
+ "@nymbalhq/config": "1.6.0",
22
+ "@nymbalhq/platform": "1.6.0",
23
+ "@nymbalhq/stack": "1.6.0",
24
24
  "next": "^16.4.2",
25
25
  "react": "^19.3.1",
26
26
  "react-dom": "^19.3.1",
27
- "@nymbalhq/sdk": "1.5.0",
28
- "@nymbalhq/react": "1.5.0",
29
- "@nymbalhq/web-components": "1.5.0",
30
- "@nymbalhq/types": "1.5.0"
27
+ "@nymbalhq/sdk": "1.6.0",
28
+ "@nymbalhq/react": "1.6.0",
29
+ "@nymbalhq/web-components": "1.6.0",
30
+ "@nymbalhq/types": "1.6.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^22.9.0",
@@ -38,26 +38,26 @@
38
38
  },
39
39
  "pnpm": {
40
40
  "overrides": {
41
- "nymbal": "1.5.0",
42
- "@nymbalhq/config": "1.5.0",
43
- "@nymbalhq/http": "1.5.0",
44
- "@nymbalhq/platform": "1.5.0",
45
- "@nymbalhq/react": "1.5.0",
46
- "@nymbalhq/sdk": "1.5.0",
47
- "@nymbalhq/stack": "1.5.0",
48
- "@nymbalhq/types": "1.5.0",
49
- "@nymbalhq/web-components": "1.5.0"
41
+ "nymbal": "1.6.0",
42
+ "@nymbalhq/config": "1.6.0",
43
+ "@nymbalhq/http": "1.6.0",
44
+ "@nymbalhq/platform": "1.6.0",
45
+ "@nymbalhq/react": "1.6.0",
46
+ "@nymbalhq/sdk": "1.6.0",
47
+ "@nymbalhq/stack": "1.6.0",
48
+ "@nymbalhq/types": "1.6.0",
49
+ "@nymbalhq/web-components": "1.6.0"
50
50
  }
51
51
  },
52
52
  "overrides": {
53
- "nymbal": "1.5.0",
54
- "@nymbalhq/config": "1.5.0",
55
- "@nymbalhq/http": "1.5.0",
56
- "@nymbalhq/platform": "1.5.0",
57
- "@nymbalhq/react": "1.5.0",
58
- "@nymbalhq/sdk": "1.5.0",
59
- "@nymbalhq/stack": "1.5.0",
60
- "@nymbalhq/types": "1.5.0",
61
- "@nymbalhq/web-components": "1.5.0"
53
+ "nymbal": "1.6.0",
54
+ "@nymbalhq/config": "1.6.0",
55
+ "@nymbalhq/http": "1.6.0",
56
+ "@nymbalhq/platform": "1.6.0",
57
+ "@nymbalhq/react": "1.6.0",
58
+ "@nymbalhq/sdk": "1.6.0",
59
+ "@nymbalhq/stack": "1.6.0",
60
+ "@nymbalhq/types": "1.6.0",
61
+ "@nymbalhq/web-components": "1.6.0"
62
62
  }
63
63
  }
@@ -1,23 +0,0 @@
1
- import '@nymbalhq/sdk/ns/auth'
2
- import { client } from '../lib/client.js'
3
-
4
- export async function guardAuth(): Promise<boolean> {
5
- let state = client.auth.getState()
6
-
7
- if (!state.isAuthenticated) {
8
- try {
9
- await client.auth.loadProfile()
10
- state = client.auth.getState()
11
- } catch {
12
- // will redirect below
13
- }
14
- }
15
-
16
- if (!state.isAuthenticated) {
17
- const redirect = encodeURIComponent(window.location.pathname + window.location.search)
18
- window.location.href = `/account/login?redirect=${redirect}`
19
- return false
20
- }
21
-
22
- return true
23
- }