@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.2

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 (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
@@ -194,7 +194,7 @@ class PollingSyncNotifier {
194
194
  }
195
195
  }
196
196
 
197
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
197
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
198
198
  function elapsedMs(startTime) {
199
199
  return Math.max(0, Date.now() - startTime);
200
200
  }
@@ -335,7 +335,7 @@ var init_utils = __esm(() => {
335
335
  _isoDate = /* @__PURE__ */ new Date;
336
336
  });
337
337
 
338
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
338
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
339
339
  function normalizeRedactPathPattern(pattern) {
340
340
  if (!pattern.includes("*") && !pattern.includes("."))
341
341
  return `**.${pattern}`;
@@ -644,7 +644,7 @@ var init_redact_C7FmdhwI = __esm(() => {
644
644
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
645
645
  });
646
646
 
647
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
647
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
648
648
  function logPluginError(name, hook, err) {
649
649
  console.error(`[evlog/${name}] ${hook} failed:`, err);
650
650
  }
@@ -814,7 +814,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
814
814
  globalConfig = getRegistry().config;
815
815
  });
816
816
 
817
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
817
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
818
818
  function pushTreeSpacer(children) {
819
819
  children.push(PRETTY_ERROR_TREE_SPACER);
820
820
  }
@@ -1115,7 +1115,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
1115
1115
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
1116
1116
  });
1117
1117
 
1118
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1118
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1119
1119
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
1120
1120
  const compact = partial.compact ?? (inDev && pretty);
1121
1121
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -1168,7 +1168,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
1168
1168
  };
1169
1169
  });
1170
1170
 
1171
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1171
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1172
1172
  function hasWideEventPublisher() {
1173
1173
  return publisher !== null;
1174
1174
  }
@@ -1184,7 +1184,7 @@ function publishWideEvent(event) {
1184
1184
  var publisher = null;
1185
1185
  var init_wideEventChannel_BUDW48oP = () => {};
1186
1186
 
1187
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1187
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
1188
1188
  function isEvlogError(error) {
1189
1189
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
1190
1190
  }
@@ -1193,7 +1193,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
1193
1193
  evlogErrorBrand = Symbol.for("evlog.error.brand");
1194
1194
  });
1195
1195
 
1196
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
1196
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
1197
1197
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
1198
1198
  var init_error = __esm(() => {
1199
1199
  init_utils();
@@ -1302,7 +1302,7 @@ var init_error = __esm(() => {
1302
1302
  });
1303
1303
  });
1304
1304
 
