@teyik0/furin 0.2.0-alpha.5 → 0.3.0-alpha.1

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 (238) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/static.d.ts +1 -1
  3. package/dist/build/bun-build.d.ts +3 -0
  4. package/dist/build/entry-template.d.ts +2 -0
  5. package/dist/build/entry-template.ts +3 -0
  6. package/dist/build/hydrate.d.ts +1 -1
  7. package/dist/build/index.js +6944 -5067
  8. package/dist/build/production-instrumentation.d.ts +1 -0
  9. package/dist/build/route-types.d.ts +1 -1
  10. package/dist/build/types.d.ts +1 -0
  11. package/dist/cli/index.js +7874 -5971
  12. package/dist/client/boundaries.d.ts +4 -4
  13. package/dist/client/internal/runtime-types.d.ts +30 -0
  14. package/dist/client/link.d.ts +2 -1
  15. package/dist/client/link.js +712 -338
  16. package/dist/client/router/boundary-tree.d.ts +1 -1
  17. package/dist/client/router/index.d.ts +1 -1
  18. package/dist/client/router/link-utils.d.ts +5 -1
  19. package/dist/client/router/sync-catch-up.d.ts +4 -4
  20. package/dist/client/router/types.d.ts +2 -2
  21. package/dist/client-only.d.ts +1 -0
  22. package/dist/client-only.js +1 -0
  23. package/dist/client.d.ts +108 -111
  24. package/dist/client.js +16 -17
  25. package/dist/config.d.ts +1 -1
  26. package/dist/config.js +2 -2
  27. package/dist/devtools/devtools-element.d.ts +1 -0
  28. package/dist/devtools/protocol.d.ts +119 -0
  29. package/dist/furin.d.ts +7 -6
  30. package/dist/furin.js +6547 -3187
  31. package/dist/isomorphic.d.ts +18 -0
  32. package/dist/plugin/binding-scope.d.ts +2 -0
  33. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  34. package/dist/plugin/index.js +933 -423
  35. package/dist/plugin/transform-client.d.ts +0 -2
  36. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  37. package/dist/rsc/build/environment.d.ts +2 -0
  38. package/dist/rsc/build/index.d.ts +15 -0
  39. package/dist/rsc/client-codec.d.ts +1 -0
  40. package/dist/rsc/codec.d.ts +4 -0
  41. package/dist/rsc/flight-drain.d.ts +11 -0
  42. package/dist/rsc/render-error.d.ts +17 -0
  43. package/dist/rsc/server-codec.d.ts +2 -0
  44. package/dist/rsc/server-codec.js +24 -0
  45. package/dist/rsc/shared.d.ts +30 -0
  46. package/dist/rsc/symbols.d.ts +2 -0
  47. package/dist/rsc/transport-benchmark.d.ts +13 -0
  48. package/dist/rsc/version.d.ts +7 -0
  49. package/dist/rsc-client.d.ts +4 -0
  50. package/dist/rsc-client.js +166 -0
  51. package/dist/rsc-server.d.ts +11 -0
  52. package/dist/rsc.d.ts +11 -0
  53. package/dist/rsc.js +353 -0
  54. package/dist/server/cache/index.d.ts +2 -2
  55. package/dist/server/cache/invalidation.d.ts +2 -3
  56. package/dist/server/cache/isr-ssg.d.ts +5 -1
  57. package/dist/server/cache/isr.d.ts +9 -0
  58. package/dist/server/cache/route-cache.d.ts +10 -8
  59. package/dist/server/cache/store-view.d.ts +7 -7
  60. package/dist/server/dev-page-plugin.d.ts +4 -0
  61. package/dist/server/devtools/hub.d.ts +11 -0
  62. package/dist/server/devtools/instrumentation.d.ts +22 -0
  63. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  64. package/dist/server/devtools/plugin.d.ts +3 -0
  65. package/dist/server/devtools/request-context.d.ts +6 -0
  66. package/dist/server/internal.d.ts +2 -0
  67. package/dist/server/internal.js +3 -3
  68. package/dist/server/lang-detect.d.ts +1 -0
  69. package/dist/server/render/assemble.d.ts +4 -0
  70. package/dist/server/render/element.d.ts +1 -1
  71. package/dist/server/render/index.d.ts +2 -2
  72. package/dist/server/render/index.ts +6 -2
  73. package/dist/server/render/loaders.d.ts +8 -0
  74. package/dist/server/render/not-found.d.ts +1 -1
  75. package/dist/server/render/ppr-route.d.ts +8 -0
  76. package/dist/server/render/route-frame-transport.d.ts +2 -0
  77. package/dist/server/render/shell.ts +0 -1
  78. package/dist/server/render/ssr.d.ts +2 -3
  79. package/dist/server/router/discovery.d.ts +1 -1
  80. package/dist/server/router/hmr.d.ts +1 -1
  81. package/dist/server/router/index.d.ts +2 -1
  82. package/dist/server/router/index.js +23 -23
  83. package/dist/server/router/index.ts +1 -1
  84. package/dist/server/router/patterns.d.ts +1 -1
  85. package/dist/server/router/plugin.d.ts +4 -7
  86. package/dist/server/router/schema-merge.d.ts +3 -0
  87. package/dist/server/router/schemas.d.ts +12 -7
  88. package/dist/server/router/types.d.ts +1 -1
  89. package/dist/server/runtime-env.js +2 -2
  90. package/dist/server/sync/adapter.d.ts +45 -26
  91. package/dist/server/sync/config.d.ts +5 -9
  92. package/dist/server/sync/fingerprint.d.ts +2 -1
  93. package/dist/server/sync/index.d.ts +15 -4
  94. package/dist/server/sync/index.js +2868 -0
  95. package/dist/server/sync/notifier.d.ts +18 -0
  96. package/dist/server/sync/plugin.d.ts +53 -54
  97. package/dist/server/sync/postgres/index.d.ts +19 -0
  98. package/dist/server/sync/postgres/index.js +252 -0
  99. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  100. package/dist/server/sync/postgres/migrate.js +16 -0
  101. package/dist/server/sync/postgres/migration.sql +66 -0
  102. package/dist/server/sync/redis/index.d.ts +30 -0
  103. package/dist/server/sync/redis/index.js +336 -0
  104. package/dist/server/sync/redis/scripts.d.ts +4 -0
  105. package/dist/server/sync/response.d.ts +10 -1
  106. package/dist/server/sync/runtime.d.ts +6 -0
  107. package/dist/server/sync/sqlite/index.d.ts +20 -0
  108. package/dist/server/sync/sqlite/index.js +250 -0
  109. package/dist/server/sync/stream.d.ts +12 -11
  110. package/dist/server-only.d.ts +1 -0
  111. package/dist/server-only.js +1 -0
  112. package/dist/shared/parser.d.ts +2 -0
  113. package/dist/shared/route-frame.d.ts +49 -0
  114. package/dist/shared/utils/index.d.ts +1 -1
  115. package/package.json +54 -12
  116. package/src/adapter/bun.ts +73 -16
  117. package/src/adapter/package.ts +3 -1
  118. package/src/adapter/static.ts +94 -48
  119. package/src/build/bun-build.ts +11 -0
  120. package/src/build/client.ts +22 -24
  121. package/src/build/entry-template.ts +3 -0
  122. package/src/build/hydrate.ts +33 -8
  123. package/src/build/index.ts +12 -0
  124. package/src/build/production-instrumentation.ts +14 -0
  125. package/src/build/route-types.ts +7 -8
  126. package/src/build/scan-server.ts +3 -2
  127. package/src/build/ssg-cache.ts +7 -2
  128. package/src/build/types.ts +1 -0
  129. package/src/cli/index.ts +53 -22
  130. package/src/client/boundaries.tsx +42 -18
  131. package/src/client/default-screens.tsx +4 -4
  132. package/src/client/internal/runtime-types.ts +31 -0
  133. package/src/client/link.tsx +35 -37
  134. package/src/client/router/boundary-tree.tsx +2 -2
  135. package/src/client/router/context.ts +13 -9
  136. package/src/client/router/index.ts +3 -0
  137. package/src/client/router/link-utils.ts +66 -3
  138. package/src/client/router/navigation.ts +9 -15
  139. package/src/client/router/provider.tsx +74 -52
  140. package/src/client/router/search/index.ts +5 -7
  141. package/src/client/router/search-store.ts +5 -1
  142. package/src/client/router/spa-response.ts +3 -4
  143. package/src/client/router/sync-catch-up.ts +9 -8
  144. package/src/client/router/types.ts +2 -2
  145. package/src/client/sync.ts +3 -2
  146. package/src/client-only.ts +1 -0
  147. package/src/client.ts +221 -174
  148. package/src/devtools/devtools-element.js +884 -0
  149. package/src/devtools/protocol.ts +139 -0
  150. package/src/furin.ts +185 -96
  151. package/src/isomorphic.ts +66 -0
  152. package/src/plugin/binding-scope.ts +158 -0
  153. package/src/plugin/dead-code-elimination.ts +202 -0
  154. package/src/plugin/index.ts +14 -18
  155. package/src/plugin/transform-client.ts +237 -273
  156. package/src/plugin/transform-isomorphic.ts +464 -0
  157. package/src/rsc/build/environment.ts +30 -0
  158. package/src/rsc/build/index.ts +94 -0
  159. package/src/rsc/client-codec.ts +11 -0
  160. package/src/rsc/codec.ts +85 -0
  161. package/src/rsc/flight-drain.ts +68 -0
  162. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  163. package/src/rsc/render-error.ts +120 -0
  164. package/src/rsc/server-codec.ts +25 -0
  165. package/src/rsc/shared.tsx +113 -0
  166. package/src/rsc/symbols.ts +2 -0
  167. package/src/rsc/transport-benchmark.ts +73 -0
  168. package/src/rsc/version.ts +57 -0
  169. package/src/rsc-client.ts +12 -0
  170. package/src/rsc-server.tsx +91 -0
  171. package/src/rsc.tsx +75 -0
  172. package/src/server/auto-invalidate/runtime.ts +32 -6
  173. package/src/server/cache/dev-loader.ts +70 -10
  174. package/src/server/cache/index.ts +7 -3
  175. package/src/server/cache/invalidation.ts +33 -15
  176. package/src/server/cache/isr-ssg.ts +12 -3
  177. package/src/server/cache/isr.ts +84 -9
  178. package/src/server/cache/route-cache.ts +49 -36
  179. package/src/server/cache/store-view.ts +7 -7
  180. package/src/server/context-logger.ts +7 -7
  181. package/src/server/dev-page-plugin.ts +8 -6
  182. package/src/server/devtools/hub.ts +64 -0
  183. package/src/server/devtools/instrumentation.production.ts +80 -0
  184. package/src/server/devtools/instrumentation.ts +72 -0
  185. package/src/server/devtools/plugin.ts +267 -0
  186. package/src/server/devtools/request-context.ts +76 -0
  187. package/src/server/instance.ts +1 -1
  188. package/src/server/internal.ts +2 -0
  189. package/src/server/lang-detect.ts +14 -10
  190. package/src/server/render/assemble.ts +73 -10
  191. package/src/server/render/element.tsx +11 -8
  192. package/src/server/render/index.ts +6 -2
  193. package/src/server/render/isr.ts +154 -110
  194. package/src/server/render/loaders.ts +259 -45
  195. package/src/server/render/not-found.ts +10 -15
  196. package/src/server/render/ppr-route.ts +146 -0
  197. package/src/server/render/route-frame-transport.ts +62 -0
  198. package/src/server/render/shell.ts +0 -1
  199. package/src/server/render/ssg.ts +6 -5
  200. package/src/server/render/ssr.ts +155 -67
  201. package/src/server/render/template.ts +2 -1
  202. package/src/server/router/discovery.ts +39 -22
  203. package/src/server/router/hmr.ts +15 -13
  204. package/src/server/router/index.ts +1 -1
  205. package/src/server/router/patterns.ts +16 -15
  206. package/src/server/router/plugin.ts +151 -158
  207. package/src/server/router/schema-merge.ts +52 -0
  208. package/src/server/router/schemas.ts +55 -73
  209. package/src/server/router/types.ts +1 -1
  210. package/src/server/sync/adapter.ts +44 -28
  211. package/src/server/sync/config.ts +9 -27
  212. package/src/server/sync/fingerprint.ts +8 -3
  213. package/src/server/sync/index.ts +37 -13
  214. package/src/server/sync/notifier.ts +109 -0
  215. package/src/server/sync/plugin.ts +184 -89
  216. package/src/server/sync/postgres/index.ts +301 -0
  217. package/src/server/sync/postgres/migrate.ts +15 -0
  218. package/src/server/sync/postgres/migration.sql +66 -0
  219. package/src/server/sync/redis/index.ts +342 -0
  220. package/src/server/sync/redis/scripts.ts +74 -0
  221. package/src/server/sync/response.ts +141 -16
  222. package/src/server/sync/runtime.ts +27 -0
  223. package/src/server/sync/sql.d.ts +4 -0
  224. package/src/server/sync/sqlite/index.ts +337 -0
  225. package/src/server/sync/sqlite/migration.sql +70 -0
  226. package/src/server/sync/stream.ts +137 -81
  227. package/src/server-only.ts +1 -0
  228. package/src/shared/await.tsx +4 -4
  229. package/src/shared/deferred-ndjson.ts +34 -6
  230. package/src/shared/digest.ts +2 -2
  231. package/src/shared/parser.ts +5 -0
  232. package/src/shared/route-frame.ts +429 -0
  233. package/src/shared/search-params.ts +7 -7
  234. package/src/shared/utils/index.ts +5 -3
  235. package/dist/server/dev-inspector.d.ts +0 -89
  236. package/dist/server/sync/memory-adapter.d.ts +0 -17
  237. package/src/server/dev-inspector.ts +0 -60
  238. package/src/server/sync/memory-adapter.ts +0 -196
