@websolutespa/bom-next 4.0.0-next.12 → 4.0.0-next.14

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 (288) hide show
  1. package/CHANGELOG.md +27 -2
  2. package/README.md +132 -114
  3. package/dist/cache-handler/redis.js.map +1 -1
  4. package/dist/cache-handlers/default.js.map +1 -1
  5. package/dist/client/client.js +5 -5
  6. package/dist/client/client.js.map +1 -1
  7. package/dist/client/extra.js.map +1 -1
  8. package/dist/client/label.js.map +1 -1
  9. package/dist/client/layout.js.map +1 -1
  10. package/dist/client/local.collection.js.map +1 -1
  11. package/dist/client/metadata.js.map +1 -1
  12. package/dist/client/page.d.ts.map +1 -1
  13. package/dist/client/page.js.map +1 -1
  14. package/dist/client/useApi.js.map +1 -1
  15. package/dist/client/useCollectionApi.js.map +1 -1
  16. package/dist/client/useExtra.js.map +1 -1
  17. package/dist/client/useHttp.js.map +1 -1
  18. package/dist/client/useLabel.js.map +1 -1
  19. package/dist/client/useLayout.js.map +1 -1
  20. package/dist/client/useLink.js.map +1 -1
  21. package/dist/client/useMetaData.js.map +1 -1
  22. package/dist/client/usePage.d.ts.map +1 -1
  23. package/dist/client/usePage.js.map +1 -1
  24. package/dist/client/useUser.js.map +1 -1
  25. package/dist/client/user.d.ts.map +1 -1
  26. package/dist/client/user.js.map +1 -1
  27. package/dist/config/with-bom.js.map +1 -1
  28. package/dist/exports/proxy.d.ts +4 -3
  29. package/dist/exports/proxy.js +4 -3
  30. package/dist/exports/server.d.ts +5 -3
  31. package/dist/exports/server.js +5 -3
  32. package/dist/index.d.ts +8 -4
  33. package/dist/index.js +6 -2
  34. package/dist/instrumentation/client.js.map +1 -1
  35. package/dist/instrumentation/sentry/capture.requestError.js.map +1 -1
  36. package/dist/instrumentation/sentry/capture.routerTransitionStart.js.map +1 -1
  37. package/dist/instrumentation/sentry/config.client.js.map +1 -1
  38. package/dist/instrumentation/sentry/config.edge.js.map +1 -1
  39. package/dist/instrumentation/sentry/config.server.js.map +1 -1
  40. package/dist/instrumentation/server.js.map +1 -1
  41. package/dist/lib/breadcrumb.js.map +1 -1
  42. package/dist/lib/const.d.ts +9 -1
  43. package/dist/lib/const.d.ts.map +1 -1
  44. package/dist/lib/const.js +16 -1
  45. package/dist/lib/const.js.map +1 -1
  46. package/dist/lib/cors.d.ts +25 -0
  47. package/dist/lib/cors.d.ts.map +1 -0
  48. package/dist/lib/cors.js +42 -0
  49. package/dist/lib/cors.js.map +1 -0
  50. package/dist/lib/debug.js.map +1 -1
  51. package/dist/lib/http.js.map +1 -1
  52. package/dist/lib/label.js.map +1 -1
  53. package/dist/lib/layout.defaults.js.map +1 -1
  54. package/dist/lib/link.js.map +1 -1
  55. package/dist/lib/page-metadata.d.ts +13 -2
  56. package/dist/lib/page-metadata.d.ts.map +1 -1
  57. package/dist/lib/page-metadata.js +10 -3
  58. package/dist/lib/page-metadata.js.map +1 -1
  59. package/dist/lib/pagination.js.map +1 -1
  60. package/dist/lib/route.js.map +1 -1
  61. package/dist/lib/seed-env.d.ts +13 -0
  62. package/dist/lib/seed-env.d.ts.map +1 -0
  63. package/dist/lib/seed-env.js +18 -0
  64. package/dist/lib/seed-env.js.map +1 -0
  65. package/dist/lib/spam.d.ts +38 -0
  66. package/dist/lib/spam.d.ts.map +1 -0
  67. package/dist/lib/spam.js +43 -0
  68. package/dist/lib/spam.js.map +1 -0
  69. package/dist/lib/store.js.map +1 -1
  70. package/dist/lib/ttl-cache.js.map +1 -1
  71. package/dist/lib/user.d.ts +16 -0
  72. package/dist/lib/user.d.ts.map +1 -0
  73. package/dist/lib/user.js +21 -0
  74. package/dist/lib/user.js.map +1 -0
  75. package/dist/lib/utils.js.map +1 -1
  76. package/dist/proxy/api-cors.d.ts +24 -0
  77. package/dist/proxy/api-cors.d.ts.map +1 -0
  78. package/dist/proxy/api-cors.js +35 -0
  79. package/dist/proxy/api-cors.js.map +1 -0
  80. package/dist/proxy/protected-route.js.map +1 -1
  81. package/dist/proxy/proxy.js.map +1 -1
  82. package/dist/proxy/route-auto-detection.d.ts +3 -1
  83. package/dist/proxy/route-auto-detection.d.ts.map +1 -1
  84. package/dist/proxy/route-auto-detection.js +20 -4
  85. package/dist/proxy/route-auto-detection.js.map +1 -1
  86. package/dist/proxy/route-proxy.d.ts +2 -1
  87. package/dist/proxy/route-proxy.d.ts.map +1 -1
  88. package/dist/proxy/route-proxy.js +8 -4
  89. package/dist/proxy/route-proxy.js.map +1 -1
  90. package/dist/server/cache/cached-types.js.map +1 -1
  91. package/dist/server/cache/cached.js.map +1 -1
  92. package/dist/server/cache/defaults.js.map +1 -1
  93. package/dist/server/cache/executor.js.map +1 -1
  94. package/dist/server/cache/handler.js.map +1 -1
  95. package/dist/server/cache/inspector/filesystem.js.map +1 -1
  96. package/dist/server/cache/inspector/index.js.map +1 -1
  97. package/dist/server/cache/inspector/redis.js.map +1 -1
  98. package/dist/server/cache/inspector/route-cache-key.js.map +1 -1
  99. package/dist/server/cache/inspector/types.js.map +1 -1
  100. package/dist/server/cache/local-executor.js.map +1 -1
  101. package/dist/server/cache/mode/classic.js.map +1 -1
  102. package/dist/server/cache/mode/components.js.map +1 -1
  103. package/dist/server/cache/profiles.js.map +1 -1
  104. package/dist/server/cache/registry.js.map +1 -1
  105. package/dist/server/cache/tag-page.js.map +1 -1
  106. package/dist/server/context.js.map +1 -1
  107. package/dist/server/handlers/auth.handler.d.ts.map +1 -1
  108. package/dist/server/handlers/auth.handler.js +6 -4
  109. package/dist/server/handlers/auth.handler.js.map +1 -1
  110. package/dist/server/handlers/captions.handler.js.map +1 -1
  111. package/dist/server/handlers/collection.handler.js.map +1 -1
  112. package/dist/server/handlers/error-response.js.map +1 -1
  113. package/dist/server/handlers/index.handler.js.map +1 -1
  114. package/dist/server/handlers/preview.handler.d.ts +27 -3
  115. package/dist/server/handlers/preview.handler.d.ts.map +1 -1
  116. package/dist/server/handlers/preview.handler.js +57 -6
  117. package/dist/server/handlers/preview.handler.js.map +1 -1
  118. package/dist/server/handlers/registry.handler.js.map +1 -1
  119. package/dist/server/handlers/revalidate.handler.js.map +1 -1
  120. package/dist/server/handlers/route.handler.js.map +1 -1
  121. package/dist/server/handlers/sitemap.handler.js.map +1 -1
  122. package/dist/server/handlers/static-params.handler.js.map +1 -1
  123. package/dist/server/handlers/vars.handler.js.map +1 -1
  124. package/dist/server/helpers.js.map +1 -1
  125. package/dist/server/json-ld.js.map +1 -1
  126. package/dist/server/layout.js.map +1 -1
  127. package/dist/server/lazy.js.map +1 -1
  128. package/dist/server/local-api.js.map +1 -1
  129. package/dist/server/metadata.d.ts +1 -1
  130. package/dist/server/metadata.js.map +1 -1
  131. package/dist/server/mixer.d.ts +1 -1
  132. package/dist/server/mixer.d.ts.map +1 -1
  133. package/dist/server/mixer.js +11 -2
  134. package/dist/server/mixer.js.map +1 -1
  135. package/dist/server/page.js.map +1 -1
  136. package/dist/server/rate-limit.d.ts +37 -0
  137. package/dist/server/rate-limit.d.ts.map +1 -0
  138. package/dist/server/rate-limit.js +55 -0
  139. package/dist/server/rate-limit.js.map +1 -0
  140. package/dist/server/utils.js.map +1 -1
  141. package/dist/server/utmz.js.map +1 -1
  142. package/package.json +2 -2
  143. package/src/cache-handler/redis.test.ts +230 -230
  144. package/src/cache-handler/redis.ts +344 -344
  145. package/src/cache-handlers/default.test.ts +125 -125
  146. package/src/cache-handlers/default.ts +246 -246
  147. package/src/client/client.tsx +20 -20
  148. package/src/client/extra.tsx +17 -17
  149. package/src/client/label.tsx +20 -20
  150. package/src/client/layout.tsx +18 -18
  151. package/src/client/local.collection.ts +72 -72
  152. package/src/client/metadata.tsx +187 -187
  153. package/src/client/page.tsx +18 -18
  154. package/src/client/useApi.test.tsx +212 -212
  155. package/src/client/useApi.ts +115 -115
  156. package/src/client/useCollectionApi.test.tsx +213 -213
  157. package/src/client/useCollectionApi.ts +135 -135
  158. package/src/client/useExtra.tsx +12 -12
  159. package/src/client/useHttp.ts +78 -78
  160. package/src/client/useLabel.test.tsx +82 -82
  161. package/src/client/useLabel.tsx +12 -12
  162. package/src/client/useLayout.tsx +13 -13
  163. package/src/client/useLink.tsx +16 -16
  164. package/src/client/useMetaData.tsx +12 -12
  165. package/src/client/usePage.tsx +12 -12
  166. package/src/client/useUser.tsx +12 -12
  167. package/src/client/user.test.tsx +63 -63
  168. package/src/client/user.tsx +73 -72
  169. package/src/config/with-bom.test.ts +61 -61
  170. package/src/config/with-bom.ts +68 -68
  171. package/src/exports/cache-handlers-default.ts +3 -3
  172. package/src/exports/cache-handlers-isr.ts +9 -9
  173. package/src/exports/client.ts +19 -19
  174. package/src/exports/config.ts +3 -3
  175. package/src/exports/instrumentation.ts +1 -1
  176. package/src/exports/proxy.ts +1 -0
  177. package/src/exports/server.ts +1 -0
  178. package/src/global.d.ts +6 -6
  179. package/src/index.ts +4 -0
  180. package/src/instrumentation/client.ts +18 -18
  181. package/src/instrumentation/sentry/capture.requestError.ts +9 -9
  182. package/src/instrumentation/sentry/capture.routerTransitionStart.ts +7 -7
  183. package/src/instrumentation/sentry/config.client.ts +9 -9
  184. package/src/instrumentation/sentry/config.edge.ts +9 -9
  185. package/src/instrumentation/sentry/config.server.ts +9 -9
  186. package/src/instrumentation/server.ts +39 -39
  187. package/src/instrumentation/types.ts +11 -11
  188. package/src/lib/breadcrumb.ts +25 -25
  189. package/src/lib/const.ts +28 -18
  190. package/src/lib/cors.test.ts +29 -0
  191. package/src/lib/cors.ts +55 -0
  192. package/src/lib/debug.ts +11 -11
  193. package/src/lib/http.test.ts +25 -25
  194. package/src/lib/http.ts +127 -127
  195. package/src/lib/label.ts +47 -47
  196. package/src/lib/layout.defaults.ts +167 -167
  197. package/src/lib/link.ts +19 -19
  198. package/src/lib/meta-data.ts +60 -60
  199. package/src/lib/open-graph.ts +165 -165
  200. package/src/lib/page-metadata.test.ts +192 -160
  201. package/src/lib/page-metadata.ts +296 -277
  202. package/src/lib/pagination.ts +80 -80
  203. package/src/lib/route.test.ts +62 -62
  204. package/src/lib/route.ts +117 -117
  205. package/src/lib/seed-env.ts +17 -0
  206. package/src/lib/spam.test.ts +39 -0
  207. package/src/lib/spam.ts +59 -0
  208. package/src/lib/store.ts +63 -63
  209. package/src/lib/structured-data.ts +24 -24
  210. package/src/lib/ttl-cache.ts +72 -72
  211. package/src/lib/twitter-card.ts +49 -49
  212. package/src/lib/user.test.ts +21 -0
  213. package/src/lib/user.ts +25 -0
  214. package/src/lib/utils.ts +44 -44
  215. package/src/mock.ts +292 -292
  216. package/src/proxy/api-cors.test.ts +30 -0
  217. package/src/proxy/api-cors.ts +42 -0
  218. package/src/proxy/protected-route.test.ts +75 -75
  219. package/src/proxy/protected-route.ts +68 -68
  220. package/src/proxy/proxy.test.ts +51 -51
  221. package/src/proxy/proxy.ts +81 -81
  222. package/src/proxy/route-auto-detection.test.ts +98 -55
  223. package/src/proxy/route-auto-detection.ts +247 -222
  224. package/src/proxy/route-proxy.test.ts +140 -104
  225. package/src/proxy/route-proxy.ts +295 -291
  226. package/src/server/cache/cached-types.ts +73 -73
  227. package/src/server/cache/cached.test.ts +115 -115
  228. package/src/server/cache/cached.ts +22 -22
  229. package/src/server/cache/defaults.ts +46 -46
  230. package/src/server/cache/executor.test.ts +134 -134
  231. package/src/server/cache/executor.ts +141 -141
  232. package/src/server/cache/handler.test.ts +122 -122
  233. package/src/server/cache/handler.ts +126 -126
  234. package/src/server/cache/index.ts +39 -39
  235. package/src/server/cache/inspector/filesystem.test.ts +142 -142
  236. package/src/server/cache/inspector/filesystem.ts +214 -214
  237. package/src/server/cache/inspector/index.ts +19 -19
  238. package/src/server/cache/inspector/redis.test.ts +97 -97
  239. package/src/server/cache/inspector/redis.ts +183 -183
  240. package/src/server/cache/inspector/route-cache-key.test.ts +31 -31
  241. package/src/server/cache/inspector/route-cache-key.ts +40 -40
  242. package/src/server/cache/inspector/types.ts +49 -49
  243. package/src/server/cache/local-executor.ts +39 -39
  244. package/src/server/cache/mode/classic.ts +59 -59
  245. package/src/server/cache/mode/components.test.ts +53 -53
  246. package/src/server/cache/mode/components.ts +64 -64
  247. package/src/server/cache/profiles.ts +41 -41
  248. package/src/server/cache/registry.test.ts +66 -66
  249. package/src/server/cache/registry.ts +82 -82
  250. package/src/server/cache/route-parity.test.ts +33 -33
  251. package/src/server/cache/tag-page.ts +23 -23
  252. package/src/server/context.cache.test.ts +79 -79
  253. package/src/server/context.test.ts +645 -645
  254. package/src/server/context.ts +488 -488
  255. package/src/server/context.type-test.ts +112 -112
  256. package/src/server/handlers/auth.handler.ts +31 -32
  257. package/src/server/handlers/captions.handler.ts +36 -36
  258. package/src/server/handlers/collection.handler.test.ts +63 -63
  259. package/src/server/handlers/collection.handler.ts +221 -221
  260. package/src/server/handlers/error-response.ts +50 -50
  261. package/src/server/handlers/index.handler.ts +153 -153
  262. package/src/server/handlers/preview.handler.test.ts +92 -0
  263. package/src/server/handlers/preview.handler.ts +95 -63
  264. package/src/server/handlers/registry.handler.test.ts +171 -171
  265. package/src/server/handlers/registry.handler.ts +514 -514
  266. package/src/server/handlers/revalidate.handler.ts +148 -148
  267. package/src/server/handlers/route.handler.test.ts +50 -50
  268. package/src/server/handlers/route.handler.ts +188 -188
  269. package/src/server/handlers/sitemap.handler.ts +432 -432
  270. package/src/server/handlers/static-params.cache.test.ts +81 -81
  271. package/src/server/handlers/static-params.handler.ts +123 -123
  272. package/src/server/handlers/vars.handler.ts +174 -174
  273. package/src/server/helpers.ts +97 -97
  274. package/src/server/json-ld.tsx +65 -65
  275. package/src/server/layout.ts +148 -148
  276. package/src/server/lazy.ts +41 -41
  277. package/src/server/local-api.ts +67 -67
  278. package/src/server/metadata.ts +79 -79
  279. package/src/server/mixer-payload.ts +115 -115
  280. package/src/server/mixer-payload.type-test.ts +27 -27
  281. package/src/server/mixer.ts +513 -496
  282. package/src/server/page.ts +148 -148
  283. package/src/server/rate-limit.test.ts +90 -0
  284. package/src/server/rate-limit.ts +95 -0
  285. package/src/server/request-data.test.ts +34 -34
  286. package/src/server/utils.ts +23 -23
  287. package/src/server/utmz.ts +11 -11
  288. package/src/types.ts +363 -363
