@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.4

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 (54) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/build/compile-entry.ts +109 -109
  4. package/dist/build/entry-template.ts +156 -156
  5. package/dist/build/server-routes-entry.ts +36 -36
  6. package/dist/cli/index.js +0 -0
  7. package/dist/client/link.js +163 -16
  8. package/dist/client/router/abort.d.ts +1 -0
  9. package/dist/client/router/sync-catch-up.d.ts +29 -0
  10. package/dist/furin.d.ts +1 -1
  11. package/dist/furin.js +499 -215
  12. package/dist/server/sync/adapter.d.ts +62 -0
  13. package/dist/server/sync/fingerprint.d.ts +6 -0
  14. package/dist/server/sync/index.d.ts +2 -2
  15. package/dist/server/sync/memory-adapter.d.ts +17 -0
  16. package/dist/server/sync/plugin.d.ts +12 -195
  17. package/dist/server/sync/response.d.ts +4 -0
  18. package/dist/server/sync/stream.d.ts +16 -4
  19. package/package.json +1 -1
  20. package/src/adapter/README.md +13 -13
  21. package/src/build/client.ts +152 -152
  22. package/src/build/compile-entry.ts +109 -109
  23. package/src/build/entry-template.ts +156 -156
  24. package/src/build/hydrate.ts +340 -340
  25. package/src/build/index.ts +152 -152
  26. package/src/build/route-types.ts +145 -145
  27. package/src/build/scan-server.ts +95 -95
  28. package/src/build/server-routes-entry.ts +36 -36
  29. package/src/build/shared.ts +80 -80
  30. package/src/build/ssg-cache.ts +32 -32
  31. package/src/build/types.ts +89 -89
  32. package/src/client/router/abort.ts +5 -0
  33. package/src/client/router/link-utils.ts +184 -184
  34. package/src/client/router/provider.tsx +883 -804
  35. package/src/client/router/sync-catch-up.ts +113 -0
  36. package/src/client/router/types.ts +276 -276
  37. package/src/client/sync.ts +98 -98
  38. package/src/client.ts +369 -369
  39. package/src/furin.ts +465 -465
  40. package/src/server/auto-invalidate/runtime.ts +134 -134
  41. package/src/server/dev-page-plugin.ts +454 -454
  42. package/src/server/render/assemble.ts +160 -160
  43. package/src/server/render/isr.ts +323 -323
  44. package/src/server/render/ssr.ts +591 -585
  45. package/src/server/router/plugin.ts +384 -384
  46. package/src/server/sync/adapter.ts +65 -0
  47. package/src/server/sync/config.ts +29 -29
  48. package/src/server/sync/fingerprint.ts +44 -0
  49. package/src/server/sync/index.ts +15 -14
  50. package/src/server/sync/memory-adapter.ts +196 -0
  51. package/src/server/sync/plugin.ts +200 -108
  52. package/src/server/sync/response.ts +77 -0
  53. package/src/server/sync/stream.ts +152 -144
  54. package/src/shared/deferred-ndjson.ts +7 -0
package/dist/furin.js CHANGED
@@ -2912,6 +2912,24 @@ function findSearchDefaultsForRouteTarget(to, routes) {
2912
2912
  }
2913
2913
  }
2914
2914
 
2915
+ // src/client/server-error.ts
2916
+ function isFurinServerError(err) {
2917
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
2918
+ }
2919
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR", FurinServerError;
2920
+ var init_server_error = __esm(() => {
2921
+ FurinServerError = class FurinServerError extends Error {
2922
+ __furinBrand = SERVER_ERROR_BRAND;
2923
+ digest;
2924
+ status;
2925
+ constructor(args) {
2926
+ super(args.message);
2927
+ this.status = args.status;
2928
+ this.digest = args.digest;
2929
+ }
2930
+ };
2931
+ });
2932
+
2915
2933
  // src/client/router/context.ts
2916
2934
  import { createContext, useContext } from "react";
