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
@@ -1,22 +1,58 @@
1
1
  ---
2
2
  import '../../styles/pages/confirmation.css'
3
+ import '../../styles/pages/error.css'
3
4
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
5
  import NymbalElement from '@nymbalhq/web-components/astro'
5
- import { fetchOrder } from '../../lib/api'
6
+ import type { ShopperOrder } from '@nymbalhq/types'
7
+ import { fetchOrder, openExpiredOrder, requestOrderLink, shopperHeaders } from '../../lib/api'
6
8
  import { isPaid, orderHeading } from '../../lib/order-status'
7
9
 
8
- // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header
9
- // and the meta tag below. The rewrite to /404 drops the header, so the not-found page sets its own.
10
+ // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header,
11
+ // the meta tag below and a canonical URL without the query. No shared cache may keep what a key opened.
10
12
  Astro.response.headers.set('Referrer-Policy', 'no-referrer')
13
+ Astro.response.headers.set('Cache-Control', 'no-store')
11
14
 
12
15
  const { orderNumber } = Astro.params
13
16
  const key = Astro.url.searchParams.get('key') ?? undefined
14
- // Rejects when the API fails, so a failed read is a 500 and never a 404 for an order the shopper has.
15
- const order = await fetchOrder(orderNumber!, key)
16
17
 
17
- if (!order) return Astro.rewrite('/404')
18
+ // A POST is one of the page's two forms sent without its script (the script sends both from the browser): this server
19
+ // answers it, the email in the form's body, never in a URL.
20
+ const form = Astro.request.method === 'POST' ? await Astro.request.formData() : null
21
+ const posted = (name: string): string => String(form?.get(name) ?? '').trim()
22
+ const intent = posted('intent')
18
23
 
