@timber-js/app 0.2.0-alpha.220 → 0.2.0-alpha.222

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 (236) hide show
  1. package/dist/_chunks/{actions-BwkmAYXq.js → actions-vBHr2vqd.js} +3 -3
  2. package/dist/_chunks/{actions-BwkmAYXq.js.map → actions-vBHr2vqd.js.map} +1 -1
  3. package/dist/_chunks/{cache-api-LA3sBpUS.js → cache-api-DdcDLpBj.js} +72 -145
  4. package/dist/_chunks/cache-api-DdcDLpBj.js.map +1 -0
  5. package/dist/_chunks/chains-B8TCLved.js +1 -0
  6. package/dist/_chunks/{chains-e_Buf9vg.js → chains-BchW_AtW.js} +2 -2
  7. package/dist/_chunks/{chains-e_Buf9vg.js.map → chains-BchW_AtW.js.map} +1 -1
  8. package/dist/_chunks/{classify-2Yp3xJY1.js → classify-IqzMpxMs.js} +2 -2
  9. package/dist/_chunks/{classify-2Yp3xJY1.js.map → classify-IqzMpxMs.js.map} +1 -1
  10. package/dist/_chunks/{cli-check-DDwCkeDY.js → cli-check-DQne_YhU.js} +3 -3
  11. package/dist/_chunks/{cli-check-DDwCkeDY.js.map → cli-check-DQne_YhU.js.map} +1 -1
  12. package/dist/_chunks/{cli-schema-sync-BdIebmk3.js → cli-schema-sync-BS-RFGE2.js} +2 -2
  13. package/dist/_chunks/{cli-schema-sync-BdIebmk3.js.map → cli-schema-sync-BS-RFGE2.js.map} +1 -1
  14. package/dist/_chunks/{cli-schema-sync-CLNfXQDK.js → cli-schema-sync-v872sHms.js} +1 -1
  15. package/dist/_chunks/{client-dep-entries-BOkpKjj1.js → client-dep-entries-BJyP9SIu.js} +2 -2
  16. package/dist/_chunks/{client-dep-entries-BOkpKjj1.js.map → client-dep-entries-BJyP9SIu.js.map} +1 -1
  17. package/dist/_chunks/{convention-lint-ByKJ6aqD.js → convention-lint-VwzrtjIt.js} +3 -3
  18. package/dist/_chunks/{convention-lint-ByKJ6aqD.js.map → convention-lint-VwzrtjIt.js.map} +1 -1
  19. package/dist/_chunks/{dev-server-DnODXuNM.js → dev-server-BNr5drEO.js} +57 -8
  20. package/dist/_chunks/dev-server-BNr5drEO.js.map +1 -0
  21. package/dist/_chunks/dev-server-CUg7Mqh_.js +1 -0
  22. package/dist/_chunks/dev-store-BOa304m_.js +283 -0
  23. package/dist/_chunks/dev-store-BOa304m_.js.map +1 -0
  24. package/dist/_chunks/{error-boundary-xxxLtXt6.js → error-boundary-Bc8QPZuq.js} +71 -21
  25. package/dist/_chunks/error-boundary-Bc8QPZuq.js.map +1 -0
  26. package/dist/_chunks/{flight-source-node-0dE-t3kq.js → flight-source-node-BdHUOUqg.js} +6 -7
  27. package/dist/_chunks/flight-source-node-BdHUOUqg.js.map +1 -0
  28. package/dist/_chunks/global-context-B9PFncvb.js +48 -0
  29. package/dist/_chunks/global-context-B9PFncvb.js.map +1 -0
  30. package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js → json-lossy-check-C3Sht92C.js} +2 -2
  31. package/dist/_chunks/{json-lossy-check-C8zBY2uZ.js.map → json-lossy-check-C3Sht92C.js.map} +1 -1
  32. package/dist/_chunks/{live-graph-tSWrv8eH.js → live-graph-DEu_GWbc.js} +4 -4
  33. package/dist/_chunks/{live-graph-tSWrv8eH.js.map → live-graph-DEu_GWbc.js.map} +1 -1
  34. package/dist/_chunks/{logger-CbLdcy-W.js → logger-CI_hThfy.js} +10 -2
  35. package/dist/_chunks/{logger-CbLdcy-W.js.map → logger-CI_hThfy.js.map} +1 -1
  36. package/dist/_chunks/{node-response-Dibufw_b.js → node-response-bF0bKoig.js} +49 -3
  37. package/dist/_chunks/node-response-bF0bKoig.js.map +1 -0
  38. package/dist/_chunks/{poison-scan-C4FgMxFl.js → poison-scan-DTWIfNgD.js} +2 -2
  39. package/dist/_chunks/{poison-scan-C4FgMxFl.js.map → poison-scan-DTWIfNgD.js.map} +1 -1
  40. package/dist/_chunks/{purge-store-Byr8XOjU.js → purge-store-WZaxu-3m.js} +2 -2
  41. package/dist/_chunks/purge-store-WZaxu-3m.js.map +1 -0
  42. package/dist/_chunks/{render-timeout-DOf_BBcO.js → render-timeout-Ln_u7fX-.js} +19 -11
  43. package/dist/_chunks/render-timeout-Ln_u7fX-.js.map +1 -0
  44. package/dist/_chunks/{resolve-schema-CBR6Lm4i.js → resolve-schema-CkAInout.js} +2 -2
  45. package/dist/_chunks/{resolve-schema-CBR6Lm4i.js.map → resolve-schema-CkAInout.js.map} +1 -1
  46. package/dist/_chunks/{scanner-Cb3fSjAC.js → scanner-C8fdKvKG.js} +2 -2
  47. package/dist/_chunks/{scanner-Cb3fSjAC.js.map → scanner-C8fdKvKG.js.map} +1 -1
  48. package/dist/_chunks/{schema-bridge-C83xa9lT.js → schema-bridge-DpOmvZlI.js} +60 -23
  49. package/dist/_chunks/schema-bridge-DpOmvZlI.js.map +1 -0
  50. package/dist/_chunks/{segment-context-xtPUGfdq.js → segment-context-D3DNxKFq.js} +4 -8
  51. package/dist/_chunks/segment-context-D3DNxKFq.js.map +1 -0
  52. package/dist/_chunks/{sizeof-QPE5nd3u.js → sizeof-CO3dk0V1.js} +2 -2
  53. package/dist/_chunks/{sizeof-QPE5nd3u.js.map → sizeof-CO3dk0V1.js.map} +1 -1
  54. package/dist/_chunks/{walkers-qu8TpiLh.js → walkers-BqzxnwGC.js} +3 -3
  55. package/dist/_chunks/{walkers-qu8TpiLh.js.map → walkers-BqzxnwGC.js.map} +1 -1
  56. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  57. package/dist/analyze/crawl-entry.js +3 -3
  58. package/dist/analyze/graph-command.js +2 -2
  59. package/dist/cache/cache-api.d.ts.map +1 -1
  60. package/dist/cache/guarded-read.d.ts +29 -0
  61. package/dist/cache/guarded-read.d.ts.map +1 -0
  62. package/dist/cache/handler-store.d.ts +13 -1
  63. package/dist/cache/handler-store.d.ts.map +1 -1
  64. package/dist/cache/index.js +3 -2
  65. package/dist/cache/invalidation-epoch.d.ts +7 -0
  66. package/dist/cache/invalidation-epoch.d.ts.map +1 -1
  67. package/dist/cache/stores/memory.js +1 -1
  68. package/dist/cache/timber-cache.d.ts.map +1 -1
  69. package/dist/cdn/index.js +1 -1
  70. package/dist/cdn/purge-store.d.ts +10 -1
  71. package/dist/cdn/purge-store.d.ts.map +1 -1
  72. package/dist/cli.js +3 -3
  73. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  74. package/dist/client/error-boundary.js +1 -1
  75. package/dist/client/global-context.d.ts +21 -1
  76. package/dist/client/global-context.d.ts.map +1 -1
  77. package/dist/client/index.js +9 -27
  78. package/dist/client/index.js.map +1 -1
  79. package/dist/client/internal.js +38 -65
  80. package/dist/client/internal.js.map +1 -1
  81. package/dist/client/link.d.ts.map +1 -1
  82. package/dist/client/navigation-context.d.ts.map +1 -1
  83. package/dist/client/navigation-transition.d.ts +68 -14
  84. package/dist/client/navigation-transition.d.ts.map +1 -1
  85. package/dist/client/params-context.d.ts.map +1 -1
  86. package/dist/client/router-effects.d.ts +35 -31
  87. package/dist/client/router-effects.d.ts.map +1 -1
  88. package/dist/client/router-pipeline.d.ts +2 -6
  89. package/dist/client/router-pipeline.d.ts.map +1 -1
  90. package/dist/client/router-types.d.ts +10 -30
  91. package/dist/client/router-types.d.ts.map +1 -1
  92. package/dist/client/router.d.ts.map +1 -1
  93. package/dist/client/slot-context.d.ts +2 -2
  94. package/dist/client/slot-context.d.ts.map +1 -1
  95. package/dist/codec.js +1 -1
  96. package/dist/cookies/index.js +1 -1
  97. package/dist/dev-tools/logs.d.ts +2 -2
  98. package/dist/dev-tools/logs.d.ts.map +1 -1
  99. package/dist/index.js +149 -56
  100. package/dist/index.js.map +1 -1
  101. package/dist/params/index.js +1 -1
  102. package/dist/plugins/dev-server.d.ts +1 -1
  103. package/dist/plugins/dev-server.d.ts.map +1 -1
  104. package/dist/plugins/dev-store-clear.d.ts +28 -0
  105. package/dist/plugins/dev-store-clear.d.ts.map +1 -0
  106. package/dist/plugins/entries.d.ts +5 -0
  107. package/dist/plugins/entries.d.ts.map +1 -1
  108. package/dist/plugins/orphaned-modules.d.ts +57 -0
  109. package/dist/plugins/orphaned-modules.d.ts.map +1 -0
  110. package/dist/plugins/prebuilt.d.ts +6 -6
  111. package/dist/plugins/prerender-sugar.d.ts.map +1 -1
  112. package/dist/plugins/routing.d.ts +1 -1
  113. package/dist/plugins/routing.d.ts.map +1 -1
  114. package/dist/routing/index.js +2 -2
  115. package/dist/rsc-runtime/dev-reference-cache.d.ts +47 -0
  116. package/dist/rsc-runtime/dev-reference-cache.d.ts.map +1 -0
  117. package/dist/rsc-runtime/rsc.d.ts +0 -15
  118. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  119. package/dist/rsc-runtime/ssr.d.ts +0 -11
  120. package/dist/rsc-runtime/ssr.d.ts.map +1 -1
  121. package/dist/schema-bridge.d.ts +28 -19
  122. package/dist/schema-bridge.d.ts.map +1 -1
  123. package/dist/search-params/define.d.ts +1 -1
  124. package/dist/search-params/define.d.ts.map +1 -1
  125. package/dist/search-params/index.js +7 -8
  126. package/dist/search-params/index.js.map +1 -1
  127. package/dist/search-params/wrappers.d.ts +3 -3
  128. package/dist/server/abort-scope.d.ts +27 -0
  129. package/dist/server/abort-scope.d.ts.map +1 -0
  130. package/dist/server/flight-source-node.d.ts.map +1 -1
  131. package/dist/server/index.js +2 -2
  132. package/dist/server/instrumentation.d.ts +2 -1
  133. package/dist/server/instrumentation.d.ts.map +1 -1
  134. package/dist/server/internal.d.ts +1 -1
  135. package/dist/server/internal.d.ts.map +1 -1
  136. package/dist/server/internal.js +350 -151
  137. package/dist/server/internal.js.map +1 -1
  138. package/dist/server/logger.d.ts +9 -0
  139. package/dist/server/logger.d.ts.map +1 -1
  140. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  141. package/dist/server/pipeline.d.ts +10 -7
  142. package/dist/server/pipeline.d.ts.map +1 -1
  143. package/dist/server/prebuilt/cache-key.d.ts +26 -0
  144. package/dist/server/prebuilt/cache-key.d.ts.map +1 -1
  145. package/dist/server/prebuilt/capture-render.d.ts +9 -4
  146. package/dist/server/prebuilt/capture-render.d.ts.map +1 -1
  147. package/dist/server/prebuilt/capture-routes.d.ts +1 -1
  148. package/dist/server/prebuilt/dev-store.d.ts +103 -0
  149. package/dist/server/prebuilt/dev-store.d.ts.map +1 -0
  150. package/dist/server/prebuilt/overlay.d.ts +14 -3
  151. package/dist/server/prebuilt/overlay.d.ts.map +1 -1
  152. package/dist/server/prebuilt/payload-source.d.ts +8 -0
  153. package/dist/server/prebuilt/payload-source.d.ts.map +1 -1
  154. package/dist/server/prebuilt/slots.d.ts +5 -6
  155. package/dist/server/prebuilt/slots.d.ts.map +1 -1
  156. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  157. package/dist/server/prebuilt-runtime.d.ts +5 -10
  158. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  159. package/dist/server/render-timeout.d.ts.map +1 -1
  160. package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -1
  161. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  162. package/dist/server/ssr-render.d.ts.map +1 -1
  163. package/docs/api/32-api-cache.mdx +2 -0
  164. package/docs/api/33-api-search-params.mdx +3 -1
  165. package/docs/learn/06-typed-params.mdx +2 -2
  166. package/docs/learn/10-caching.mdx +12 -0
  167. package/docs/learn/11-middleware.mdx +2 -0
  168. package/package.json +1 -1
  169. package/src/cache/cache-api.ts +7 -1
  170. package/src/cache/guarded-read.ts +44 -0
  171. package/src/cache/handler-store.ts +38 -1
  172. package/src/cache/invalidation-epoch.ts +18 -6
  173. package/src/cache/timber-cache.ts +9 -3
  174. package/src/cdn/purge-store.ts +29 -1
  175. package/src/client/browser-entry/action-dispatch.ts +5 -5
  176. package/src/client/browser-entry/router-init.ts +2 -4
  177. package/src/client/global-context.ts +42 -14
  178. package/src/client/link.tsx +14 -18
  179. package/src/client/navigation-context.ts +4 -11
  180. package/src/client/navigation-transition.ts +86 -33
  181. package/src/client/params-context.ts +5 -17
  182. package/src/client/router-effects.ts +70 -45
  183. package/src/client/router-lifecycle.ts +1 -1
  184. package/src/client/router-pipeline.ts +52 -65
  185. package/src/client/router-types.ts +11 -31
  186. package/src/client/router.ts +98 -104
  187. package/src/client/segment-update-context.ts +1 -1
  188. package/src/client/slot-content-cache-context.ts +1 -1
  189. package/src/client/slot-context.ts +6 -17
  190. package/src/dev-tools/logs.ts +76 -50
  191. package/src/plugins/dev-server.ts +58 -9
  192. package/src/plugins/dev-store-clear.ts +47 -0
  193. package/src/plugins/entries.ts +6 -0
  194. package/src/plugins/orphaned-modules.ts +78 -0
  195. package/src/plugins/prebuilt.ts +17 -17
  196. package/src/plugins/prerender-sugar.ts +38 -6
  197. package/src/plugins/routing.ts +23 -1
  198. package/src/rsc-runtime/dev-reference-cache.ts +115 -0
  199. package/src/rsc-runtime/rsc.ts +10 -0
  200. package/src/rsc-runtime/ssr.ts +10 -0
  201. package/src/rsc-runtime/vendor-types.d.ts +8 -0
  202. package/src/schema-bridge.ts +93 -38
  203. package/src/search-params/define.ts +5 -6
  204. package/src/search-params/wrappers.ts +3 -3
  205. package/src/server/abort-scope.ts +49 -0
  206. package/src/server/action-handler.ts +18 -2
  207. package/src/server/flight-source-node.ts +5 -4
  208. package/src/server/instrumentation.ts +32 -8
  209. package/src/server/internal.ts +1 -6
  210. package/src/server/logger.ts +9 -0
  211. package/src/server/pipeline-helpers.ts +5 -3
  212. package/src/server/pipeline.ts +31 -20
  213. package/src/server/prebuilt/cache-key.ts +41 -0
  214. package/src/server/prebuilt/capture-render.ts +10 -6
  215. package/src/server/prebuilt/capture-routes.ts +1 -1
  216. package/src/server/prebuilt/dev-store.ts +173 -0
  217. package/src/server/prebuilt/overlay.ts +21 -5
  218. package/src/server/prebuilt/payload-source.ts +19 -0
  219. package/src/server/prebuilt/slots.ts +5 -6
  220. package/src/server/prebuilt-builder.ts +3 -2
  221. package/src/server/prebuilt-runtime.ts +194 -177
  222. package/src/server/render-timeout.ts +12 -17
  223. package/src/server/rsc-entry/action-dispatcher.ts +3 -1
  224. package/src/server/rsc-entry/index.ts +47 -13
  225. package/src/server/ssr-render.ts +9 -11
  226. package/dist/_chunks/cache-api-LA3sBpUS.js.map +0 -1
  227. package/dist/_chunks/chains-CDK1AWZQ.js +0 -1
  228. package/dist/_chunks/dev-server-DkytOEG2.js +0 -1
  229. package/dist/_chunks/dev-server-DnODXuNM.js.map +0 -1
  230. package/dist/_chunks/error-boundary-xxxLtXt6.js.map +0 -1
  231. package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +0 -1
  232. package/dist/_chunks/node-response-Dibufw_b.js.map +0 -1
  233. package/dist/_chunks/purge-store-Byr8XOjU.js.map +0 -1
  234. package/dist/_chunks/render-timeout-DOf_BBcO.js.map +0 -1
  235. package/dist/_chunks/schema-bridge-C83xa9lT.js.map +0 -1
  236. package/dist/_chunks/segment-context-xtPUGfdq.js.map +0 -1