2917
2935
  function useRouter() {
@@ -2968,74 +2986,6 @@ function normalizeHref(href) {
2968
2986
  }
2969
2987
  var init_link_utils = () => {};
2970
2988
 
2971
- // src/client/router/search-store.ts
2972
- import { createContext as createContext2 } from "react";
2973
- function searchSnapshotChanged(a, b) {
2974
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
2975
- }
2976
- function createSearchStore(initialSnapshot) {
2977
- let snapshot = initialSnapshot;
2978
- let version = 0;
2979
- let flushedVersion = 0;
2980
- const listeners = new Set;
2981
- return {
2982
- flush: () => {
2983
- if (flushedVersion === version) {
2984
- return;
2985
- }
2986
- flushedVersion = version;
2987
- for (const listener of [...listeners]) {
2988
- listener();
2989
- }
2990
- },
2991
- getServerSnapshot: () => snapshot,
2992
- getSnapshot: () => snapshot,
2993
- setSnapshot: (next) => {
2994
- if (!searchSnapshotChanged(snapshot, next)) {
2995
- return;
2996
- }
2997
- snapshot = next;
2998
- version++;
2999
- },
3000
- subscribe: (listener) => {
3001
- listeners.add(listener);
3002
- return () => {
3003
- listeners.delete(listener);
3004
- };
3005
- }
3006
- };
3007
- }
3008
- function searchSnapshotFromRouterContext(context) {
3009
- return {
3010
- currentHref: context.currentHref,
3011
- navigate: context.navigate,
3012
- search: context.search,
3013
- searchRoutes: context.searchRoutes
3014
- };
3015
- }
3016
- var FALLBACK_SEARCH_STORE, SearchStoreContext;
3017
- var init_search_store = __esm(() => {
3018
- FALLBACK_SEARCH_STORE = createSearchStore({
3019
- currentHref: "/",
3020
- navigate: (href, _opts) => {
3021
- if (typeof window !== "undefined") {
3022
- window.location.href = href;
3023
- }
3024
- return Promise.resolve();
3025
- },
3026
- search: {},
3027
- searchRoutes: []
3028
- });
3029
- SearchStoreContext = createContext2(null);
3030
- });
3031
-
3032
- // src/client/router/index.ts
3033
- var init_router = __esm(() => {
3034
- init_context();
3035
- init_link_utils();
3036
- init_search_store();
3037
- });
3038
-
3039
2989
  // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
3040
2990
  function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
3041
2991
  return {
@@ -4490,6 +4440,74 @@ There are few workarounds for this problem:
4490
4440
  REF_CHARS_LEN = REF_CHARS.length;
4491
4441
  });
4492
4442
 
4443
+ // src/client/router/search-store.ts
4444
+ import { createContext as createContext2 } from "react";
4445
+ function searchSnapshotChanged(a, b) {
4446
+ return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4447
+ }
4448
+ function createSearchStore(initialSnapshot) {
4449
+ let snapshot = initialSnapshot;
4450
+ let version = 0;
4451
+ let flushedVersion = 0;
4452
+ const listeners = new Set;
4453
+ return {
4454
+ flush: () => {
4455
+ if (flushedVersion === version) {
4456
+ return;
4457
+ }
4458
+ flushedVersion = version;
4459
+ for (const listener of [...listeners]) {
4460
+ listener();
4461
+ }
4462
+ },
4463
+ getServerSnapshot: () => snapshot,
4464
+ getSnapshot: () => snapshot,
4465
+ setSnapshot: (next) => {
4466
+ if (!searchSnapshotChanged(snapshot, next)) {
4467
+ return;
4468
+ }
4469
+ snapshot = next;
4470
+ version++;
4471
+ },
4472
+ subscribe: (listener) => {
4473
+ listeners.add(listener);
4474
+ return () => {
4475
+ listeners.delete(listener);
4476
+ };
4477
+ }
4478
+ };
4479
+ }
4480
+ function searchSnapshotFromRouterContext(context) {
4481
+ return {
4482
+ currentHref: context.currentHref,
4483
+ navigate: context.navigate,
4484
+ search: context.search,
4485
+ searchRoutes: context.searchRoutes
4486
+ };
4487
+ }
4488
+ var FALLBACK_SEARCH_STORE, SearchStoreContext;
4489
+ var init_search_store = __esm(() => {
4490
+ FALLBACK_SEARCH_STORE = createSearchStore({
4491
+ currentHref: "/",
4492
+ navigate: (href, _opts) => {
4493
+ if (typeof window !== "undefined") {
4494
+ window.location.href = href;
4495
+ }
4496
+ return Promise.resolve();
4497
+ },
4498
+ search: {},
4499
+ searchRoutes: []
4500
+ });
4501
+ SearchStoreContext = createContext2(null);
4502
+ });
4503
+
4504
+ // src/client/router/index.ts
4505
+ var init_router = __esm(() => {
4506
+ init_context();
4507
+ init_link_utils();
4508
+ init_search_store();
4509
+ });
4510
+
4493
4511
  // src/client/link.tsx