19
- const summary = {
24
+ // Every read rejects when the API fails, so a failed read is a 500 and never a not-found page for an order the shopper
25
+ // has.
26
+ let read: ShopperOrder | 'expired' | null
27
+ let emailLimited = false
28
+ let link: 'idle' | 'sent' | 'limited' = 'idle'
29
+ if (intent === 'link') {
30
+ link = await requestOrderLink(
31
+ posted('orderNumber'),
32
+ posted('email'),
33
+ shopperHeaders(Astro.request.headers),
34
+ )
35
+ read = null
36
+ } else if (intent === 'open' && key !== undefined) {
37
+ const opened = await openExpiredOrder(
38
+ orderNumber!,
39
+ key,
40
+ posted('email'),
41
+ shopperHeaders(Astro.request.headers),
42
+ )
43
+ emailLimited = opened === 'limited'
44
+ read = opened === 'limited' ? 'expired' : opened === 'not-found' ? null : opened
45
+ } else {
46
+ read = await fetchOrder(orderNumber!, key)
47
+ }
48
+ const order = read === 'expired' ? null : read
49
+ const canonical = new URL(Astro.url.pathname, Astro.url).href
50
+
51
+ // The order page's own not-found state, which offers a fresh link; the site-wide 404 would drop the headers above.
52
+ if (read === null) Astro.response.status = 404
53
+ if (emailLimited || link === 'limited') Astro.response.status = 429
54
+
55
+ const summary = order && {
20
56
  items: JSON.stringify(
21
57
  (order.lineItems ?? []).map((item) => ({
22
58
  name: `${item.productName}${item.variantName ? ` - ${item.variantName}` : ''}`,
@@ -33,81 +69,171 @@ const summary = {
33
69
  currency: order.currency,
34
70
  }
35
71
 
36
- const shippingAddress = order.shippingAddress
37
- const heading = orderHeading(order.status)
38
- const paid = isPaid(order.status)
72
+ const shippingAddress = order?.shippingAddress
73
+ const heading = order ? orderHeading(order.status) : read === 'expired' ? 'Open your order' : 'Order not found'
74
+ const paid = order ? isPaid(order.status) : false
39
75
  ---
40
76
 
41
- <BaseLayout title={`${heading} | Nymbal`} description="Your order with Nymbal.">
77
+ <BaseLayout title={`${heading} | Nymbal`} description="Your order with Nymbal." canonical={canonical}>
42
78
  <meta slot="head" name="referrer" content="no-referrer" />
43
- <div class="container section">
44
- <div class="confirmation-page" data-order-number={order.orderNumber} data-order-status={order.status}>
45
- {paid && (
46
- <div class="confirmation-icon">
79
+ {read === 'expired' && (
80
+ <div class="container section" id="order-email-prompt">
81
+ <form method="post" class="error-page" id="order-email-form" data-order-number={orderNumber}>
82
+ <input type="hidden" name="intent" value="open" />
83
+ <h1 class="error-title">Open your order</h1>
84
+ <p class="error-message">This order link has expired. Enter the email you gave at checkout to open the order.</p>
85
+ <div class="form-group">
86
+ <label for="order-email">Email</label>
87
+ <input id="order-email" type="email" name="email" autocomplete="email" required data-testid="order-email-input" />
88
+ </div>
89
+ <p class="error-message" data-testid="order-email-limited" hidden={!emailLimited}>
90
+ Too many tries for now. Please try again in a while.
91
+ </p>
92
+ <p class="error-message" id="order-email-failed" hidden>We could not open the order just now. Please try again.</p>
93
+ <div class="error-actions">
94
+ <button type="submit" class="btn btn-primary" data-testid="order-email-submit">Open order</button>
95
+ </div>
96
+ </form>
97
+ </div>
98
+ )}
99
+ {read === 'expired' && (
100
+ <div class="container section" id="order-opened" hidden>
101
+ <div class="confirmation-page">
102
+ <div class="confirmation-icon" data-order-field="paid">
47
103
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
48
104
  <polyline points="20 6 9 17 4 12"></polyline>
49
105
  </svg>
50
106
  </div>
51
- )}
52
-
53
- <h1 class="confirmation-title" data-testid="order-heading">{heading}</h1>
54
- {paid ? (
55
- <p class="confirmation-subtitle">
56
- Thank you. Your order <strong data-testid="order-number">{order.orderNumber}</strong> is paid.
57
- We'll send a confirmation to <strong>{order.email}</strong>.
58
- </p>
59
- ) : order.status === 'pending' ? (
60
- <p class="confirmation-subtitle">
61
- Your order <strong data-testid="order-number">{order.orderNumber}</strong> is waiting for its payment.
62
- We'll email <strong>{order.email}</strong> once it arrives.
63
- </p>
64
- ) : (
65
- <p class="confirmation-subtitle">
66
- Your order <strong data-testid="order-number">{order.orderNumber}</strong> is {order.status.replace(/_/g, ' ')}.
107
+ <h1 class="confirmation-title" data-order-field="heading"></h1>
108
+ <p class="confirmation-subtitle" data-order-field="subtitle"></p>
109
+ <div class="confirmation-card">
110
+ <h2 class="confirmation-card-title">Order Details</h2>
111
+ <dl>
112
+ <div class="confirmation-detail-row">
113
+ <dt>Order Number</dt>
114
+ <dd data-order-field="number"></dd>
115
+ </div>
116
+ <div class="confirmation-detail-row">
117
+ <dt>Status</dt>
118
+ <dd style="text-transform: capitalize;" data-order-field="status"></dd>
119
+ </div>
120
+ </dl>
121
+ </div>
122
+ <nymbal-order-timeline class="confirmation-summary"></nymbal-order-timeline>
123
+ <nymbal-order-summary class="confirmation-summary"></nymbal-order-summary>
124
+ <div class="confirmation-card" data-order-field="shipping" hidden>
125
+ <h2 class="confirmation-card-title">Shipping Address</h2>
126
+ <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;" data-order-field="address"></p>
127
+ </div>
128
+ <div class="confirmation-actions">
129
+ <a href="/account/register" class="btn btn-primary">Create an Account</a>
130
+ <a href="/products" class="btn btn-secondary">Continue Shopping</a>
131
+ </div>
132
+ </div>
133
+ </div>
134
+ )}
135
+ {(read === 'expired' || read === null) && (
136
+ <div class="container section" id="order-not-found" data-order-number={orderNumber} hidden={read === 'expired'}>
137
+ <div class="error-page">
138
+ <span class="error-code">404</span>
139
+ <h1 class="error-title">Order not found</h1>
140
+ <p class="error-message">
141
+ This link does not open an order. Give its order number and the email you gave at checkout, and we'll email
142
+ you a fresh link if they match.
67
143
  </p>
68
- )}
69
-
70
- <div class="confirmation-card">
71
- <h2 class="confirmation-card-title">Order Details</h2>
72
-
73
- <dl>
74
- <div class="confirmation-detail-row">
75
- <dt>Order Number</dt>
76
- <dd>{order.orderNumber}</dd>
144
+ <form method="post" id="order-link-form" hidden={link === 'sent'}>
145
+ <input type="hidden" name="intent" value="link" />
146
+ <div class="form-group">
147
+ <label for="order-link-number">Order number</label>
148
+ <input id="order-link-number" name="orderNumber" required data-testid="order-link-number" />
149
+ </div>
150
+ <div class="form-group">
151
+ <label for="order-link-email">Email</label>
152
+ <input id="order-link-email" type="email" name="email" autocomplete="email" required data-testid="order-link-email" />
77
153
  </div>
78
- <div class="confirmation-detail-row">
79
- <dt>Status</dt>
80
- <dd style="text-transform: capitalize;" data-testid="order-status">{order.status}</dd>
154
+ {link === 'limited' && <p class="error-message">Too many tries for now. Please try again in a while.</p>}
155
+ <div class="error-actions">
156
+ <button type="submit" class="btn btn-primary" data-testid="order-link-submit">Send me my order link</button>
81
157
  </div>
82
- </dl>
158
+ </form>
159
+ <p class="error-message" data-testid="order-link-sent" hidden={link !== 'sent'}>
160
+ If that number and email match an order, its link is on its way to that email.
161
+ </p>
162
+ <p class="error-message" id="order-link-failed" hidden>We could not send the link just now. Please try again.</p>
83
163
  </div>
164
+ </div>
165
+ )}
166
+ {order && (
167
+ <div class="container section">
168
+ <div class="confirmation-page" data-order-number={order.orderNumber} data-order-status={order.status}>
169
+ {paid && (
170
+ <div class="confirmation-icon">
171
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
172
+ <polyline points="20 6 9 17 4 12"></polyline>
173
+ </svg>
174
+ </div>
175
+ )}
84
176
 
85
- <NymbalElement tag="nymbal-order-timeline" attributes={{ class: 'confirmation-summary', entries: JSON.stringify(order.timeline ?? []) }} />
86
-
87
- <NymbalElement tag="nymbal-order-summary" attributes={{ class: 'confirmation-summary', ...summary }} />
177
+ <h1 class="confirmation-title" data-testid="order-heading">{heading}</h1>
178
+ {paid ? (
179
+ <p class="confirmation-subtitle">
180
+ Thank you. Your order <strong data-testid="order-number">{order.orderNumber}</strong> is paid.
181
+ We'll send a confirmation to the email you gave at checkout.
182
+ </p>
183
+ ) : order.status === 'pending' ? (
184
+ <p class="confirmation-subtitle">
185
+ Your order <strong data-testid="order-number">{order.orderNumber}</strong> is waiting for its payment.
186
+ We'll email the address you gave at checkout once it arrives.
187
+ </p>
188
+ ) : (
189
+ <p class="confirmation-subtitle">
190
+ Your order <strong data-testid="order-number">{order.orderNumber}</strong> is {order.status.replace(/_/g, ' ')}.
191
+ </p>
192
+ )}
88
193
 
89
- {shippingAddress && (
90
194
  <div class="confirmation-card">
91
- <h2 class="confirmation-card-title">Shipping Address</h2>
92
- <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;">
93
- {shippingAddress.addressLine1}<br />
94
- {shippingAddress.addressLine2 && <>{shippingAddress.addressLine2}<br /></>}
95
- {shippingAddress.city}, {shippingAddress.region} {shippingAddress.postalCode}<br />
96
- {shippingAddress.country}
97
- </p>
195
+ <h2 class="confirmation-card-title">Order Details</h2>
196
+
197
+ <dl>
198
+ <div class="confirmation-detail-row">
199
+ <dt>Order Number</dt>
200
+ <dd>{order.orderNumber}</dd>
201
+ </div>
202
+ <div class="confirmation-detail-row">
203
+ <dt>Status</dt>
204
+ <dd style="text-transform: capitalize;" data-testid="order-status">{order.status}</dd>
205
+ </div>
206
+ </dl>
98
207
  </div>
99
- )}
100
208
 
101
- <div class="confirmation-actions">
102
- <a href="/account/register" class="btn btn-primary">Create an Account</a>
103
- <a href="/products" class="btn btn-secondary">Continue Shopping</a>
209
+ <NymbalElement tag="nymbal-order-timeline" attributes={{ class: 'confirmation-summary', entries: JSON.stringify(order.timeline ?? []) }} />
210
+
211
+ <NymbalElement tag="nymbal-order-summary" attributes={{ class: 'confirmation-summary', ...summary }} />
212
+
213
+ {shippingAddress && (
214
+ <div class="confirmation-card">
215
+ <h2 class="confirmation-card-title">Shipping Address</h2>
216
+ <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); line-height: 1.6;">
217
+ {shippingAddress.addressLine1}<br />
218
+ {shippingAddress.addressLine2 && <>{shippingAddress.addressLine2}<br /></>}
219
+ {shippingAddress.city}, {shippingAddress.region} {shippingAddress.postalCode}<br />
220
+ {shippingAddress.country}
221
+ </p>
222
+ </div>
223
+ )}
224
+
225
+ <div class="confirmation-actions">
226
+ <a href="/account/register" class="btn btn-primary">Create an Account</a>
227
+ <a href="/products" class="btn btn-secondary">Continue Shopping</a>
228
+ </div>
104
229
  </div>
105
230
  </div>
106
- </div>
231
+ )}
107
232
  </BaseLayout>
108
233
 
109
234
  <script>
110
235
  import '../../scripts/order-status.js'
236
+ import '../../scripts/order-access.js'
111
237
  import { NymbalOrderSummary } from '@nymbalhq/web-components/elements/nymbal-order-summary'
112
238
  import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
113
239
 
@@ -4,7 +4,8 @@ import BaseLayout from '../../layouts/BaseLayout.astro'
4
4
  import NymbalElement from '@nymbalhq/web-components/astro'
5
5
  import { cardProductOf } from '@nymbalhq/web-components/ssr'
6
6
  import { loadProduct, fetchReviews, fetchProducts, fetchCapabilities } from '../../lib/api'
7
- import { productJsonLd, breadcrumbJsonLd } from '../../lib/seo'
7
+ import { productJsonLd, breadcrumbJsonLd, descriptionText } from '../../lib/seo'
8
+ import { acceptsReviews } from '../../lib/reviews'
8
9
 
9
10
  const { slug } = Astro.params
10
11
 
@@ -50,7 +51,7 @@ const offersAlerts = capabilities?.email?.delivers === true && defaultVariant !=
50
51
  const hasVariantChoice = (product.variants?.length ?? 0) > 1
51
52
  ---
52
53
 
53
- <BaseLayout title={`${product.name} | Nymbal`} description={product.shortDescription ?? product.description ?? ''} jsonLd={jsonLd}>
54
+ <BaseLayout title={`${product.name} | Nymbal`} description={descriptionText(product.shortDescription || product.description)} jsonLd={jsonLd}>
54
55
  <!-- The gallery's main image is the page's LCP: the browser starts it before it parses the body. -->
55
56
  <link slot="head" rel="preload" as="image" href={images[0]!.url} fetchpriority="high" />
56
57
  <div class="container section" data-product-slug={product.slug}>
@@ -116,8 +117,13 @@ const hasVariantChoice = (product.variants?.length ?? 0) > 1
116
117
 
117
118
  <section class="pdp-reviews">
118
119
  <h2 class="pdp-reviews-title">Customer Reviews</h2>
119
- <NymbalElement tag="nymbal-review-list" attributes={{ reviews: JSON.stringify(reviews) }} />
120
- <NymbalElement tag="nymbal-review-form" attributes={{ class: 'pdp-review-form', 'product-id': product.id }} />
120
+ <NymbalElement
121
+ tag="nymbal-review-list"
122
+ attributes={{ reviews: JSON.stringify(reviews), rating: JSON.stringify(product.rating ?? null) }}
123
+ />
124
+ {acceptsReviews(capabilities) && (
125
+ <NymbalElement tag="nymbal-review-form" attributes={{ class: 'pdp-review-form', 'product-id': product.id }} />
126
+ )}
121
127
  </section>
122
128
 
123
129
  {relatedProducts.length > 0 && (
@@ -9,9 +9,10 @@ import { fetchProducts, fetchCategories, fetchCapabilities, sortFromUrl } from '
9
9
  const capabilities = await fetchCapabilities()
10
10
  const sortKeys = capabilities?.catalog.sortKeys ?? []
11
11
  const sort = sortFromUrl(Astro.url, capabilities?.catalog)
12
+ const category = Astro.url.searchParams.get('category') || undefined
12
13
 
13
14
  const [productResult, categories] = await Promise.all([
14
- fetchProducts({ limit: 24, sort }),
15
+ fetchProducts({ limit: 24, category, sort }),
15
16
  fetchCategories(),
16
17
  ])
17
18
 
@@ -0,0 +1,181 @@
1
+ import { NymbalApiError } from '@nymbalhq/sdk/core'
2
+ import '@nymbalhq/sdk/ns/auth'
3
+ import type { ShopperAddress, ShopperOrder } from '@nymbalhq/types'
4
+ import { client } from '../lib/client.js'
5
+ import { isPaid, orderHeading } from '../lib/order-status.js'
6
+ import { submitOnce } from '../lib/submit-once.js'
7
+
8
+ // The order page's two forms, each sent once per click from the browser. The expired key's email prompt reads the
9
+ // order with the email in a header and shows it on this page: read by the storefront's server instead, every shopper's
10
+ // tries would count against the API's per-address limit as one. "Send me my order link" asks the API, which answers
11
+ // the same whatever matched. Without this script the forms post to the page, whose server answers them.
12
+
13
+ const byId = (id: string): HTMLElement | null => document.getElementById(id)
14
+
15
+ const field = (root: HTMLElement, name: string): HTMLElement | null =>
16
+ root.querySelector<HTMLElement>(`[data-order-field="${name}"]`)
17
+
18
+ /** The subtitle the server-rendered page gives the same status, its number under the same test id. */
19
+ function subtitle(order: ShopperOrder): Node[] {
20
+ const number = document.createElement('strong')
21
+ number.dataset.testid = 'order-number'
22
+ number.textContent = order.orderNumber
23
+ const text = (value: string) => document.createTextNode(value)
24
+ if (isPaid(order.status)) {
25
+ return [
26
+ text('Thank you. Your order '),
27
+ number,
28
+ text(" is paid. We'll send a confirmation to the email you gave at checkout."),
29
+ ]
30
+ }
31
+ if (order.status === 'pending') {
32
+ return [
33
+ text('Your order '),
34
+ number,
35
+ text(
36
+ " is waiting for its payment. We'll email the address you gave at checkout once it arrives.",
37
+ ),
38
+ ]
39
+ }
40
+ return [text('Your order '), number, text(` is ${order.status.replace(/_/g, ' ')}.`)]
41
+ }
42
+
43
+ function addressLines(address: ShopperAddress): Node[] {
44
+ const lines = [
45
+ address.addressLine1,
46
+ address.addressLine2,
47
+ `${address.city}, ${address.region} ${address.postalCode}`,
48
+ address.country,
49
+ ].filter((line): line is string => typeof line === 'string' && line !== '')
50
+ return lines.flatMap((line, i) => {
51
+ const node = document.createTextNode(line)
52
+ return i === 0 ? [node] : [document.createElement('br'), node]
53
+ })
54
+ }
55
+
56
+ /** Fills the page's empty confirmation with the order, as the server renders a key's order. */
57
+ function fillOrder(view: HTMLElement, order: ShopperOrder): void {
58
+ // The check mark is a flex box, which `hidden` does not hide: an unpaid order's is removed.
59
+ if (!isPaid(order.status)) field(view, 'paid')?.remove()
60
+ const heading = field(view, 'heading')
61
+ if (heading) {
62
+ heading.textContent = orderHeading(order.status)
63
+ heading.dataset.testid = 'order-heading'
64
+ }
65
+ field(view, 'subtitle')?.replaceChildren(...subtitle(order))
66
+ const number = field(view, 'number')
67
+ if (number) number.textContent = order.orderNumber
68
+ const status = field(view, 'status')
69
+ if (status) {
70
+ status.textContent = order.status
71
+ status.dataset.testid = 'order-status'
72
+ }
73
+ view
74
+ .querySelector('nymbal-order-timeline')
75
+ ?.setAttribute('entries', JSON.stringify(order.timeline ?? []))
76
+ const summary = view.querySelector('nymbal-order-summary')
77
+ if (summary) {
78
+ const items = (order.lineItems ?? []).map((item) => ({
79
+ name: `${item.productName}${item.variantName ? ` - ${item.variantName}` : ''}`,
80
+ qty: item.qty,
81
+ unitPriceMinor: item.unitPriceMinor,
82
+ lineTotalMinor: item.lineTotalMinor,
83
+ }))
84
+ summary.setAttribute('items', JSON.stringify(items))
85
+ summary.setAttribute('subtotal-minor', String(order.subtotalMinor))
86
+ summary.setAttribute('discount-minor', String(order.discountTotalMinor ?? 0))
87
+ summary.setAttribute('shipping-minor', String(order.shippingTotalMinor ?? 0))
88
+ summary.setAttribute('tax-minor', String(order.taxTotalMinor ?? 0))
89
+ summary.setAttribute('total-minor', String(order.totalMinor))
90
+ summary.setAttribute('currency', order.currency)
91
+ }
92
+ const shipping = field(view, 'shipping')
93
+ if (shipping) {
94
+ field(shipping, 'address')?.replaceChildren(...addressLines(order.shippingAddress))
95
+ shipping.hidden = false
96
+ }
97
+ }
98
+
99
+ /** Shows one of the expired page's three views: the prompt, the order, or the not-found state. */
100
+ function show(id: 'order-email-prompt' | 'order-opened' | 'order-not-found'): void {
101
+ for (const view of ['order-email-prompt', 'order-opened', 'order-not-found']) {
102
+ const el = byId(view)
103
+ if (el) el.hidden = view !== id
104
+ }
105
+ }
106
+
107
+ const prompt = document.getElementById('order-email-form') as HTMLFormElement | null
108
+ submitOnce(prompt, async () => {
109
+ if (prompt === null) return
110
+ const limited = prompt.querySelector<HTMLElement>('[data-testid="order-email-limited"]')
111
+ const failed = byId('order-email-failed')
112
+ if (limited) limited.hidden = true
113
+ if (failed) failed.hidden = true
114
+ const orderNumber = prompt.dataset.orderNumber ?? ''
115
+ const key = new URLSearchParams(window.location.search).get('key') ?? ''
116
+ const email = String(new FormData(prompt).get('email') ?? '').trim()
117
+
118
+ let order: ShopperOrder
119
+ try {
120
+ order = await client.orders.get(orderNumber, { key, email })
121
+ } catch (err) {
122
+ // The answer an unknown number gets: the email did not open the order.
123
+ if (err instanceof NymbalApiError && err.status === 404) return show('order-not-found')
124
+ if (err instanceof NymbalApiError && err.status === 429) {
125
+ if (limited) limited.hidden = false
126
+ return
127
+ }
128
+ if (failed) failed.hidden = false
129
+ throw err
130
+ }
131
+ const view = byId('order-opened')
132
+ if (view === null) return
133
+ fillOrder(view, order)
134
+ show('order-opened')
135
+ })
136
+
137
+ const linkForm = document.getElementById('order-link-form') as HTMLFormElement | null
138
+ submitOnce(linkForm, async () => {
139
+ if (linkForm === null) return
140
+ const data = new FormData(linkForm)
141
+ const failed = document.getElementById('order-link-failed')
142
+ if (failed) failed.hidden = true
143
+ try {
144
+ await client.orders.requestLink({
145
+ orderNumber: String(data.get('orderNumber') ?? '').trim(),
146
+ email: String(data.get('email') ?? '').trim(),
147
+ })
148
+ } catch (err) {
149
+ if (failed) failed.hidden = false
150
+ throw err
151
+ }
152
+ linkForm.hidden = true
153
+ const sent = document.querySelector<HTMLElement>('[data-testid="order-link-sent"]')
154
+ if (sent) sent.hidden = false
155
+ })
156
+
157
+ /**
158
+ * A signed-in shopper who opens their own order here without a working key is sent to it in their account. The
159
+ * session is restored first, which refreshes a lapsed token: the API reads a lapsed bearer as a guest's. Only the
160
+ * owner's read answering moves the page, so anyone else's order stays this page's not-found state and the page says
161
+ * nothing about whether it exists. Replacing the entry keeps Back from returning here.
162
+ */
163
+ async function sendOwnerToAccount(orderNumber: string): Promise<void> {
164
+ await client.auth.restore()
165
+ if (!client.auth.getState().isAuthenticated) return
166
+ try {
167
+ await client.customer.orders.get(orderNumber)
168
+ } catch (err) {
169
+ if (err instanceof NymbalApiError && err.status === 404) return
170
+ throw err
171
+ }
172
+ window.location.replace(`/account/orders/${encodeURIComponent(orderNumber)}`)
173
+ }
174
+
175
+ // The not-found state is on the page, shown or behind the expired key's prompt: the key did not open the order.
176
+ const notFound = byId('order-not-found')
177
+ if (notFound?.dataset.orderNumber) {
178
+ sendOwnerToAccount(notFound.dataset.orderNumber).catch((err: unknown) => {
179
+ console.error('The signed-in order check failed', err)
180
+ })
181
+ }
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/product'
1
2
  import { NymbalAddToCart } from '@nymbalhq/web-components/elements/nymbal-add-to-cart'
2
3
  import { NymbalBreadcrumb } from '@nymbalhq/web-components/elements/nymbal-breadcrumb'
3
4
  import { NymbalImageGallery } from '@nymbalhq/web-components/elements/nymbal-image-gallery'
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/product-list'
1
2
  import type { ProductSortKey } from '@nymbalhq/types'
2
3
  import { NymbalBreadcrumb } from '@nymbalhq/web-components/elements/nymbal-breadcrumb'
3
4
  import { NymbalProductFilter } from '@nymbalhq/web-components/elements/nymbal-product-filter'
@@ -1,3 +1,4 @@
1
+ import '@nymbalhq/sdk/ns/search'
1
2
  import { NymbalProductFilter } from '@nymbalhq/web-components/elements/nymbal-product-filter'
2
3
  import { NymbalSearchResults } from '@nymbalhq/web-components/elements/nymbal-search-results'
3
4
  import { client } from '../lib/client.js'
@@ -1,4 +1,17 @@
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
+ }
12
+
1
13
  // Signed in or registered: on to the page that sent the shopper here (`?redirect`), or the account.
2
14
  document.addEventListener('nymbal:auth:signed-in', () => {
3
- window.location.href = new URLSearchParams(window.location.search).get('redirect') ?? '/account'
15
+ const redirect = new URLSearchParams(window.location.search).get('redirect')
16
+ window.location.href = signedInTarget(redirect, window.location.origin)
4
17
  })
@@ -20,6 +20,9 @@ html {
20
20
  -moz-text-size-adjust: 100%;
21
21
  text-size-adjust: 100%;
22
22
  scroll-behavior: smooth;
23
+ /* What is scrolled to the top edge (a fragment, scrollIntoView, keyboard focus) lands below the sticky site header:
24
+ at least its height at every width, with room for a phone header that also holds the mini-cart. */
25
+ scroll-padding-top: 5.5rem;
23
26
  }
24
27
 
25
28
  body {
@@ -26,10 +26,13 @@
26
26
 
27
27
  /* ---- Image gallery (nymbal-image-gallery) ---- */
28
28
 
29
- .pdp-gallery {
30
- position: sticky;
31
- top: 80px;
32
- align-self: start;
29
+ /* Sticky only beside the info column: in one column it would paint over the actions scrolling under it. */
30
+ @media (min-width: 769px) {
31
+ .pdp-gallery {
32
+ position: sticky;
33
+ top: 80px;
34
+ align-self: start;
35
+ }
33
36
  }
34
37
 
35
38
  /* ---- Product info ---- */