@@ -12,9 +12,10 @@
12
12
  *
13
13
  * One parse loop, four candidate orders. Which shapes a bridge offers, and
14
14
  * in what order, is the ONLY thing that differs — see §"Shape tolerance"
15
- * below and in design/23-search-params.md. `serialize` is deliberately NOT
16
- * shared: `null` means "omit the key" for a search param and "delete the
17
- * cookie" for a cookie, so unifying it silently changed what
15
+ * below and in design/23-search-params.md. `serialize` is shared only by
16
+ * the two search-param bridges (`serializeSearchValue`), never with the
17
+ * cookie bridge: `null` means "omit the key" for a search param and
18
+ * "delete the cookie" for a cookie, so unifying it silently changed what
18
19
  * `cookie.set([])` did (TIM-1352).
19
20
  *
20
21
  * These are re-exported from @timber-js/app/search-params, @timber-js/app/segment-params,
@@ -132,22 +133,24 @@ export function fromParamSchema<T>(fieldName: string, schema: StandardSchemaV1<T
132
133
  *
133
134
  * @param fieldName - used in error messages
134
135
  * @param value - the codec or schema to resolve
136
+ * Search params don't come through here: `defineSearchParams` wraps
137
+ * schemas with `fromSchema`, whose `serialize` may return `string[]`.
138
+ *
139
+ * @param fieldName - used in error messages
140
+ * @param value - the codec or schema to resolve
135
141
  * @param mode - 'param' uses fromParamSchema (throws on parse failure),
136
- * 'search' uses fromSchema (falls back to default on failure,
137
- * tolerant of the repeated-key array shape),
138
- * 'cookie' uses fromCookieSchema (same, minus the array shape,
139
- * which a cookie value cannot have)
142
+ * 'cookie' uses fromCookieSchema (falls back to default on
143
+ * failure; scalar shape only, since a cookie has no array shape)
140
144
  */
141
145
  export function resolveCodecOrSchema(
142
146
  fieldName: string,
143
147
  value: unknown,
144
- mode: 'param' | 'search' | 'cookie' = 'search'
148
+ mode: 'param' | 'cookie'
145
149
  ): Codec<unknown> {
146
150
  if (isCodec(value)) return value;
147
151
  if (isStandardSchema(value)) {
148
152
  if (mode === 'param') return fromParamSchema(fieldName, value);
149
- if (mode === 'cookie') return fromCookieSchema(value) as Codec<unknown>;
150
- return fromSchema(value) as Codec<unknown>;
153
+ return fromCookieSchema(value) as Codec<unknown>;
151
154
  }
152
155
  throw new Error(
153
156
  `[timber] Field '${fieldName}' is not a valid codec or Standard Schema. ` +
@@ -272,10 +275,9 @@ function parseThroughSchema<T>(
272
275
  * schema should have a `.default()` call). If that also fails, returns
273
276
  * `undefined`.
274
277
  *
275
- * Serialize: `String()` for primitives, `null` for null/undefined. Note
276
- * that `String(['a','b'])` is `'a,b'` — the same string `fromArraySchema`
277
- * writes — so a bare array schema round-trips exactly as design/09
278
- * §"Array params" describes.
278
+ * Serialize: `String()` for primitives, `null` for null/undefined. An
279
+ * array is written in whichever encoding the schema reads back as the same
280
+ * array — see `serializeArrayForSchema`.
279
281
  *
280
282
  * This is the SEARCH-PARAM bridge. Cookies use `fromCookieSchema`; a
281
283
  * cookie has no array shape (see below).
@@ -287,19 +289,86 @@ function parseThroughSchema<T>(
287
289
  * const tagsCodec = fromSchema(z.array(z.string()).default([]))
288
290
  * ```
289
291
  */
290
- export function fromSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {
292
+ export function fromSchema<T>(schema: StandardSchemaV1<T>): SearchValueCodec<T> {
291
293
  return {
292
294
  parse: (value: string | string[] | undefined): T =>
293
295
  parseThroughSchema(schema, scalarFirst, value),
294
- serialize(value: T): string | null {
295
- if (value === null || value === undefined) {
296
- return null;
297
- }
298
- return String(value);
299
- },
296
+ serialize: (value: T): string | string[] | null =>
297
+ Array.isArray(value) ? serializeArrayForSchema(schema, value) : serializeSearchValue(value),
300
298
  };
301
299
  }
302
300
 
301
+ /**
302
+ * An array value has two URL encodings, and the schema alone decides which
303
+ * one reads back. `z.array(z.string())` reads repeated keys
304
+ * (`?tags=a&tags=b`); the comma idiom, `z.string().transform(v =>
305
+ * v.split(','))`, reads ONE key (`?tags=a,b`) and takes only the first of
306
+ * repeated keys. Writing the wrong one is silent data corruption: joining
307
+ * for an array schema reads back as the single element `'a,b'`, and
308
+ * repeating for the comma idiom reads back as `['a']`.
309
+ *
310
+ * Standard Schema exposes no input type at runtime, so ask the schema:
311
+ * parse the preferred encoding exactly as a request would deliver it, and
312
+ * keep it if the same array comes back. Otherwise write the joined string,
313
+ * which is what the comma idiom reads.
314
+ *
315
+ * An empty array prefers omitting the key, which reads back as `[]` for
316
+ * `z.array(z.string()).default([])`. A comma schema whose absent value is
317
+ * a non-empty default (`.catch(['all'])`) instead needs `tags=`, which its
318
+ * transform turns into `[]` — omitting would read back as `['all']`.
319
+ */
320
+ function serializeArrayForSchema<T>(
321
+ schema: StandardSchemaV1<T>,
322
+ value: unknown[]
323
+ ): string | string[] | null {
324
+ const preferred = value.length === 0 ? null : value.map(String);
325
+ return readsBack(schema, preferred, value) ? preferred : String(value);
326
+ }
327
+
328
+ /** Does `encoded`, delivered as a request would, parse back to `value`? */
329
+ function readsBack<T>(
330
+ schema: StandardSchemaV1<T>,
331
+ encoded: string[] | null,
332
+ value: unknown[]
333
+ ): boolean {
334
+ // An omitted key arrives as undefined; URLSearchParams.getAll() yields
335
+ // one value as a plain string.
336
+ const delivered = encoded === null ? undefined : encoded.length === 1 ? encoded[0] : encoded;
337
+ let readBack: unknown;
338
+ try {
339
+ readBack = parseThroughSchema(schema, scalarFirst, delivered);
340
+ } catch {
341
+ // The schema refuses this URL outright, so it is not the encoding.
342
+ return false;
343
+ }
344
+ return (
345
+ Array.isArray(readBack) &&
346
+ readBack.length === value.length &&
347
+ readBack.every((item, i) => String(item) === String(value[i]))
348
+ );
349
+ }
350
+
351
+ /**
352
+ * The codec shape both search-param bridges return. Structurally a
353
+ * `SearchParamCodec<T>` (search-params/define.ts), declared here because
354
+ * define.ts imports this module.
355
+ */
356
+ interface SearchValueCodec<T> {
357
+ parse(value: string | string[] | undefined): T;
358
+ serialize(value: T): string | string[] | null;
359
+ }
360
+
361
+ /**
362
+ * Search-param serialize for `fromSchema` and `fromArraySchema`. An array
363
+ * becomes `string[]` so it is written as repeated keys (TIM-1353); an empty
364
+ * array omits the key.
365
+ */
366
+ function serializeSearchValue(value: unknown): string | string[] | null {
367
+ if (value === null || value === undefined) return null;
368
+ if (Array.isArray(value)) return value.length === 0 ? null : value.map(String);
369
+ return String(value);
370
+ }
371
+
303
372
  // ---------------------------------------------------------------------------
304
373
  // fromCookieSchema — bridge for cookie values
305
374
  // ---------------------------------------------------------------------------
@@ -357,26 +426,12 @@ export function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {
357
426
  * 2. An array schema wrapped in `.catch([])`, which swallows the failure
358
427
  * that would otherwise trigger the array attempt.
359
428
  *
360
- * It also serializes an empty array to `null` (omitting the key) where
361
- * `fromSchema` writes `''`.
429
+ * Serialization is identical to `fromSchema`.
362
430
  */
363
- export function fromArraySchema<T>(schema: StandardSchemaV1<T>): {
364
- parse(value: string | string[] | undefined): T;
365
- serialize(value: T): string | string[] | null;
366
- } {
431
+ export function fromArraySchema<T>(schema: StandardSchemaV1<T>): SearchValueCodec<T> {
367
432
  return {
368
433
  parse: (value: string | string[] | undefined): T =>
369
434
  parseThroughSchema(schema, arrayFirst, value),
370
- serialize(value: T): string | string[] | null {
371
- if (value === null || value === undefined) {
372
- return null;
373
- }
374
- // TIM-1353: return string[] so buildSearchParams emits repeated keys
375
- // (?tag=a&tag=b) instead of comma-joining into one key (?tag=a%2Cb).
376
- if (Array.isArray(value)) {
377
- return value.length === 0 ? null : value.map(String);
378
- }
379
- return String(value);
380
- },
435
+ serialize: serializeSearchValue,
381
436
  };
382
437
  }
@@ -339,10 +339,9 @@ function getDefaultSerialized(codec: SearchParamCodec<unknown>): string | string
339
339
  * objects and wraps them with fromSchema. Reads .urlKey from codecs.
340
340
  *
341
341
  * The returned codec is typed as `SearchParamCodec<unknown>` because the
342
- * codec map uses that type. At runtime, the value may be a `Codec<T>` from
343
- * `fromSchema` (whose serialize returns `string | null`) or a nuqs parser
344
- * (whose serialize returns `string | string[] | null`). Both are safe
345
- * because `buildSearchParams` handles the union.
342
+ * codec map uses that type. Both `fromSchema` results and nuqs parsers may
343
+ * serialize to `string | string[] | null`; `buildSearchParams` handles the
344
+ * union.
346
345
  */
347
346
  function resolveField(
348
347
  fieldName: string,
@@ -359,7 +358,7 @@ function resolveField(
359
358
  // for absent params, and InferField widens the output type to
360
359
  // T | undefined. design/23-search-params.md §"Implicit Optionality"
361
360
  if (isStandardSchema(value)) {
362
- return { codec: fromSchema(value) as SearchParamCodec<unknown> };
361
+ return { codec: fromSchema(value) };
363
362
  }
364
363
 
365
364
  throw new Error(
@@ -380,7 +379,7 @@ function resolveField(
380
379
  *
381
380
  * ```ts
382
381
  * import { defineSearchParams, withDefault, withUrlKey } from '@timber-js/app/search-params'
383
- * import { parseAsString, parseAsStringEnum } from 'nuqs'
382
+ * import { parseAsString, parseAsStringEnum } from 'nuqs/server'
384
383
  * import { z } from 'zod/v4'
385
384
  *
386
385
  * export const searchParams = defineSearchParams({
@@ -45,7 +45,7 @@ import { parseTotal } from './parse-total.ts';
45
45
  * Works with any codec — nuqs parsers, custom codecs, fromSchema results.
46
46
  *
47
47
  * ```ts
48
- * import { parseAsInteger } from 'nuqs'
48
+ * import { parseAsInteger } from 'nuqs/server'
49
49
  * import { withDefault } from '@timber-js/app/search-params'
50
50
  *
51
51
  * const page = withDefault(parseAsInteger, 1)
@@ -97,7 +97,7 @@ export function withDefault<T>(
97
97
  * the aliases come along automatically.
98
98
  *
99
99
  * ```ts
100
- * import { parseAsString } from 'nuqs'
100
+ * import { parseAsString } from 'nuqs/server'
101
101
  * import { withUrlKey } from '@timber-js/app/search-params'
102
102
  *
103
103
  * export const searchable = {
@@ -108,7 +108,7 @@ export function withDefault<T>(
108
108
  *
109
109
  * Composes with withDefault:
110
110
  * ```ts
111
- * import { parseAsInteger } from 'nuqs'
111
+ * import { parseAsInteger } from 'nuqs/server'
112
112
  * withUrlKey(withDefault(parseAsInteger, 1), 'p')
113
113
  * ```
114
114
  */
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Abort listeners scoped to the work they guard.
3
+ *
4
+ * A request's signal outlives the render, stream, or timer that listens to
5
+ * it, and a listener left on it keeps everything its closure holds reachable
6
+ * from the request. In production that only delays collection until the
7
+ * request is garbage. In dev it pins the request forever: React's dev Flight
8
+ * server tracks every live promise in an async-hook Map whose debug chains
9
+ * reach the request, so any promise reachable from the request is never
10
+ * collected and never leaves that Map (TIM-1589).
11
+ *
12
+ * So server code never calls `signal.addEventListener('abort', …)` itself
13
+ * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}
14
+ * takes the end of the listener's scope as a required argument, which makes
15
+ * a listener without a removal unwritable.
16
+ */
17
+
18
+ /**
19
+ * Call `onAbort` if `signal` aborts before the scope `until` ends. If
20
+ * `signal` has already aborted, `onAbort` runs now.
21
+ *
22
+ * `until` is the scope: a promise (the listener is removed when it fulfills
23
+ * or rejects, a microtask later) or an `AbortSignal` (removed synchronously
24
+ * when it aborts; use one when an abort later in the same tick must not
25
+ * fire, as after a timeout's `cancel()`).
26
+ */
27
+ export function onAbortUntil(
28
+ signal: AbortSignal | undefined,
29
+ onAbort: () => void,
30
+ until: PromiseLike<unknown> | AbortSignal
31
+ ): void {
32
+ if (!signal) return;
33
+ if (signal.aborted) {
34
+ onAbort();
35
+ return;
36
+ }
37
+ let scope: AbortSignal;
38
+ if (until instanceof AbortSignal) {
39
+ scope = until;
40
+ } else {
41
+ const ended = new AbortController();
42
+ const end = (): void => ended.abort();
43
+ until.then(end, end);
44
+ scope = ended.signal;
45
+ }
46
+ // addEventListener's own `signal` option removes the listener when the
47
+ // scope aborts: the platform's one-step removal, no handle to keep.
48
+ signal.addEventListener('abort', onAbort, { once: true, signal: scope });
49
+ }
@@ -321,6 +321,22 @@ async function rejectedActionResponse(req: Request, error: unknown): Promise<Res
321
321
  );
322
322
  }
323
323
 
324
+ /** The tag React's `registerServerReference` stamps on a server function. */
325
+ const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
326
+
327
+ /**
328
+ * Whether a loaded value is a function a `'use server'` module registered.
329
+ * Being a function is not enough: in a build, plugin-rsc looks the reference
330
+ * up in plain objects, so `<id>#constructor` loads `Object` and `constructor`
331
+ * as a module ID loads it too. Only the use-server transform's exports carry
332
+ * React's tag, so the tag is the allowlist.
333
+ */
334
+ function isServerReference(value: unknown): value is (...args: unknown[]) => Promise<unknown> {
335
+ return (
336
+ typeof value === 'function' && '$$typeof' in value && value.$$typeof === SERVER_REFERENCE_TAG
337
+ );
338
+ }
339
+
324
340
  /**
325
341
  * Load the action by reference ID and decode its args from the request body
326
342
  * (RSC wire format). Returns a Response for a request that fails before the
@@ -338,11 +354,11 @@ async function decodeRscActionCall(
338
354
  } catch (error) {
339
355
  return rejectActionRequest(req, error, 500);
340
356
  }
341
- if (typeof loaded !== 'function') {
357
+ if (!isServerReference(loaded)) {
342
358
  // The module loaded but has no such export: a reference the client made up.
343
359
  return rejectActionRequest(req, new Error(`Unknown server action "${actionId}"`), 400);
344
360
  }
345
- const actionFn = loaded as (...args: unknown[]) => Promise<unknown>;
361
+ const actionFn = loaded;
346
362
 
347
363
  let decoded: unknown;
348
364
  try {
@@ -19,6 +19,7 @@
19
19
  import { Readable, Transform } from 'node:stream';
20
20
  import { NodeBodyResponse } from './node-body-response.ts';
21
21
  import { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';
22
+ import { onAbortUntil } from './abort-scope.ts';
22
23
  import { RenderTimeoutError } from './render-timeout.ts';
23
24
 
24
25
  // `String.prototype.toWellFormed` ships in every Node timber supports
@@ -93,7 +94,7 @@ export function pipeFlightToNode(
93
94
  flight: PipeableFlight,
94
95
  { signal, timeoutMs }: NodeFlightAbort
95
96
  ): Readable {
96
- const onAbort = (): void => flight.abort(signal?.reason);
97
+ const scope = new AbortController();
97
98
  const timer =
98
99
  timeoutMs === undefined
99
100
  ? undefined
@@ -107,7 +108,7 @@ export function pipeFlightToNode(
107
108
  callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);
108
109
  },
109
110
  destroy(error, callback) {
110
- signal?.removeEventListener('abort', onAbort);
111
+ scope.abort();
111
112
  clearTimeout(timer);
112
113
  // A no-op once Flight has finished (it ignores abort after close).
113
114
  flight.abort(error ?? undefined);
@@ -115,8 +116,8 @@ export function pipeFlightToNode(
115
116
  },
116
117
  });
117
118
  stream.on('error', ignoreError);
118
- if (signal?.aborted) flight.abort(signal.reason);
119
- else signal?.addEventListener('abort', onAbort, { once: true });
119
+ // The listener lasts until the stream is destroyed (server/abort-scope.ts).
120
+ onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);
120
121
  flight.pipe(stream);
121
122
  return stream;
122
123
  }
@@ -9,7 +9,7 @@
9
9
  * See design/17-logging.md §"instrumentation.ts — The Entry Point"
10
10
  */
11
11
 
12
- import { setLogger, type TimberLogger } from './logger.ts';
12
+ import { getLogger, setLogger, type TimberLogger } from './logger.ts';
13
13
 
14
14
  // ─── Instrumentation Types ────────────────────────────────────────────────
15
15
 
@@ -60,7 +60,19 @@ interface InstrumentationModule {
60
60
  // once at server startup and persists for the lifetime of the process/isolate.
61
61
  // These must NOT be migrated to ALS — they are correctly scoped to the app.
62
62
 
63
- let _initialized = false;
63
+ type InstrumentationLoader = () => Promise<InstrumentationModule | null>;
64
+
65
+ /**
66
+ * The loader the current hooks came from. One app passes one loader
67
+ * (`virtual:timber-instrumentation`), so a second call with it is a no-op.
68
+ * In dev a new loader means instrumentation.ts changed: the RSC entry is an
69
+ * HMR boundary (design/21 §HMR Wiring), so editing instrumentation.ts
70
+ * re-executes the virtual loader module and the entry, while this module
71
+ * keeps its state. The new module then replaces the old one's hooks.
72
+ */
73
+ let _loadedFrom: InstrumentationLoader | null = null;
74
+ /** The framework logger before any instrumentation module replaced it. */
75
+ let _loggerBeforeLoad: TimberLogger | null = null;
64
76
  let _onRequestError: InstrumentationOnRequestError | null = null;
65
77
 
66
78
  /**
@@ -73,11 +85,16 @@ let _onRequestError: InstrumentationOnRequestError | null = null;
73
85
  * @param loader - Function that dynamically imports the user's instrumentation module.
74
86
  * Returns null if no instrumentation.ts exists.
75
87
  */
76
- export async function loadInstrumentation(
77
- loader: () => Promise<InstrumentationModule | null>
78
- ): Promise<void> {
79
- if (_initialized) return;
80
- _initialized = true;
88
+ export async function loadInstrumentation(loader: InstrumentationLoader): Promise<void> {
89
+ if (_loadedFrom === loader) return;
90
+ if (_loadedFrom === null) {
91
+ _loggerBeforeLoad = getLogger();
92
+ } else {
93
+ // A changed instrumentation.ts (dev): drop what the previous one installed.
94
+ _onRequestError = null;
95
+ setLogger(_loggerBeforeLoad!);
96
+ }
97
+ _loadedFrom = loader;
81
98
 
82
99
  let mod: InstrumentationModule | null;
83
100
  try {
@@ -105,6 +122,12 @@ export async function loadInstrumentation(
105
122
  await mod.register();
106
123
  } catch (error) {
107
124
  console.error('[timber] instrumentation.ts register() threw:', error);
125
+ // Not loaded: the entry fails, and its next run (the next request or
126
+ // edit in dev) must call register() again instead of returning early
127
+ // on this loader and serving without it (TIM-1589).
128
+ _onRequestError = null;
129
+ if (_loggerBeforeLoad) setLogger(_loggerBeforeLoad);
130
+ _loadedFrom = null;
108
131
  throw error;
109
132
  }
110
133
  }
@@ -138,6 +161,7 @@ export function hasOnRequestError(): boolean {
138
161
  * Reset instrumentation state. Test-only.
139
162
  */
140
163
  export function resetInstrumentation(): void {
141
- _initialized = false;
164
+ _loadedFrom = null;
165
+ _loggerBeforeLoad = null;
142
166
  _onRequestError = null;
143
167
  }
@@ -152,12 +152,7 @@ export { RenderTimeoutError } from './render-timeout.ts';
152
152
  export type { RenderTimeout } from './render-timeout.ts';
153
153
 
154
154
  // ── Prebuilt Components (cache.component transform targets) ─────────────
155
- export {
156
- __prebuilt,
157
- __prebuiltDev,
158
- getPrebuiltRegistration,
159
- getPrebuiltRegistry,
160
- } from './prebuilt-runtime.ts';
155
+ export { __prebuilt, getPrebuiltRegistration, getPrebuiltRegistry } from './prebuilt-runtime.ts';
161
156
  export type { PrebuiltComponentOptions, PrebuiltRegistration } from './prebuilt-runtime.ts';
162
157
  export { setPrebuiltPayloadSource, hasPrebuiltPayloadSource } from './prebuilt/payload-source.ts';
163
158
  export type {
@@ -220,6 +220,15 @@ export function logCacheMiss(data: { cacheKey: string }): void {
220
220
  _logger.debug('timber.cache MISS', withTraceContext(data));
221
221
  }
222
222
 
223
+ /**
224
+ * Log a cache read that threw or timed out and was served as a miss.
225
+ * Level: warn — the request still succeeds, but a failing store (Redis down,
226
+ * KV erroring) means every read is paying for a live fetch.
227
+ */
228
+ export function logCacheReadFailed(data: { cacheKey: string; error: unknown }): void {
229
+ _logger.warn('cache read failed — treating as a miss', withTraceContext(data));
230
+ }
231
+
223
232
  // ─── Swallow Helper ───────────────────────────────────────────────────────
224
233
 
225
234
  /**
@@ -18,6 +18,7 @@ import {
18
18
  } from './instrumentation.ts';
19
19
  import { getTraceId } from './tracing.ts';
20
20
  import { requestContextAls } from './als-registry.ts';
21
+ import { onAbortUntil } from './abort-scope.ts';
21
22
  import { RedirectSignal } from './primitives.ts';
22
23
  import { isControlFlowSignal } from './signal-identity.ts';
23
24
  import { logRenderError, logSkippedModule, swallow } from './logger.ts';
@@ -522,14 +523,15 @@ export async function runBackgroundFlight(
522
523
  const request = requestContextAls.getStore()?.request;
523
524
  if (request && isReportableError(error)) fireInBackground(callHook(error, request, 'render'));
524
525
  };
525
- const onTimeout = (): void => failed(signal.reason);
526
- signal.addEventListener('abort', onTimeout, { once: true });
526
+ // The listener lasts until the work settles (server/abort-scope.ts).
527
+ const settled = new AbortController();
528
+ onAbortUntil(signal, () => failed(signal.reason), settled.signal);
527
529
  try {
528
530
  await work();
529
531
  } catch (error) {
530
532
  if (!signal.aborted) failed(error);
531
533
  } finally {
532
- signal.removeEventListener('abort', onTimeout);
534
+ settled.abort();
533
535
  }
534
536
  }
535
537
 
@@ -251,16 +251,19 @@ export interface PipelineConfig {
251
251
  * value that `handleRequest` and `matchRoute` use. Do NOT re-derive it
252
252
  * from `req.url` (which re-encodes).
253
253
  *
254
- * The `reenter` parameter is the full pipeline function (including proxy,
255
- * ALS, tracing) for the no-JS action rerender path — the synthetic GET
256
- * flows through the complete pipeline. Its `cookies` become that request's
257
- * parsed cookies and its `formState` the action's form state for SSR
258
- * (`runWithRequestContext`'s options), so the rerender reads both without
259
- * the pipeline needing the same `Request` object to reach them.
254
+ * The `reenter` parameter renders the page for a no-JS action that did
255
+ * not redirect. It enters the pipeline after proxy.ts: the synthetic GET
256
+ * is an internal render of the POST's answer, not a second wire request,
257
+ * so it keeps the POST's trace ID and is neither proxied nor logged again
258
+ * (TIM-1445). Route matching, middleware.ts and access.ts run as for any
259
+ * page render. It runs in its own request context: the GET, with the
260
+ * reentry's `cookies` as its parsed cookies and its `formState` or
261
+ * `actionError` for the render (`runWithRequestContext`'s options).
260
262
  *
261
263
  * Moved into the pipeline (TIM-1213) so proxy.ts runs on action POSTs,
262
264
  * matching the design doc contract: "proxy.ts runs on every request,
263
- * no exclusions."
265
+ * no exclusions." It runs once per wire request; the outer pass wraps
266
+ * the rerendered response.
264
267
  */
265
268
  dispatchAction?: (
266
269
  req: Request,
@@ -307,11 +310,7 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
307
310
  // Logged with each request for diagnosing resource contention.
308
311
  let activeRequests = 0;
309
312
 
310
- // Self-reference for re-entry — the no-JS validation rerender path
311
- // passes a synthetic GET back through the full pipeline (including
312
- // proxy, ALS, tracing). The inner closure captures `pipelineFn` by
313
- // name; by the time it's invoked, the const binding is initialized.
314
- const pipelineFn = async (req: Request, reentry?: PipelineReentry): Promise<Response> => {
313
+ return async (req: Request): Promise<Response> => {
315
314
  const url = new URL(req.url);
316
315
  const method = req.method;
317
316
  const path = url.pathname;
@@ -416,10 +415,28 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
416
415
  );
417
416
  if (redirect) return redirect;
418
417
  if (config.dispatchAction) {
418
+ // A no-JS action's answer re-enters here, inside this
419
+ // request's proxy.ts, trace and log scope, which ran once
420
+ // for the wire POST (TIM-1445). Only the request context
421
+ // is new. It renders the POST's canonical path: the
422
+ // answer is always the page the form posted to.
423
+ const reenter = (rerenderReq: Request, reentry: PipelineReentry) =>
424
+ runWithRequestContext(
425
+ rerenderReq,
426
+ () =>
427
+ handleRequest(
428
+ config,
429
+ rerenderReq,
430
+ rerenderReq.method,
431
+ canonicalPath,
432
+ true
433
+ ),
434
+ reentry
435
+ );
419
436
  const actionResult = await config.dispatchAction(
420
437
  canonicalReq,
421
438
  canonicalPath,
422
- pipelineFn
439
+ reenter
423
440
  );
424
441
  if (actionResult) return actionResult;
425
442
  }
@@ -571,13 +588,7 @@ export function createPipeline(config: PipelineConfig): (req: Request) => Promis
571
588
 
572
589
  return serverTiming === 'detailed' ? runWithTimingCollector(runRequest) : runRequest();
573
590
  };
574
- return runWithRequestContext(req, inRequestContext, {
575
- cookies: reentry?.cookies,
576
- formState: reentry?.formState,
577
- actionError: reentry?.actionError,
578
- });
591
+ return runWithRequestContext(req, inRequestContext);
579
592
  });
580
593
  };
581
-
582
- return pipelineFn;
583
594
  }
@@ -42,6 +42,7 @@
42
42
 
43
43
  import { createHash } from 'node:crypto';
44
44
  import type { CoercedParams } from '../../shared/param-value.ts';
45
+ import type { SlotParamsRecord } from '../../shared/slot-params.ts';
45
46
 
46
47
  class UnkeyableValueError extends Error {}
47
48
 
@@ -297,3 +298,43 @@ export function computeComponentCacheKey(
297
298
  // aggressively.
298
299
  return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
299
300
  }
301
+
302
+ /**
303
+ * Resolve the params the cache key may faithfully hash, or null if this
304
+ * render is unkeyable.
305
+ *
306
+ * A wrapper rendered inside a parallel slot reads params merged with that
307
+ * slot's overrides (`getSegmentParams`: `{...segmentParams, ...slotParams}`)
308
+ * — but the cache key hashes only the route-level params, and the wrapper
309
+ * cannot know which slot it renders under. The route params are usable
310
+ * only when every slot's merged view canonicalizes identically to them;
311
+ * otherwise two renders with the same key could see different effective
312
+ * inputs and a hit could serve the WRONG cached subtree — so the render
313
+ * goes live: slower, never wrong. (Build-time capture doesn't model slot
314
+ * params either, so a divergent request could never have a faithful
315
+ * entry. Codex review on PR #835; revisit with segment-path-scoped keys
316
+ * if slot-scoped prebuilt is ever needed.)
317
+ *
318
+ * Comparison happens through `tryCanonicalize` — the same single
319
+ * definition of value equality the cache key uses — so anything it
320
+ * cannot represent faithfully (bigint-coerced codec params, accessors,
321
+ * aliases, …) is unkeyable here too, and this guard can never throw.
322
+ */
323
+ export function resolveKeyParams(store: {
324
+ segmentParams?: CoercedParams;
325
+ slotParams?: SlotParamsRecord;
326
+ }): CoercedParams | null {
327
+ const main = store.segmentParams ?? {};
328
+ const slots = store.slotParams;
329
+ if (!slots || Object.keys(slots).length === 0) return main;
330
+ // Spread before canonicalizing: param records are framework-produced
331
+ // Object.create(null) objects (prototype-pollution defense) — normalize
332
+ // the records themselves, let nested values face the full allowlist.
333
+ const mainCanonical = tryCanonicalize({ ...main });
334
+ if (mainCanonical === null) return null;
335
+ for (const slotParams of Object.values(slots)) {
336
+ const merged = tryCanonicalize({ ...main, ...slotParams });
337
+ if (merged === null || merged !== mainCanonical) return null;
338
+ }
339
+ return main;
340
+ }