1305
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1305
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
1306
1306
  function extractSafeHeaders(headers) {
1307
1307
  const raw = {};
1308
1308
  headers.forEach((value, key) => {
@@ -1323,7 +1323,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
1323
1323
  init_utils();
1324
1324
  });
1325
1325
 
1326
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
1326
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
1327
1327
  function writePrettyStdout(text) {
1328
1328
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
1329
1329
  }
@@ -2245,12 +2245,12 @@ var init_audit_C8euLMvu = __esm(() => {
2245
2245
  initLogger(__EVLOG_CONFIG__);
2246
2246
  });
2247
2247
 
2248
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
2248
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
2249
2249
  var init_dist = __esm(() => {
2250
2250
  init_audit_C8euLMvu();
2251
2251
  });
2252
2252
 
2253
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2253
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
2254
2254
  function shouldDeferEmitForResponse(response) {
2255
2255
  if (!response.body)
2256
2256
  return false;
@@ -2330,7 +2330,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
2330
2330
  }
2331
2331
  var init_streamResponse_OlirMA5P = () => {};
2332
2332
 
2333
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2333
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
2334
2334
  function extractErrorStatus(error) {
2335
2335
  if (error === null || typeof error !== "object")
2336
2336
  return 500;
@@ -2340,7 +2340,7 @@ function extractErrorStatus(error) {
2340
2340
  }
2341
2341
  var init_errors_CL8dDgIi = () => {};
2342
2342
 
2343
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2343
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
2344
2344
  function shouldLog(path, include, exclude) {
2345
2345
  if (exclude && exclude.length > 0) {
2346
2346
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -2368,7 +2368,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
2368
2368
  init_utils();
2369
2369
  });
2370
2370
 
2371
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2371
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
2372
2372
  function resolveMiddlewarePluginRunner(options) {
2373
2373
  const global = getGlobalPluginRunner();
2374
2374
  const local = options.plugins;
@@ -2563,7 +2563,7 @@ var init_middleware_fam3VyaL = __esm(() => {
2563
2563
  runnerCache = /* @__PURE__ */ new WeakMap;
2564
2564
  });
2565
2565
 
2566
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
2566
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
2567
2567
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2568
2568
  const log = parent;
2569
2569
  log.fork = (label, fn) => {
@@ -2666,7 +2666,7 @@ var init_integration_CGD18W8r = __esm(() => {
2666
2666
  init_middleware_fam3VyaL();
2667
2667
  });
2668
2668
 
2669
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
2669
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
2670
2670
  import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
2671
2671
  function createLoggerStorage(contextHint, id = contextHint) {
2672
2672
  const storage = getSharedStorage(id, () => new AsyncLocalStorage4);
@@ -2685,7 +2685,7 @@ var init_storage = __esm(() => {
2685
2685
  init_globalRegistry_Bh3bIGwA();
2686
2686
  });
2687
2687
 
2688
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
2688
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
2689
2689
  var init_toolkit = __esm(() => {
2690
2690
  init_integration_CGD18W8r();
2691
2691
  init_storage();
@@ -2791,33 +2791,26 @@ function parseChangeQuery(request) {
2791
2791
  }
2792
2792
  return { after, limit };
2793
2793
  }
2794
- function clientInvalidations(change) {
2795
- const entries = new Set;
2796
- for (const invalidation of change.invalidations) {
2797
- if (invalidation.kind === "tags") {
2798
- entries.add("/:layout");
2799
- } else {
2800
- entries.add(invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path);
2801
- }
2802
- }
2803
- return [...entries];
2804
- }
2805
2794
  function createSyncChangesPlugin(options) {
2806
2795
  const syncPath = options.path ?? defaultSyncPath;
2807
2796
  const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
2808
- return new Elysia2({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async ({ request, set }) => {
2797
+ return new Elysia2({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
2798
+ const { request, set } = context;
2809
2799
  set.headers["cache-control"] = "no-store";
2810
2800
  const query = parseChangeQuery(request);
2811
2801
  if ("error" in query) {
2812
2802
  return query.error;
2813
2803
  }
2814
- const page = await runtime.adapter.readChanges(query);
2804
+ const principal = await options.principal(context);
2805
+ if (principal.length === 0) {
2806
+ return new Response("Unauthorized", { status: 401 });
2807
+ }
2808
+ const cursor = await runtime.adapter.currentCursor();
2815
2809
  return {
2816
- ...page,
2817
- changes: page.changes.map((change) => ({
2818
- cursor: change.cursor,
2819
- invalidations: clientInvalidations(change)
2820
- }))
2810
+ changes: [],
2811
+ cursor,
2812
+ hasMore: false,
2813
+ reset: query.after !== undefined && query.after !== cursor
2821
2814
  };
2822
2815
  });
2823
2816
  }
@@ -2836,7 +2829,41 @@ var init_stream = __esm(() => {
2836
2829
  init_config();
2837
2830
 
2838
2831
  // src/server/sync/plugin.ts
2839
- import { Elysia as Elysia3 } from "elysia";
2832
+ import { Elysia as Elysia3, ElysiaStatus as ElysiaStatus3 } from "elysia";
2833
+
2834
+ // src/shared/sync-query.ts
2835
+ function serializeQueryHeader(identity) {
2836
+ return JSON.stringify(identity).replace(/[^\u0020-\u007e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
2837
+ }
2838
+ var PREFIX = "__furin.query:";
2839
+ function queryTag(identity) {
2840
+ for (const [key, value] of Object.entries(identity.scope)) {
2841
+ if (value === undefined) {
2842
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
2843
+ }
2844
+ }
2845
+ return PREFIX + JSON.stringify([
2846
+ identity.id,
2847
+ Object.entries(identity.scope).sort(([a], [b]) => {
2848
+ if (a === b) {
2849
+ return 0;
2850
+ }
2851
+ return a < b ? -1 : 1;
2852
+ })
2853
+ ]);
2854
+ }
2855
+ function queryFromTag(tag) {
2856
+ if (!tag.startsWith(PREFIX)) {
2857
+ return;
2858
+ }
2859
+ try {
2860
+ const value = JSON.parse(tag.slice(PREFIX.length));
2861
+ if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !Array.isArray(value[1]) || value[1].some((entry) => !Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !(entry[1] === null || typeof entry[1] === "string" || typeof entry[1] === "number" || typeof entry[1] === "boolean"))) {
2862
+ return;
2863
+ }
2864
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
2865
+ } catch {}
2866
+ }
2840
2867
 
2841
2868
  // src/shared/prefix.ts
2842
2869
  function physicalPath(prefix, path) {
@@ -2940,6 +2967,9 @@ class AutoInvalidateRegistry {
2940
2967
  }
2941
2968
  return [...paths];
2942
2969
  }
2970
+ tagsForPath(path) {
2971
+ return [...this.pathToTags.get(path) ?? []];
2972
+ }
2943
2973
  unregisterPath(urlPath, owner) {
2944
2974
  if (owner === undefined) {
2945
2975
  this.pathOwners.delete(urlPath);
@@ -3211,6 +3241,7 @@ async function invalidateTagsForInstance(instance, tagList) {
3211
3241
  let deleted = false;
3212
3242
  const purgedPaths = new Set;
3213
3243
  const logicalPurgedPaths = new Set;
3244
+ const sharedInvalidations = [];
3214
3245
  const pageCache = getPageCacheAdapter(instance);
3215
3246
  const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
3216
3247
  kind: "tags",
@@ -3224,9 +3255,19 @@ async function invalidateTagsForInstance(instance, tagList) {
3224
3255
  ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
3225
3256
  ...sharedResult?.paths ?? []
3226
3257
  ]);
3258
+ const tags = new Set(tagList);
3227
3259
  for (const path of taggedPaths) {
3228
3260
  const logicalPath = pathWithoutSearch(path);
3261
+ const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
3229
3262
  const result = revalidatePathForInstance(instance, logicalPath, "page", false);
3263
+ if (pageCache !== undefined && registered) {
3264
+ sharedInvalidations.push(pageCache.invalidate({
3265
+ kind: "path",
3266
+ scope: instance.prefix,
3267
+ path: logicalPath,
3268
+ type: "page"
3269
+ }));
3270
+ }
3230
3271
  deleted = result.deleted || deleted;
3231
3272
  purgedPaths.add(physicalPath(instance.prefix, logicalPath));
3232
3273
  logicalPurgedPaths.add(logicalPath);
@@ -3235,6 +3276,8 @@ async function invalidateTagsForInstance(instance, tagList) {
3235
3276
  logicalPurgedPaths.add(purged);
3236
3277
  }
3237
3278
  }
3279
+ const pathResults = await Promise.all(sharedInvalidations);
3280
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
3238
3281
  if (IS_DEV) {
3239
3282
  withInstance(instance, () => {
3240
3283
  const request = currentInstrumentationRequest();
@@ -3284,38 +3327,38 @@ async function runInvalidationRules(input) {
3284
3327
  // src/server/sync/plugin.ts
3285
3328
  init_context_logger();
3286
3329
 
3287
- // src/server/sync/fingerprint.ts
3288
- function compareCodePoints(left, right) {
3289
- if (left === right) {
3290
- return 0;
3330
+ // src/server/sync/atomic.ts
3331
+ import { ElysiaStatus as ElysiaStatus2, StatusMap as StatusMap2, Validator } from "elysia";
3332
+ init_context_logger();
3333
+
3334
+ // src/server/sync/queries.ts
3335
+ function resolveSyncInvalidations(input, context, value) {
3336
+ if (input === undefined) {
3337
+ return;
3291
3338
  }
3292
- return left < right ? -1 : 1;
3339
+ const selected = typeof input === "function" ? input(Object.assign(Object.create(Object.getPrototypeOf(context)), context, {
3340
+ responseValue: value
3341
+ })) : input;
3342
+ const rules = Array.isArray(selected) ? selected : [selected];
3343
+ return rules.map((rule) => ("id" in rule) ? { tags: [queryTag(rule)] } : rule);
3293
3344
  }
3294
- function canonicalize(value) {
3295
- if (Array.isArray(value)) {
3296
- return value.map(canonicalize);
3345
+ function appendQueryInvalidations(input, context) {
3346
+ if (input === undefined) {
3347
+ return;
3297
3348
  }
3298
- if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
3299
- return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
3349
+ const queries = [];
3350
+ for (const rule of Array.isArray(input) ? input : [input]) {
3351
+ for (const tag of rule.tags ?? []) {
3352
+ const identity = queryFromTag(tag);
3353
+ if (identity) {
3354
+ queries.push(identity);
3355
+ }
3356
+ }
3357
+ }
3358
+ if (queries.length > 0) {
3359
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
3360
+ context.set.headers["x-furin-sync"] = "1";
3300
3361
  }
3301
- return value;
3302
- }
3303
- function sha256Hex(source) {
3304
- const hasher = new Bun.CryptoHasher("sha256");
3305
- hasher.update(source);
3306
- return hasher.digest("hex");
3307
- }
3308
- function createMutationFingerprint(input) {
3309
- const url = new URL(input.request.url);
3310
- const query = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => leftKey === rightKey ? compareCodePoints(leftValue, rightValue) : compareCodePoints(leftKey, rightKey));
3311
- const source = JSON.stringify({
3312
- body: canonicalize(input.body) ?? null,
3313
- contentType: input.request.headers.get("content-type") ?? "",
3314
- method: input.request.method,
3315
- pathname: url.pathname,
3316
- query
3317
- });
3318
- return sha256Hex(source);
3319
3362
  }
3320
3363
 
3321
3364
  // src/server/sync/response.ts
@@ -3456,6 +3499,15 @@ async function storeResponse(responseValue, set) {
3456
3499
  const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
3457
3500
  return storedResponseResult(headers, body, clone.status);
3458
3501
  }
3502
+ return storeResponseSync(responseValue, set);
3503
+ }
3504
+ function storeResponseSync(responseValue, set) {
3505
+ if (responseValue instanceof Response) {
3506
+ if (responseValue.body !== null) {
3507
+ return unreplayable();
3508
+ }
3509
+ return storedResponseResult(new Headers([...responseValue.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))), new Uint8Array, responseValue.status);
3510
+ }
3459
3511
  const headers = responseHeaders(set.headers);
3460
3512
  const statusResponse = unwrapStatusResponse(responseValue);
3461
3513
  const value = statusResponse?.value ?? responseValue;
@@ -3486,34 +3538,166 @@ function replayResponse(stored) {
3486
3538
  });
3487
3539
  }
3488
3540
 
3489
- // src/server/sync/plugin.ts
3490
- init_runtime();
3491
- var routeMetadata = new WeakMap;
3492
- var activeMutations = new WeakMap;
3493
- function hideTransportResponse(hook) {
3494
- return hook;
3541
+ // src/server/sync/atomic.ts
3542
+ var TRAILING_SLASH_PATTERN = /\/$/;
3543
+
3544
+ class RejectedMutation {
3545
+ value;
3546
+ constructor(value) {
3547
+ this.value = value;
3548
+ }
3495
3549
  }
3496
- function invalidationInputFromSync(input) {
3497
- if (input && typeof input === "object" && "invalidate" in input) {
3498
- return input.invalidate;
3550
+ function responseStatus(context, value) {
3551
+ if (value instanceof Response && value.status !== 200) {
3552
+ return value.status;
3499
3553
  }
3500
- return input;
3554
+ if (value instanceof ElysiaStatus2) {
3555
+ return value.status;
3556
+ }
3557
+ if (typeof context.set.status === "string") {
3558
+ return StatusMap2[context.set.status];
3559
+ }
3560
+ return context.set.status ?? 200;
3501
3561
  }
3502
- function isMutationMethod(method) {
3503
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
3562
+ function withStatus(original, value) {
3563
+ return original instanceof ElysiaStatus2 ? new ElysiaStatus2(original.status, value, original.headers) : value;
3504
3564
  }
3505
- function getIdempotencyKey(ctx) {
3506
- const fromCtxHeaders = ctx.headers["idempotency-key"];
3507
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
3508
- return fromCtxHeaders;
3565
+ function validateResult(execution, value) {
3566
+ if (value instanceof Error) {
3567
+ throw value;
3509
3568
  }
3510
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
3511
- return fromRequest || undefined;
3569
+ if (value instanceof Response) {
3570
+ return value;
3571
+ }
3572
+ const { app, context, adapter } = execution;
3573
+ const registeredPath = context.route ?? context.path;
3574
+ const strictPath = app["~config"]?.strictPath === true;
3575
+ const [match] = app.routes.toReversed().filter((entry) => entry.method === context.request.method || entry.method === "*").map((candidate) => {
3576
+ const paths = [candidate.path, encodeURI(candidate.path)];
3577
+ const exact = paths.includes(registeredPath);
3578
+ const loose = !strictPath && paths.some((path) => path.replace(TRAILING_SLASH_PATTERN, "") === registeredPath.replace(TRAILING_SLASH_PATTERN, ""));
3579
+ return { route: candidate, priority: exact ? 2 : Number(loose) };
3580
+ }).filter((entry) => entry.priority > 0).sort((left, right) => Number(right.route.method === context.request.method) - Number(left.route.method === context.request.method) || right.priority - left.priority);
3581
+ if (!match) {
3582
+ throw new Error("[furin] Could not resolve the effective mutation route for response validation.");
3583
+ }
3584
+ const { route } = match;
3585
+ const validators = Validator.response(route?.hooks.response, {
3586
+ models: app["~ext"]?.models,
3587
+ normalize: app["~config"]?.normalize,
3588
+ sanitize: app["~config"]?.sanitize,
3589
+ schemas: route?.hooks.schemas?.flatMap((schema) => schema.response ? [schema.response] : [])
3590
+ });
3591
+ const validator = validators?.[responseStatus(context, value)];
3592
+ if (!validator) {
3593
+ return value;
3594
+ }
3595
+ const body = value instanceof ElysiaStatus2 ? value.response : value;
3596
+ const encoder = validator;
3597
+ const encoded = validator.mayReturnPromise ? validator.From?.(body, "response", adapter.transactionMode !== "sync") : encoder.EncodeFrom?.(body, "response");
3598
+ if (!(encoded instanceof Promise)) {
3599
+ return withStatus(value, encoded);
3600
+ }
3601
+ if (adapter.transactionMode === "sync") {
3602
+ throw new Error("[furin] Bun SQLite mutations require synchronous response validation.");
3603
+ }
3604
+ return encoded.then((result) => withStatus(value, result));
3605
+ }
3606
+ function prepare(execution, value, original) {
3607
+ const { context } = execution;
3608
+ const status = responseStatus(context, value);
3609
+ if (status < 200 || status >= 400) {
3610
+ throw new RejectedMutation(original);
3611
+ }
3612
+ const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
3613
+ execution.resolvedInvalidate = invalidate;
3614
+ appendQueryInvalidations(invalidate, context);
3615
+ const invalidations = [
3616
+ ...normalizedInvalidations(invalidate),
3617
+ ...pendingPathInvalidations(peekPendingInvalidations())
3618
+ ];
3619
+ if (invalidations.length > 0) {
3620
+ context.set.headers["x-furin-sync"] = "1";
3621
+ }
3622
+ const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => entry.type === "layout" ? `${entry.path}:layout` : entry.path);
3623
+ if (paths.length > 0) {
3624
+ context.set.headers["x-furin-revalidate"] = paths.join(",");
3625
+ }
3626
+ const finish = (stored) => {
3627
+ if (stored.kind === "unreplayable") {
3628
+ throw new Error("[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses.");
3629
+ }
3630
+ let { headers } = context.set;
3631
+ if (value instanceof ElysiaStatus2) {
3632
+ headers = { ...headers, ...value.headers };
3633
+ } else if (value instanceof Response) {
3634
+ headers = { ...headers, ...Object.fromEntries(value.headers) };
3635
+ }
3636
+ return {
3637
+ invalidations,
3638
+ response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
3639
+ value: original
3640
+ };
3641
+ };
3642
+ return execution.adapter.transactionMode === "sync" ? finish(storeResponseSync(value, context.set)) : storeResponse(value, context.set).then(finish);
3512
3643
  }
3513
- function supportsReplayBody(request) {
3514
- const contentType = request.headers.get("content-type")?.toLowerCase();
3515
- const mediaType = contentType?.split(";", 1)[0]?.trim();
3516
- return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
3644
+ function assertSynchronous(mode, value) {
3645
+ if (mode === "sync" && (value instanceof Promise || Object.prototype.toString.call(value) === "[object AsyncFunction]")) {
3646
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
3647
+ }
3648
+ }
3649
+ function invoke(execution, callback, tx) {
3650
+ assertSynchronous(execution.adapter.transactionMode, callback);
3651
+ const value = callback(tx);
3652
+ assertSynchronous(execution.adapter.transactionMode, value);
3653
+ if (value instanceof Promise) {
3654
+ return value.then(async (original) => prepare(execution, await validateResult(execution, original), original));
3655
+ }
3656
+ const encoded = validateResult(execution, value);
3657
+ return encoded instanceof Promise ? encoded.then((result) => prepare(execution, result, value)) : prepare(execution, encoded, value);
3658
+ }
3659
+ async function afterCommit(execution, result) {
3660
+ execution.onCommit(result);
3661
+ if (execution.resolvedInvalidate) {
3662
+ await runInvalidationRules(execution.resolvedInvalidate).catch(() => getLogger().warn("Sync cache invalidation failed after mutation; preserving the idempotent result"));
3663
+ appendPendingInvalidationHeader(execution.context.set);
3664
+ }
3665
+ const { notifier } = execution.runtime;
3666
+ if (result.cursor !== undefined) {
3667
+ notifier.publish(result.cursor).catch(() => {
3668
+ return;
3669
+ });
3670
+ }
3671
+ }
3672
+ async function executeAtomicMutation(execution, callback) {
3673
+ const { context } = execution;
3674
+ const previousSyncHeader = context.set.headers["x-furin-sync"];
3675
+ const previousPathHeader = context.set.headers["x-furin-revalidate"];
3676
+ const previousQueryHeader = context.set.headers["x-furin-queries"];
3677
+ let committed = false;
3678
+ try {
3679
+ const result = await execution.adapter.executeMutation(execution.lease, (tx) => invoke(execution, callback, tx));
3680
+ committed = true;
3681
+ await afterCommit(execution, result);
3682
+ return result.value;
3683
+ } catch (error) {
3684
+ if (!committed) {
3685
+ restoreHeader(context, "x-furin-sync", previousSyncHeader);
3686
+ restoreHeader(context, "x-furin-revalidate", previousPathHeader);
3687
+ restoreHeader(context, "x-furin-queries", previousQueryHeader);
3688
+ }
3689
+ if (error instanceof RejectedMutation) {
3690
+ return error.value;
3691
+ }
3692
+ throw error;
3693
+ }
3694
+ }
3695
+ function restoreHeader(context, key, value) {
3696
+ if (value === undefined) {
3697
+ delete context.set.headers[key];
3698
+ } else {
3699
+ context.set.headers[key] = value;
3700
+ }
3517
3701
  }
3518
3702
  function conflictResponse(reason) {
3519
3703
  const inProgress = reason === "in-progress";
@@ -3525,12 +3709,6 @@ function conflictResponse(reason) {
3525
3709
  status: 409
3526
3710
  });
3527
3711
  }
3528
- function leaseLostResponse() {
3529
- return Response.json({
3530
- code: "FURIN_SYNC_LEASE_LOST",
3531
- message: "The mutation lease was lost before its response could be committed."
3532
- }, { status: 503 });
3533
- }
3534
3712
  function normalizedInvalidations(input) {
3535
3713
  if (!input) {
3536
3714
  return [];
@@ -3550,8 +3728,201 @@ function normalizedInvalidations(input) {
3550
3728
  function pendingPathInvalidations(entries) {
3551
3729
  return entries.map((entry) => entry.endsWith(":layout") ? { kind: "path", path: entry.slice(0, -":layout".length), type: "layout" } : { kind: "path", path: entry, type: "page" });
3552
3730
  }
3553
- function furinSync(options) {
3731
+
3732
+ // src/server/sync/execution-error.ts
3733
+ class MutationLeaseLost extends Error {
3734
+ }
3735
+
3736
+ // src/server/sync/fingerprint.ts
3737
+ function compareCodePoints(left, right) {
3738
+ if (left === right) {
3739
+ return 0;
3740
+ }
3741
+ return left < right ? -1 : 1;
3742
+ }
3743
+ function canonicalize(value) {
3744
+ if (Array.isArray(value)) {
3745
+ return value.map(canonicalize);
3746
+ }
3747
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
3748
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
3749
+ }
3750
+ return value;
3751
+ }
3752
+ function sha256Hex(source) {
3753
+ const hasher = new Bun.CryptoHasher("sha256");
3754
+ hasher.update(source);
3755
+ return hasher.digest("hex");
3756
+ }
3757
+ function createMutationFingerprint(input) {
3758
+ const url = new URL(input.request.url);
3759
+ url.searchParams.sort();
3760
+ const query = [...url.searchParams.entries()];
3761
+ const source = JSON.stringify({
3762
+ body: canonicalize(input.body) ?? null,
3763
+ contentType: input.request.headers.get("content-type") ?? "",
3764
+ method: input.request.method,
3765
+ pathname: url.pathname,
3766
+ query
3767
+ });
3768
+ return sha256Hex(source);
3769
+ }
3770
+
3771
+ // src/server/sync/mutation-handler.ts
3772
+ import { createContext } from "elysia/context";
3773
+ var mutationBeginnings = new WeakMap;
3774
+ var installedApplications = new WeakSet;
3775
+ var installedContexts = new WeakSet;
3776
+ function prepareMutationHandler(context, begin) {
3777
+ if (!installedContexts.has(context.constructor)) {
3778
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation routes.");
3779
+ }
3780
+ mutationBeginnings.set(context.request, begin);
3781
+ }
3782
+ function installMutationHandlers(app) {
3783
+ if (installedApplications.has(app)) {
3784
+ return;
3785
+ }
3786
+ installedApplications.add(app);
3787
+ app.decorate("_furinMutationHandlers", true);
3788
+ app.wrap((fetch) => {
3789
+ installedContexts.add(createContext(app));
3790
+ return fetch;
3791
+ });
3792
+ const compileHandler = app.handler.bind(app);
3793
+ app.handler = (index, immediate, route, aliases, table) => {
3794
+ const nativeRoute = route ?? (table ? [
3795
+ table.method[index],
3796
+ table.path[index],
3797
+ table.handler[index],
3798
+ table.owner[index],
3799
+ table.localHook[index],
3800
+ table.appHook[index],
3801
+ table.inheritedChain[index],
3802
+ table.macroScope?.get(index)
3803
+ ] : app["~routes"][index]);
3804
+ if (!nativeRoute || ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0])) {
3805
+ return compileHandler(index, immediate, route, aliases, table);
3806
+ }
3807
+ const [method, path, handle, owner, hooks, chain, inherited, macroScope] = nativeRoute;
3808
+ const wrapped = async (context) => {
3809
+ const begin = mutationBeginnings.get(context.request);
3810
+ mutationBeginnings.delete(context.request);
3811
+ const response = await begin?.();
3812
+ if (response !== undefined) {
3813
+ return response;
3814
+ }
3815
+ return typeof handle === "function" ? handle(context) : handle;
3816
+ };
3817
+ return compileHandler(index, immediate, [method, path, wrapped, owner, hooks, chain, inherited, macroScope], aliases, table);
3818
+ };
3819
+ }
3820
+
3821
+ // src/server/sync/plugin.ts
3822
+ init_runtime();
3823
+
3824
+ // src/server/sync/validation.ts
3825
+ import { createContext as createContext2 } from "elysia/context";
3826
+ var applications = new WeakMap;
3827
+ var boundApplications = new WeakSet;
3828
+ function bindSyncValidation(app) {
3829
+ installMutationHandlers(app);
3830
+ if (boundApplications.has(app)) {
3831
+ return;
3832
+ }
3833
+ boundApplications.add(app);
3834
+ app.decorate("_furinSyncValidation", true);
3835
+ app.wrap((fetch) => {
3836
+ applications.set(createContext2(app), app);
3837
+ return fetch;
3838
+ });
3839
+ app.setup((root) => {
3840
+ applications.set(createContext2(root), root);
3841
+ });
3842
+ }
3843
+ function syncValidationApp(context) {
3844
+ const app = applications.get(context.constructor);
3845
+ if (!app) {
3846
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation().");
3847
+ }
3848
+ return app;
3849
+ }
3850
+
3851
+ // src/server/sync/plugin.ts
3852
+ var routeMetadata = new WeakMap;
3853
+ var activeMutations = new WeakMap;
3854
+ var atomicCalls = new WeakSet;
3855
+ var atomicResponses = new WeakMap;
3856
+ function hideTransportResponse(hook) {
3857
+ return hook;
3858
+ }
3859
+ function invalidationInputFromSync(input) {
3860
+ if (input && typeof input === "object" && "invalidate" in input) {
3861
+ return input.invalidate;
3862
+ }
3863
+ if ("id" in input) {
3864
+ return;
3865
+ }
3866
+ return input;
3867
+ }
3868
+ function isMutationMethod(method) {
3869
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
3870
+ }
3871
+ function getIdempotencyKey(ctx) {
3872
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
3873
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
3874
+ return fromCtxHeaders;
3875
+ }
3876
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
3877
+ return fromRequest || undefined;
3878
+ }
3879
+ function supportsReplayBody(request) {
3880
+ const contentType = request.headers.get("content-type")?.toLowerCase();
3881
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
3882
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
3883
+ }
3884
+ function leaseLostResponse() {
3885
+ return Response.json({
3886
+ code: "FURIN_SYNC_LEASE_LOST",
3887
+ message: "The mutation lease was lost before its response could be committed."
3888
+ }, { status: 503 });
3889
+ }
3890
+ function createSyncPlugin(options) {
3554
3891
  const runtime = resolveSyncRuntime(options);
3892
+ const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
3893
+ function mutationFor(ctx) {
3894
+ const mutation = async (callback) => {
3895
+ const active = activeMutations.get(ctx.request);
3896
+ if (!(transactional && active)) {
3897
+ throw new Error("[furin] mutation() requires a transactional sync adapter and an enabled mutation route.");
3898
+ }
3899
+ if (atomicCalls.has(ctx.request)) {
3900
+ throw new Error("[furin] Call mutation() once and return its result from the handler.");
3901
+ }
3902
+ atomicCalls.add(ctx.request);
3903
+ try {
3904
+ return await executeAtomicMutation({
3905
+ adapter: transactional,
3906
+ app: syncValidationApp(ctx),
3907
+ context: ctx,
3908
+ lease: active.lease,
3909
+ invalidate: routeMetadata.get(ctx.request)?.invalidate,
3910
+ runtime,
3911
+ onCommit: (result) => atomicResponses.set(ctx.request, result)
3912
+ }, callback);
3913
+ } finally {
3914
+ if (atomicResponses.has(ctx.request)) {
3915
+ releaseMutation(ctx.request);
3916
+ } else {
3917
+ await abortMutation(ctx.request).catch(() => {
3918
+ return;
3919
+ });
3920
+ }
3921
+ atomicCalls.delete(ctx.request);
3922
+ }
3923
+ };
3924
+ return mutation;
3925
+ }
3555
3926
  async function beginMutation(ctx) {
3556
3927
  if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
3557
3928
  return;
@@ -3599,21 +3970,25 @@ function furinSync(options) {
3599
3970
  activeMutations.set(ctx.request, active);
3600
3971
  scheduleRenewal();
3601
3972
  }
3602
- async function abortMutation(request) {
3973
+ function releaseMutation(request) {
3603
3974
  const active = activeMutations.get(request);
3604
- if (!active) {
3605
- return;
3606
- }
3607
3975
  activeMutations.delete(request);
3608
- if (active.renewal) {
3976
+ if (active?.renewal) {
3609
3977
  clearTimeout(active.renewal);
3610
3978
  }
3611
- await runtime.adapter.abortMutation(active.lease);
3979
+ return active;
3980
+ }
3981
+ async function abortMutation(request) {
3982
+ const active = releaseMutation(request);
3983
+ if (active) {
3984
+ await runtime.adapter.abortMutation(active.lease);
3985
+ }
3612
3986
  }
3613
3987
  async function persistMutation(ctx, active) {
3614
3988
  const result = await storeResponse(ctx.responseValue, ctx.set);
3615
3989
  const manualPending = peekPendingInvalidations();
3616
- const invalidate = routeMetadata.get(ctx.request)?.invalidate;
3990
+ const invalidate = resolveSyncInvalidations(routeMetadata.get(ctx.request)?.invalidate, ctx, ctx.responseValue);
3991
+ appendQueryInvalidations(invalidate, ctx);
3617
3992
  const logger = getLogger();
3618
3993
  if (invalidate) {
3619
3994
  try {
@@ -3643,7 +4018,7 @@ function furinSync(options) {
3643
4018
  if (completion.kind === "lost") {
3644
4019
  return leaseLostResponse();
3645
4020
  }
3646
- const notificationAlreadyPublished = runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
4021
+ const notificationAlreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
3647
4022
  if (completion.cursor !== undefined && !notificationAlreadyPublished) {
3648
4023
  runtime.notifier.publish(completion.cursor).catch(() => {
3649
4024
  return;
@@ -3654,6 +4029,19 @@ function furinSync(options) {
3654
4029
  }
3655
4030
  }
3656
4031
  async function finishMutation(ctx) {
4032
+ const atomic = atomicResponses.get(ctx.request);
4033
+ atomicResponses.delete(ctx.request);
4034
+ atomicCalls.delete(ctx.request);
4035
+ if (atomic && ctx.responseValue === atomic.value) {
4036
+ if (atomic.value instanceof Response) {
4037
+ return atomic.value;
4038
+ }
4039
+ if (atomic.value instanceof ElysiaStatus3) {
4040
+ ctx.set.status = atomic.value.status;
4041
+ Object.assign(ctx.set.headers, atomic.value.headers);
4042
+ }
4043
+ return replayResponse(atomic.response);
4044
+ }
3657
4045
  const active = activeMutations.get(ctx.request);
3658
4046
  if (!active) {
3659
4047
  return;
@@ -3676,17 +4064,57 @@ function furinSync(options) {
3676
4064
  }
3677
4065
  }
3678
4066
  }
3679
- const beginMutationHook = hideTransportResponse(beginMutation);
3680
4067
  const finishMutationHook = hideTransportResponse(finishMutation);
3681
- return new Elysia3({ name: "furin-sync" }).beforeHandle("global", beginMutationHook).afterHandle("global", finishMutationHook).error("global", ({ request }) => abortMutation(request)).macro({
4068
+ const plugin = new Elysia3({ name: "furin-sync" }).derive("global", (ctx) => ({ mutation: mutationFor(ctx) })).beforeHandle("global", (context) => {
4069
+ if (isMutationMethod(context.request.method) && !routeMetadata.get(context.request)?.disabled) {
4070
+ prepareMutationHandler(context, () => beginMutation(context));
4071
+ }
4072
+ }).afterHandle("global", finishMutationHook).afterHandle("global", async (ctx) => {
4073
+ const read = routeMetadata.get(ctx.request)?.read;
4074
+ if (ctx.request.method !== "GET" || !read || !isSuccessfulMutationResponse({
4075
+ set: ctx.set,
4076
+ responseValue: ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
4077
+ })) {
4078
+ return;
4079
+ }
4080
+ const principal = await options.principal(ctx);
4081
+ if (principal.length === 0) {
4082
+ throw new Error("[furin] Sync principal must not be empty.");
4083
+ }
4084
+ const identity = {
4085
+ id: read.id,
4086
+ scope: typeof read.scope === "function" ? read.scope(ctx) : read.scope ?? {},
4087
+ session: new Bun.CryptoHasher("sha256").update(principal).digest("hex")
4088
+ };
4089
+ queryTag(identity);
4090
+ ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
4091
+ }).error("global", MutationLeaseLost, hideTransportResponse(() => Promise.resolve(leaseLostResponse()))).error("global", hideTransportResponse(async ({ request }) => {
4092
+ atomicResponses.delete(request);
4093
+ atomicCalls.delete(request);
4094
+ await abortMutation(request);
4095
+ })).macro({
3682
4096
  sync(input) {
3683
4097
  return {
3684
4098
  transform({ request }) {
3685
- routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
4099
+ routeMetadata.set(request, input === false ? { disabled: true } : {
4100
+ disabled: false,
4101
+ invalidate: invalidationInputFromSync(input),
4102
+ read: "id" in input ? input : undefined
4103
+ });
3686
4104
  }
3687
4105
  };
3688
4106
  }
3689
4107
  });
4108
+ return plugin;
4109
+ }
4110
+ function furinSync(options) {
4111
+ return (app) => {
4112
+ installMutationHandlers(app);
4113
+ if ("executeMutation" in options.adapter) {
4114
+ bindSyncValidation(app);
4115
+ }
4116
+ return app.use(createSyncPlugin(options));
4117
+ };
3690
4118
  }
3691
4119
 
3692
4120
  // src/server/sync/index.ts