create-nymbal-app 0.4.0 → 0.6.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 (175) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.js +14 -5
  3. package/dist/index.js.map +1 -1
  4. package/package.json +5 -4
  5. package/scaffold/project/astro/src/pages/index.astro +13 -15
  6. package/scaffold/templates/astro/_dot.node-version +1 -1
  7. package/scaffold/templates/astro/astro.config.mjs +23 -0
  8. package/scaffold/templates/astro/package.json +26 -26
  9. package/scaffold/templates/astro/src/components/SkipNav.astro +3 -1
  10. package/scaffold/templates/astro/src/elements/index.ts +11 -0
  11. package/scaffold/templates/astro/src/layouts/BaseLayout.astro +15 -4
  12. package/scaffold/templates/astro/src/lib/api.ts +162 -38
  13. package/scaffold/templates/astro/src/lib/chrome.ts +59 -0
  14. package/scaffold/templates/astro/src/lib/client.ts +4 -4
  15. package/scaffold/templates/astro/src/lib/fragments.ts +48 -0
  16. package/scaffold/templates/astro/src/lib/server-elements.ts +5 -0
  17. package/scaffold/templates/astro/src/middleware.ts +37 -0
  18. package/scaffold/templates/astro/src/pages/404.astro +3 -0
  19. package/scaffold/templates/astro/src/pages/account/addresses.astro +5 -97
  20. package/scaffold/templates/astro/src/pages/account/login.astro +7 -34
  21. package/scaffold/templates/astro/src/pages/account/orders/[orderNumber].astro +11 -3
  22. package/scaffold/templates/astro/src/pages/account/profile.astro +6 -56
  23. package/scaffold/templates/astro/src/pages/account/register.astro +7 -73
  24. package/scaffold/templates/astro/src/pages/alerts/confirm.astro +59 -0
  25. package/scaffold/templates/astro/src/pages/alerts/unsubscribe.astro +53 -0
  26. package/scaffold/templates/astro/src/pages/cart.astro +14 -7
  27. package/scaffold/templates/astro/src/pages/category/[slug].astro +25 -27
  28. package/scaffold/templates/astro/src/pages/checkout.astro +30 -94
  29. package/scaffold/templates/astro/src/pages/fragments/footer.astro +5 -2
  30. package/scaffold/templates/astro/src/pages/fragments/header.astro +12 -2
  31. package/scaffold/templates/astro/src/pages/fragments/nav.astro +8 -5
  32. package/scaffold/templates/astro/src/pages/fragments/product/[slug].astro +9 -10
  33. package/scaffold/templates/astro/src/pages/index.astro +25 -15
  34. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +34 -45
  35. package/scaffold/templates/astro/src/pages/product/[slug].astro +64 -34
  36. package/scaffold/templates/astro/src/pages/products/index.astro +16 -21
  37. package/scaffold/templates/astro/src/pages/search.astro +10 -11
  38. package/scaffold/templates/astro/src/scripts/init-client.ts +14 -0
  39. package/scaffold/templates/astro/src/scripts/order-status.ts +3 -1
  40. package/scaffold/templates/astro/src/scripts/pdp.ts +29 -21
  41. package/scaffold/templates/astro/src/scripts/plp.ts +15 -93
  42. package/scaffold/templates/astro/src/scripts/search.ts +7 -132
  43. package/scaffold/templates/astro/src/scripts/signed-in-redirect.ts +4 -0
  44. package/scaffold/templates/astro/src/styles/global.css +49 -45
  45. package/scaffold/templates/astro/src/styles/pages/account.css +4 -90
  46. package/scaffold/templates/astro/src/styles/pages/confirmation.css +6 -0
  47. package/scaffold/templates/astro/src/styles/pages/home.css +9 -100
  48. package/scaffold/templates/astro/src/styles/pages/pdp.css +5 -171
  49. package/scaffold/templates/astro/src/styles/pages/plp.css +3 -42
  50. package/scaffold/templates/astro/src/styles/pages/search.css +4 -110
  51. package/scaffold/templates/astro/src/styles/tokens.css +56 -0
  52. package/scaffold/templates/nextjs/_dot.node-version +1 -1
  53. package/scaffold/templates/nextjs/app/(catalog)/category/[slug]/page.tsx +74 -0
  54. package/scaffold/templates/nextjs/app/(catalog)/home/[key]/page.tsx +85 -0
  55. package/scaffold/templates/nextjs/app/(catalog)/layout.tsx +13 -0
  56. package/scaffold/templates/nextjs/app/(catalog)/not-found.tsx +7 -0
  57. package/scaffold/templates/nextjs/app/(catalog)/product/[slug]/page.tsx +201 -0
  58. package/scaffold/templates/nextjs/app/(catalog)/products/page.tsx +62 -0
  59. package/scaffold/templates/nextjs/app/(catalog)/search/SearchView.tsx +90 -0
  60. package/scaffold/templates/nextjs/app/(catalog)/search/page.tsx +46 -0
  61. package/scaffold/templates/nextjs/app/(shopper)/account/addresses/AddressesView.tsx +5 -0
  62. package/scaffold/templates/nextjs/app/(shopper)/account/addresses/page.tsx +17 -0
  63. package/scaffold/templates/nextjs/app/(shopper)/account/login/LoginView.tsx +28 -0
  64. package/scaffold/templates/nextjs/app/(shopper)/account/login/page.tsx +23 -0
  65. package/scaffold/templates/nextjs/app/{account → (shopper)/account}/orders/[orderNumber]/page.tsx +10 -3
  66. package/scaffold/templates/nextjs/app/(shopper)/account/profile/ProfileView.tsx +5 -0
  67. package/scaffold/templates/nextjs/app/(shopper)/account/profile/page.tsx +20 -0
  68. package/scaffold/templates/nextjs/app/(shopper)/account/register/RegisterView.tsx +26 -0
  69. package/scaffold/templates/nextjs/app/(shopper)/account/register/page.tsx +11 -0
  70. package/scaffold/templates/nextjs/app/(shopper)/alerts/AlertLinkForm.tsx +90 -0
  71. package/scaffold/templates/nextjs/app/(shopper)/alerts/LinkInvalid.tsx +19 -0
  72. package/scaffold/templates/nextjs/app/(shopper)/alerts/actions.ts +33 -0
  73. package/scaffold/templates/nextjs/app/(shopper)/alerts/confirm/page.tsx +19 -0
  74. package/scaffold/templates/nextjs/app/(shopper)/alerts/unsubscribe/page.tsx +17 -0
  75. package/scaffold/templates/nextjs/app/(shopper)/cart/CartView.tsx +5 -0
  76. package/scaffold/templates/nextjs/app/(shopper)/cart/page.tsx +22 -0
  77. package/scaffold/templates/nextjs/app/(shopper)/checkout/CheckoutView.tsx +34 -0
  78. package/scaffold/templates/nextjs/app/(shopper)/checkout/page.tsx +39 -0
  79. package/scaffold/templates/nextjs/app/(shopper)/layout.tsx +12 -0
  80. package/scaffold/templates/nextjs/app/(shopper)/not-found.tsx +6 -0
  81. package/scaffold/templates/nextjs/app/{order → (shopper)/order}/[orderNumber]/page.tsx +44 -9
  82. package/scaffold/templates/nextjs/app/error.tsx +3 -7
  83. package/scaffold/templates/nextjs/app/fragments/footer/route.ts +13 -0
  84. package/scaffold/templates/nextjs/app/fragments/header/[key]/route.ts +18 -0
  85. package/scaffold/templates/nextjs/app/fragments/nav/[key]/route.ts +23 -0
  86. package/scaffold/templates/nextjs/app/fragments/product/[slug]/route.ts +22 -0
  87. package/scaffold/templates/nextjs/app/globals.css +5 -23
  88. package/scaffold/templates/nextjs/app/layout.tsx +8 -5
  89. package/scaffold/templates/nextjs/app/not-found.tsx +9 -33
  90. package/scaffold/templates/nextjs/app/tokens.css +56 -0
  91. package/scaffold/templates/nextjs/components/client/ListingControls.tsx +87 -0
  92. package/scaffold/templates/nextjs/components/client/NymbalSetup.tsx +48 -6
  93. package/scaffold/templates/nextjs/components/client/OrderStatusRefresh.tsx +8 -2
  94. package/scaffold/templates/nextjs/components/client/ProductInteractive.tsx +47 -15
  95. package/scaffold/templates/nextjs/components/client/elements.tsx +17 -0
  96. package/scaffold/templates/nextjs/components/server/Header.tsx +33 -102
  97. package/scaffold/templates/nextjs/components/server/NotFoundView.tsx +39 -0
  98. package/scaffold/templates/nextjs/components/server/SkipNav.tsx +7 -3
  99. package/scaffold/templates/nextjs/elements/index.ts +12 -0
  100. package/scaffold/templates/nextjs/lib/api.ts +198 -62
  101. package/scaffold/templates/nextjs/lib/chrome.ts +40 -0
  102. package/scaffold/templates/nextjs/lib/fragments.ts +16 -0
  103. package/scaffold/templates/nextjs/lib/header.ts +39 -0
  104. package/scaffold/templates/nextjs/lib/render.ts +14 -0
  105. package/scaffold/templates/nextjs/next.config.mjs +41 -0
  106. package/scaffold/templates/nextjs/package.json +28 -27
  107. package/scaffold/templates/nextjs/styles/pages/account.module.css +0 -70
  108. package/scaffold/templates/nextjs/styles/pages/confirmation.module.css +6 -85
  109. package/scaffold/templates/nextjs/styles/pages/home.module.css +2 -103
  110. package/scaffold/templates/nextjs/styles/pages/pdp.module.css +3 -183
  111. package/scaffold/templates/nextjs/styles/pages/plp.module.css +9 -143
  112. package/scaffold/templates/nextjs/styles/pages/search.module.css +1 -145
  113. package/scaffold/templates/nextjs/tsconfig.dist.json +5 -0
  114. package/scaffold/templates/astro/src/components/AddressForm.astro +0 -107
  115. package/scaffold/templates/astro/src/components/Breadcrumb.astro +0 -20
  116. package/scaffold/templates/astro/src/components/CategoryNav.astro +0 -27
  117. package/scaffold/templates/astro/src/components/CheckoutSteps.astro +0 -29
  118. package/scaffold/templates/astro/src/components/Footer.astro +0 -108
  119. package/scaffold/templates/astro/src/components/Header.astro +0 -198
  120. package/scaffold/templates/astro/src/components/ImageGallery.astro +0 -42
  121. package/scaffold/templates/astro/src/components/OrderSummary.astro +0 -53
  122. package/scaffold/templates/astro/src/components/Pagination.astro +0 -13
  123. package/scaffold/templates/astro/src/components/PriceDisplay.astro +0 -25
  124. package/scaffold/templates/astro/src/components/ProductCard.astro +0 -44
  125. package/scaffold/templates/astro/src/components/RelatedProducts.astro +0 -28
  126. package/scaffold/templates/astro/src/components/ReviewForm.astro +0 -74
  127. package/scaffold/templates/astro/src/components/ReviewList.astro +0 -41
  128. package/scaffold/templates/astro/src/components/StockBadge.astro +0 -15
  129. package/scaffold/templates/astro/src/scripts/auth-forms.ts +0 -82
  130. package/scaffold/templates/astro/src/scripts/cart-page.ts +0 -118
  131. package/scaffold/templates/astro/src/scripts/checkout.ts +0 -271
  132. package/scaffold/templates/astro/src/scripts/image-gallery.ts +0 -22
  133. package/scaffold/templates/astro/src/scripts/profile-form.ts +0 -57
  134. package/scaffold/templates/astro/src/scripts/review-form.ts +0 -27
  135. package/scaffold/templates/astro/src/styles/pages/cart.css +0 -215
  136. package/scaffold/templates/astro/src/styles/pages/checkout.css +0 -270
  137. package/scaffold/templates/nextjs/app/account/addresses/page.tsx +0 -10
  138. package/scaffold/templates/nextjs/app/account/login/page.tsx +0 -23
  139. package/scaffold/templates/nextjs/app/account/profile/page.tsx +0 -10
  140. package/scaffold/templates/nextjs/app/account/register/page.tsx +0 -10
  141. package/scaffold/templates/nextjs/app/cart/page.tsx +0 -10
  142. package/scaffold/templates/nextjs/app/category/[slug]/page.tsx +0 -61
  143. package/scaffold/templates/nextjs/app/checkout/page.tsx +0 -17
  144. package/scaffold/templates/nextjs/app/page.tsx +0 -63
  145. package/scaffold/templates/nextjs/app/product/[slug]/page.tsx +0 -111
  146. package/scaffold/templates/nextjs/app/products/page.tsx +0 -40
  147. package/scaffold/templates/nextjs/app/search/page.tsx +0 -24
  148. package/scaffold/templates/nextjs/components/client/AddressManager.tsx +0 -181
  149. package/scaffold/templates/nextjs/components/client/CartPage.tsx +0 -121
  150. package/scaffold/templates/nextjs/components/client/CheckoutForm.tsx +0 -482
  151. package/scaffold/templates/nextjs/components/client/ImageGallery.tsx +0 -68
  152. package/scaffold/templates/nextjs/components/client/LoginForm.tsx +0 -89
  153. package/scaffold/templates/nextjs/components/client/MiniCartWrapper.tsx +0 -12
  154. package/scaffold/templates/nextjs/components/client/ProductGrid.tsx +0 -137
  155. package/scaffold/templates/nextjs/components/client/ProfileForm.tsx +0 -112
  156. package/scaffold/templates/nextjs/components/client/RegisterForm.tsx +0 -131
  157. package/scaffold/templates/nextjs/components/client/ReviewForm.tsx +0 -116
  158. package/scaffold/templates/nextjs/components/client/SearchBarWrapper.tsx +0 -27
  159. package/scaffold/templates/nextjs/components/client/SearchResults.tsx +0 -181
  160. package/scaffold/templates/nextjs/components/server/Breadcrumb.tsx +0 -36
  161. package/scaffold/templates/nextjs/components/server/CategoryNav.tsx +0 -29
  162. package/scaffold/templates/nextjs/components/server/CheckoutSteps.tsx +0 -60
  163. package/scaffold/templates/nextjs/components/server/Footer.module.css +0 -64
  164. package/scaffold/templates/nextjs/components/server/Footer.tsx +0 -79
  165. package/scaffold/templates/nextjs/components/server/Header.module.css +0 -147
  166. package/scaffold/templates/nextjs/components/server/OrderSummary.tsx +0 -79
  167. package/scaffold/templates/nextjs/components/server/PriceDisplay.tsx +0 -31
  168. package/scaffold/templates/nextjs/components/server/ProductCard.tsx +0 -59
  169. package/scaffold/templates/nextjs/components/server/RelatedProducts.tsx +0 -31
  170. package/scaffold/templates/nextjs/components/server/ReviewList.tsx +0 -62
  171. package/scaffold/templates/nextjs/styles/pages/cart.module.css +0 -240
  172. package/scaffold/templates/nextjs/styles/pages/checkout.module.css +0 -404
  173. /package/scaffold/templates/nextjs/app/{account → (shopper)/account}/layout.tsx +0 -0
  174. /package/scaffold/templates/nextjs/app/{account → (shopper)/account}/orders/page.tsx +0 -0
  175. /package/scaffold/templates/nextjs/app/{account → (shopper)/account}/page.tsx +0 -0