@@ -1,8 +1,7 @@
1
- import { t } from "elysia";
2
1
  import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
3
2
  import { getSchemaValidator } from "elysia/schema";
4
3
  import type { AnySchema } from "elysia/types";
5
- import type { RuntimeRoute } from "../../client.ts";
4
+ import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
6
5
  import {
7
6
  collectSearchDefaults,
8
7
  type SearchParamsInput,
@@ -10,6 +9,8 @@ import {
10
9
  } from "../../shared/search-params.ts";
11
10
  import { buildRouteRegex } from "./patterns.ts";
12
11
 
12
+ import { mergeRouteSchemas } from "./schema-merge.ts";
13
+
13
14
  interface UnknownObject {
14
15
  [key: string]: unknown;
15
16
  }
@@ -44,7 +45,7 @@ export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: st
44
45
  if (url.origin !== "http://localhost") {
45
46
  return;
46
47
  }
47
- return { url, pathname: url.pathname };
48
+ return { pathname: url.pathname, url };
48
49
  }
49
50
 
50
51
  function isObjectSchema(schema: unknown): schema is UnknownObject {
@@ -129,103 +130,84 @@ export type ParseRouteQueryResult =
129
130
  | { ok: true; query: SearchParamsInput }
130
131
  | { errors: unknown; ok: false };
131
132
 
132
- /**
133
- * Parses and validates a logical route URL's search string for the synthetic
134
- * `/_furin/data` request path. This keeps SPA navigations aligned with the
135
- * Elysia guard used by the full SSR route.
136
- *
137
- * @internal Exported for unit testing.
138
- */
139
- export async function parseRouteQuery(
140
- url: URL,
141
- schema: AnySchema | undefined
142
- ): Promise<ParseRouteQueryResult> {
143
- if (!schema) {
144
- return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
145
- }
133
+ export type ParseRouteParamsResult =
134
+ | { ok: true; params: UnknownObject }
135
+ | { errors: unknown; ok: false };
146
136
 
137
+ type RouteInputValidationResult =
138
+ | { ok: true; value: UnknownObject }
139
+ | { errors: unknown; ok: false };
140
+
141
+ async function validateRouteInput(
142
+ input: UnknownObject,
143
+ schema: AnySchema
144
+ ): Promise<RouteInputValidationResult> {
147
145
  if (isStandardSchema(schema)) {
148
- const rawQuery = parseQueryStandardSchema(url.search, 1) as UnknownObject;
149
146
  const validator = getSchemaValidator(schema, { dynamic: true });
150
- const checked = await validator?.Check(rawQuery);
147
+ const checked = await validator?.Check(input);
151
148
  if (checked && typeof checked === "object" && "issues" in checked) {
152
149
  return { errors: checked.issues, ok: false };
153
150
  }
154
151
  if (checked && typeof checked === "object" && "value" in checked) {
155
- return { ok: true, query: checked.value as SearchParamsInput };
152
+ return { ok: true, value: checked.value as UnknownObject };
156
153
  }
157
- return { ok: true, query: rawQuery as SearchParamsInput };
154
+ return { ok: true, value: input };
158
155
  }
159
156
 
160
- const rawQuery = parseJsonQueryObjects(
161
- parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
162
- collectQueryObjectKeys(schema)
163
- );
164
- const queryWithDefaults = applySchemaDefaults(schema as UnknownObject, rawQuery);
157
+ const inputWithDefaults = applySchemaDefaults(schema as UnknownObject, input);
165
158
  const validator = getSchemaValidator(schema, { coerce: true, dynamic: true });
166
- if (validator?.Check(queryWithDefaults) === false) {
167
- return { errors: [...(validator?.Errors(queryWithDefaults) ?? [])], ok: false };
159
+ if (validator?.Check(inputWithDefaults) === false) {
160
+ return { errors: [...(validator?.Errors(inputWithDefaults) ?? [])], ok: false };
168
161
  }
169
162
 
170
163
  return {
171
164
  ok: true,
172
- query: (validator?.parse(queryWithDefaults) ?? queryWithDefaults) as SearchParamsInput,
165
+ value: (validator?.parse(inputWithDefaults) ?? inputWithDefaults) as UnknownObject,
173
166
  };
174
167
  }
175
168
 
176
- // Standard structural keys on a TObject — everything else is a user-supplied option
177
- // (e.g. additionalProperties, $id, description, title) and must be preserved.
178
- const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
179
- const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
169
+ /**
170
+ * Parses and validates a logical route URL's search string for the synthetic
171
+ * `/_furin/data` request path. This keeps SPA navigations aligned with the
172
+ * Elysia guard used by the full SSR route.
173
+ *
174
+ * @internal Exported for unit testing.
175
+ */
176
+ export async function parseRouteQuery(
177
+ url: URL,
178
+ schema: AnySchema | undefined
179
+ ): Promise<ParseRouteQueryResult> {
180
+ if (!schema) {
181
+ return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
182
+ }
180
183
 
181
- function isTypeBoxObjectSchema(schema: unknown): schema is UnknownObject {
182
- return (
183
- isObjectSchema(schema) &&
184
- (schema as UnknownObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
185
- );
184
+ const rawQuery = isStandardSchema(schema)
185
+ ? (parseQueryStandardSchema(url.search, 1) as UnknownObject)
186
+ : parseJsonQueryObjects(
187
+ parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
188
+ collectQueryObjectKeys(schema)
189
+ );
190
+ const result = await validateRouteInput(rawQuery, schema);
191
+ return result.ok ? { ok: true, query: result.value as SearchParamsInput } : result;
186
192
  }
187
193
 
188
194
  /**
189
- * Merges TObject schemas from all routeChain entries for a given key.
190
- * Properties are spread left-to-right (leaf wins on key conflict).
191
- * Object-level options (additionalProperties, $id, description, …) are also
192
- * merged with the same leaf-wins semantics so they are not silently dropped.
193
- * Returns undefined when no entry in the chain defines the key.
195
+ * Validates and coerces path params for the synthetic `/_furin/data` request
196
+ * path. This mirrors the params schema installed by createRoutePlugin's Elysia
197
+ * guard so SPA loaders receive the same values as full SSR loaders.
194
198
  *
195
199
  * @internal Exported for unit testing.
196
200
  */
197
- export function mergeRouteSchemas(
198
- routeChain: RuntimeRoute[],
199
- key: "params" | "query"
200
- ): AnySchema | undefined {
201
- const schemas = routeChain.flatMap((r) => (r[key] ? [r[key]] : [])) as Record<string, unknown>[];
202
-
203
- if (schemas.length === 0) {
204
- return;
205
- }
206
- if (schemas.length === 1) {
207
- return schemas[0] as AnySchema;
208
- }
209
-
210
- if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
211
- throw new Error(
212
- `[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
213
- );
201
+ export async function parseRouteParams(
202
+ params: UnknownObject,
203
+ schema: AnySchema | undefined
204
+ ): Promise<ParseRouteParamsResult> {
205
+ if (!schema) {
206
+ return { ok: true, params };
214
207
  }
215
208
 
216
- const mergedProperties = Object.assign(
217
- {},
218
- ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
219
- );
220
-
221
- const mergedOptions = Object.assign(
222
- {},
223
- ...schemas.map((s) =>
224
- Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
225
- )
226
- );
227
-
228
- return t.Object(mergedProperties, mergedOptions) as AnySchema;
209
+ const result = await validateRouteInput(params, schema);
210
+ return result.ok ? { ok: true, params: result.value } : result;
229
211
  }
230
212
 
231
213
  export function createSearchRouteMetadata(
@@ -1,4 +1,4 @@
1
- import type { RuntimePage, RuntimeRoute } from "../../client.ts";
1
+ import type { RuntimePage, RuntimeRoute } from "../../client/internal/runtime-types.ts";
2
2
  import type { ErrorComponent } from "../../shared/error.ts";
3
3
  import type { NotFoundComponent } from "../../shared/not-found.ts";
4
4
 
@@ -10,39 +10,40 @@ export interface BeginMutationInput {
10
10
  principal: string;
11
11
  }
12
12
 
13
+ export interface MutationLease {
14
+ id: string;
15
+ key: string;
16
+ leaseMs: number;
17
+ principal: string;
18
+ }
19
+
13
20
  export type BeginMutationResult =
14
- | { kind: "execute"; mutationId: string }
21
+ | { kind: "execute"; lease: MutationLease }
15
22
  | { kind: "replay"; response: StoredResponse }
16
- | { kind: "conflict"; reason: "in-progress" | "payload-mismatch" }
17
- | { kind: "unavailable" };
23
+ | { kind: "conflict"; reason: "in-progress" | "payload-mismatch" };
24
+
25
+ export type SyncInvalidation =
26
+ | { kind: "path"; path: string; type: "layout" | "page" }
27
+ | { kind: "tags"; tags: readonly string[] };
18
28
 
19
- export interface CommitMutationInput {
20
- mutationId: string;
29
+ export interface CompleteMutationInput {
30
+ invalidations: readonly SyncInvalidation[];
31
+ lease: MutationLease;
21
32
  response: StoredResponse;
22
33
  }
23
34
 
24
- export interface AbortMutationInput {
25
- mutationId: string;
26
- }
35
+ export type CompleteMutationResult =
36
+ | { cursor: string | undefined; kind: "committed" }
37
+ | { kind: "lost" };
27
38
 
28
39
  export interface SyncChange {
29
40
  cursor: string;
30
- invalidations: readonly string[];
31
- }
32
-
33
- export interface AppendChangesInput {
34
- invalidations: readonly string[];
35
- path: string;
36
- }
37
-
38
- export interface AppendChangesResult {
39
- change: SyncChange;
41
+ invalidations: readonly SyncInvalidation[];
40
42
  }
41
43
 
42
44
  export interface ReadChangesInput {
43
45
  after: string | undefined;
44
46
  limit: number;
45
- path: string;
46
47
  }
47
48
 
48
49
  export interface ChangePage {
@@ -52,14 +53,29 @@ export interface ChangePage {
52
53
  reset: boolean;
53
54
  }
54
55
 
55
- export type SyncChangeListener = (change: SyncChange) => void;
56
- type MaybePromise<T> = Promise<T> | T;
57
-
58
56
  export interface SyncAdapter {
59
- abortMutation(input: AbortMutationInput): MaybePromise<void>;
60
- appendChanges(input: AppendChangesInput): MaybePromise<AppendChangesResult>;
61
- beginMutation(input: BeginMutationInput): MaybePromise<BeginMutationResult>;
62
- commitMutation(input: CommitMutationInput): MaybePromise<void>;
63
- readChanges(input: ReadChangesInput): MaybePromise<ChangePage>;
64
- subscribe(path: string, listener: SyncChangeListener): () => void;
57
+ abortMutation: (lease: MutationLease) => Promise<void>;
58
+ beginMutation: (input: BeginMutationInput) => Promise<BeginMutationResult>;
59
+ completeMutation: (input: CompleteMutationInput) => Promise<CompleteMutationResult>;
60
+ currentCursor: () => Promise<string>;
61
+ readChanges: (input: ReadChangesInput) => Promise<ChangePage>;
62
+ renewMutation: (lease: MutationLease) => Promise<"lost" | "renewed">;
63
+ readonly scope: "distributed" | "host-local" | "process-local";
65
64
  }
65
+
66
+ export interface SyncSubscription {
67
+ unsubscribe: () => Promise<void>;
68
+ }
69
+
70
+ export interface SyncNotifier {
71
+ publish: (cursor: string) => Promise<void>;
72
+ subscribe: (listener: (cursor: string) => void) => Promise<SyncSubscription>;
73
+ }
74
+
75
+ export interface SyncRuntimeOptions {
76
+ adapter: SyncAdapter;
77
+ notifier?: SyncNotifier;
78
+ principal: (context: Context) => Promise<string> | string;
79
+ }
80
+
81
+ import type { Context } from "elysia";
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { allInstances, currentInstance } from "../instance.ts";
2
+ import { currentInstance } from "../instance.ts";
3
+ import type { SyncRuntimeOptions } from "./adapter.ts";
3
4
 
4
5
  const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
5
6
 
@@ -7,19 +8,16 @@ const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
7
8
  // stream path comes from the current furin instance.
8
9
  const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
9
10
 
10
- export type FurinSyncOption =
11
- | boolean
12
- | {
13
- streamPath?: string;
14
- };
11
+ export interface FurinSyncOptions extends SyncRuntimeOptions {
12
+ streamPath?: string;
13
+ }
14
+
15
+ export type FurinSyncOption = FurinSyncOptions | false;
15
16
 
16
17
  export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
17
18
  if (!sync) {
18
19
  return;
19
20
  }
20
- if (sync === true) {
21
- return SYNC_STREAM_DEFAULT_PATH;
22
- }
23
21
  return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
24
22
  }
25
23
 
@@ -39,22 +37,6 @@ export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T):
39
37
  return requestSyncStreamPath.run(path, fn);
40
38
  }
41
39
 
42
- /**
43
- * Physical adapter channels a sync publication must reach. An explicit
44
- * override wins (historical single-channel behaviour); otherwise every
45
- * sync-enabled instance gets notified — a mutation on a shared API must wake
46
- * the SSE clients of every mounted app.
47
- */
48
- export function syncPublishChannels(): string[] {
49
- const override = requestSyncStreamPath.getStore();
50
- if (override !== undefined) {
51
- return [override];
52
- }
53
- const channels = allInstances()
54
- .filter((instance) => instance.syncStreamPath !== undefined)
55
- .map((instance) => `${instance.prefix}${instance.syncStreamPath}`);
56
- if (channels.length > 0) {
57
- return channels;
58
- }
59
- return [SYNC_STREAM_DEFAULT_PATH];
40
+ export function syncRuntimeOptions(sync: FurinSyncOptions): SyncRuntimeOptions {
41
+ return { adapter: sync.adapter, notifier: sync.notifier, principal: sync.principal };
60
42
  }
@@ -24,7 +24,13 @@ function canonicalize(value: unknown): unknown {
24
24
  return value;
25
25
  }
26
26
 
27
- export async function createMutationFingerprint(input: FingerprintInput): Promise<string> {
27
+ export function sha256Hex(source: string): string {
28
+ const hasher = new Bun.CryptoHasher("sha256");
29
+ hasher.update(source);
30
+ return hasher.digest("hex");
31
+ }
32
+
33
+ export function createMutationFingerprint(input: FingerprintInput): string {
28
34
  const url = new URL(input.request.url);
29
35
  const query = [...url.searchParams.entries()].sort(
30
36
  ([leftKey, leftValue], [rightKey, rightValue]) =>
@@ -39,6 +45,5 @@ export async function createMutationFingerprint(input: FingerprintInput): Promis
39
45
  pathname: url.pathname,
40
46
  query,
41
47
  });
42
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
43
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
48
+ return sha256Hex(source);
44
49
  }
@@ -1,15 +1,39 @@
1
1
  // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
- export type { FurinSyncOption } from "./config.ts";
3
- export {
4
- getSyncStreamPath,
5
- resolveSyncStreamPath,
6
- runWithSyncStreamPath,
2
+
3
+ import {
4
+ getSyncStreamPath as getSyncStreamPathImplementation,
5
+ resolveSyncStreamPath as resolveSyncStreamPathImplementation,
6
+ runWithSyncStreamPath as runWithSyncStreamPathImplementation,
7
7
  } from "./config.ts";
8
- export { furinSync, type SyncInput, type SyncRouteOption } from "./plugin.ts";
9
- export {
10
- __resetSyncState,
11
- createSyncStreamPlugin,
12
- publishSyncInvalidation,
13
- type SyncChange,
14
- type SyncChangePage,
15
- } from "./stream.ts";
8
+ import { PollingSyncNotifier as PollingSyncNotifierImplementation } from "./notifier.ts";
9
+ import { furinSync as furinSyncImplementation } from "./plugin.ts";
10
+ import { createSyncStreamPlugin as createSyncStreamPluginImplementation } from "./stream.ts";
11
+
12
+ export const createSyncStreamPlugin = createSyncStreamPluginImplementation;
13
+ export const furinSync = furinSyncImplementation;
14
+ export const getSyncStreamPath = getSyncStreamPathImplementation;
15
+ export const PollingSyncNotifier = PollingSyncNotifierImplementation;
16
+ export const resolveSyncStreamPath = resolveSyncStreamPathImplementation;
17
+ export const runWithSyncStreamPath = runWithSyncStreamPathImplementation;
18
+
19
+ export type PollingSyncNotifier = PollingSyncNotifierImplementation;
20
+
21
+ export type {
22
+ BeginMutationInput,
23
+ BeginMutationResult,
24
+ ChangePage,
25
+ CompleteMutationInput,
26
+ CompleteMutationResult,
27
+ MutationLease,
28
+ ReadChangesInput,
29
+ StoredResponse,
30
+ SyncAdapter,
31
+ SyncChange,
32
+ SyncInvalidation,
33
+ SyncNotifier,
34
+ SyncRuntimeOptions,
35
+ SyncSubscription,
36
+ } from "./adapter.ts";
37
+ export type { FurinSyncOption, FurinSyncOptions } from "./config.ts";
38
+ export type { SyncInput, SyncRouteOption } from "./plugin.ts";
39
+ export type { SyncChangePage } from "./stream.ts";
@@ -0,0 +1,109 @@
1
+ import type { SyncAdapter, SyncNotifier, SyncSubscription } from "./adapter.ts";
2
+
3
+ interface ListenerSubscription {
4
+ listener: (cursor: string) => void;
5
+ }
6
+
7
+ export class PollingSyncNotifier implements SyncNotifier {
8
+ private readonly adapter: SyncAdapter;
9
+ private readonly intervalMs: number;
10
+ private readonly listeners = new Set<ListenerSubscription>();
11
+ private cursor: string | undefined;
12
+ private initialization: Promise<void> | undefined;
13
+ private polling: Promise<void> | undefined;
14
+ private revision = 0;
15
+ private timer: ReturnType<typeof setTimeout> | undefined;
16
+
17
+ constructor(adapter: SyncAdapter, intervalMs: number) {
18
+ this.adapter = adapter;
19
+ this.intervalMs = intervalMs;
20
+ }
21
+
22
+ publish(cursor: string): Promise<void> {
23
+ this.revision += 1;
24
+ this.emit(cursor);
25
+ return Promise.resolve();
26
+ }
27
+
28
+ async subscribe(listener: (cursor: string) => void): Promise<SyncSubscription> {
29
+ const subscription = { listener };
30
+ this.listeners.add(subscription);
31
+ try {
32
+ await this.start();
33
+ } catch (error) {
34
+ this.listeners.delete(subscription);
35
+ throw error;
36
+ }
37
+ return {
38
+ unsubscribe: () => {
39
+ this.listeners.delete(subscription);
40
+ if (this.listeners.size === 0 && this.timer) {
41
+ clearTimeout(this.timer);
42
+ this.timer = undefined;
43
+ }
44
+ return Promise.resolve();
45
+ },
46
+ };
47
+ }
48
+
49
+ private emit(cursor: string): void {
50
+ if (cursor === this.cursor) {
51
+ return;
52
+ }
53
+ this.cursor = cursor;
54
+ for (const subscription of [...this.listeners]) {
55
+ try {
56
+ subscription.listener(cursor);
57
+ } catch {
58
+ // Notifications are best-effort wake-ups; durable recovery reads the change log.
59
+ }
60
+ }
61
+ }
62
+
63
+ private async poll(): Promise<void> {
64
+ const { revision } = this;
65
+ try {
66
+ const cursor = await this.adapter.currentCursor();
67
+ if (revision === this.revision && this.listeners.size > 0) {
68
+ this.emit(cursor);
69
+ }
70
+ } catch {
71
+ // A later poll retries transient adapter failures.
72
+ }
73
+ }
74
+
75
+ private async start(): Promise<void> {
76
+ if (this.timer || this.polling) {
77
+ return;
78
+ }
79
+ if (!this.initialization) {
80
+ const { revision } = this;
81
+ this.initialization = this.adapter
82
+ .currentCursor()
83
+ .then((cursor) => {
84
+ if (revision === this.revision) {
85
+ this.cursor = cursor;
86
+ }
87
+ })
88
+ .finally(() => {
89
+ this.initialization = undefined;
90
+ });
91
+ }
92
+ await this.initialization;
93
+ this.schedulePoll();
94
+ }
95
+
96
+ private schedulePoll(): void {
97
+ if (this.listeners.size === 0 || this.timer || this.polling) {
98
+ return;
99
+ }
100
+ this.timer = setTimeout(() => {
101
+ this.timer = undefined;
102
+ this.polling = this.poll().finally(() => {
103
+ this.polling = undefined;
104
+ this.schedulePoll();
105
+ });
106
+ }, this.intervalMs);
107
+ this.timer.unref?.();
108
+ }
109
+ }