4494
4512
  import { createElement, useCallback, useEffect, useRef } from "react";
4495
4513
  function computeLinkView({
@@ -4961,24 +4979,6 @@ html, body {
4961
4979
  `;
4962
4980
  });
4963
4981
 
4964
- // src/client/server-error.ts
4965
- function isFurinServerError(err) {
4966
- return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
4967
- }
4968
- var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR", FurinServerError;
4969
- var init_server_error = __esm(() => {
4970
- FurinServerError = class FurinServerError extends Error {
4971
- __furinBrand = SERVER_ERROR_BRAND;
4972
- digest;
4973
- status;
4974
- constructor(args) {
4975
- super(args.message);
4976
- this.status = args.status;
4977
- this.digest = args.digest;
4978
- }
4979
- };
4980
- });
4981
-
4982
4982
  // src/client/boundaries.tsx
4983
4983
  import { Component, Fragment } from "react";
4984
4984
  import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
@@ -5804,6 +5804,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult, searchRoutes
5804
5804
  if (prepared instanceof Response) {
5805
5805
  return prepared;
5806
5806
  }
5807
+ autoInvalidateRegistry.registerLoaderTags(resolvePath(route.pattern, ctx.params ?? {}), route.tags);
5807
5808
  useLogger3().set({
5808
5809
  furin: {
5809
5810
  render: route.mode,
@@ -5894,6 +5895,7 @@ var init_ssr = __esm(() => {
5894
5895
  init_development();
5895
5896
  init_router();
5896
5897
  init_search_store();
5898
+ init_registry();
5897
5899
  init_context_logger();
5898
5900
  init_assemble();
5899
5901
  init_element();
@@ -8085,7 +8087,7 @@ init_router2();
8085
8087
  init_config();
8086
8088
 
8087
8089
  // src/server/sync/plugin.ts
8088
- import { Elysia as Elysia4 } from "elysia";
8090
+ import { Elysia as Elysia3 } from "elysia";
8089
8091
 
8090
8092
  // src/server/auto-invalidate/runtime.ts
8091
8093
  init_registry();
@@ -8198,12 +8200,387 @@ function runInvalidationRules(input) {
8198
8200
  return deleted;
8199
8201
  }
8200
8202
 
8201
- // src/server/sync/stream.ts
8203
+ // src/server/sync/plugin.ts
8202
8204
  init_config();
8203
- import { Elysia as Elysia3 } from "elysia";
8204
- var encoder = new TextEncoder;
8205
+
8206
+ // src/server/sync/fingerprint.ts
8207
+ function compareCodePoints(left, right) {
8208
+ if (left === right) {
8209
+ return 0;
8210
+ }
8211
+ return left < right ? -1 : 1;
8212
+ }
8213
+ function canonicalize(value) {
8214
+ if (Array.isArray(value)) {
8215
+ return value.map(canonicalize);
8216
+ }
8217
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
8218
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
8219
+ }
8220
+ return value;
8221
+ }
8222
+ async function createMutationFingerprint(input) {
8223
+ const url = new URL(input.request.url);
8224
+ const query = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => leftKey === rightKey ? compareCodePoints(leftValue, rightValue) : compareCodePoints(leftKey, rightKey));
8225
+ const source = JSON.stringify({
8226
+ body: canonicalize(input.body) ?? null,
8227
+ contentType: input.request.headers.get("content-type") ?? "",
8228
+ method: input.request.method,
8229
+ pathname: url.pathname,
8230
+ query
8231
+ });
8232
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
8233
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8234
+ }
8235
+
8236
+ // src/server/sync/memory-adapter.ts
8237
+ var MAX_CHANGES = 1000;
8238
+ var MAX_MUTATIONS = 1e4;
8239
+ var MUTATION_TTL_MS = 24 * 60 * 60 * 1000;
8240
+
8241
+ class MemorySyncAdapter {
8242
+ changes = new Map;
8243
+ mutationKeys = new Map;
8244
+ mutations = new Map;
8245
+ beginMutation(input) {
8246
+ this.evictMutations();
8247
+ const mutationKey = `${input.principal}:${input.key}`;
8248
+ const existingId = this.mutationKeys.get(mutationKey);
8249
+ const existing = existingId ? this.mutations.get(existingId) : undefined;
8250
+ if (existing) {
8251
+ if (existing.fingerprint !== input.fingerprint) {
8252
+ return { kind: "conflict", reason: "payload-mismatch" };
8253
+ }
8254
+ if (existing.state === "in-progress") {
8255
+ return { kind: "conflict", reason: "in-progress" };
8256
+ }
8257
+ return { kind: "replay", response: existing.response };
8258
+ }
8259
+ if (this.mutations.size >= MAX_MUTATIONS) {
8260
+ return { kind: "unavailable" };
8261
+ }
8262
+ const mutationId = crypto.randomUUID();
8263
+ this.mutationKeys.set(mutationKey, mutationId);
8264
+ this.mutations.set(mutationId, {
8265
+ createdAt: Date.now(),
8266
+ fingerprint: input.fingerprint,
8267
+ mutationId,
8268
+ state: "in-progress"
8269
+ });
8270
+ return { kind: "execute", mutationId };
8271
+ }
8272
+ commitMutation(input) {
8273
+ const existing = this.mutations.get(input.mutationId);
8274
+ if (!existing) {
8275
+ return;
8276
+ }
8277
+ this.mutations.set(input.mutationId, {
8278
+ ...existing,
8279
+ response: input.response,
8280
+ state: "succeeded"
8281
+ });
8282
+ }
8283
+ abortMutation(input) {
8284
+ const existing = this.mutations.get(input.mutationId);
8285
+ if (!existing) {
8286
+ return;
8287
+ }
8288
+ this.mutations.delete(input.mutationId);
8289
+ for (const [key, mutationId] of this.mutationKeys) {
8290
+ if (mutationId === input.mutationId) {
8291
+ this.mutationKeys.delete(key);
8292
+ break;
8293
+ }
8294
+ }
8295
+ }
8296
+ appendChanges(input) {
8297
+ const state = this.getChangeState(input.path);
8298
+ const change = {
8299
+ cursor: String(state.nextCursor),
8300
+ invalidations: [...input.invalidations]
8301
+ };
8302
+ state.nextCursor += 1;
8303
+ state.changes.push(change);
8304
+ if (state.changes.length > MAX_CHANGES) {
8305
+ state.changes.shift();
8306
+ }
8307
+ for (const listener of [...state.listeners]) {
8308
+ listener(change);
8309
+ }
8310
+ return { change };
8311
+ }
8312
+ readChanges(input) {
8313
+ const state = this.getChangeState(input.path);
8314
+ const currentCursor = String(state.nextCursor - 1);
8315
+ if (input.after === undefined) {
8316
+ return { changes: [], cursor: currentCursor, hasMore: false, reset: false };
8317
+ }
8318
+ const after = Number.parseInt(input.after, 10);
8319
+ const oldest = Number.parseInt(state.changes[0]?.cursor ?? currentCursor, 10);
8320
+ if (after < oldest - 1) {
8321
+ return {
8322
+ changes: [{ cursor: currentCursor, invalidations: ["/:layout"] }],
8323
+ cursor: currentCursor,
8324
+ hasMore: false,
8325
+ reset: true
8326
+ };
8327
+ }
8328
+ const available = state.changes.filter((change) => Number.parseInt(change.cursor, 10) > after);
8329
+ const changes = available.slice(0, input.limit);
8330
+ return {
8331
+ changes,
8332
+ cursor: changes.at(-1)?.cursor ?? input.after,
8333
+ hasMore: available.length > changes.length,
8334
+ reset: false
8335
+ };
8336
+ }
8337
+ subscribe(path, listener) {
8338
+ const listeners = this.getChangeState(path).listeners;
8339
+ listeners.add(listener);
8340
+ return () => listeners.delete(listener);
8341
+ }
8342
+ reset() {
8343
+ this.changes.clear();
8344
+ this.mutationKeys.clear();
8345
+ this.mutations.clear();
8346
+ }
8347
+ evictMutations() {
8348
+ const expiredBefore = Date.now() - MUTATION_TTL_MS;
8349
+ for (const [mutationId, mutation] of this.mutations) {
8350
+ if (mutation.createdAt < expiredBefore) {
8351
+ this.deleteMutation(mutationId);
8352
+ }
8353
+ }
8354
+ while (this.mutations.size >= MAX_MUTATIONS) {
8355
+ const oldest = [...this.mutations.values()].find((entry) => entry.state === "succeeded");
8356
+ if (!oldest) {
8357
+ break;
8358
+ }
8359
+ this.deleteMutation(oldest.mutationId);
8360
+ }
8361
+ }
8362
+ deleteMutation(mutationId) {
8363
+ this.mutations.delete(mutationId);
8364
+ for (const [key, storedId] of this.mutationKeys) {
8365
+ if (storedId === mutationId) {
8366
+ this.mutationKeys.delete(key);
8367
+ return;
8368
+ }
8369
+ }
8370
+ }
8371
+ getChangeState(path) {
8372
+ const existing = this.changes.get(path);
8373
+ if (existing) {
8374
+ return existing;
8375
+ }
8376
+ const state = { changes: [], listeners: new Set, nextCursor: 1 };
8377
+ this.changes.set(path, state);
8378
+ return state;
8379
+ }
8380
+ }
8381
+ var memorySyncAdapter = new MemorySyncAdapter;
8382
+
8383
+ // src/server/sync/response.ts
8384
+ import { ElysiaCustomStatusResponse, StatusMap } from "elysia";
8385
+ var HOP_BY_HOP_HEADERS = new Set(["connection", "keep-alive", "transfer-encoding", "upgrade"]);
8386
+ function statusCode(status) {
8387
+ if (typeof status === "number") {
8388
+ return status;
8389
+ }
8390
+ return status === undefined ? 200 : StatusMap[status];
8391
+ }
8392
+ function unwrapStatusResponse(value) {
8393
+ if (!(value instanceof ElysiaCustomStatusResponse)) {
8394
+ return;
8395
+ }
8396
+ return { status: value.code, value: value.response };
8397
+ }
8398
+ function responseHeaders(headers) {
8399
+ const result = new Headers;
8400
+ for (const [name, value] of Object.entries(headers)) {
8401
+ if (value !== undefined && !HOP_BY_HOP_HEADERS.has(name.toLowerCase())) {
8402
+ for (const entry of Array.isArray(value) ? value : [value]) {
8403
+ result.append(name, String(entry));
8404
+ }
8405
+ }
8406
+ }
8407
+ return result;
8408
+ }
8409
+ async function storeResponse(responseValue, set) {
8410
+ if (responseValue instanceof Response) {
8411
+ const clone = responseValue.clone();
8412
+ const headers2 = [...clone.headers.entries()].filter(([name]) => !HOP_BY_HOP_HEADERS.has(name.toLowerCase()));
8413
+ return {
8414
+ body: new Uint8Array(await clone.arrayBuffer()),
8415
+ headers: headers2,
8416
+ status: clone.status
8417
+ };
8418
+ }
8419
+ const headers = responseHeaders(set.headers);
8420
+ const statusResponse = unwrapStatusResponse(responseValue);
8421
+ const value = statusResponse?.value ?? responseValue;
8422
+ let body;
8423
+ if (value === undefined || value === null) {
8424
+ body = new Uint8Array;
8425
+ } else if (typeof value === "string") {
8426
+ headers.set("content-type", headers.get("content-type") ?? "text/plain;charset=utf-8");
8427
+ body = new TextEncoder().encode(value);
8428
+ } else {
8429
+ headers.set("content-type", headers.get("content-type") ?? "application/json");
8430
+ body = new TextEncoder().encode(JSON.stringify(value));
8431
+ }
8432
+ return {
8433
+ body,
8434
+ headers: [...headers.entries()],
8435
+ status: statusResponse?.status ?? statusCode(set.status)
8436
+ };
8437
+ }
8438
+ function replayResponse(stored) {
8439
+ const body = stored.status === 204 || stored.status === 205 || stored.status === 304 ? null : stored.body.slice();
8440
+ return new Response(body, {
8441
+ headers: new Headers(stored.headers.map(([name, value]) => [name, value])),
8442
+ status: stored.status
8443
+ });
8444
+ }
8445
+
8446
+ // src/server/sync/plugin.ts
8447
+ var routeMetadata = new WeakMap;
8448
+ var activeMutations = new WeakMap;
8449
+ function invalidationInputFromSync(input) {
8450
+ if (input && typeof input === "object" && "invalidate" in input) {
8451
+ return input.invalidate;
8452
+ }
8453
+ return input;
8454
+ }
8455
+ function isMutationMethod(method) {
8456
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
8457
+ }
8458
+ function getIdempotencyKey(ctx) {
8459
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
8460
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
8461
+ return fromCtxHeaders;
8462
+ }
8463
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
8464
+ return fromRequest || undefined;
8465
+ }
8466
+ async function getPrincipalScope(request) {
8467
+ const authorization = request.headers.get("authorization");
8468
+ const credentials = authorization ? JSON.stringify(["authorization", authorization]) : JSON.stringify(["cookie", request.headers.get("cookie") ?? ""]);
8469
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(credentials));
8470
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8471
+ }
8472
+ function supportsReplayBody(request) {
8473
+ const contentType = request.headers.get("content-type")?.toLowerCase();
8474
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
8475
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
8476
+ }
8477
+ function conflictResponse(reason) {
8478
+ const inProgress = reason === "in-progress";
8479
+ return Response.json({
8480
+ code: inProgress ? "FURIN_MUTATION_IN_PROGRESS" : "FURIN_IDEMPOTENCY_MISMATCH",
8481
+ message: inProgress ? "A mutation with this Idempotency-Key is still running." : "The Idempotency-Key was already used with a different request."
8482
+ }, {
8483
+ status: 409,
8484
+ headers: inProgress ? { "retry-after": "1" } : undefined
8485
+ });
8486
+ }
8487
+ async function beginMutation(ctx) {
8488
+ if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
8489
+ return;
8490
+ }
8491
+ const idempotencyKey = getIdempotencyKey(ctx);
8492
+ if (!idempotencyKey) {
8493
+ return new Response("Missing Idempotency-Key header", {
8494
+ status: 428,
8495
+ headers: { "content-type": "text/plain; charset=utf-8" }
8496
+ });
8497
+ }
8498
+ if (!supportsReplayBody(ctx.request)) {
8499
+ return Response.json({
8500
+ code: "FURIN_UNSUPPORTED_SYNC_BODY",
8501
+ message: "This request body cannot be replayed. Set sync: false on the route."
8502
+ }, { status: 415 });
8503
+ }
8504
+ const url = new URL(ctx.request.url);
8505
+ const principal = await getPrincipalScope(ctx.request);
8506
+ const key = `${ctx.request.method}:${url.pathname}:${idempotencyKey}`;
8507
+ const fingerprint = await createMutationFingerprint({ body: ctx.body, request: ctx.request });
8508
+ const result = await memorySyncAdapter.beginMutation({ fingerprint, key, principal });
8509
+ if (result.kind === "replay") {
8510
+ return replayResponse(result.response);
8511
+ }
8512
+ if (result.kind === "conflict") {
8513
+ return conflictResponse(result.reason);
8514
+ }
8515
+ if (result.kind === "unavailable") {
8516
+ return Response.json({
8517
+ code: "FURIN_SYNC_CAPACITY_EXCEEDED",
8518
+ message: "The mutation replay store is temporarily full."
8519
+ }, { headers: { "retry-after": "1" }, status: 503 });
8520
+ }
8521
+ activeMutations.set(ctx.request, { mutationId: result.mutationId });
8522
+ }
8523
+ async function abortMutation(request) {
8524
+ const active = activeMutations.get(request);
8525
+ if (!active) {
8526
+ return;
8527
+ }
8528
+ activeMutations.delete(request);
8529
+ await memorySyncAdapter.abortMutation(active);
8530
+ }
8531
+ function furinSync() {
8532
+ return new Elysia3({ name: "furin-sync" }).macro({
8533
+ sync(input) {
8534
+ return {
8535
+ transform({ request }) {
8536
+ routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
8537
+ }
8538
+ };
8539
+ }
8540
+ }).onBeforeHandle({ as: "global" }, beginMutation).onAfterHandle({ as: "global" }, async (ctx) => {
8541
+ const active = activeMutations.get(ctx.request);
8542
+ if (!active) {
8543
+ return;
8544
+ }
8545
+ if (!isSuccessfulMutationResponse(ctx)) {
8546
+ await abortMutation(ctx.request);
8547
+ return;
8548
+ }
8549
+ const invalidate = routeMetadata.get(ctx.request)?.invalidate;
8550
+ if (invalidate) {
8551
+ runInvalidationRules(invalidate);
8552
+ }
8553
+ const pending = appendPendingInvalidationHeader(ctx.set);
8554
+ if (pending.length > 0) {
8555
+ ctx.set.headers["x-furin-sync"] = "1";
8556
+ }
8557
+ const response = await storeResponse(ctx.responseValue, ctx.set);
8558
+ await memorySyncAdapter.commitMutation({ ...active, response });
8559
+ activeMutations.delete(ctx.request);
8560
+ if (pending.length > 0) {
8561
+ await memorySyncAdapter.appendChanges({
8562
+ invalidations: pending,
8563
+ path: getSyncStreamPath() ?? "/_furin/sync"
8564
+ });
8565
+ }
8566
+ }).onError({ as: "global" }, ({ request }) => abortMutation(request));
8567
+ }
8568
+ // src/server/sync/stream.ts
8569
+ import { Elysia as Elysia4 } from "elysia";
8570
+ var DEFAULT_CHANGE_LIMIT = 100;
8571
+ var MAX_CHANGE_LIMIT = 500;
8572
+ var CURSOR_PATTERN = /^\d+$/;
8205
8573
  var defaultStreamPath = "/_furin/sync";
8574
+ var encoder = new TextEncoder;
8206
8575
  var streams = new Map;
8576
+ function encodeSseChange(change) {
8577
+ return encoder.encode(`id: ${change.cursor}
8578
+ event: furin.sync
8579
+ retry: 3000
8580
+ data: ${JSON.stringify({ cursor: change.cursor })}
8581
+
8582
+ `);
8583
+ }
8207
8584
  function getStreamState(path) {
8208
8585
  const existing = streams.get(path);
8209
8586
  if (existing) {
@@ -8212,44 +8589,47 @@ function getStreamState(path) {
8212
8589
  const state = {
8213
8590
  clients: new Set,
8214
8591
  heartbeats: new Set,
8215
- history: [],
8216
- nextEventId: 1
8592
+ unsubscribe: undefined
8217
8593
  };
8594
+ state.unsubscribe = memorySyncAdapter.subscribe(path, (change) => {
8595
+ const chunk = encodeSseChange(change);
8596
+ for (const client of [...state.clients]) {
8597
+ try {
8598
+ client.enqueue(chunk);
8599
+ } catch {
8600
+ state.clients.delete(client);
8601
+ }
8602
+ }
8603
+ });
8218
8604
  streams.set(path, state);
8219
8605
  return state;
8220
8606
  }
8221
- function encodeSseEvent(id, event, data) {
8222
- return encoder.encode(`id: ${id}
8223
- event: ${event}
8224
- retry: 3000
8225
- data: ${JSON.stringify(data)}
8226
-
8227
- `);
8228
- }
8229
- function publishSyncInvalidation(invalidations) {
8230
- if (invalidations.length === 0) {
8231
- return;
8607
+ function parseChangeQuery(request) {
8608
+ const url = new URL(request.url);
8609
+ const after = url.searchParams.get("after") ?? undefined;
8610
+ if (after !== undefined && !CURSOR_PATTERN.test(after)) {
8611
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_CURSOR" }, { status: 400 }) };
8232
8612
  }
8233
- const state = getStreamState(getSyncStreamPath() ?? defaultStreamPath);
8234
- const id = state.nextEventId++;
8235
- const chunk = encodeSseEvent(id, "furin.invalidate", {
8236
- invalidations
8237
- });
8238
- state.history.push({ chunk, id });
8239
- if (state.history.length > 100) {
8240
- state.history.shift();
8613
+ const limitValue = url.searchParams.get("limit");
8614
+ if (limitValue !== null && !CURSOR_PATTERN.test(limitValue)) {
8615
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8241
8616
  }
8242
- for (const client of [...state.clients]) {
8243
- try {
8244
- client.enqueue(chunk);
8245
- } catch {
8246
- state.clients.delete(client);
8247
- }
8617
+ const limit = limitValue === null ? DEFAULT_CHANGE_LIMIT : Number.parseInt(limitValue, 10);
8618
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHANGE_LIMIT) {
8619
+ return { error: Response.json({ code: "FURIN_INVALID_SYNC_LIMIT" }, { status: 400 }) };
8248
8620
  }
8621
+ return { after, limit };
8249
8622
  }
8250
8623
  function createSyncStreamPlugin(path) {
8251
8624
  const streamPath = path ?? defaultStreamPath;
8252
- return new Elysia3({ name: `furin-sync-stream-${streamPath}` }).get(streamPath, ({ request }) => {
8625
+ return new Elysia4({ name: `furin-sync-stream-${streamPath}` }).get(`${streamPath}/changes`, ({ request, set }) => {
8626
+ set.headers["cache-control"] = "no-store";
8627
+ const query = parseChangeQuery(request);
8628
+ if ("error" in query) {
8629
+ return query.error;
8630
+ }
8631
+ return memorySyncAdapter.readChanges({ ...query, path: streamPath });
8632
+ }).get(streamPath, () => {
8253
8633
  const state = getStreamState(streamPath);
8254
8634
  let controllerRef;
8255
8635
  let heartbeat;
@@ -8257,24 +8637,10 @@ function createSyncStreamPlugin(path) {
8257
8637
  start(controller) {
8258
8638
  controllerRef = controller;
8259
8639
  state.clients.add(controller);
8260
- const lastEventId = Number.parseInt(request.headers.get("Last-Event-ID") ?? "", 10);
8261
- const oldestEventId = state.history[0]?.id;
8262
- const hasReplayGap = !Number.isNaN(lastEventId) && oldestEventId !== undefined && lastEventId < oldestEventId - 1;
8263
- const replay = Number.isNaN(lastEventId) ? [] : state.history.filter((entry) => entry.id > lastEventId);
8264
- if (hasReplayGap) {
8265
- controller.enqueue(encodeSseEvent(state.nextEventId - 1, "furin.invalidate", {
8266
- invalidations: ["/:layout"]
8267
- }));
8268
- } else if (replay.length > 0) {
8269
- for (const entry of replay) {
8270
- controller.enqueue(entry.chunk);
8271
- }
8272
- } else {
8273
- controller.enqueue(encoder.encode(`: connected
8640
+ controller.enqueue(encoder.encode(`: connected
8274
8641
  retry: 3000
8275
8642
 
8276
8643
  `));
8277
- }
8278
8644
  heartbeat = setInterval(() => {
8279
8645
  try {
8280
8646
  controller.enqueue(encoder.encode(`: heartbeat
@@ -8309,88 +8675,6 @@ retry: 3000
8309
8675
  });
8310
8676
  });
8311
8677
  }
8312
-
8313
- // src/server/sync/plugin.ts
8314
- function invalidationInputFromSync(input) {
8315
- if (input && typeof input === "object" && "invalidate" in input) {
8316
- return input.invalidate;
8317
- }
8318
- return input;
8319
- }
8320
- function isMutationMethod(method) {
8321
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
8322
- }
8323
- function getIdempotencyKey(ctx) {
8324
- const fromCtxHeaders = ctx.headers["idempotency-key"];
8325
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
8326
- return fromCtxHeaders;
8327
- }
8328
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
8329
- return fromRequest || undefined;
8330
- }
8331
- function furinSync() {
8332
- const idempotencyKeys = new Set;
8333
- const requestKeys = new WeakMap;
8334
- return new Elysia4({ name: "furin-sync" }).macro({
8335
- sync(input) {
8336
- const invalidate = invalidationInputFromSync(input);
8337
- return {
8338
- beforeHandle(ctx) {
8339
- if (!isMutationMethod(ctx.request.method)) {
8340
- return;
8341
- }
8342
- const key = getIdempotencyKey(ctx);
8343
- if (!key) {
8344
- return new Response("Missing Idempotency-Key header", {
8345
- status: 428,
8346
- headers: { "content-type": "text/plain; charset=utf-8" }
8347
- });
8348
- }
8349
- const requestKey = `${ctx.request.method}:${new URL(ctx.request.url).pathname}:${key}`;
8350
- if (idempotencyKeys.has(requestKey)) {
8351
- return new Response("Duplicate Idempotency-Key header", {
8352
- status: 409,
8353
- headers: { "content-type": "text/plain; charset=utf-8" }
8354
- });
8355
- }
8356
- idempotencyKeys.add(requestKey);
8357
- requestKeys.set(ctx.request, requestKey);
8358
- if (idempotencyKeys.size > 1000) {
8359
- const oldest = idempotencyKeys.values().next().value;
8360
- if (typeof oldest === "string") {
8361
- idempotencyKeys.delete(oldest);
8362
- }
8363
- }
8364
- },
8365
- afterHandle(ctx) {
8366
- if (!isSuccessfulMutationResponse(ctx)) {
8367
- const requestKey = requestKeys.get(ctx.request);
8368
- if (requestKey) {
8369
- idempotencyKeys.delete(requestKey);
8370
- requestKeys.delete(ctx.request);
8371
- }
8372
- return;
8373
- }
8374
- requestKeys.delete(ctx.request);
8375
- runInvalidationRules(invalidate);
8376
- const pending = appendPendingInvalidationHeader(ctx.set);
8377
- if (pending.length === 0) {
8378
- return;
8379
- }
8380
- ctx.set.headers["x-furin-sync"] = "1";
8381
- publishSyncInvalidation(pending);
8382
- },
8383
- error({ request }) {
8384
- const requestKey = requestKeys.get(request);
8385
- if (requestKey) {
8386
- idempotencyKeys.delete(requestKey);
8387
- requestKeys.delete(request);
8388
- }
8389
- }
8390
- };
8391
- }
8392
- });
8393
- }
8394
8678
  // src/furin.ts
8395
8679
  init_boundaries();
8396
8680
  init_client();