package/CHANGELOG.md CHANGED
@@ -1,11 +1,37 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.14
4
+
5
+ ### Minor Changes
6
+
7
+ - e88fd77: - **`isEndUser(user)`** (main entry, isomorphic): a site end user has the `user` role and comes from the `end_users` collection (or carries the end user's name fields); a back-office user given the `user` role is not one. `/api/auth/me` uses the same rule.
8
+ - **`createRateLimiter({ prefix, limit, windowSeconds })`** (`/server`): fixed-window limiter for public endpoints such as form actions. Counts in Redis (`<REDIS_PREFIX>:rate:...`, shared by every instance) when `REDIS_URL` is set and ready, in a bounded per-process map otherwise; a Redis error falls back to memory.
9
+ - e88fd77: Security helpers shared by every site, moved from the bom-sample app:
10
+ - CORS: `getAllowedOrigins`, `getCsrfOrigins`, `getCorsHeaders` (main entry) and `createApiCorsProxy` (`/proxy`), an allowlist echoed with credentials instead of `Access-Control-Allow-Origin: *`.
11
+ - Anti-spam: `SPAM_FIELDS`, `getSpamReason`, `ANTI_SPAM_DEFAULTS`, `getClientIp` (main entry, isomorphic).
12
+ - Seed credentials: `requireSeedEnv(key)` (main entry), no literal fallback.
13
+
14
+ ### Patch Changes
15
+
16
+ - f13b6ab: Route proxy fixes.
17
+ - Draft Mode: public URLs are resolved as usual (editors see drafts on them) instead of falling through to a 404; unresolved paths, such as the internal preview path, are still left to Next. A project workaround that drops `__prerender_bypass` on public URLs can be removed.
18
+ - `routeAutoDetection`: a `detectedRoute` cookie redirects only when it names a current root route; a stale one (e.g. a removed market) runs detection again and is overwritten. Root routes are cached per instance for `BOM_ROUTE_CACHE_TTL` seconds.
19
+
20
+ ## 4.0.0-next.13
21
+
22
+ ### Minor Changes
23
+
24
+ - **Security: Draft Mode only for editors.** `previewHandler` turned Next.js Draft Mode on for any visitor (its secret check was commented out), and draft renders then showed unpublished pages to anyone.
25
+ - New `getPreviewHandler(config, { roles })` for `src/app/api/-preview/route.ts`: it turns Draft Mode on for a logged-in editor (admin, contributor, editor: the admin session cookie, or the `_token` Bowl adds to the admin's preview URL, for an admin on another origin) or for `secret` equal to `MIXER_SECRET`; everyone else gets 401 and no cookie. The redirect accepts path segments only.
26
+ - `previewHandler(request)` is deprecated: without the config it cannot authenticate a user, so it now requires `secret` (`MIXER_SECRET`). Switch the route to `export const GET = getPreviewHandler(config)`.
27
+ - Draft reads: Bowl now serves drafts to the editing roles only, so `getPayload` reads a draft render without an editor session as an editor identity (`previewer`), and only while Draft Mode is really on; a `draft: true` read outside Draft Mode reads the published site. `PREVIEW_ROLES` and `previewer` are exported.
28
+ - **Indexing policy.** `buildPageMetadata` (and `getPageMetadata`) take `indexable: boolean | (page) => boolean`; a page that is not indexable gets `robots: 'noindex, nofollow'` over its own `meta.robots`. The default is `isIndexableDeployment()`: indexable only with `PRODUCTION=true` and without `NOINDEX=true`, as the BOM 3 `Meta` component did, so staging and preview deployments are no longer indexable. **A production site must set `PRODUCTION=true`.**
29
+
3
30
  ## 4.0.0-next.12
4
31
 
5
32
  ### Patch Changes
6
33
 
7
34
  - Shared Redis cache across instances and cold starts.
8
-
9
35
  - **Lifetime of shared entries.** `cache-handlers/isr` stores the route lifetime (`cacheControl`) with every entry and returns it from `get`. Next.js 16.4 knows the lifetime only of the paths an instance rendered or prerendered, and treated an entry written by another instance as revalidate 1 s: every instance served it stale once and re-rendered it. Entries written before this release fall back to their stored `revalidate`.
10
36
  - **One client per process.** The Redis client lives on `globalThis`, so the handler (loaded by Next.js from node_modules) and the bundled server code share one connection, and concurrent first calls no longer create two clients.
11
37
  - **Cold start.** `registerIntrumentation()` connects the client before the first request (at most the 2 s connect timeout while Redis is down; skipped during `next build`), so the first page of a new instance reads Redis instead of rendering. The cache panel inspector waits for the connection the same way instead of reporting `none`. New export `connectRedisClient(timeout)` from `@websolutespa/bom-next/cache-handlers/isr`.
@@ -15,7 +41,6 @@
15
41
  ### Minor Changes
16
42
 
17
43
  - 67f9535: Site side of the Next.js cache panel, named cached functions, and support for both caching models (classic ISR and Cache Components).
18
-
19
44
  - **Page tags.** `createPageContext` and `createLayoutContext` tag every rendered page from its route: market, locale, collection, document, route, category ancestors and the layout collections. Decorators that list other documents call `tagPage([collectionTag('…')])`.
20
45
  - **Cache endpoint.** `getCacheHandler()` (`/api/-cache`, Bearer `MIXER_SECRET`) reports the cached pages, functions and process caches of the instance (file system, Redis, or none on Vercel) and applies cache actions. `revalidate` maps to `revalidateTag(tag, 'max')`, `invalidate` to `revalidateTag(tag, { expire: 0 })`; actions can also revalidate paths, clear process caches and warm pages after the response. `registerIntrumentation()` registers it in process for the Bowl admin, so sites need no change.
21
46
  - **Next.js 16.4 route cache.** The inspector reads both `.next/server/app` and the runtime route cache (`.next/server/route-cache/<kind>/<sha256(source route)>/$/<path>`).
package/README.md CHANGED
@@ -1,114 +1,132 @@
1
- # @websolutespa/bom-next
2
-
3
- [![npm version](https://badge.fury.io/js/%40websolutespa%2Fbom-next.svg)](https://badge.fury.io/js/%40websolutespa%2Fbom-next)
4
-
5
- [![status alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://shields.io/)
6
-
7
- Next module of the [BOM Repository](https://github.com/websolutespa/bom) by [websolute](https://www.websolute.com/).
8
-
9
- ---
10
-
11
- ##### _this library is for internal usage and not production ready_
12
-
13
- ## Page context
14
-
15
- ```ts
16
- import { createPageContext, getMetadata } from '@websolutespa/bom-next/server';
17
-
18
- export const generateMetadata = getMetadata('post_detail', config);
19
-
20
- const { page, layout, label, link } = await createPageContext(market, locale, 'post_detail', id, {
21
- config,
22
- depth: 2, // default DEFAULT_PAGE_DEPTH
23
- select: { title: true, abstract: true, media: true, components: true },
24
- populate: { media: { url: true, alt: true, width: true, height: true, type: true } },
25
- });
26
-
27
- const { layout } = await createLayoutContext(market, locale, { config }); // depth: DEFAULT_LAYOUT_DEPTH (1)
28
- ```
29
-
30
- | option | default | |
31
- | ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------ |
32
- | `depth` | `2` | `0` ids only, `1` direct relations/uploads (including those inside blocks), `2` relations of relations |
33
- | `select` | – | Payload select; envelope fields (`id`, `slug`, `title`, `category`, `markets`, `meta`, `template`) are always read |
34
- | `populate` | – | per-collection select for populated documents |
35
- | `draft` | `'auto'` | `true` / `false`, or `'auto'` to read Next `draftMode()` |
36
- | `layout` | `{ depth: 1 }` | layout options, or `false` to skip the layout |
37
-
38
- Page and layout reads are memoized per request, so `getMetadata` and the page component share them when called with the same options.
39
- To bind `config` once: `export const { createPageContext, createLayoutContext, getMetadata } = createContextHelpers({ config, defaults: { depth: 2 } });`
40
-
41
- ## Metadata
42
-
43
- `getPageMetadata` (and `getMetadata`, its `config`-first form) returns a `generateMetadata` function that renders on the server: plain-text title and description, canonical (keeping `?pagination[page]=N` after the first page), `alternates.languages` with one `locale-COUNTRY` entry per market country plus `x-default`, robots, keywords, Open Graph and Twitter.
44
-
45
- ```ts
46
- import { getPageMetadata, JsonLd, buildPageStructuredData } from '@websolutespa/bom-next/server';
47
-
48
- export const generateMetadata = getPageMetadata('post_detail', {
49
- config,
50
- metadata: {
51
- brand: { name: 'Example', logo: '/logo.png', twitterName: '@example' },
52
- extend: (metadata, { page }) => ({ ...metadata, title: `${metadata.title} | Example` }),
53
- },
54
- });
55
-
56
- // JSON-LD in the page component
57
- <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
- ```
59
-
60
- `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field).
61
-
62
- The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
-
64
- `layout.homeHref` is the root page href for the current market and locale; prefer it to `layout.topLevelHrefs.<slug>`, which is keyed by collection slug or template.
65
-
66
- ## Routing proxy
67
-
68
- `createRouteProxy` resolves each request through `/api/-route` and caches the result per instance: found routes for `BOM_ROUTE_CACHE_TTL` seconds (default `30`, `0` disables), misses and redirects for at most 10 seconds. Draft requests and server errors are never cached. CMS redirects send the browser to the target returned by the resolver.
69
-
70
- `routeAutoDetection` redirects `/` straight from the `detectedRoute` cookie when present; otherwise it detects the market (GeoIP, 2 s timeout, cached per IP for one hour) and the locale.
71
-
72
- The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
-
74
- ## Cache
75
-
76
- Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
77
-
78
- ```ts
79
- // src/app/api/-cache/route.ts
80
- import { getCacheHandler } from '@websolutespa/bom-next/server';
81
-
82
- export const { GET, POST } = getCacheHandler();
83
- export const dynamic = 'force-dynamic';
84
- ```
85
-
86
- - `tagPage(tags)` adds tags to the page being rendered, for example a decorator that lists another collection: `tagPage([collectionTag('post_detail')])`.
87
- - `bomCached(name, fn, { life, tags, resultTags })` caches a data function by name. `life` is a BOM profile (`bom-layout`, `bom-page`, `bom-listing`, `bom-static`, see `bomProfiles`) or an inline profile. `documentTags(collection, result)` tags a result by its documents. Every entry carries `bom:fn:<name>`, so the panel lists and revalidates it.
88
- - `withBom(nextConfig)` (`@websolutespa/bom-next/config`) wires the caching model:
89
- - **Classic ISR** (default): `bomCached` uses `unstable_cache`, templates keep `generateStaticParams` and `export const revalidate`.
90
- - **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
91
- - **`REDIS_URL` at build time**: `cacheHandler` is the shared Redis handler (`@websolutespa/bom-next/cache-handlers/isr`), which applies `revalidateTag(tag, 'max')` as stale-while-revalidate across instances; `'use cache'` entries share its tag keys.
92
- - `registerIntrumentation()` registers the in-process cache executor; Bowl uses `/api/-cache` (Bearer `MIXER_SECRET`) when it runs in another process.
93
-
94
- The cache panel reads the file-system cache (`.next/server/app` and the Next.js 16.4 runtime route cache under `.next/server/route-cache`), the Redis handlers' meta keys, or nothing on Vercel. `next dev` has no ISR cache: check the panel after `next build && next start`.
95
-
96
- ## Environment
97
-
98
- Per-request diagnostics (proxy, local API calls, context cache) are logged in development only (`NODE_ENV` unset or `development`).
99
-
100
- | Variable | Default | |
101
- | ----------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
102
- | `BOM_ROUTE_CACHE_TTL` | `30` | proxy route cache lifetime in seconds, `0` disables it |
103
- | `MEMORY_CACHE_DURATION` | `300` | server context cache lifetime in seconds |
104
- | `BOM_USE_CACHE_MAX_BYTES` | `67108864` | memory limit of the in-process `'use cache'` handler (Cache Components without Redis) |
105
- | `MIXER_SECRET` | – | Bearer token of `/api/-revalidate` and `/api/-cache` |
106
- | `REDIS_URL`, `REDIS_PREFIX` | – | shared Redis cache handlers (set at build time for `withBom`) and key prefix |
107
- | `UI_REGISTRY_SOURCE_DIR` | `packages/ui/src` | registry source directory |
108
- | `UI_REGISTRY_COMPONENTS_JSON` | nearest `components.json` | shadcn config whose aliases (e.g. `@/ui/lib/utils`) are mapped to registry imports |
109
- | `UI_REGISTRY_SOURCE_ALIAS` | – | extra import prefix pointing at the registry source, e.g. `@/ui/` |
110
- | `UI_REGISTRY_SKIP_UNRESOLVED` | – | `1` hides registry items that import app code; otherwise they are listed with `meta.unresolvedImports` |
111
-
112
- ## User
113
-
114
- `UserProvider` reads `/api/auth/me` once per page load, shared by every mount and client navigation. Pass `initialUser` (a user or `null`) when the server already knows it to skip the request; `setUser` and `invalidateUser()` keep the cached value current after login or logout.
1
+ # @websolutespa/bom-next
2
+
3
+ [![npm version](https://badge.fury.io/js/%40websolutespa%2Fbom-next.svg)](https://badge.fury.io/js/%40websolutespa%2Fbom-next)
4
+
5
+ [![status alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://shields.io/)
6
+
7
+ Next module of the [BOM Repository](https://github.com/websolutespa/bom) by [websolute](https://www.websolute.com/).
8
+
9
+ ---
10
+
11
+ ##### _this library is for internal usage and not production ready_
12
+
13
+ ## Page context
14
+
15
+ ```ts
16
+ import { createPageContext, getMetadata } from '@websolutespa/bom-next/server';
17
+
18
+ export const generateMetadata = getMetadata('post_detail', config);
19
+
20
+ const { page, layout, label, link } = await createPageContext(market, locale, 'post_detail', id, {
21
+ config,
22
+ depth: 2, // default DEFAULT_PAGE_DEPTH
23
+ select: { title: true, abstract: true, media: true, components: true },
24
+ populate: { media: { url: true, alt: true, width: true, height: true, type: true } },
25
+ });
26
+
27
+ const { layout } = await createLayoutContext(market, locale, { config }); // depth: DEFAULT_LAYOUT_DEPTH (1)
28
+ ```
29
+
30
+ | option | default | |
31
+ | ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------ |
32
+ | `depth` | `2` | `0` ids only, `1` direct relations/uploads (including those inside blocks), `2` relations of relations |
33
+ | `select` | – | Payload select; envelope fields (`id`, `slug`, `title`, `category`, `markets`, `meta`, `template`) are always read |
34
+ | `populate` | – | per-collection select for populated documents |
35
+ | `draft` | `'auto'` | `true` / `false`, or `'auto'` to read Next `draftMode()` |
36
+ | `layout` | `{ depth: 1 }` | layout options, or `false` to skip the layout |
37
+
38
+ Page and layout reads are memoized per request, so `getMetadata` and the page component share them when called with the same options.
39
+ To bind `config` once: `export const { createPageContext, createLayoutContext, getMetadata } = createContextHelpers({ config, defaults: { depth: 2 } });`
40
+
41
+ ## Metadata
42
+
43
+ `getPageMetadata` (and `getMetadata`, its `config`-first form) returns a `generateMetadata` function that renders on the server: plain-text title and description, canonical (keeping `?pagination[page]=N` after the first page), `alternates.languages` with one `locale-COUNTRY` entry per market country plus `x-default`, robots, keywords, Open Graph and Twitter.
44
+
45
+ ```ts
46
+ import { getPageMetadata, JsonLd, buildPageStructuredData } from '@websolutespa/bom-next/server';
47
+
48
+ export const generateMetadata = getPageMetadata('post_detail', {
49
+ config,
50
+ metadata: {
51
+ brand: { name: 'Example', logo: '/logo.png', twitterName: '@example' },
52
+ extend: (metadata, { page }) => ({ ...metadata, title: `${metadata.title} | Example` }),
53
+ },
54
+ });
55
+
56
+ // JSON-LD in the page component
57
+ <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
+ ```
59
+
60
+ `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field), on indexable pages only. `indexable` (`boolean` or `(page) => boolean`) decides; the default, `isIndexableDeployment()`, makes pages indexable only with `PRODUCTION=true` and without `NOINDEX=true`, so staging and preview deployments answer `noindex, nofollow`. Set `PRODUCTION=true` in production.
61
+
62
+ The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
+
64
+ `layout.homeHref` is the root page href for the current market and locale; prefer it to `layout.topLevelHrefs.<slug>`, which is keyed by collection slug or template.
65
+
66
+ ## Routing proxy
67
+
68
+ `createRouteProxy` resolves each request through `/api/-route` and caches the result per instance: found routes for `BOM_ROUTE_CACHE_TTL` seconds (default `30`, `0` disables), misses and redirects for at most 10 seconds. Server errors are never cached. In Draft Mode public URLs are resolved as usual, while unresolved paths (such as the internal preview path) are left to Next instead of the 404 page. CMS redirects send the browser to the target returned by the resolver.
69
+
70
+ `routeAutoDetection` redirects `/` straight from the `detectedRoute` cookie when it names a current root route (root routes are cached like route resolutions, `BOM_ROUTE_CACHE_TTL`); otherwise it detects the market (GeoIP, 2 s timeout, cached per IP for one hour) and the locale.
71
+
72
+ The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
+
74
+ ## Preview
75
+
76
+ `getPreviewHandler(config)` is the `/api/-preview` route (`export const GET = getPreviewHandler(config)`). It turns Next.js Draft Mode on and redirects to the page, only for an editor (`PREVIEW_ROLES`: admin, contributor, editor; the admin session cookie, or the `_token` Bowl adds to the admin's preview URL) or with `secret` equal to `MIXER_SECRET`; anyone else gets 401 and no cookie. Templates pass `draft: (await draftMode()).isEnabled` to `createPageContext`; draft renders without an editor session read as `previewer` (an editing role), and only while Draft Mode is on, because Bowl serves drafts to the editing roles only. The old `previewHandler(request)` is deprecated and accepts only the secret.
77
+
78
+ ## Cache
79
+
80
+ Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
81
+
82
+ ```ts
83
+ // src/app/api/-cache/route.ts
84
+ import { getCacheHandler } from '@websolutespa/bom-next/server';
85
+
86
+ export const { GET, POST } = getCacheHandler();
87
+ export const dynamic = 'force-dynamic';
88
+ ```
89
+
90
+ - `tagPage(tags)` adds tags to the page being rendered, for example a decorator that lists another collection: `tagPage([collectionTag('post_detail')])`.
91
+ - `bomCached(name, fn, { life, tags, resultTags })` caches a data function by name. `life` is a BOM profile (`bom-layout`, `bom-page`, `bom-listing`, `bom-static`, see `bomProfiles`) or an inline profile. `documentTags(collection, result)` tags a result by its documents. Every entry carries `bom:fn:<name>`, so the panel lists and revalidates it.
92
+ - `withBom(nextConfig)` (`@websolutespa/bom-next/config`) wires the caching model:
93
+ - **Classic ISR** (default): `bomCached` uses `unstable_cache`, templates keep `generateStaticParams` and `export const revalidate`.
94
+ - **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
95
+ - **`REDIS_URL` at build time**: `cacheHandler` is the shared Redis handler (`@websolutespa/bom-next/cache-handlers/isr`), which applies `revalidateTag(tag, 'max')` as stale-while-revalidate across instances; `'use cache'` entries share its tag keys.
96
+ - `registerIntrumentation()` registers the in-process cache executor; Bowl uses `/api/-cache` (Bearer `MIXER_SECRET`) when it runs in another process.
97
+
98
+ The cache panel reads the file-system cache (`.next/server/app` and the Next.js 16.4 runtime route cache under `.next/server/route-cache`), the Redis handlers' meta keys, or nothing on Vercel. `next dev` has no ISR cache: check the panel after `next build && next start`.
99
+
100
+ ## Environment
101
+
102
+ Per-request diagnostics (proxy, local API calls, context cache) are logged in development only (`NODE_ENV` unset or `development`).
103
+
104
+ | Variable | Default | |
105
+ | ----------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
106
+ | `BOM_ROUTE_CACHE_TTL` | `30` | proxy route cache lifetime in seconds, `0` disables it |
107
+ | `MEMORY_CACHE_DURATION` | `300` | server context cache lifetime in seconds |
108
+ | `BOM_USE_CACHE_MAX_BYTES` | `67108864` | memory limit of the in-process `'use cache'` handler (Cache Components without Redis) |
109
+ | `MIXER_SECRET` | – | Bearer token of `/api/-revalidate` and `/api/-cache` |
110
+ | `REDIS_URL`, `REDIS_PREFIX` | – | shared Redis cache handlers (set at build time for `withBom`) and key prefix |
111
+ | `UI_REGISTRY_SOURCE_DIR` | `packages/ui/src` | registry source directory |
112
+ | `UI_REGISTRY_COMPONENTS_JSON` | nearest `components.json` | shadcn config whose aliases (e.g. `@/ui/lib/utils`) are mapped to registry imports |
113
+ | `UI_REGISTRY_SOURCE_ALIAS` | – | extra import prefix pointing at the registry source, e.g. `@/ui/` |
114
+ | `UI_REGISTRY_SKIP_UNRESOLVED` | – | `1` hides registry items that import app code; otherwise they are listed with `meta.unresolvedImports` |
115
+
116
+ ## User
117
+
118
+ `UserProvider` reads `/api/auth/me` once per page load, shared by every mount and client navigation. Pass `initialUser` (a user or `null`) when the server already knows it to skip the request; `setUser` and `invalidateUser()` keep the cached value current after login or logout.
119
+
120
+ `isEndUser(user)` (main entry, isomorphic) tells a site end user from a back-office user: the `user` role and the `end_users` collection (or the end user's name fields when the collection is unknown). Use it to guard the end users' reserved area; `/api/auth/me` answers with the same rule.
121
+
122
+ ## Rate limit
123
+
124
+ `createRateLimiter({ prefix, limit, windowSeconds })` (`/server`) is a fixed-window limiter for public endpoints such as form actions: `await limiter.hit(ip)` returns `{ allowed, remaining, reset, backend }`. With `REDIS_URL` the counters live in Redis (`<REDIS_PREFIX>:rate:<prefix>:<key>:<window>`), shared by every instance; without it, or while Redis is down, a bounded per-process map is used.
125
+
126
+ ## Security helpers
127
+
128
+ Generic pieces of a site's public surface, so every project gets the same safe defaults:
129
+
130
+ - **CORS** (main entry): `getAllowedOrigins()` (`NEXT_PUBLIC_URL` + `PAYLOAD_PUBLIC_CORS_URLS`, `*` ignored) and `getCsrfOrigins()` for the `cors` and `csrf` options of `payload.config.ts`; `getCorsHeaders(origin, allowed)`. `createApiCorsProxy()` (`/proxy`) applies them to `/api/*` as the first step of the proxy chain (add `/api/:path*` to the matcher): an allowed origin is echoed with credentials, never `*`.
131
+ - **Anti-spam** (main entry, isomorphic): `SPAM_FIELDS` (honeypot `website`, render time `_t`), `getSpamReason(body, minFillMs)`, `ANTI_SPAM_DEFAULTS`, and `getClientIp(request)` as the key of `createRateLimiter`.
132
+ - **Seed credentials** (main entry): `requireSeedEnv(key)` reads a seed user's email or password from the environment and stops the seed with a hint when it is missing. Call it inside the fixture function, never at module level.
@@ -1 +1 @@
1
- {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\n *\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in\n * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored\n * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or\n * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).\n * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from\n * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\n */\n\n/** The subset of a `redis` client this handler uses (injectable for tests). */\nexport type RedisLike = {\n isReady: boolean;\n get(key: string): Promise<string | null>;\n mGet(keys: string[]): Promise<(string | null)[]>;\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\n mSet(entries: [string, string][]): Promise<unknown>;\n del(key: string | string[]): Promise<unknown>;\n};\n\nexport type CacheHandlerContext = {\n tags?: string[];\n softTags?: string[];\n revalidate?: number | false;\n cacheControl?: { revalidate?: number | false; expire?: number };\n};\n\nexport const tagsHeader = 'x-next-cache-tags';\n\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\n}\n\nexport const keys = (prefix: string) => ({\n entry: `${prefix}next:`,\n meta: `${prefix}next-meta:`,\n expired: `${prefix}next-tag:`,\n stale: `${prefix}next-tag-stale:`,\n});\n\nfunction replacer(_key: string, value: unknown) {\n if (value instanceof Map) {\n return { __t: 'map', d: Array.from(value.entries()) };\n }\n if (\n value &&\n typeof value === 'object' &&\n (value as { type?: string }).type === 'Buffer' &&\n Array.isArray((value as { data?: unknown }).data)\n ) {\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\n }\n return value;\n}\n\nfunction reviver(_key: string, value: unknown) {\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\n return new Map((value as { d: [unknown, unknown][] }).d);\n }\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\n return Buffer.from((value as { d: string }).d, 'base64');\n }\n return value;\n}\n\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\nexport function encode(entry: unknown): string {\n return JSON.stringify(entry, replacer);\n}\n\n/** Restores a cache entry written by {@link encode}. */\nexport function decode<T = unknown>(raw: string): T {\n return JSON.parse(raw, reviver) as T;\n}\n\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\ntype CacheValue = {\n kind?: string;\n status?: number;\n revalidate?: number | false;\n headers?: Record<string, string | string[] | undefined>;\n};\n\n/** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */\ntype StoredCacheControl = { revalidate: number | false; expire: number | undefined };\n\ntype StoredEntry = {\n lastModified: number;\n tags: string[];\n revalidate: number | false | null;\n /** Absent on entries written before 4.0.0-next.12. */\n cacheControl?: StoredCacheControl;\n value: CacheValue;\n};\n\n/** The lifetime returned with an entry, so every instance applies the one it was written with. */\nfunction cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {\n if (entry.cacheControl) {\n return entry.cacheControl;\n }\n return typeof entry.revalidate === 'number' || entry.revalidate === false\n ? { revalidate: entry.revalidate, expire: undefined }\n : undefined;\n}\n\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\nexport function entryTags(\n value: CacheValue | null | undefined,\n ctx: CacheHandlerContext | undefined\n): string[] {\n const tags = new Set(ctx?.tags ?? []);\n const header = value?.headers?.[tagsHeader];\n if (typeof header === 'string') {\n header\n .split(',')\n .filter(Boolean)\n .forEach((tag) => tags.add(tag));\n }\n return Array.from(tags);\n}\n\nfunction revalidateOf(\n value: CacheValue,\n ctx: CacheHandlerContext | undefined\n): number | false | null {\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\n}\n\ntype ConnectingClient = RedisLike & {\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\n once(event: 'ready', listener: () => void): unknown;\n off(event: 'ready', listener: () => void): unknown;\n connect(): Promise<unknown>;\n};\n\n/**\n * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the\n * instrumentation are bundled into the app, and module state would give each its own connection.\n */\nconst shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };\n\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\n if (!process.env.REDIS_URL) {\n return undefined;\n }\n if (!shared.__bomRedisClient) {\n const { createClient } = await import('redis');\n // another caller may have created it while the module loaded\n if (shared.__bomRedisClient) {\n return getRedisClient();\n }\n const client = createClient({\n url: process.env.REDIS_URL,\n // fail fast while disconnected instead of queueing commands behind a dead socket\n disableOfflineQueue: true,\n socket: {\n connectTimeout: 2000,\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\n },\n }) as unknown as ConnectingClient;\n shared.__bomRedisClient = client;\n let logged = false;\n client.on('error', (error: Error) => {\n if (!logged) {\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\n logged = true;\n }\n });\n client.on('ready', () => {\n logged = false;\n });\n client.connect().catch(() => {\n /* reported by the error listener, retried by reconnectStrategy */\n });\n }\n const sharedClient = shared.__bomRedisClient;\n return sharedClient.isReady ? sharedClient : undefined;\n}\n\n/**\n * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that\n * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance\n * already reads Redis.\n */\nexport async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {\n const ready = await getRedisClient();\n const client = shared.__bomRedisClient;\n if (ready || !client) {\n return ready;\n }\n await new Promise<void>((resolve) => {\n const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };\n const onReady = () => {\n clearTimeout(done.timer);\n resolve();\n };\n // no listener left behind while Redis stays down and the panel keeps asking\n done.timer = setTimeout(() => {\n client.off('ready', onReady);\n resolve();\n }, timeout);\n client.once('ready', onReady);\n });\n return client.isReady ? client : undefined;\n}\n\n/** Builds the handler class around a client getter, so tests can inject one. */\nexport function createRedisCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix()\n) {\n const k = keys(prefix);\n return class RedisCacheHandler {\n constructor(_ctx?: unknown) {}\n\n async get(key: string, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return null;\n }\n try {\n const raw = await client.get(k.entry + key);\n if (!raw) {\n return null;\n }\n const entry = decode<StoredEntry>(raw);\n const tags = [\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\n ];\n const cacheControl = cacheControlOf(entry);\n if (!tags.length) {\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n }\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n const now = Date.now();\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\n return null;\n }\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\n if (typeof entry.revalidate !== 'number') {\n // never revalidated by time: a stale entry can only be regenerated by a miss\n return null;\n }\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\n return {\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\n value: entry.value,\n cacheControl,\n };\n }\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\n } catch {\n return null;\n }\n }\n\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\n const client = await getClient();\n if (!client?.isReady) {\n return;\n }\n try {\n if (data == null) {\n await client.del([k.entry + key, k.meta + key]);\n return;\n }\n const revalidate = revalidateOf(data, ctx);\n const entry: StoredEntry = {\n lastModified: Date.now(),\n tags: entryTags(data, ctx),\n revalidate,\n cacheControl:\n revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },\n value: data,\n };\n const raw = encode(entry);\n const expire = ctx?.cacheControl?.expire;\n const ttl =\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\n ? { EX: Math.ceil(expire) }\n : undefined;\n const meta = {\n lastModified: entry.lastModified,\n tags: entry.tags,\n revalidate: entry.revalidate,\n kind: data.kind ?? null,\n status: typeof data.status === 'number' ? data.status : null,\n size: Buffer.byteLength(raw),\n };\n await Promise.all([\n client.set(k.entry + key, raw, ttl),\n client.set(k.meta + key, JSON.stringify(meta), ttl),\n ]);\n } catch {\n // a failed write only costs a regeneration on the next request\n }\n }\n\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\n const client = await getClient();\n if (!client?.isReady || !list.length) {\n return;\n }\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of list) {\n if (durations) {\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\n }\n } else {\n writes.push([k.expired + tag, String(now)]);\n }\n }\n try {\n await client.mSet(writes);\n } catch {\n // the entries expire on their own\n }\n }\n\n resetRequestCache() {}\n };\n}\n\nexport default createRedisCacheHandler();\n"],"mappings":";AAqCA,MAAa,aAAa;AAE1B,SAAgB,YAAY,MAAyB,QAAQ,KAAa;AACxE,QAAO,IAAI,eAAe,GAAG,IAAI,aAAa,KAAK;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AACb,WAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,QAAI,UAAU,WAAW,KAAA,EACvB,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,IAAK,CAAC,CAAC;SAGvE,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;AAG/C,OAAI;AACF,UAAM,OAAO,KAAK,OAAO;WACnB;;EAKV,oBAAoB;;;AAIxB,IAAA,gBAAe,yBAAyB"}
1
+ {"version":3,"file":"redis.js","names":[],"sources":["../../src/cache-handler/redis.ts"],"sourcesContent":["/**\r\n * Next.js incremental cache handler (ISR pages, route handlers, `fetch` and `unstable_cache` entries) backed by\r\n * Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:\r\n * `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.\r\n *\r\n * - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in\r\n * this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored\r\n * `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or\r\n * prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).\r\n * - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from\r\n * node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).\r\n * - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.\r\n * - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),\r\n * `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).\r\n * `revalidateTag(tag, 'max')` sets the stale time; `revalidateTag(tag, { expire: 0 })`, `updateTag` and\r\n * `revalidatePath` set the expiry. Next.js only applies stale tags of its own file-system cache, so this handler\r\n * reports a stale entry by moving its `lastModified` back past its revalidate time.\r\n * - Redis down: reads miss and writes are dropped, so pages still render (uncached) instead of failing.\r\n */\r\n\r\n/** The subset of a `redis` client this handler uses (injectable for tests). */\r\nexport type RedisLike = {\r\n isReady: boolean;\r\n get(key: string): Promise<string | null>;\r\n mGet(keys: string[]): Promise<(string | null)[]>;\r\n set(key: string, value: string, options?: { EX?: number }): Promise<unknown>;\r\n mSet(entries: [string, string][]): Promise<unknown>;\r\n del(key: string | string[]): Promise<unknown>;\r\n};\r\n\r\nexport type CacheHandlerContext = {\r\n tags?: string[];\r\n softTags?: string[];\r\n revalidate?: number | false;\r\n cacheControl?: { revalidate?: number | false; expire?: number };\r\n};\r\n\r\nexport const tagsHeader = 'x-next-cache-tags';\r\n\r\nexport function redisPrefix(env: NodeJS.ProcessEnv = process.env): string {\r\n return env.REDIS_PREFIX ? `${env.REDIS_PREFIX}:` : '';\r\n}\r\n\r\nexport const keys = (prefix: string) => ({\r\n entry: `${prefix}next:`,\r\n meta: `${prefix}next-meta:`,\r\n expired: `${prefix}next-tag:`,\r\n stale: `${prefix}next-tag-stale:`,\r\n});\r\n\r\nfunction replacer(_key: string, value: unknown) {\r\n if (value instanceof Map) {\r\n return { __t: 'map', d: Array.from(value.entries()) };\r\n }\r\n if (\r\n value &&\r\n typeof value === 'object' &&\r\n (value as { type?: string }).type === 'Buffer' &&\r\n Array.isArray((value as { data?: unknown }).data)\r\n ) {\r\n return { __t: 'buf', d: Buffer.from((value as { data: number[] }).data).toString('base64') };\r\n }\r\n return value;\r\n}\r\n\r\nfunction reviver(_key: string, value: unknown) {\r\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'map') {\r\n return new Map((value as { d: [unknown, unknown][] }).d);\r\n }\r\n if (value && typeof value === 'object' && (value as { __t?: string }).__t === 'buf') {\r\n return Buffer.from((value as { d: string }).d, 'base64');\r\n }\r\n return value;\r\n}\r\n\r\n/** Serializes a cache entry, keeping Buffers and Maps (RSC payloads, segment data). */\r\nexport function encode(entry: unknown): string {\r\n return JSON.stringify(entry, replacer);\r\n}\r\n\r\n/** Restores a cache entry written by {@link encode}. */\r\nexport function decode<T = unknown>(raw: string): T {\r\n return JSON.parse(raw, reviver) as T;\r\n}\r\n\r\n/** The fields of a Next.js cache value this handler reads; the rest is stored as it is. */\r\ntype CacheValue = {\r\n kind?: string;\r\n status?: number;\r\n revalidate?: number | false;\r\n headers?: Record<string, string | string[] | undefined>;\r\n};\r\n\r\n/** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */\r\ntype StoredCacheControl = { revalidate: number | false; expire: number | undefined };\r\n\r\ntype StoredEntry = {\r\n lastModified: number;\r\n tags: string[];\r\n revalidate: number | false | null;\r\n /** Absent on entries written before 4.0.0-next.12. */\r\n cacheControl?: StoredCacheControl;\r\n value: CacheValue;\r\n};\r\n\r\n/** The lifetime returned with an entry, so every instance applies the one it was written with. */\r\nfunction cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {\r\n if (entry.cacheControl) {\r\n return entry.cacheControl;\r\n }\r\n return typeof entry.revalidate === 'number' || entry.revalidate === false\r\n ? { revalidate: entry.revalidate, expire: undefined }\r\n : undefined;\r\n}\r\n\r\n/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */\r\nexport function entryTags(\r\n value: CacheValue | null | undefined,\r\n ctx: CacheHandlerContext | undefined\r\n): string[] {\r\n const tags = new Set(ctx?.tags ?? []);\r\n const header = value?.headers?.[tagsHeader];\r\n if (typeof header === 'string') {\r\n header\r\n .split(',')\r\n .filter(Boolean)\r\n .forEach((tag) => tags.add(tag));\r\n }\r\n return Array.from(tags);\r\n}\r\n\r\nfunction revalidateOf(\r\n value: CacheValue,\r\n ctx: CacheHandlerContext | undefined\r\n): number | false | null {\r\n const revalidate = ctx?.cacheControl?.revalidate ?? ctx?.revalidate ?? value?.revalidate;\r\n return typeof revalidate === 'number' || revalidate === false ? revalidate : null;\r\n}\r\n\r\ntype ConnectingClient = RedisLike & {\r\n on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;\r\n once(event: 'ready', listener: () => void): unknown;\r\n off(event: 'ready', listener: () => void): unknown;\r\n connect(): Promise<unknown>;\r\n};\r\n\r\n/**\r\n * The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the\r\n * instrumentation are bundled into the app, and module state would give each its own connection.\r\n */\r\nconst shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };\r\n\r\n/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */\r\nexport async function getRedisClient(): Promise<RedisLike | undefined> {\r\n if (!process.env.REDIS_URL) {\r\n return undefined;\r\n }\r\n if (!shared.__bomRedisClient) {\r\n const { createClient } = await import('redis');\r\n // another caller may have created it while the module loaded\r\n if (shared.__bomRedisClient) {\r\n return getRedisClient();\r\n }\r\n const client = createClient({\r\n url: process.env.REDIS_URL,\r\n // fail fast while disconnected instead of queueing commands behind a dead socket\r\n disableOfflineQueue: true,\r\n socket: {\r\n connectTimeout: 2000,\r\n reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),\r\n },\r\n }) as unknown as ConnectingClient;\r\n shared.__bomRedisClient = client;\r\n let logged = false;\r\n client.on('error', (error: Error) => {\r\n if (!logged) {\r\n console.warn('[cache-handler] redis unavailable, serving uncached:', error.message);\r\n logged = true;\r\n }\r\n });\r\n client.on('ready', () => {\r\n logged = false;\r\n });\r\n client.connect().catch(() => {\r\n /* reported by the error listener, retried by reconnectStrategy */\r\n });\r\n }\r\n const sharedClient = shared.__bomRedisClient;\r\n return sharedClient.isReady ? sharedClient : undefined;\r\n}\r\n\r\n/**\r\n * Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that\r\n * may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance\r\n * already reads Redis.\r\n */\r\nexport async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {\r\n const ready = await getRedisClient();\r\n const client = shared.__bomRedisClient;\r\n if (ready || !client) {\r\n return ready;\r\n }\r\n await new Promise<void>((resolve) => {\r\n const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };\r\n const onReady = () => {\r\n clearTimeout(done.timer);\r\n resolve();\r\n };\r\n // no listener left behind while Redis stays down and the panel keeps asking\r\n done.timer = setTimeout(() => {\r\n client.off('ready', onReady);\r\n resolve();\r\n }, timeout);\r\n client.once('ready', onReady);\r\n });\r\n return client.isReady ? client : undefined;\r\n}\r\n\r\n/** Builds the handler class around a client getter, so tests can inject one. */\r\nexport function createRedisCacheHandler(\r\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\r\n prefix = redisPrefix()\r\n) {\r\n const k = keys(prefix);\r\n return class RedisCacheHandler {\r\n constructor(_ctx?: unknown) {}\r\n\r\n async get(key: string, ctx?: CacheHandlerContext) {\r\n const client = await getClient();\r\n if (!client?.isReady) {\r\n return null;\r\n }\r\n try {\r\n const raw = await client.get(k.entry + key);\r\n if (!raw) {\r\n return null;\r\n }\r\n const entry = decode<StoredEntry>(raw);\r\n const tags = [\r\n ...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),\r\n ];\r\n const cacheControl = cacheControlOf(entry);\r\n if (!tags.length) {\r\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\r\n }\r\n const [expired, stale] = await Promise.all([\r\n client.mGet(tags.map((tag) => k.expired + tag)),\r\n client.mGet(tags.map((tag) => k.stale + tag)),\r\n ]);\r\n const now = Date.now();\r\n // an expiry set after this entry was written, and already reached, is a miss: blocking regeneration\r\n if (expired.some((at) => at && Number(at) > entry.lastModified && Number(at) <= now)) {\r\n return null;\r\n }\r\n if (stale.some((at) => at && Number(at) > entry.lastModified)) {\r\n if (typeof entry.revalidate !== 'number') {\r\n // never revalidated by time: a stale entry can only be regenerated by a miss\r\n return null;\r\n }\r\n // serve once more and regenerate in the background: Next.js sees an entry past its revalidate time\r\n return {\r\n lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),\r\n value: entry.value,\r\n cacheControl,\r\n };\r\n }\r\n return { lastModified: entry.lastModified, value: entry.value, cacheControl };\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n async set(key: string, data: CacheValue | null, ctx?: CacheHandlerContext) {\r\n const client = await getClient();\r\n if (!client?.isReady) {\r\n return;\r\n }\r\n try {\r\n if (data == null) {\r\n await client.del([k.entry + key, k.meta + key]);\r\n return;\r\n }\r\n const revalidate = revalidateOf(data, ctx);\r\n const entry: StoredEntry = {\r\n lastModified: Date.now(),\r\n tags: entryTags(data, ctx),\r\n revalidate,\r\n cacheControl:\r\n revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },\r\n value: data,\r\n };\r\n const raw = encode(entry);\r\n const expire = ctx?.cacheControl?.expire;\r\n const ttl =\r\n typeof expire === 'number' && Number.isFinite(expire) && expire > 0\r\n ? { EX: Math.ceil(expire) }\r\n : undefined;\r\n const meta = {\r\n lastModified: entry.lastModified,\r\n tags: entry.tags,\r\n revalidate: entry.revalidate,\r\n kind: data.kind ?? null,\r\n status: typeof data.status === 'number' ? data.status : null,\r\n size: Buffer.byteLength(raw),\r\n };\r\n await Promise.all([\r\n client.set(k.entry + key, raw, ttl),\r\n client.set(k.meta + key, JSON.stringify(meta), ttl),\r\n ]);\r\n } catch {\r\n // a failed write only costs a regeneration on the next request\r\n }\r\n }\r\n\r\n async revalidateTag(tags: string | string[], durations?: { expire?: number }) {\r\n const list = (Array.isArray(tags) ? tags : [tags]).filter(Boolean);\r\n const client = await getClient();\r\n if (!client?.isReady || !list.length) {\r\n return;\r\n }\r\n const now = Date.now();\r\n const writes: [string, string][] = [];\r\n for (const tag of list) {\r\n if (durations) {\r\n writes.push([k.stale + tag, String(now)]);\r\n if (durations.expire !== undefined) {\r\n writes.push([k.expired + tag, String(now + durations.expire * 1000)]);\r\n }\r\n } else {\r\n writes.push([k.expired + tag, String(now)]);\r\n }\r\n }\r\n try {\r\n await client.mSet(writes);\r\n } catch {\r\n // the entries expire on their own\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E,OAAO,QAAQ;GAClE,MAAM,SAAS,MAAM,WAAW;AAChC,OAAI,CAAC,QAAQ,WAAW,CAAC,KAAK,OAC5B;GAEF,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,SAA6B,EAAE;AACrC,QAAK,MAAM,OAAO,KAChB,KAAI,WAAW;AACb,WAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,QAAI,UAAU,WAAW,KAAA,EACvB,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,IAAK,CAAC,CAAC;SAGvE,QAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;AAG/C,OAAI;AACF,UAAM,OAAO,KAAK,OAAO;WACnB;;EAKV,oBAAoB;;;AAIxB,IAAA,gBAAe,yBAAyB"}
@@ -1 +1 @@
1
- {"version":3,"file":"default.js","names":[],"sources":["../../src/cache-handlers/default.ts"],"sourcesContent":["import type { CacheEntry, CacheHandler } from 'next/cache';\nimport { getRedisClient, keys, redisPrefix, type RedisLike } from '../cache-handler/redis';\n\n/**\n * `cacheHandlers.default` for `'use cache'` (Cache Components), set by `withBom()`. In memory per process by\n * default (bounded, least recently used out first); shared in Redis when `REDIS_URL` is set. Tag state uses the\n * same keys as the ISR handler (`next-tag:` expired, `next-tag-stale:` stale), so one `revalidateTag` reaches\n * pages and cached functions on every instance. It also keeps a small index of what it stores, which the cache\n * panel lists (`listUseCacheEntries`).\n */\nexport type UseCacheMeta = {\n key: string;\n tags: string[];\n timestamp: number;\n revalidate: number;\n expire: number;\n size: number;\n};\n\ntype Stored = Omit<CacheEntry, 'value'> & { value: Uint8Array };\ntype TagState = { stale?: number; expired?: number };\n\nconst maxBytes = Number(process.env.BOM_USE_CACHE_MAX_BYTES) || 64 * 1024 * 1024;\n\n/** Shared through `globalThis`: Next.js loads the handler outside the bundles the cache panel runs in. */\nconst shared = globalThis as {\n __bomUseCache?: {\n entries: Map<string, Stored>;\n meta: Map<string, UseCacheMeta>;\n tags: Map<string, TagState>;\n bytes: number;\n };\n};\nconst memory = (shared.__bomUseCache ??= {\n entries: new Map(),\n meta: new Map(),\n tags: new Map(),\n bytes: 0,\n});\n\nfunction stream(bytes: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream({\n start(controller) {\n controller.enqueue(bytes);\n controller.close();\n },\n });\n}\n\nfunction evict() {\n // Map iteration order is insertion order; `get` re-inserts, so the first entries are the least recently used\n for (const [key, entry] of memory.entries) {\n if (memory.bytes <= maxBytes) break;\n memory.entries.delete(key);\n memory.meta.delete(key);\n memory.bytes -= entry.value.byteLength;\n }\n}\n\n/** Entries of this process (memory mode) for the cache panel. */\nexport function listUseCacheEntries(): UseCacheMeta[] {\n return [...memory.meta.values()];\n}\n\n/** Reported state of an entry from the tag timestamps: an expiry reached after it was written, or a stale mark. */\nexport function tagState(\n entry: { tags: string[]; timestamp: number },\n read: (tag: string) => TagState,\n now = Date.now()\n) {\n let stale = false;\n for (const tag of entry.tags) {\n const { stale: staleAt = 0, expired = 0 } = read(tag);\n if (expired > entry.timestamp && expired <= now) {\n return 'expired' as const;\n }\n if (staleAt > entry.timestamp) {\n stale = true;\n }\n }\n return stale ? ('stale' as const) : ('fresh' as const);\n}\n\nexport function createUseCacheHandler(\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\n prefix = redisPrefix(),\n useRedis = Boolean(process.env.REDIS_URL)\n): CacheHandler {\n const k = keys(prefix);\n const entryKey = `${prefix}use-cache:`;\n const metaKey = `${prefix}use-cache-meta:`;\n const pending = new Map<string, Promise<void>>();\n\n async function readTags(tags: string[]): Promise<Map<string, TagState>> {\n const states = new Map<string, TagState>(tags.map((tag) => [tag, memory.tags.get(tag) ?? {}]));\n const client = useRedis ? await getClient() : undefined;\n if (client?.isReady && tags.length) {\n try {\n const [expired, stale] = await Promise.all([\n client.mGet(tags.map((tag) => k.expired + tag)),\n client.mGet(tags.map((tag) => k.stale + tag)),\n ]);\n tags.forEach((tag, index) => {\n states.set(tag, {\n expired: Number(expired[index] ?? 0) || undefined,\n stale: Number(stale[index] ?? 0) || undefined,\n });\n });\n } catch {\n // tag state unknown: serve what is stored\n }\n }\n return states;\n }\n\n async function load(cacheKey: string): Promise<Stored | undefined> {\n if (!useRedis) {\n const entry = memory.entries.get(cacheKey);\n if (entry) {\n // most recently used goes last\n memory.entries.delete(cacheKey);\n memory.entries.set(cacheKey, entry);\n }\n return entry;\n }\n const client = await getClient();\n if (!client?.isReady) return undefined;\n const raw = await client.get(entryKey + cacheKey);\n if (!raw) return undefined;\n const data = JSON.parse(raw) as Omit<Stored, 'value'> & { value: string };\n return { ...data, value: Buffer.from(data.value, 'base64') };\n }\n\n return {\n async get(cacheKey) {\n await pending.get(cacheKey);\n try {\n const entry = await load(cacheKey);\n if (!entry) return undefined;\n const states = await readTags(entry.tags);\n const state = tagState(entry, (tag) => states.get(tag) ?? {});\n if (state === 'expired') return undefined;\n // a stale tag: served once more, regenerated in the background\n return {\n ...entry,\n revalidate: state === 'stale' ? -1 : entry.revalidate,\n value: stream(entry.value),\n };\n } catch {\n return undefined;\n }\n },\n\n async set(cacheKey, pendingEntry) {\n let done!: () => void;\n pending.set(\n cacheKey,\n new Promise<void>((resolve) => {\n done = resolve;\n })\n );\n try {\n const entry = await pendingEntry;\n const value = new Uint8Array(await new Response(entry.value).arrayBuffer());\n const stored: Stored = { ...entry, value };\n const meta: UseCacheMeta = {\n key: cacheKey,\n tags: entry.tags,\n timestamp: entry.timestamp,\n revalidate: entry.revalidate,\n expire: entry.expire,\n size: value.byteLength,\n };\n if (useRedis) {\n const client = await getClient();\n if (client?.isReady) {\n const ttl = Number.isFinite(entry.expire)\n ? { EX: Math.max(1, Math.ceil(entry.expire)) }\n : undefined;\n const { value: _bytes, ...rest } = stored;\n await Promise.all([\n client.set(\n entryKey + cacheKey,\n JSON.stringify({ ...rest, value: Buffer.from(value).toString('base64') }),\n ttl\n ),\n client.set(metaKey + cacheKey, JSON.stringify(meta), ttl),\n ]);\n }\n } else {\n const previous = memory.entries.get(cacheKey);\n if (previous) memory.bytes -= previous.value.byteLength;\n memory.entries.delete(cacheKey);\n memory.entries.set(cacheKey, stored);\n memory.meta.set(cacheKey, meta);\n memory.bytes += value.byteLength;\n evict();\n }\n } catch {\n // an interrupted value is discarded: the next read regenerates it\n } finally {\n pending.delete(cacheKey);\n done();\n }\n },\n\n async refreshTags() {\n // tag state is read from Redis on every lookup; in memory it is already local\n },\n\n async getExpiration(tags) {\n const states = await readTags(tags);\n const now = Date.now();\n return Math.max(\n 0,\n ...[...states.values()].map(({ expired = 0 }) => (expired <= now ? expired : 0))\n );\n },\n\n async updateTags(tags, durations) {\n const now = Date.now();\n const writes: [string, string][] = [];\n for (const tag of tags) {\n const state = memory.tags.get(tag) ?? {};\n if (durations) {\n state.stale = now;\n writes.push([k.stale + tag, String(now)]);\n if (durations.expire !== undefined) {\n state.expired = now + durations.expire * 1000;\n writes.push([k.expired + tag, String(state.expired)]);\n }\n } else {\n state.expired = now;\n writes.push([k.expired + tag, String(now)]);\n }\n memory.tags.set(tag, state);\n }\n if (useRedis && writes.length) {\n const client = await getClient();\n await client?.mSet(writes).catch(() => {});\n }\n },\n };\n}\n\nexport default createUseCacheHandler();\n"],"mappings":";;AAsBA,MAAM,WAAW,OAAO,QAAQ,IAAI,wBAAwB,IAAI,KAAK,OAAO;;AAG5E,MAAM,SAAS;AAQf,MAAM,SAAU,OAAO,kBAAkB;CACvC,yBAAS,IAAI,KAAK;CAClB,sBAAM,IAAI,KAAK;CACf,sBAAM,IAAI,KAAK;CACf,OAAO;CACR;AAED,SAAS,OAAO,OAA+C;AAC7D,QAAO,IAAI,eAAe,EACxB,MAAM,YAAY;AAChB,aAAW,QAAQ,MAAM;AACzB,aAAW,OAAO;IAErB,CAAC;;AAGJ,SAAS,QAAQ;AAEf,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,SAAS;AACzC,MAAI,OAAO,SAAS,SAAU;AAC9B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AAI,EAAE;AACxC,QAAI,WAAW;AACb,WAAM,QAAQ;AACd,YAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,SAAI,UAAU,WAAW,KAAA,GAAW;AAClC,YAAM,UAAU,MAAM,UAAU,SAAS;AACzC,aAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,QAAQ,CAAC,CAAC;;WAElD;AACL,WAAM,UAAU;AAChB,YAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;;AAE7C,WAAO,KAAK,IAAI,KAAK,MAAM;;AAE7B,OAAI,YAAY,OAAO,OAErB,QADe,MAAM,WAAW,GAClB,KAAK,OAAO,CAAC,YAAY,GAAG;;EAG/C;;AAGH,IAAA,kBAAe,uBAAuB"}
1
+ {"version":3,"file":"default.js","names":[],"sources":["../../src/cache-handlers/default.ts"],"sourcesContent":["import type { CacheEntry, CacheHandler } from 'next/cache';\r\nimport { getRedisClient, keys, redisPrefix, type RedisLike } from '../cache-handler/redis';\r\n\r\n/**\r\n * `cacheHandlers.default` for `'use cache'` (Cache Components), set by `withBom()`. In memory per process by\r\n * default (bounded, least recently used out first); shared in Redis when `REDIS_URL` is set. Tag state uses the\r\n * same keys as the ISR handler (`next-tag:` expired, `next-tag-stale:` stale), so one `revalidateTag` reaches\r\n * pages and cached functions on every instance. It also keeps a small index of what it stores, which the cache\r\n * panel lists (`listUseCacheEntries`).\r\n */\r\nexport type UseCacheMeta = {\r\n key: string;\r\n tags: string[];\r\n timestamp: number;\r\n revalidate: number;\r\n expire: number;\r\n size: number;\r\n};\r\n\r\ntype Stored = Omit<CacheEntry, 'value'> & { value: Uint8Array };\r\ntype TagState = { stale?: number; expired?: number };\r\n\r\nconst maxBytes = Number(process.env.BOM_USE_CACHE_MAX_BYTES) || 64 * 1024 * 1024;\r\n\r\n/** Shared through `globalThis`: Next.js loads the handler outside the bundles the cache panel runs in. */\r\nconst shared = globalThis as {\r\n __bomUseCache?: {\r\n entries: Map<string, Stored>;\r\n meta: Map<string, UseCacheMeta>;\r\n tags: Map<string, TagState>;\r\n bytes: number;\r\n };\r\n};\r\nconst memory = (shared.__bomUseCache ??= {\r\n entries: new Map(),\r\n meta: new Map(),\r\n tags: new Map(),\r\n bytes: 0,\r\n});\r\n\r\nfunction stream(bytes: Uint8Array): ReadableStream<Uint8Array> {\r\n return new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(bytes);\r\n controller.close();\r\n },\r\n });\r\n}\r\n\r\nfunction evict() {\r\n // Map iteration order is insertion order; `get` re-inserts, so the first entries are the least recently used\r\n for (const [key, entry] of memory.entries) {\r\n if (memory.bytes <= maxBytes) break;\r\n memory.entries.delete(key);\r\n memory.meta.delete(key);\r\n memory.bytes -= entry.value.byteLength;\r\n }\r\n}\r\n\r\n/** Entries of this process (memory mode) for the cache panel. */\r\nexport function listUseCacheEntries(): UseCacheMeta[] {\r\n return [...memory.meta.values()];\r\n}\r\n\r\n/** Reported state of an entry from the tag timestamps: an expiry reached after it was written, or a stale mark. */\r\nexport function tagState(\r\n entry: { tags: string[]; timestamp: number },\r\n read: (tag: string) => TagState,\r\n now = Date.now()\r\n) {\r\n let stale = false;\r\n for (const tag of entry.tags) {\r\n const { stale: staleAt = 0, expired = 0 } = read(tag);\r\n if (expired > entry.timestamp && expired <= now) {\r\n return 'expired' as const;\r\n }\r\n if (staleAt > entry.timestamp) {\r\n stale = true;\r\n }\r\n }\r\n return stale ? ('stale' as const) : ('fresh' as const);\r\n}\r\n\r\nexport function createUseCacheHandler(\r\n getClient: () => Promise<RedisLike | undefined> = getRedisClient,\r\n prefix = redisPrefix(),\r\n useRedis = Boolean(process.env.REDIS_URL)\r\n): CacheHandler {\r\n const k = keys(prefix);\r\n const entryKey = `${prefix}use-cache:`;\r\n const metaKey = `${prefix}use-cache-meta:`;\r\n const pending = new Map<string, Promise<void>>();\r\n\r\n async function readTags(tags: string[]): Promise<Map<string, TagState>> {\r\n const states = new Map<string, TagState>(tags.map((tag) => [tag, memory.tags.get(tag) ?? {}]));\r\n const client = useRedis ? await getClient() : undefined;\r\n if (client?.isReady && tags.length) {\r\n try {\r\n const [expired, stale] = await Promise.all([\r\n client.mGet(tags.map((tag) => k.expired + tag)),\r\n client.mGet(tags.map((tag) => k.stale + tag)),\r\n ]);\r\n tags.forEach((tag, index) => {\r\n states.set(tag, {\r\n expired: Number(expired[index] ?? 0) || undefined,\r\n stale: Number(stale[index] ?? 0) || undefined,\r\n });\r\n });\r\n } catch {\r\n // tag state unknown: serve what is stored\r\n }\r\n }\r\n return states;\r\n }\r\n\r\n async function load(cacheKey: string): Promise<Stored | undefined> {\r\n if (!useRedis) {\r\n const entry = memory.entries.get(cacheKey);\r\n if (entry) {\r\n // most recently used goes last\r\n memory.entries.delete(cacheKey);\r\n memory.entries.set(cacheKey, entry);\r\n }\r\n return entry;\r\n }\r\n const client = await getClient();\r\n if (!client?.isReady) return undefined;\r\n const raw = await client.get(entryKey + cacheKey);\r\n if (!raw) return undefined;\r\n const data = JSON.parse(raw) as Omit<Stored, 'value'> & { value: string };\r\n return { ...data, value: Buffer.from(data.value, 'base64') };\r\n }\r\n\r\n return {\r\n async get(cacheKey) {\r\n await pending.get(cacheKey);\r\n try {\r\n const entry = await load(cacheKey);\r\n if (!entry) return undefined;\r\n const states = await readTags(entry.tags);\r\n const state = tagState(entry, (tag) => states.get(tag) ?? {});\r\n if (state === 'expired') return undefined;\r\n // a stale tag: served once more, regenerated in the background\r\n return {\r\n ...entry,\r\n revalidate: state === 'stale' ? -1 : entry.revalidate,\r\n value: stream(entry.value),\r\n };\r\n } catch {\r\n return undefined;\r\n }\r\n },\r\n\r\n async set(cacheKey, pendingEntry) {\r\n let done!: () => void;\r\n pending.set(\r\n cacheKey,\r\n new Promise<void>((resolve) => {\r\n done = resolve;\r\n })\r\n );\r\n try {\r\n const entry = await pendingEntry;\r\n const value = new Uint8Array(await new Response(entry.value).arrayBuffer());\r\n const stored: Stored = { ...entry, value };\r\n const meta: UseCacheMeta = {\r\n key: cacheKey,\r\n tags: entry.tags,\r\n timestamp: entry.timestamp,\r\n revalidate: entry.revalidate,\r\n expire: entry.expire,\r\n size: value.byteLength,\r\n };\r\n if (useRedis) {\r\n const client = await getClient();\r\n if (client?.isReady) {\r\n const ttl = Number.isFinite(entry.expire)\r\n ? { EX: Math.max(1, Math.ceil(entry.expire)) }\r\n : undefined;\r\n const { value: _bytes, ...rest } = stored;\r\n await Promise.all([\r\n client.set(\r\n entryKey + cacheKey,\r\n JSON.stringify({ ...rest, value: Buffer.from(value).toString('base64') }),\r\n ttl\r\n ),\r\n client.set(metaKey + cacheKey, JSON.stringify(meta), ttl),\r\n ]);\r\n }\r\n } else {\r\n const previous = memory.entries.get(cacheKey);\r\n if (previous) memory.bytes -= previous.value.byteLength;\r\n memory.entries.delete(cacheKey);\r\n memory.entries.set(cacheKey, stored);\r\n memory.meta.set(cacheKey, meta);\r\n memory.bytes += value.byteLength;\r\n evict();\r\n }\r\n } catch {\r\n // an interrupted value is discarded: the next read regenerates it\r\n } finally {\r\n pending.delete(cacheKey);\r\n done();\r\n }\r\n },\r\n\r\n async refreshTags() {\r\n // tag state is read from Redis on every lookup; in memory it is already local\r\n },\r\n\r\n async getExpiration(tags) {\r\n const states = await readTags(tags);\r\n const now = Date.now();\r\n return Math.max(\r\n 0,\r\n ...[...states.values()].map(({ expired = 0 }) => (expired <= now ? expired : 0))\r\n );\r\n },\r\n\r\n async updateTags(tags, durations) {\r\n const now = Date.now();\r\n const writes: [string, string][] = [];\r\n for (const tag of tags) {\r\n const state = memory.tags.get(tag) ?? {};\r\n if (durations) {\r\n state.stale = now;\r\n writes.push([k.stale + tag, String(now)]);\r\n if (durations.expire !== undefined) {\r\n state.expired = now + durations.expire * 1000;\r\n writes.push([k.expired + tag, String(state.expired)]);\r\n }\r\n } else {\r\n state.expired = now;\r\n writes.push([k.expired + tag, String(now)]);\r\n }\r\n memory.tags.set(tag, state);\r\n }\r\n if (useRedis && writes.length) {\r\n const client = await getClient();\r\n await client?.mSet(writes).catch(() => {});\r\n }\r\n },\r\n };\r\n}\r\n\r\nexport default createUseCacheHandler();\r\n"],"mappings":";;AAsBA,MAAM,WAAW,OAAO,QAAQ,IAAI,wBAAwB,IAAI,KAAK,OAAO;;AAG5E,MAAM,SAAS;AAQf,MAAM,SAAU,OAAO,kBAAkB;CACvC,yBAAS,IAAI,KAAK;CAClB,sBAAM,IAAI,KAAK;CACf,sBAAM,IAAI,KAAK;CACf,OAAO;CACR;AAED,SAAS,OAAO,OAA+C;AAC7D,QAAO,IAAI,eAAe,EACxB,MAAM,YAAY;AAChB,aAAW,QAAQ,MAAM;AACzB,aAAW,OAAO;IAErB,CAAC;;AAGJ,SAAS,QAAQ;AAEf,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,SAAS;AACzC,MAAI,OAAO,SAAS,SAAU;AAC9B,SAAO,QAAQ,OAAO,IAAI;AAC1B,SAAO,KAAK,OAAO,IAAI;AACvB,SAAO,SAAS,MAAM,MAAM;;;;AAKhC,SAAgB,sBAAsC;AACpD,QAAO,CAAC,GAAG,OAAO,KAAK,QAAQ,CAAC;;;AAIlC,SAAgB,SACd,OACA,MACA,MAAM,KAAK,KAAK,EAChB;CACA,IAAI,QAAQ;AACZ,MAAK,MAAM,OAAO,MAAM,MAAM;EAC5B,MAAM,EAAE,OAAO,UAAU,GAAG,UAAU,MAAM,KAAK,IAAI;AACrD,MAAI,UAAU,MAAM,aAAa,WAAW,IAC1C,QAAO;AAET,MAAI,UAAU,MAAM,UAClB,SAAQ;;AAGZ,QAAO,QAAS,UAAqB;;AAGvC,SAAgB,sBACd,YAAkD,gBAClD,SAAS,aAAa,EACtB,WAAW,QAAQ,QAAQ,IAAI,UAAU,EAC3B;CACd,MAAM,IAAI,KAAK,OAAO;CACtB,MAAM,WAAW,GAAG,OAAO;CAC3B,MAAM,UAAU,GAAG,OAAO;CAC1B,MAAM,0BAAU,IAAI,KAA4B;CAEhD,eAAe,S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YAAO,QAAQ,IAAI,UAAU,OAAO;AACpC,YAAO,KAAK,IAAI,UAAU,KAAK;AAC/B,YAAO,SAAS,MAAM;AACtB,YAAO;;WAEH,WAEE;AACR,YAAQ,OAAO,SAAS;AACxB,UAAM;;;EAIV,MAAM,cAAc;EAIpB,MAAM,cAAc,MAAM;GACxB,MAAM,SAAS,MAAM,SAAS,KAAK;GACnC,MAAM,MAAM,KAAK,KAAK;AACtB,UAAO,KAAK,IACV,GACA,GAAG,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,KAAK,EAAE,UAAU,QAAS,WAAW,MAAM,UAAU,EAAG,CACjF;;EAGH,MAAM,WAAW,MAAM,WAAW;GAChC,MAAM,MAAM,KAAK,KAAK;GACtB,MAAM,SAA6B,EAAE;AACrC,QAAK,MAAM,OAAO,MAAM;IACtB,MAAM,QAAQ,OAAO,KAAK,IAAI,IAAI,IAAI,EAAE;AACxC,QAAI,WAAW;AACb,WAAM,QAAQ;AACd,YAAO,KAAK,CAAC,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AACzC,SAAI,UAAU,WAAW,KAAA,GAAW;AAClC,YAAM,UAAU,MAAM,UAAU,SAAS;AACzC,aAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,MAAM,QAAQ,CAAC,CAAC;;WAElD;AACL,WAAM,UAAU;AAChB,YAAO,KAAK,CAAC,EAAE,UAAU,KAAK,OAAO,IAAI,CAAC,CAAC;;AAE7C,WAAO,KAAK,IAAI,KAAK,MAAM;;AAE7B,OAAI,YAAY,OAAO,OAErB,QADe,MAAM,WAAW,GAClB,KAAK,OAAO,CAAC,YAAY,GAAG;;EAG/C;;AAGH,IAAA,kBAAe,uBAAuB"}
@@ -7,11 +7,11 @@ function Client() {
7
7
  const label = useLabel();
8
8
  const page = usePage();
9
9
  const classNames = getClassNames("client");
10
- return <div className={classNames}>
11
- <h2 className="display-2">
12
- {page.title} <sup>{page.id}</sup>
13
- </h2>
14
- <h2>{label("label")}</h2>
10
+ return <div className={classNames}>
11
+ <h2 className="display-2">
12
+ {page.title} <sup>{page.id}</sup>
13
+ </h2>
14
+ <h2>{label("label")}</h2>
15
15
  </div>;
16
16
  }
17
17
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../src/client/client.tsx"],"sourcesContent":["'use client';\n\nimport { getClassNames } from '@websolutespa/bom-core';\nimport { useLabel } from './useLabel';\nimport { usePage } from './usePage';\n\nexport function Client() {\n const label = useLabel();\n const page = usePage();\n // console.log('Client', layout, page, label('label'));\n const classNames = getClassNames('client');\n return (\n <div className={classNames}>\n <h2 className=\"display-2\">\n {page.title} <sup>{page.id}</sup>\n </h2>\n <h2>{label('label')}</h2>\n </div>\n );\n}\n"],"mappings":";;;;;AAMA,SAAgB,SAAS;CACvB,MAAM,QAAQ,UAAU;CACxB,MAAM,OAAO,SAAS;CAEtB,MAAM,aAAa,cAAc,SAAS;AAC1C,QACE,CAAC,IAAI,WAAW,YAAY;MAC1B,CAAC,GAAG,sBAAsB;SACvB,KAAK,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,EAAE,IAAI;MACnC,EAAE,GAAG;MACL,CAAC,IAAI,MAAM,QAAQ,CAAC,EAAE,GAAG;IAC3B,EAAE"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/client/client.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { getClassNames } from '@websolutespa/bom-core';\r\nimport { useLabel } from './useLabel';\r\nimport { usePage } from './usePage';\r\n\r\nexport function Client() {\r\n const label = useLabel();\r\n const page = usePage();\r\n // console.log('Client', layout, page, label('label'));\r\n const classNames = getClassNames('client');\r\n return (\r\n <div className={classNames}>\r\n <h2 className=\"display-2\">\r\n {page.title} <sup>{page.id}</sup>\r\n </h2>\r\n <h2>{label('label')}</h2>\r\n </div>\r\n );\r\n}\r\n"],"mappings":";;;;;AAMA,SAAgB,SAAS;CACvB,MAAM,QAAQ,UAAU;CACxB,MAAM,OAAO,SAAS;CAEtB,MAAM,aAAa,cAAc,SAAS;AAC1C,QACE,CAAC,IAAI,WAAW,YAAY;MAC1B,CAAC,GAAG,sBAAsB;SACvB,KAAK,MAAM,CAAC,CAAC,KAAK,KAAK,GAAG,EAAE,IAAI;MACnC,EAAE,GAAG;MACL,CAAC,IAAI,MAAM,QAAQ,CAAC,EAAE,GAAG;IAC3B,EAAE"}
@@ -1 +1 @@
1
- {"version":3,"file":"extra.js","names":[],"sources":["../../src/client/extra.tsx"],"sourcesContent":["'use client';\n\nimport { createContext } from 'react';\n\nexport type IExtraContext = Record<string, any>;\n\nexport const ExtraContext = createContext<IExtraContext | undefined>(undefined);\n\nexport function ExtraProvider({\n extra = {},\n children,\n}: {\n extra?: Record<string, any>;\n children?: React.ReactNode;\n}) {\n return <ExtraContext.Provider value={extra}>{children}</ExtraContext.Provider>;\n}\n"],"mappings":";;;AAMA,MAAa,eAAe,cAAyC,KAAA,EAAU;AAE/E,SAAgB,cAAc,EAC5B,QAAQ,EAAE,EACV,YAIC;AACD,QAAO,CAAC,aAAa,SAAS,OAAO,QAAQ,SAAS,EAAE,aAAa"}
1
+ {"version":3,"file":"extra.js","names":[],"sources":["../../src/client/extra.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { createContext } from 'react';\r\n\r\nexport type IExtraContext = Record<string, any>;\r\n\r\nexport const ExtraContext = createContext<IExtraContext | undefined>(undefined);\r\n\r\nexport function ExtraProvider({\r\n extra = {},\r\n children,\r\n}: {\r\n extra?: Record<string, any>;\r\n children?: React.ReactNode;\r\n}) {\r\n return <ExtraContext.Provider value={extra}>{children}</ExtraContext.Provider>;\r\n}\r\n"],"mappings":";;;AAMA,MAAa,eAAe,cAAyC,KAAA,EAAU;AAE/E,SAAgB,cAAc,EAC5B,QAAQ,EAAE,EACV,YAIC;AACD,QAAO,CAAC,aAAa,SAAS,OAAO,QAAQ,SAAS,EAAE,aAAa"}
@@ -1 +1 @@
1
- {"version":3,"file":"label.js","names":[],"sources":["../../src/client/label.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, useMemo } from 'react';\nimport { LabelService } from '../lib/label';\nimport { useLayout } from './useLayout';\n\nexport type ILabelContext = (key: string, params?: Record<string, any>) => string;\n\nexport const LabelContext = createContext<ILabelContext | undefined>(undefined);\n\nexport function LabelProvider({ children }: { children?: React.ReactNode }) {\n const { labels } = useLayout();\n // one function per labels: consumers list `label` in effect dependencies, a new function on every\n // render would run their effects again (e.g. a toast shown twice)\n const getLabel = useMemo<ILabelContext>(() => {\n const labelService = new LabelService(labels);\n return (key, params) => labelService.getLabel(key, params);\n }, [labels]);\n return <LabelContext.Provider value={getLabel}>{children}</LabelContext.Provider>;\n}\n"],"mappings":";;;;;AAQA,MAAa,eAAe,cAAyC,KAAA,EAAU;AAE/E,SAAgB,cAAc,EAAE,YAA4C;CAC1E,MAAM,EAAE,WAAW,WAAW;CAG9B,MAAM,WAAW,cAA6B;EAC5C,MAAM,eAAe,IAAI,aAAa,OAAO;AAC7C,UAAQ,KAAK,WAAW,aAAa,SAAS,KAAK,OAAO;IACzD,CAAC,OAAO,CAAC;AACZ,QAAO,CAAC,aAAa,SAAS,OAAO,WAAW,SAAS,EAAE,aAAa"}
1
+ {"version":3,"file":"label.js","names":[],"sources":["../../src/client/label.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { createContext, useMemo } from 'react';\r\nimport { LabelService } from '../lib/label';\r\nimport { useLayout } from './useLayout';\r\n\r\nexport type ILabelContext = (key: string, params?: Record<string, any>) => string;\r\n\r\nexport const LabelContext = createContext<ILabelContext | undefined>(undefined);\r\n\r\nexport function LabelProvider({ children }: { children?: React.ReactNode }) {\r\n const { labels } = useLayout();\r\n // one function per labels: consumers list `label` in effect dependencies, a new function on every\r\n // render would run their effects again (e.g. a toast shown twice)\r\n const getLabel = useMemo<ILabelContext>(() => {\r\n const labelService = new LabelService(labels);\r\n return (key, params) => labelService.getLabel(key, params);\r\n }, [labels]);\r\n return <LabelContext.Provider value={getLabel}>{children}</LabelContext.Provider>;\r\n}\r\n"],"mappings":";;;;;AAQA,MAAa,eAAe,cAAyC,KAAA,EAAU;AAE/E,SAAgB,cAAc,EAAE,YAA4C;CAC1E,MAAM,EAAE,WAAW,WAAW;CAG9B,MAAM,WAAW,cAA6B;EAC5C,MAAM,eAAe,IAAI,aAAa,OAAO;AAC7C,UAAQ,KAAK,WAAW,aAAa,SAAS,KAAK,OAAO;IACzD,CAAC,OAAO,CAAC;AACZ,QAAO,CAAC,aAAa,SAAS,OAAO,WAAW,SAAS,EAAE,aAAa"}
@@ -1 +1 @@
1
- {"version":3,"file":"layout.js","names":[],"sources":["../../src/client/layout.tsx"],"sourcesContent":["'use client';\n\nimport { ILayout } from '@websolutespa/bom-core';\nimport { createContext } from 'react';\n\nexport type ILayoutContext = ILayout;\n\nexport const LayoutContext = createContext<ILayoutContext | undefined>(undefined);\n\nexport function LayoutProvider({\n layout,\n children,\n}: {\n layout: ILayout;\n children?: React.ReactNode;\n}) {\n return <LayoutContext.Provider value={layout}>{children}</LayoutContext.Provider>;\n}\n"],"mappings":";;;AAOA,MAAa,gBAAgB,cAA0C,KAAA,EAAU;AAEjF,SAAgB,eAAe,EAC7B,QACA,YAIC;AACD,QAAO,CAAC,cAAc,SAAS,OAAO,SAAS,SAAS,EAAE,cAAc"}
1
+ {"version":3,"file":"layout.js","names":[],"sources":["../../src/client/layout.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { ILayout } from '@websolutespa/bom-core';\r\nimport { createContext } from 'react';\r\n\r\nexport type ILayoutContext = ILayout;\r\n\r\nexport const LayoutContext = createContext<ILayoutContext | undefined>(undefined);\r\n\r\nexport function LayoutProvider({\r\n layout,\r\n children,\r\n}: {\r\n layout: ILayout;\r\n children?: React.ReactNode;\r\n}) {\r\n return <LayoutContext.Provider value={layout}>{children}</LayoutContext.Provider>;\r\n}\r\n"],"mappings":";;;AAOA,MAAa,gBAAgB,cAA0C,KAAA,EAAU;AAEjF,SAAgB,eAAe,EAC7B,QACA,YAIC;AACD,QAAO,CAAC,cAAc,SAAS,OAAO,SAAS,SAAS,EAAE,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"local.collection.js","names":[],"sources":["../../src/client/local.collection.ts"],"sourcesContent":["import { httpFetch, merge } from '@websolutespa/bom-core';\nimport { ApiRequestOptions, getLocalApiRequestOptions, getLocalApiUrl } from '../lib/http';\n\nexport async function localCollectionFetch<T = unknown>(\n pathname: string,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n const url = new URL(getLocalApiUrl(pathname));\n if (serviceOptions) {\n url.searchParams.append('locale', serviceOptions.locale);\n url.searchParams.append('market', serviceOptions.market);\n }\n const apiOptions = merge({ ...getLocalApiRequestOptions() }, options);\n const apiResponse = await httpFetch(url.href, apiOptions);\n return apiResponse;\n}\n\nexport async function localCollectionGet<T = unknown>(\n url: string,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n return await localCollectionFetch<T>(url, { ...options, method: 'GET' }, serviceOptions);\n}\n\nexport async function localCollectionPost<T = unknown>(\n url: string,\n payload?: unknown,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n return await localCollectionFetch<T>(\n url,\n { ...options, method: 'POST', body: payload ? JSON.stringify(payload) : undefined },\n serviceOptions\n );\n}\n\nexport async function localCollectionPut<T = unknown>(\n url: string,\n payload?: unknown,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n return await localCollectionFetch<T>(\n url,\n { ...options, method: 'PUT', body: payload ? JSON.stringify(payload) : undefined },\n serviceOptions\n );\n}\n\nexport async function localCollectionPatch<T = unknown>(\n url: string,\n payload?: unknown,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n return await localCollectionFetch<T>(\n url,\n { ...options, method: 'PATCH', body: payload ? JSON.stringify(payload) : undefined },\n serviceOptions\n );\n}\n\nexport async function localCollectionDelete<T = unknown>(\n url: string,\n options: ApiRequestOptions = {},\n serviceOptions?: { locale: string; market: string }\n): Promise<T> {\n return await localCollectionFetch<T>(url, { ...options, method: 'DELETE' }, serviceOptions);\n}\n"],"mappings":";;;AAGA,eAAsB,qBACpB,UACA,UAA6B,EAAE,EAC/B,gBACY;CACZ,MAAM,MAAM,IAAI,IAAI,eAAe,SAAS,CAAC;AAC7C,KAAI,gBAAgB;AAClB,MAAI,aAAa,OAAO,UAAU,eAAe,OAAO;AACxD,MAAI,aAAa,OAAO,UAAU,eAAe,OAAO;;CAE1D,MAAM,aAAa,MAAM,EAAE,GAAG,2BAA2B,EAAE,EAAE,QAAQ;AAErE,QADoB,MAAM,UAAU,IAAI,MAAM,WAAW;;AAI3D,eAAsB,mBACpB,KACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBAAwB,KAAK;EAAE,GAAG;EAAS,QAAQ;EAAO,EAAE,eAAe;;AAG1F,eAAsB,oBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAQ,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EACnF,eACD;;AAGH,eAAsB,mBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAO,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EAClF,eACD;;AAGH,eAAsB,qBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAS,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EACpF,eACD;;AAGH,eAAsB,sBACpB,KACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBAAwB,KAAK;EAAE,GAAG;EAAS,QAAQ;EAAU,EAAE,eAAe"}
1
+ {"version":3,"file":"local.collection.js","names":[],"sources":["../../src/client/local.collection.ts"],"sourcesContent":["import { httpFetch, merge } from '@websolutespa/bom-core';\r\nimport { ApiRequestOptions, getLocalApiRequestOptions, getLocalApiUrl } from '../lib/http';\r\n\r\nexport async function localCollectionFetch<T = unknown>(\r\n pathname: string,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n const url = new URL(getLocalApiUrl(pathname));\r\n if (serviceOptions) {\r\n url.searchParams.append('locale', serviceOptions.locale);\r\n url.searchParams.append('market', serviceOptions.market);\r\n }\r\n const apiOptions = merge({ ...getLocalApiRequestOptions() }, options);\r\n const apiResponse = await httpFetch(url.href, apiOptions);\r\n return apiResponse;\r\n}\r\n\r\nexport async function localCollectionGet<T = unknown>(\r\n url: string,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n return await localCollectionFetch<T>(url, { ...options, method: 'GET' }, serviceOptions);\r\n}\r\n\r\nexport async function localCollectionPost<T = unknown>(\r\n url: string,\r\n payload?: unknown,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n return await localCollectionFetch<T>(\r\n url,\r\n { ...options, method: 'POST', body: payload ? JSON.stringify(payload) : undefined },\r\n serviceOptions\r\n );\r\n}\r\n\r\nexport async function localCollectionPut<T = unknown>(\r\n url: string,\r\n payload?: unknown,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n return await localCollectionFetch<T>(\r\n url,\r\n { ...options, method: 'PUT', body: payload ? JSON.stringify(payload) : undefined },\r\n serviceOptions\r\n );\r\n}\r\n\r\nexport async function localCollectionPatch<T = unknown>(\r\n url: string,\r\n payload?: unknown,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n return await localCollectionFetch<T>(\r\n url,\r\n { ...options, method: 'PATCH', body: payload ? JSON.stringify(payload) : undefined },\r\n serviceOptions\r\n );\r\n}\r\n\r\nexport async function localCollectionDelete<T = unknown>(\r\n url: string,\r\n options: ApiRequestOptions = {},\r\n serviceOptions?: { locale: string; market: string }\r\n): Promise<T> {\r\n return await localCollectionFetch<T>(url, { ...options, method: 'DELETE' }, serviceOptions);\r\n}\r\n"],"mappings":";;;AAGA,eAAsB,qBACpB,UACA,UAA6B,EAAE,EAC/B,gBACY;CACZ,MAAM,MAAM,IAAI,IAAI,eAAe,SAAS,CAAC;AAC7C,KAAI,gBAAgB;AAClB,MAAI,aAAa,OAAO,UAAU,eAAe,OAAO;AACxD,MAAI,aAAa,OAAO,UAAU,eAAe,OAAO;;CAE1D,MAAM,aAAa,MAAM,EAAE,GAAG,2BAA2B,EAAE,EAAE,QAAQ;AAErE,QADoB,MAAM,UAAU,IAAI,MAAM,WAAW;;AAI3D,eAAsB,mBACpB,KACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBAAwB,KAAK;EAAE,GAAG;EAAS,QAAQ;EAAO,EAAE,eAAe;;AAG1F,eAAsB,oBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAQ,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EACnF,eACD;;AAGH,eAAsB,mBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAO,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EAClF,eACD;;AAGH,eAAsB,qBACpB,KACA,SACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBACX,KACA;EAAE,GAAG;EAAS,QAAQ;EAAS,MAAM,UAAU,KAAK,UAAU,QAAQ,GAAG,KAAA;EAAW,EACpF,eACD;;AAGH,eAAsB,sBACpB,KACA,UAA6B,EAAE,EAC/B,gBACY;AACZ,QAAO,MAAM,qBAAwB,KAAK;EAAE,GAAG;EAAS,QAAQ;EAAU,EAAE,eAAe"}