@@ -1,6 +1,18 @@
1
- import type { DenormalisedProduct, ProductListResult, ReviewsListResult } from '@nymbalhq/sdk'
2
- import { DEFAULT_PRODUCT_SORT, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
3
- import type { Category, Order, ProductSortKey, StoreCapabilities } from '@nymbalhq/types'
1
+ import type {
2
+ DenormalisedProduct,
3
+ ProductListResult,
4
+ ProductSearchResult,
5
+ ReviewsListResult,
6
+ } from '@nymbalhq/sdk'
7
+ import { DEFAULT_PRODUCT_SORT, ORDER_KEY_HEADER, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
8
+ import type {
9
+ AlertKind,
10
+ Cart,
11
+ Category,
12
+ ProductSortKey,
13
+ ShopperOrder,
14
+ StoreCapabilities,
15
+ } from '@nymbalhq/types'
4
16
 
5
17
  const API_URL = import.meta.env.NYMBAL_API_URL ?? 'http://localhost:3001'
6
18
 
@@ -27,13 +39,34 @@ export async function fetchProducts(params?: {
27
39
  }
28
40
  }
29
41
 
42
+ /** The API failed: it did not answer, answered an error other than a 404, or answered with no data. */
43
+ export class ApiUnavailableError extends Error {
44
+ override name = 'ApiUnavailableError'
45
+ }
46
+
47
+ /** `GET <path>`'s data; null on a 404; rejects with ApiUnavailableError (or fetch's own error) on any other failure. */
48
+ async function apiData<T>(path: string): Promise<T | null> {
49
+ const res = await fetch(`${API_URL}${path}`)
50
+ if (res.status === 404) return null
51
+ if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
52
+ const envelope = (await res.json()) as { data?: T | null }
53
+ if (envelope.data === undefined || envelope.data === null) {
54
+ throw new ApiUnavailableError(`GET ${path} answered no data`)
55
+ }
56
+ return envelope.data
57
+ }
58
+
59
+ /** What the store can do, as the API sent it; rejects when the API fails. */
60
+ export async function loadCapabilities(): Promise<StoreCapabilities> {
61
+ const capabilities = await apiData<StoreCapabilities>('/api/capabilities')
62
+ if (capabilities === null) throw new ApiUnavailableError('GET /api/capabilities answered 404')
63
+ return capabilities
64
+ }
65
+
30
66
  /** What the store can do, which decides what the page renders; null when the API did not answer. */
31
67
  export async function fetchCapabilities(): Promise<StoreCapabilities | null> {
32
68
  try {
33
- const res = await fetch(`${API_URL}/api/capabilities`)
34
- if (!res.ok) return null
35
- const envelope = (await res.json()) as { data: StoreCapabilities }
36
- return envelope.data ?? null
69
+ return await loadCapabilities()
37
70
  } catch (err) {
38
71
  console.error('[api] fetchCapabilities failed', err)
39
72
  return null
@@ -47,47 +80,46 @@ export function sortFromUrl(url: URL, catalog?: StoreCapabilities['catalog']): P
47
80
  return keys.find((key) => key === sort) ?? catalog?.defaultSort ?? DEFAULT_PRODUCT_SORT
48
81
  }
49
82
 
50
- export async function fetchProduct(slug: string): Promise<DenormalisedProduct | null> {
51
- try {
52
- const res = await fetch(`${API_URL}/api/products/${encodeURIComponent(slug)}`)
53
- if (!res.ok) return null
54
- const envelope = (await res.json()) as { data: DenormalisedProduct }
55
- return envelope.data ?? null
56
- } catch (err) {
57
- console.error('[api] fetchProduct failed', err)
58
- return null
59
- }
83
+ /** A product as the API sent it; null when the API has none (a 404); rejects when the API fails. */
84
+ export async function loadProduct(slug: string): Promise<DenormalisedProduct | null> {
85
+ return apiData<DenormalisedProduct>(`/api/products/${encodeURIComponent(slug)}`)
60
86
  }
61
87
 
62
- const SEED_CATEGORIES: Category[] = [
63
- { id: 'cat_apparel', parentId: null, name: 'Apparel', slug: 'apparel', description: 'Clothing and accessories', position: 0, createdAt: '2024-01-01T00:00:00Z' },
64
- { id: 'cat_home', parentId: null, name: 'Home', slug: 'home', description: 'Home goods and decor', position: 1, createdAt: '2024-01-01T00:00:00Z' },
65
- { id: 'cat_electronics', parentId: null, name: 'Electronics', slug: 'electronics', description: 'Gadgets and devices', position: 2, createdAt: '2024-01-01T00:00:00Z' },
66
- { id: 'cat_books', parentId: null, name: 'Books', slug: 'books', description: 'Books and reading', position: 3, createdAt: '2024-01-01T00:00:00Z' },
67
- ]
88
+ /** The store's categories as the API sent them; rejects when the API fails. */
89
+ export async function loadCategories(): Promise<Category[]> {
90
+ const categories = await apiData<Category[]>('/api/categories')
91
+ if (categories === null) throw new ApiUnavailableError('GET /api/categories answered 404')
92
+ return categories
93
+ }
68
94
 
95
+ /**
96
+ * The store's categories, or none when the API failed: a page renders per request and no shared cache keeps it, so
97
+ * the next request shows the store's own; a list the API did not send would link to categories the store lacks.
98
+ */
69
99
  export async function fetchCategories(): Promise<Category[]> {
70
100
  try {
71
- const res = await fetch(`${API_URL}/api/categories`)
72
- if (!res.ok) return SEED_CATEGORIES
73
- const envelope = (await res.json()) as { data: Category[] }
74
- return envelope.data ?? SEED_CATEGORIES
101
+ return await loadCategories()
75
102
  } catch (err) {
76
103
  console.error('[api] fetchCategories failed', err)
77
- return SEED_CATEGORIES
104
+ return []
78
105
  }
79
106
  }
80
107
 
81
- export async function fetchOrder(orderNumber: string): Promise<Order | null> {
82
- try {
83
- const res = await fetch(`${API_URL}/api/orders/${encodeURIComponent(orderNumber)}`)
84
- if (!res.ok) return null
85
- const envelope = (await res.json()) as { data: Order }
86
- return envelope.data ?? null
87
- } catch (err) {
88
- console.error('[api] fetchOrder failed', err)
89
- return null
90
- }
108
+ /**
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.
112
+ */
113
+ export async function fetchOrder(orderNumber: string, key?: string): Promise<ShopperOrder | null> {
114
+ const path = `/api/orders/${encodeURIComponent(orderNumber)}`
115
+ const res = await fetch(`${API_URL}${path}`, {
116
+ headers: key ? { [ORDER_KEY_HEADER]: key } : {},
117
+ })
118
+ if (res.status === 404) return null
119
+ if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
120
+ const envelope = (await res.json()) as { data?: ShopperOrder | null }
121
+ if (!envelope.data) throw new ApiUnavailableError(`GET ${path} answered no data`)
122
+ return envelope.data
91
123
  }
92
124
 
93
125
  export async function fetchReviews(productId: string): Promise<ReviewsListResult> {
@@ -101,3 +133,95 @@ export async function fetchReviews(productId: string): Promise<ReviewsListResult
101
133
  return { items: [], nextCursor: null }
102
134
  }
103
135
  }
136
+
137
+ /** The cart the cart elements take as their `cart` attribute: its lines and sums, never the cart token. */
138
+ export interface CartProjection {
139
+ items: Cart['items']
140
+ subtotalMinor: number
141
+ currency: string
142
+ itemCount: number
143
+ }
144
+
145
+ const CART_COOKIE = 'nymbal.cart'
146
+
147
+ /** The `nymbal.cart` value in a request's Cookie header, or null. */
148
+ function cartToken(cookie: string | null): string | null {
149
+ for (const pair of (cookie ?? '').split(';')) {
150
+ const [name, ...value] = pair.trim().split('=')
151
+ if (name === CART_COOKIE && value.length > 0) return value.join('=')
152
+ }
153
+ return null
154
+ }
155
+
156
+ /**
157
+ * The shopper's cart, read with the request's `nymbal.cart` cookie, as the projection the elements take. Null without
158
+ * the cookie: `GET /api/cart` with none would make a cart the page could not keep, so the element renders its shell
159
+ * and the browser fills it. The cookie reaches this server when the store and the API share a host or a proxy.
160
+ */
161
+ export async function fetchCart(cookie: string | null): Promise<CartProjection | null> {
162
+ const token = cartToken(cookie)
163
+ if (token === null) return null
164
+ try {
165
+ const res = await fetch(`${API_URL}/api/cart`, {
166
+ headers: { Cookie: `${CART_COOKIE}=${token}` },
167
+ })
168
+ if (!res.ok) return null
169
+ const { items, subtotalMinor, currency } = ((await res.json()) as { data: Cart }).data
170
+ return {
171
+ items,
172
+ subtotalMinor,
173
+ currency,
174
+ itemCount: items.reduce((n, item) => n + item.qty, 0),
175
+ }
176
+ } catch (err) {
177
+ console.error('[api] fetchCart failed', err)
178
+ return null
179
+ }
180
+ }
181
+
182
+ /** The search the search page shows for `q` (and its category), as the search store would hold it. */
183
+ export async function fetchSearch(
184
+ q: string,
185
+ category: string | null,
186
+ ): Promise<ProductSearchResult | null> {
187
+ const url = new URL('/api/products/search', API_URL)
188
+ url.searchParams.set('q', q)
189
+ if (category) url.searchParams.set('category', category)
190
+ try {
191
+ const res = await fetch(url.toString())
192
+ if (!res.ok) return null
193
+ return ((await res.json()) as { data: ProductSearchResult }).data ?? null
194
+ } catch (err) {
195
+ console.error('[api] fetchSearch failed', err)
196
+ return null
197
+ }
198
+ }
199
+
200
+ /** 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> {
202
+ const res = await fetch(`${API_URL}${path}`, {
203
+ method: 'POST',
204
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
205
+ body: JSON.stringify({ token }),
206
+ })
207
+ if (res.status === 404 || res.status === 400) return null
208
+ if (!res.ok) throw new ApiUnavailableError(`POST ${path} answered ${res.status}`)
209
+ return ((await res.json()) as { data: T }).data
210
+ }
211
+
212
+ export interface AlertConfirmation {
213
+ kind: AlertKind
214
+ product: { name: string; slug: string }
215
+ }
216
+
217
+ /** 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)
220
+ }
221
+
222
+ /** 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> {
224
+ return (
225
+ (await postAlertToken<{ status: 'unsubscribed' }>('/api/alerts/unsubscribe', token)) !== null
226
+ )
227
+ }
@@ -0,0 +1,59 @@
1
+ import { renderElement } from '@nymbalhq/web-components/ssr'
2
+ import './server-elements'
3
+
4
+ // The store's header and footer, rendered by nymbal-site-header and nymbal-site-footer: edit the links here.
5
+
6
+ export const HEADER = {
7
+ logo: 'Nymbal',
8
+ 'account-href': '/account',
9
+ links: JSON.stringify([
10
+ { label: 'Apparel', href: '/category/apparel' },
11
+ { label: 'Home', href: '/category/home' },
12
+ { label: 'Electronics', href: '/category/electronics' },
13
+ { label: 'Books', href: '/category/books' },
14
+ { label: 'All Products', href: '/products' },
15
+ ]),
16
+ }
17
+
18
+ export const FOOTER = {
19
+ columns: JSON.stringify([
20
+ {
21
+ heading: 'Shop',
22
+ links: [
23
+ { label: 'All Products', href: '/products' },
24
+ { label: 'Apparel', href: '/category/apparel' },
25
+ { label: 'Home', href: '/category/home' },
26
+ { label: 'Electronics', href: '/category/electronics' },
27
+ { label: 'Books', href: '/category/books' },
28
+ ],
29
+ },
30
+ {
31
+ heading: 'Account',
32
+ links: [
33
+ { label: 'Login', href: '/account/login' },
34
+ { label: 'Register', href: '/account/register' },
35
+ { label: 'Orders', href: '/account/orders' },
36
+ ],
37
+ },
38
+ {
39
+ heading: 'About',
40
+ text: 'Nymbal is a modern headless commerce platform built for developers. Fast, flexible, and fully customisable.',
41
+ },
42
+ ]),
43
+ }
44
+
45
+ /**
46
+ * The header's light-DOM children, each rendered by the server with the slot it fills: the search bar (when the store
47
+ * searches) and the mini-cart with the shopper's count (none in a shared, cached header). HTML, not markup: Astro
48
+ * would take `slot` on a component's child as a slot of NymbalElement's own.
49
+ */
50
+ export function headerSlots(canSearch: boolean, cartCount?: number): string {
51
+ const search = canSearch
52
+ ? renderElement('nymbal-search-bar', {
53
+ attributes: { slot: 'search', placeholder: 'Search products...', 'debounce-ms': '300' },
54
+ })
55
+ : ''
56
+ const attributes: Record<string, string> = { slot: 'cart' }
57
+ if (cartCount !== undefined) attributes['count'] = String(cartCount)
58
+ return search + renderElement('nymbal-mini-cart', { attributes })
59
+ }
@@ -1,5 +1,6 @@
1
+ import '../elements/index.js'
1
2
  import { createNymbalClient } from '@nymbalhq/sdk'
2
- import { registerClient, registerComponents } from '@nymbalhq/web-components'
3
+ import { registerClient } from '@nymbalhq/web-components'
3
4
 
4
5
  const client = createNymbalClient({
5
6
  baseUrl: import.meta.env.PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
@@ -7,9 +8,8 @@ const client = createNymbalClient({
7
8
  })
8
9
 
9
10
  registerClient(client)
10
- // A payment driver of the project's own goes here, before the components: registerPaymentDriver(name, driver) from
11
- // @nymbalhq/sdk, named by the driver of the payments adapter's client half.
12
- registerComponents()
11
+ // 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.
13
13
  client.cart.load()
14
14
 
15
15
  export { client }
@@ -0,0 +1,48 @@
1
+ import type { DenormalisedProduct } from '@nymbalhq/sdk'
2
+ import type { Category } from '@nymbalhq/types'
3
+ import { loadCapabilities, loadCategories, loadProduct } from './api'
4
+
5
+ // A fragment is cached by a CDN for hours, so it carries only what the API sent: when the API fails, the fragment
6
+ // answers an error no cache keeps, never a fallback (no categories, no search bar) a CDN would hold for its TTL.
7
+
8
+ const NOT_STORED = { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }
9
+
10
+ function apiFailed(fragment: string, err: unknown): Response {
11
+ console.error(`[fragments] ${fragment}: the API failed`, err)
12
+ return new Response('The store API is unavailable', { status: 502, headers: NOT_STORED })
13
+ }
14
+
15
+ /** The header fragment's data: whether the store searches; a 502 `no-store` response when the API failed. */
16
+ export async function headerFragment(): Promise<{ canSearch: boolean } | Response> {
17
+ try {
18
+ const capabilities = await loadCapabilities()
19
+ return { canSearch: capabilities.search.capabilities.includes('search') }
20
+ } catch (err) {
21
+ return apiFailed('header', err)
22
+ }
23
+ }
24
+
25
+ /** The nav fragment's data: the API's categories; a 502 `no-store` response when the API failed. */
26
+ export async function navFragment(): Promise<{ categories: Category[] } | Response> {
27
+ try {
28
+ return { categories: await loadCategories() }
29
+ } catch (err) {
30
+ return apiFailed('nav', err)
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The product fragment's data: the API's product; a 404 `no-store` response for a product the API does not have (a CDN
36
+ * would apply its default 404 TTL to a 404 with no Cache-Control), a 502 `no-store` one when the API failed.
37
+ */
38
+ export async function productFragment(
39
+ slug: string,
40
+ ): Promise<{ product: DenormalisedProduct } | Response> {
41
+ try {
42
+ const product = await loadProduct(slug)
43
+ if (product === null) return new Response('Not found', { status: 404, headers: NOT_STORED })
44
+ return { product }
45
+ } catch (err) {
46
+ return apiFailed('product', err)
47
+ }
48
+ }
@@ -0,0 +1,5 @@
1
+ import { registerServerElements } from '@nymbalhq/web-components/ssr'
2
+ import { serverElements } from '../elements/index.js'
3
+
4
+ // The store's own elements render on the server under their tags, as the browser defines them there.
5
+ registerServerElements(serverElements)
@@ -0,0 +1,37 @@
1
+ import { defineMiddleware } from 'astro:middleware'
2
+
3
+ /** Whether an `Accept-Encoding` value accepts gzip: a `gzip` entry (or, without one, `*`) with a q-value above 0. */
4
+ function acceptsGzip(header: string): boolean {
5
+ let star = false
6
+ for (const entry of header.split(',')) {
7
+ const [coding = '', ...params] = entry.split(';').map((part) => part.trim().toLowerCase())
8
+ const q = params.find((param) => param.startsWith('q='))
9
+ const accepted = q === undefined || Number(q.slice(2)) > 0
10
+ if (coding === 'gzip' || coding === 'x-gzip') return accepted
11
+ if (coding === '*') star = accepted
12
+ }
13
+ return star
14
+ }
15
+
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.
20
+ export const onRequest = defineMiddleware(async (context, next) => {
21
+ const response = await next()
22
+ const type = response.headers.get('content-type') ?? ''
23
+ if (!type.startsWith('text/html') || response.headers.has('content-encoding')) return response
24
+ const headers = new Headers(response.headers)
25
+ headers.append('vary', 'Accept-Encoding')
26
+ 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'))
31
+ }
32
+ return new Response(body, {
33
+ status: response.status,
34
+ statusText: response.statusText,
35
+ headers,
36
+ })
37
+ })
@@ -1,6 +1,9 @@
1
1
  ---
2
2
  import '../styles/pages/error.css'
3
3
  import BaseLayout from '../layouts/BaseLayout.astro'
4
+
5
+ // An order page's not-found render, at a URL that may carry a key: the rewrite drops that page's own headers.
6
+ if (Astro.originPathname.startsWith('/order/')) Astro.response.headers.set('Referrer-Policy', 'no-referrer')
4
7
  ---
5
8
 
6
9
  <BaseLayout title="Page Not Found | Nymbal" description="The page you're looking for doesn't exist.">
@@ -1,110 +1,18 @@
1
1
  ---
2
2
  import '../../styles/pages/account.css'
3
- import '../../styles/pages/checkout.css'
3
+ import NymbalElement from '@nymbalhq/web-components/astro'
4
4
  import AccountLayout from '../../layouts/AccountLayout.astro'
5
- import AddressForm from '../../components/AddressForm.astro'
6
5
  ---
7
6
 
8
7
  <AccountLayout title="Addresses">
9
8
  <h1 class="account-page-title">Addresses</h1>
10
9
 
11
- <div id="addresses-container" data-testid="addresses-list">
12
- <p style="color: var(--nymbal-color-text-muted, #71717a); font-size: var(--nymbal-font-size-sm, 0.875rem);">
13
- Loading addresses...
14
- </p>
15
- </div>
16
-
17
- <div style="margin-top: var(--nymbal-spacing-xl, 2rem);">
18
- <h2 class="section-title">Add New Address</h2>
19
- <form id="add-address-form" class="account-form" data-testid="add-address-form">
20
- <AddressForm id="new-address" />
21
- <div class="account-form-actions">
22
- <button type="submit" class="btn btn-primary" data-testid="save-address">Save Address</button>
23
- </div>
24
- </form>
25
- <p class="form-message" id="address-form-message" style="display:none; margin-top: var(--nymbal-spacing-md, 1rem); font-size: var(--nymbal-font-size-sm, 0.875rem);"></p>
26
- </div>
10
+ <NymbalElement tag="nymbal-address-book" />
27
11
  </AccountLayout>
28
12
 
29
13
  <script>
30
- import type { Address, CustomerAddress } from '@nymbalhq/types'
31
- import { client } from '../../lib/client.js'
32
- import { escapeHtml } from '../../lib/format.js'
33
- import { submitOnce } from '../../lib/submit-once.js'
34
-
35
- const container = document.getElementById('addresses-container')
36
- const form = document.getElementById('add-address-form') as HTMLFormElement | null
37
- const messageEl = document.getElementById('address-form-message')
38
-
39
- function renderAddress(addr: CustomerAddress): string {
40
- const isDefault = addr.isDefaultShipping || addr.isDefaultBilling
41
- return `
42
- <div class="address-card ${isDefault ? 'default' : ''}" data-testid="address-${escapeHtml(addr.id)}">
43
- ${isDefault ? '<span class="address-card-badge">Default</span>' : ''}
44
- <div class="address-card-line">${escapeHtml(`${addr.firstName} ${addr.lastName}`)}</div>
45
- <div class="address-card-line">${escapeHtml(addr.addressLine1)}</div>
46
- ${addr.addressLine2 ? `<div class="address-card-line">${escapeHtml(addr.addressLine2)}</div>` : ''}
47
- <div class="address-card-line">${escapeHtml(`${addr.city}, ${addr.region} ${addr.postalCode}`)}</div>
48
- <div class="address-card-line">${escapeHtml(addr.country)}</div>
49
- </div>
50
- `
51
- }
52
-
53
- async function loadAddresses() {
54
- if (!container) return
55
-
56
- try {
57
- const addresses = await client.customer.addresses.list()
58
-
59
- if (addresses.length === 0) {
60
- container.innerHTML = `
61
- <div class="account-empty">
62
- <h2 class="account-empty-title">No saved addresses</h2>
63
- <p class="account-empty-text">Add an address below to get started.</p>
64
- </div>
65
- `
66
- return
67
- }
68
-
69
- container.innerHTML = `<div class="address-list">${addresses.map(renderAddress).join('')}</div>`
70
- } catch {
71
- container.innerHTML = `
72
- <div class="account-empty">
73
- <p class="account-empty-text">Unable to load addresses.</p>
74
- </div>
75
- `
76
- }
77
- }
78
-
79
- submitOnce(form, async () => {
80
- if (!form || !messageEl) return
81
-
82
- const formData = new FormData(form)
83
- const field = (name: string) => String(formData.get(name) ?? '').trim()
84
- const address: Address = {
85
- firstName: field('firstName'),
86
- lastName: field('lastName'),
87
- addressLine1: field('addressLine1'),
88
- city: field('city'),
89
- region: field('region'),
90
- postalCode: field('postalCode'),
91
- country: field('country'),
92
- ...(field('addressLine2') && { addressLine2: field('addressLine2') }),
93
- }
94
-
95
- try {
96
- await client.customer.addresses.create(address)
97
- messageEl.textContent = 'Address saved successfully.'
98
- messageEl.style.color = 'var(--nymbal-color-success, #16a34a)'
99
- messageEl.style.display = 'block'
100
- form.reset()
101
- await loadAddresses()
102
- } catch {
103
- messageEl.textContent = 'Failed to save address. Please try again.'
104
- messageEl.style.color = 'var(--nymbal-color-error, #dc2626)'
105
- messageEl.style.display = 'block'
106
- }
107
- })
14
+ import '../../lib/client.js'
15
+ import { NymbalAddressBook } from '@nymbalhq/web-components/elements/nymbal-address-book'
108
16
 
109
- loadAddresses()
17
+ NymbalAddressBook.define()
110
18
  </script>
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  import '../../styles/pages/account.css'
3
+ import NymbalElement from '@nymbalhq/web-components/astro'
3
4
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
5
  ---
5
6
 
@@ -9,39 +10,7 @@ import BaseLayout from '../../layouts/BaseLayout.astro'
9
10
  <h1 class="auth-card-title">Sign In</h1>
10
11
  <p class="auth-card-subtitle">Welcome back. Enter your credentials to continue.</p>
11
12
 
12
- <div class="checkout-error" id="login-error" style="display:none; margin-bottom: var(--nymbal-spacing-md, 1rem);" role="alert"></div>
13
-
14
- <form id="login-form" data-testid="login-form">
15
- <div class="form-group">
16
- <label for="login-email">Email</label>
17
- <input
18
- type="email"
19
- id="login-email"
20
- name="email"
21
- required
22
- autocomplete="email"
23
- placeholder="you@example.com"
24
- data-testid="login-email"
25
- />
26
- </div>
27
-
28
- <div class="form-group">
29
- <label for="login-password">Password</label>
30
- <input
31
- type="password"
32
- id="login-password"
33
- name="password"
34
- required
35
- autocomplete="current-password"
36
- placeholder="Your password"
37
- data-testid="login-password"
38
- />
39
- </div>
40
-
41
- <button type="submit" class="btn btn-primary" data-testid="login-submit">
42
- Sign In
43
- </button>
44
- </form>
13
+ <NymbalElement tag="nymbal-login-form" />
45
14
 
46
15
  <p class="auth-footer">
47
16
  Don't have an account? <a href="/account/register">Create one</a>
@@ -51,5 +20,9 @@ import BaseLayout from '../../layouts/BaseLayout.astro'
51
20
  </BaseLayout>
52
21
 
53
22
  <script>
54
- import '../../scripts/auth-forms.js'
23
+ import '../../lib/client.js'
24
+ import { NymbalLoginForm } from '@nymbalhq/web-components/elements/nymbal-login-form'
25
+ import '../../scripts/signed-in-redirect.js'
26
+
27
+ NymbalLoginForm.define()
55
28
  </script>
@@ -13,8 +13,12 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
13
13
  </AccountLayout>
14
14
 
15
15
  <script>
16
+ import { NymbalApiError } from '@nymbalhq/sdk'
16
17
  import { client } from '../../../lib/client.js'
17
18
  import { escapeHtml, formatPrice, formatDate } from '../../../lib/format.js'
19
+ import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
20
+
21
+ NymbalOrderTimeline.define()
18
22
 
19
23
  const container = document.getElementById('order-detail-container')
20
24
  const orderNumber = container?.dataset.orderNumber
@@ -35,6 +39,8 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
35
39
  <span class="order-status status-${escapeHtml(order.status)}">${escapeHtml(order.status)}</span>
36
40
  </div>
37
41
 
42
+ ${order.timeline?.length ? `<nymbal-order-timeline style="display: block; margin-bottom: var(--nymbal-spacing-lg, 1.5rem);" entries="${escapeHtml(JSON.stringify(order.timeline))}"></nymbal-order-timeline>` : ''}
43
+
38
44
  <div class="confirmation-card">
39
45
  <h2 class="confirmation-card-title">Items</h2>
40
46
  <div class="confirmation-items" style="margin-top: 0; padding-top: 0; border-top: none;">
@@ -93,11 +99,13 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
93
99
 
94
100
  <a href="/account/orders" class="btn btn-secondary" style="margin-top: var(--nymbal-spacing-md, 1rem);">Back to Orders</a>
95
101
  `
96
- } catch {
102
+ } catch (err) {
103
+ // The API answers another shopper's order as it answers a number no order has: a 404 is not found, not a failure.
104
+ const notFound = err instanceof NymbalApiError && err.status === 404
97
105
  container.innerHTML = `
98
106
  <div class="account-empty">
99
- <h2 class="account-empty-title">Unable to load order</h2>
100
- <p class="account-empty-text">Please try again later.</p>
107
+ <h2 class="account-empty-title">${notFound ? 'Order Not Found' : 'Unable to load order'}</h2>
108
+ <p class="account-empty-text">${notFound ? 'This order could not be found.' : 'Please try again later.'}</p>
101
109
  <a href="/account/orders" class="btn btn-secondary">Back to Orders</a>
102
110
  </div>
103
111
  `