instant_record 0.1.0 → 0.3.0

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 (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,1692 @@
1
+ // Core worker runtime: coordinates leader election per (origin, partition), OPFS page-level
2
+ // WASI SQLite storage (with IndexedDB fallback), non-blocking outbox draining, a
3
+ // leader-elected visibility-aware SSE change stream, server-directed background history fill,
4
+ // and multi-tab RPC routing.
5
+ import { BranchManager } from "./branch-manager.js";
6
+ import { CircuitBreaker, WasmFaultError } from "./faults.js";
7
+ import { FlightRecorder } from "./flight-recorder.js";
8
+ import { advance, fresh, held, query } from "./history-fill.js";
9
+ import { redirectHeaders } from "./http-headers.js";
10
+ import { createLeaderCoordinator } from "./leader-election.js";
11
+ import { isServerAllowed, parseManifest } from "./manifest.js";
12
+ import { detectSchemaDrift, openOrRehydrate, rehydrateFromBytes, reloadOrRehydrateSnapshot } from "./schema-recovery.js";
13
+ import { resolveServerRequest, serverRoot } from "./server-request.js";
14
+ import { isValidSqliteBytes, parseShellGrant, shouldFetchShell, validateShellState } from "./shell.js";
15
+ import { openDatabaseStorage } from "./storage-backend.js";
16
+ import { createStreamLeader } from "./stream-leader.js";
17
+ import { parseRules, resolveSyncContext } from "./sync-context.js";
18
+ import { runDrain } from "./sync-drain.js";
19
+ import { nextSyncAction } from "./sync-schedule.js";
20
+
21
+ const QUIET_MS = 30;
22
+ const DRAIN_RETRY_BASE_MS = 500;
23
+ const DRAIN_RETRY_CAP_MS = 10000;
24
+
25
+ const DATABASE = "development.sqlite3";
26
+ const FILL = "history_fill";
27
+ const FILL_PAUSE_MS = 300;
28
+ const FILL_RETRY_CAP_MS = 60000;
29
+ const REVISION = "snapshot_revision";
30
+ const SCHEMA = "rails_schema_version";
31
+ const STORAGE_BACKEND = "storage_backend";
32
+
33
+ function randomHex(bytes) {
34
+ const buf = new Uint8Array(bytes);
35
+ globalThis.crypto.getRandomValues(buf);
36
+ return [...buf].map(b => b.toString(16).padStart(2, "0")).join("");
37
+ }
38
+
39
+ function parseTraceSchema(raw) {
40
+ try {
41
+ return JSON.parse(raw || "{}");
42
+ } catch {
43
+ return {};
44
+ }
45
+ }
46
+
47
+ export function createWorkerRuntime({
48
+ env = {},
49
+ AppHost,
50
+ PagedSyncOPFSFile,
51
+ openSnapshot,
52
+ withFiles,
53
+ openStorage = openDatabaseStorage,
54
+ createCoordinator = createLeaderCoordinator,
55
+ fetchImpl = (...args) => globalThis.fetch(...args),
56
+ postMessage = msg => globalThis.postMessage(msg),
57
+ origin = globalThis.location?.origin || "http://localhost",
58
+ locks = globalThis.navigator?.locks,
59
+ storageApi = globalThis.navigator?.storage,
60
+ createChannel,
61
+ compileWasm = url => WebAssembly.compileStreaming(fetchImpl(url)),
62
+ pollIntervalMs = 1000,
63
+ streamEnabled = pollIntervalMs !== 0,
64
+ streamOptions = {},
65
+ fillInitialDelayMs = 1000,
66
+ contextOf = path => resolveSyncContext(path, parseRules(env.VITE_SYNC_PARTITIONS)),
67
+ now = () => performance.now(),
68
+ } = {}) {
69
+ const manifest = parseManifest(env.VITE_MANIFEST);
70
+ const syncEndpoint = env.VITE_SYNC_ENDPOINT || "/instant_record";
71
+ const mountPath = env.VITE_MOUNT_PATH || "/instant_record";
72
+ const targetSchema = Number(env.VITE_SCHEMA_VERSION);
73
+ const legacySchema = env.VITE_SCHEMA_BASELINE;
74
+ const migrationHistory = JSON.parse(env.VITE_MIGRATION_HISTORY || "{}");
75
+ const schemaDigest = env.VITE_SCHEMA_DIGEST || "";
76
+ const shellFingerprint = env.VITE_SHELL_FINGERPRINT || "";
77
+ const shellAlways = env.VITE_SHELL_SNAPSHOT === "1";
78
+ const sourceVersion = env.VITE_SOURCE_VERSION || "";
79
+ const wasmUrl = env.VITE_WASM_URL || "/app.wasm";
80
+
81
+ // Client-side sync scope & pluggable headers (partition, auth, custom headers).
82
+ let syncScope = "";
83
+ let syncHeaders = {};
84
+ let syncContext = null;
85
+ let currentScope = "";
86
+ let localSimulation = { offline: false, latencyMs: 0, report: false };
87
+ const history = [];
88
+
89
+ let coordinator = null;
90
+ let storage = null;
91
+ let host = null;
92
+ const branches = new BranchManager();
93
+ let snapshotRevision;
94
+ let kickTimer = null;
95
+ let kickHeld = false;
96
+ let draining = null;
97
+ let localRevision = 0;
98
+ const drainRetry = { baseMs: DRAIN_RETRY_BASE_MS, capMs: DRAIN_RETRY_CAP_MS, delayMs: DRAIN_RETRY_BASE_MS };
99
+
100
+ let streamLeader = null;
101
+ let streamOpen = false;
102
+ let pageVisible = true;
103
+ let pageTornDown = false;
104
+ let pageSuspended = false;
105
+ let fillState = null;
106
+ let fillTimer = null;
107
+ let fillInFlight = false;
108
+ let fillDelayMs = FILL_PAUSE_MS;
109
+
110
+ let savedBootPayload = null;
111
+ let savedModule = null;
112
+ let dbQueue = Promise.resolve();
113
+ let snapshotOpened = false;
114
+
115
+ function isLeaderOrStandalone() {
116
+ return coordinator && (coordinator.role === "leader" || coordinator.role === "standalone");
117
+ }
118
+
119
+ function effectiveSimulation() {
120
+ if (coordinator && coordinator.role === "leader") return coordinator.effectiveSimulation();
121
+ return localSimulation;
122
+ }
123
+
124
+ function report(entry) {
125
+ const stamped = { ...entry, at: Date.now() };
126
+ history.push(stamped);
127
+ if (history.length > 150) history.shift();
128
+ if (coordinator && coordinator.role === "leader") {
129
+ if (localSimulation.report) postMessage({ type: "instant_record.debug", entry: stamped });
130
+ coordinator.notifyOthers(coordinator.workerId, { type: "instant_record.debug", entry: stamped });
131
+ } else if (localSimulation.report) {
132
+ postMessage({ type: "instant_record.debug", entry: stamped });
133
+ }
134
+ }
135
+
136
+ function emitRecordsChanged(changes = null, { excludeTabId = null } = {}) {
137
+ if (coordinator && coordinator.role === "leader") {
138
+ coordinator.broadcast({ type: "records_changed", changes }, { excludeTabId });
139
+ } else if (excludeTabId == null) {
140
+ postMessage({ type: "records_changed", changes });
141
+ }
142
+ }
143
+
144
+ function emitBranchState(state) {
145
+ if (!state) return;
146
+ const msg = { type: "instant_record.branch", state };
147
+ if (coordinator && coordinator.role === "leader") {
148
+ coordinator.broadcast(msg);
149
+ } else {
150
+ postMessage(msg);
151
+ }
152
+ }
153
+
154
+ function emitSyncNotices(notices) {
155
+ const msg = { type: "instant_record.sync_notices", notices: Array.isArray(notices) ? notices : [] };
156
+ emitToTabs(msg);
157
+ }
158
+
159
+ function emitToTabs(msg) {
160
+ if (coordinator && coordinator.role === "leader") {
161
+ coordinator.broadcast(msg);
162
+ } else {
163
+ postMessage(msg);
164
+ }
165
+ }
166
+
167
+ function stopBackgroundTimers() {
168
+ clearTimeout(kickTimer);
169
+ kickTimer = null;
170
+ kickHeld = false;
171
+ clearTimeout(fillTimer);
172
+ fillTimer = null;
173
+ streamLeader?.setCanLead?.(false);
174
+ }
175
+
176
+ const breaker = new CircuitBreaker({
177
+ maxConsecutiveFailures: 3,
178
+ onTrip: snapshot => {
179
+ stopBackgroundTimers();
180
+ console.error(`[instant_record] Circuit breaker OPEN (${snapshot.tripReason})`, snapshot);
181
+ },
182
+ });
183
+
184
+ const recorder = new FlightRecorder({
185
+ enabled: false,
186
+ schema: parseTraceSchema(env.VITE_TRACE_SCHEMA),
187
+ });
188
+
189
+ function traceMeta() {
190
+ return {
191
+ sourceVersion,
192
+ schemaVersion: targetSchema || 0,
193
+ schemaDigest,
194
+ wasmUrl,
195
+ syncEndpoint,
196
+ userAgent: globalThis.navigator?.userAgent || "",
197
+ };
198
+ }
199
+
200
+ function handleHostFault(fault) {
201
+ const { trippedNow, snapshot } = breaker.recordFault(fault);
202
+ console.error(
203
+ `[instant_record] WASM fault in ${fault.exportName} (exit=${fault.exit}, circuit=${snapshot.state}): ${fault.message}`,
204
+ fault.errors,
205
+ );
206
+ report({
207
+ kind: "fault",
208
+ path: `${fault.exportName}: ${fault.message}`,
209
+ status: "failed",
210
+ exit: fault.exit,
211
+ errors: fault.errors,
212
+ circuit: snapshot.state,
213
+ });
214
+ emitToTabs({
215
+ type: "instant_record.fault",
216
+ fault,
217
+ circuit: snapshot,
218
+ trippedNow,
219
+ traceAvailable: recorder.enabled,
220
+ });
221
+ }
222
+
223
+ function handleHostEvents(events, exportName) {
224
+ for (const event of events) {
225
+ const durationMs = typeof event.duration_ms === "number" ? Math.round(event.duration_ms) : undefined;
226
+ report({
227
+ kind: "ruby",
228
+ path: event.name || "instant_record",
229
+ status: event.payload?.exception ? "failed" : "ok",
230
+ ms: durationMs,
231
+ payload: event.payload || {},
232
+ exportName,
233
+ });
234
+ emitToTabs({
235
+ type: "instant_record.notification",
236
+ name: event.name,
237
+ payload: event.payload || {},
238
+ durationMs: event.duration_ms ?? null,
239
+ exportName,
240
+ at: Date.now(),
241
+ });
242
+ }
243
+ }
244
+
245
+ function makeHost(mod, hostEnv = {}) {
246
+ return new AppHost(mod, {
247
+ env: hostEnv,
248
+ onFault: handleHostFault,
249
+ onEvents: handleHostEvents,
250
+ onSuccess: exportName => breaker.recordSuccess(exportName),
251
+ recorder,
252
+ });
253
+ }
254
+
255
+ async function runNoticeAction(payload = { action: "list" }) {
256
+ const action = payload.action || "list";
257
+ if (action === "list") {
258
+ return withDb("readonly", () => host.notices({ action: "list" }));
259
+ }
260
+ const result = await withDb("readwrite", save => {
261
+ const resolved = host.notices(payload);
262
+ if (resolved.ok) {
263
+ localRevision++;
264
+ save();
265
+ if (action === "retry" || action === "fork") {
266
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
267
+ kickSync();
268
+ }
269
+ }
270
+ return resolved;
271
+ });
272
+ if (Array.isArray(result.notices)) emitSyncNotices(result.notices);
273
+ if (result.notified) emitRecordsChanged(result.changes);
274
+ return result;
275
+ }
276
+
277
+ function matchSyncNoticeRoute(method, path, body = "", contentType = "") {
278
+ const url = new URL(path, origin);
279
+ const base = new URL(syncEndpoint, origin).pathname.replace(/\/+$/, "") + "/sync_notices";
280
+ const pathname = url.pathname.replace(/\.json$/, "");
281
+ let verb = method.toUpperCase();
282
+ if (verb === "POST" && (!contentType || contentType.startsWith("application/x-www-form-urlencoded"))) {
283
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body || new Uint8Array());
284
+ const override = new URLSearchParams(text).get("_method");
285
+ if (override && /^delete$/i.test(override)) verb = "DELETE";
286
+ }
287
+ if (pathname === base && verb === "GET") return { action: "list", json: url.pathname.endsWith(".json") };
288
+ if (!pathname.startsWith(base + "/")) return null;
289
+ const parts = pathname.slice(base.length + 1).split("/");
290
+ const id = decodeURIComponent(parts[0] || "");
291
+ if (!id) return null;
292
+ if (parts.length === 1 && verb === "DELETE") return { action: "dismiss", id, json: url.pathname.endsWith(".json") };
293
+ if (parts.length === 2 && verb === "POST" && ["retry", "fork", "dismiss"].includes(parts[1])) {
294
+ return { action: parts[1], id, json: url.pathname.endsWith(".json") };
295
+ }
296
+ return null;
297
+ }
298
+
299
+ function parseNoticeForm(body, contentType) {
300
+ const text = typeof body === "string" ? body : new TextDecoder().decode(body || new Uint8Array());
301
+ if (contentType && contentType.includes("application/json")) {
302
+ try {
303
+ const parsed = JSON.parse(text || "{}");
304
+ return { overrides: parsed.overrides || {}, returnTo: parsed.return_to || "" };
305
+ } catch {
306
+ return { overrides: {}, returnTo: "" };
307
+ }
308
+ }
309
+ const params = new URLSearchParams(text);
310
+ const overrides = {};
311
+ for (const [key, value] of params.entries()) {
312
+ const match = /^overrides\[(.+)\]$/.exec(key);
313
+ if (match) overrides[match[1]] = value;
314
+ }
315
+ return { overrides, returnTo: params.get("return_to") || "" };
316
+ }
317
+
318
+ function handleSyncNoticeHttp(route, body, contentType, targetHost = host) {
319
+ const { overrides, returnTo } = parseNoticeForm(body, contentType);
320
+ const result = targetHost.notices(route.action === "list" ? { action: "list" } : { action: route.action, id: route.id, overrides });
321
+ const status = result.ok ? (route.json || route.action === "list" ? 200 : 303) : 422;
322
+ const headers = [];
323
+ let responseBody = "";
324
+ if (status === 303) {
325
+ const target = returnTo && returnTo.startsWith("/") && !returnTo.startsWith("//") ? returnTo : "/";
326
+ headers.push(["Location", target]);
327
+ } else {
328
+ headers.push(["Content-Type", "application/json; charset=utf-8"]);
329
+ responseBody = JSON.stringify(result);
330
+ }
331
+ return { status, headers, body: responseBody, exit: 0, errors: [], noticeResult: result };
332
+ }
333
+
334
+ function announceFill() {
335
+ if (!fillState) return;
336
+ const msg = {
337
+ type: "instant_record.history",
338
+ state: { done: fillState.done, full: fillState.full, rows: fillState.rows },
339
+ };
340
+ if (coordinator && coordinator.role === "leader") {
341
+ coordinator.broadcast(msg);
342
+ } else {
343
+ postMessage(msg);
344
+ }
345
+ }
346
+
347
+ function ensureSnapshotOpen(scope) {
348
+ if (snapshotOpened) return;
349
+ snapshotOpened = true;
350
+ openSnapshot(scope);
351
+ }
352
+
353
+ // Serialize DB operations on the leader without ever holding this lock across network I/O.
354
+ function serializeDb(fn) {
355
+ const run = dbQueue.then(fn, fn);
356
+ dbQueue = run.then(() => {}, () => {});
357
+ return run;
358
+ }
359
+
360
+ async function withDb(mode, operation) {
361
+ return serializeDb(async () => {
362
+ breaker.assertClosed("withDb");
363
+ if (!host) throw new Error("AppHost is not booted");
364
+
365
+ if (storage?.mode === "opfs") {
366
+ let dirty = false;
367
+ const metaUpdates = [];
368
+ const save = () => {
369
+ host.flushDatabase();
370
+ snapshotRevision = (snapshotRevision ?? 0) + 1;
371
+ dirty = true;
372
+ };
373
+ const putMeta = (key, value) => {
374
+ metaUpdates.push([key, value]);
375
+ };
376
+ const result = await operation(save, putMeta);
377
+ if (metaUpdates.length > 0) {
378
+ await withFiles("readwrite", async (_get, put) => {
379
+ for (const [key, value] of metaUpdates) put(key, value);
380
+ if (dirty) put(REVISION, snapshotRevision);
381
+ });
382
+ }
383
+ return result;
384
+ }
385
+
386
+ // IndexedDB fallback mode (whole-file snapshots).
387
+ let pendingPersist = null;
388
+ let needsSync = false;
389
+ try {
390
+ const result = await withFiles(mode, async (get, put) => {
391
+ const revision = await get(REVISION);
392
+ let allowSave = true;
393
+ // Only standalone (no Web Locks) needs to check for peer writes in IndexedDB.
394
+ if (coordinator?.role === "standalone" && revision !== snapshotRevision) {
395
+ const [bytes, savedSchema] = await Promise.all([get(DATABASE), get(SCHEMA)]);
396
+ const previous = host;
397
+ const recovered = reloadOrRehydrateSnapshot({
398
+ bytes,
399
+ savedSchema,
400
+ targetSchema,
401
+ createHost: () => {
402
+ const next = makeHost(previous.module, previous.env);
403
+ next.cookies = previous.cookies;
404
+ return next;
405
+ },
406
+ onReleaseRequired: () => postMessage({ type: "release_required" }),
407
+ onReport: report,
408
+ });
409
+ host = recovered.host;
410
+ if (recovered.rehydrated) breaker.reset();
411
+ localRevision++;
412
+ if (recovered.rehydrated) {
413
+ needsSync = true;
414
+ if (recovered.persist) {
415
+ const rebuiltBytes = host.databaseBytes();
416
+ if (mode === "readwrite") {
417
+ snapshotRevision = (revision ?? 0) + 1;
418
+ put(DATABASE, rebuiltBytes);
419
+ put(REVISION, snapshotRevision);
420
+ put(SCHEMA, targetSchema);
421
+ put("migration_history", migrationHistory);
422
+ put("schema_digest", schemaDigest);
423
+ put(STORAGE_BACKEND, "indexeddb");
424
+ put(FILL, null);
425
+ } else {
426
+ pendingPersist = { expectedRevision: revision, bytes: rebuiltBytes };
427
+ }
428
+ } else {
429
+ allowSave = false;
430
+ snapshotRevision = revision;
431
+ }
432
+ } else {
433
+ snapshotRevision = revision;
434
+ }
435
+ }
436
+ return operation(() => {
437
+ if (!allowSave) return;
438
+ const bytes = host.databaseBytes();
439
+ if (!bytes) throw new Error("SQLite did not produce a database snapshot");
440
+ snapshotRevision = (revision ?? 0) + 1;
441
+ put(DATABASE, bytes);
442
+ put(REVISION, snapshotRevision);
443
+ }, put);
444
+ });
445
+ if (pendingPersist) {
446
+ await withFiles("readwrite", async (get, put) => {
447
+ const currentRev = await get(REVISION);
448
+ const currentSchema = await get(SCHEMA);
449
+ if (currentRev !== pendingPersist.expectedRevision || (currentSchema != null && currentSchema > targetSchema)) {
450
+ return;
451
+ }
452
+ snapshotRevision = (currentRev ?? 0) + 1;
453
+ put(DATABASE, pendingPersist.bytes);
454
+ put(REVISION, snapshotRevision);
455
+ put(SCHEMA, targetSchema);
456
+ put("migration_history", migrationHistory);
457
+ put("schema_digest", schemaDigest);
458
+ put(STORAGE_BACKEND, "indexeddb");
459
+ put(FILL, null);
460
+ });
461
+ }
462
+ if (needsSync) kickSync(0);
463
+ return result;
464
+ } catch (error) {
465
+ if (coordinator?.role === "standalone") snapshotRevision = Symbol("reload");
466
+ throw error;
467
+ }
468
+ });
469
+ }
470
+
471
+ function buildHeaders(method, extra = {}, contentType = undefined) {
472
+ const headers = { ...syncHeaders, ...extra };
473
+ if (syncScope && !headers["X-Instant-Record-Scope"]) {
474
+ headers["X-Instant-Record-Scope"] = syncScope;
475
+ }
476
+ if (method !== "GET" && method !== "HEAD") {
477
+ const headerType = contentType === undefined ? "application/json" : contentType;
478
+ if (headerType && !headers["Content-Type"]) headers["Content-Type"] = headerType;
479
+ }
480
+ return headers;
481
+ }
482
+
483
+ async function fetchReply(method, path, body = "", endpoint = syncEndpoint, extraHeaders = {}, contentType = undefined) {
484
+ const url = endpoint + path;
485
+ const started = now();
486
+ let status = 0;
487
+ let text = "";
488
+ let responseContentType = "";
489
+ let outcome = "failed";
490
+ try {
491
+ if (coordinator?.role === "leader") await coordinator.pruneDeadPeers();
492
+ const sim = effectiveSimulation();
493
+ if (sim.latencyMs && !sim.offline) {
494
+ await new Promise(resolve => setTimeout(resolve, sim.latencyMs));
495
+ }
496
+ if (effectiveSimulation().offline) {
497
+ outcome = "offline";
498
+ return { method, url, body, status, text, contentType: responseContentType };
499
+ }
500
+ const headers = buildHeaders(method, extraHeaders, contentType);
501
+ const options = { method, signal: AbortSignal.timeout(30000) };
502
+ if (Object.keys(headers).length > 0) options.headers = headers;
503
+ if (method !== "GET" && method !== "HEAD") options.body = body;
504
+ const response = await fetchImpl(url, options);
505
+ text = await response.text();
506
+ responseContentType = response.headers?.get?.("content-type") || "";
507
+ outcome = status = response.status;
508
+ } catch {
509
+ // A failed exchange stays in the durable outbox for retry.
510
+ } finally {
511
+ report({
512
+ kind: "sync",
513
+ method,
514
+ path: new URL(url, origin).pathname,
515
+ status: outcome,
516
+ ms: Math.round(now() - started),
517
+ });
518
+ }
519
+ return { method, url, body, status, text, contentType: responseContentType };
520
+ }
521
+
522
+ function kickSync(delay = QUIET_MS, { held = false } = {}) {
523
+ if (!isLeaderOrStandalone() || breaker.isOpen() || branches.isActive()) return;
524
+ clearTimeout(kickTimer);
525
+ kickHeld = held;
526
+ kickTimer = setTimeout(syncPass, delay);
527
+ }
528
+
529
+ function clearHeldKick() {
530
+ if (kickTimer && kickHeld) {
531
+ clearTimeout(kickTimer);
532
+ kickTimer = null;
533
+ kickHeld = false;
534
+ }
535
+ }
536
+
537
+ function applySyncSchedule(action) {
538
+ if (breaker.isOpen()) return;
539
+ if (action.kind === "immediate") kickSync(action.delay);
540
+ else if (action.kind === "held") kickSync(action.delay, { held: true });
541
+ else clearHeldKick();
542
+ }
543
+
544
+ function handleOnline() {
545
+ if (!breaker.isOpen()) streamLeader?.setOnline(true);
546
+ if (!isLeaderOrStandalone() || breaker.isOpen()) return;
547
+ kickSync(0);
548
+ if (fillState && fillState.type && !fillState.done && !fillState.full) scheduleFill(0);
549
+ }
550
+
551
+ function handleOffline() {
552
+ streamLeader?.setOnline(false);
553
+ }
554
+
555
+ function syncPass() {
556
+ if (!isLeaderOrStandalone()) return Promise.resolve({ changed: false });
557
+ clearTimeout(kickTimer);
558
+ kickTimer = null;
559
+ kickHeld = false;
560
+ if (breaker.isOpen()) {
561
+ return Promise.resolve({ changed: false, fault: breaker.lastFault, circuit: breaker.snapshot() });
562
+ }
563
+ if (branches.isActive()) return Promise.resolve({ skipped: true, reason: "branched" });
564
+ if (!draining) {
565
+ const revision = localRevision;
566
+ let drainOutcome = null;
567
+ draining = drain()
568
+ .then(result => {
569
+ drainOutcome = result;
570
+ return result;
571
+ })
572
+ .catch(error => {
573
+ if (error instanceof WasmFaultError || breaker.isOpen()) {
574
+ drainOutcome = { changed: false, fault: error.fault || breaker.lastFault, circuit: breaker.snapshot() };
575
+ return drainOutcome;
576
+ }
577
+ throw error;
578
+ })
579
+ .finally(() => {
580
+ draining = null;
581
+ if (!breaker.isOpen() && revision !== localRevision && !kickTimer) kickSync();
582
+ if (!breaker.isOpen() && drainOutcome && !drainOutcome.skipped && !drainOutcome.fault) {
583
+ if (drainOutcome.bootstrappedNow) streamLeader?.reconnect();
584
+ else if (drainOutcome.pending === 0) streamLeader?.wake();
585
+ }
586
+ });
587
+ }
588
+ return draining;
589
+ }
590
+
591
+ async function drain(initial = false, early = null) {
592
+ if (breaker.isOpen()) return { changed: false, fault: breaker.lastFault, circuit: breaker.snapshot() };
593
+ if (branches.isActive()) return { changed: false, skipped: true };
594
+ let hadBootstrap = false;
595
+ const result = await runDrain({
596
+ withSnapshot: (mode, op) => withDb(mode, (save, put) => op(() => {
597
+ localRevision++;
598
+ save();
599
+ }, put)),
600
+ fetchReply,
601
+ getHost: () => host,
602
+ syncEndpoint,
603
+ initial,
604
+ early,
605
+ report,
606
+ setCursor: cursor => { if (cursor === null) hadBootstrap = true; },
607
+ onBootstrapFill: (descriptor, put) => {
608
+ fillState = fresh(descriptor);
609
+ put?.(FILL, fillState);
610
+ },
611
+ onRecordsChanged: changedRecords => emitRecordsChanged(changedRecords),
612
+ onSyncNotices: notices => emitSyncNotices(notices),
613
+ scheduleRetry: delay => { if (!breaker.isOpen()) kickSync(delay); },
614
+ scheduleHeld: delay => { if (!breaker.isOpen()) applySyncSchedule({ kind: "held", delay }); },
615
+ onIdle: () => applySyncSchedule({ kind: "idle" }),
616
+ retryState: drainRetry,
617
+ });
618
+ const bootstrappedNow = hadBootstrap && !breaker.isOpen() && !result.fault && !!host?.syncState?.().bootstrapped;
619
+ return { ...result, bootstrappedNow };
620
+ }
621
+
622
+ async function readStreamParams() {
623
+ if (!isLeaderOrStandalone() || !host || breaker.isOpen() || draining || (kickTimer && !kickHeld)) return { ready: false };
624
+ const state = await withDb("readonly", () => host.syncState());
625
+ if (state.fault || (state.exit !== undefined && state.exit !== 0)) return { ready: false };
626
+ const action = nextSyncAction(state, 0);
627
+ if (action.kind === "immediate") {
628
+ if (!draining && (!kickTimer || kickHeld)) kickSync(0);
629
+ return { ready: false };
630
+ }
631
+ applySyncSchedule(action);
632
+ return { ready: true, cursor: state.cursor, identity: state.identity };
633
+ }
634
+
635
+ async function applyStreamFrames(framesText) {
636
+ if (draining) await draining.catch(() => {});
637
+ if (!isLeaderOrStandalone() || !host || breaker.isOpen()) return { applied: 0, cursor: 0, reset: false };
638
+ const outcome = await withDb("readwrite", save => {
639
+ const previousState = host.syncState();
640
+ if (previousState.fault || (previousState.exit !== undefined && previousState.exit !== 0)) {
641
+ return { applied: 0, cursor: 0, reset: false, changes: null, notify: false, syncNotices: null, fault: previousState.fault };
642
+ }
643
+ const previousCursor = previousState.cursor;
644
+ const consumed = host.consumeStream(framesText);
645
+ if (consumed.fault || (consumed.exit !== undefined && consumed.exit !== 0)) {
646
+ if (coordinator?.role === "standalone") snapshotRevision = Symbol("reload");
647
+ return { applied: 0, cursor: previousCursor, reset: false, changes: null, notify: false, syncNotices: null, fault: consumed.fault };
648
+ }
649
+ const reset = !consumed.bootstrapped;
650
+ const notify = consumed.applied > 0 || consumed.notified || reset;
651
+ const syncNotices = consumed.notices?.length && typeof host.notices === "function"
652
+ ? host.notices({ action: "list" }).notices
653
+ : null;
654
+ if (notify || consumed.cursor > previousCursor) {
655
+ localRevision++;
656
+ save();
657
+ }
658
+ return { applied: consumed.applied, cursor: consumed.cursor, reset, changes: notify ? consumed.changes : null, notify, syncNotices };
659
+ });
660
+ if (outcome.fault) return outcome;
661
+ if (outcome.syncNotices) emitSyncNotices(outcome.syncNotices);
662
+ if (outcome.reset && !breaker.isOpen()) kickSync(0);
663
+ if (outcome.notify) {
664
+ if (branches.isActive()) {
665
+ emitBranchState(branches.noteMainDelta(outcome.applied || 1));
666
+ } else {
667
+ emitRecordsChanged(outcome.changes);
668
+ }
669
+ }
670
+ return outcome;
671
+ }
672
+
673
+ function ensureStreamLeader() {
674
+ if (!streamEnabled || streamLeader) return;
675
+ streamLeader = createStreamLeader({
676
+ ...streamOptions,
677
+ getEndpoint: () => syncEndpoint,
678
+ mailboxScope: currentScope,
679
+ getSyncScope: () => syncScope,
680
+ getHeaders: () => buildHeaders("GET"),
681
+ initialVisible: pageVisible,
682
+ canLead: false,
683
+ locks,
684
+ ...(createChannel ? { createChannel } : {}),
685
+ fetch: fetchImpl,
686
+ isOfflineSimulated: () => effectiveSimulation().offline,
687
+ getLatencyMs: () => effectiveSimulation().latencyMs,
688
+ getStreamParams: readStreamParams,
689
+ applyFrames: applyStreamFrames,
690
+ onReport: entry => report(entry),
691
+ onStreamStateChange: open => {
692
+ streamOpen = open;
693
+ const msg = { type: "instant_record.stream_state", streamOpen: open };
694
+ if (coordinator && coordinator.role === "leader") {
695
+ coordinator.broadcast(msg);
696
+ } else {
697
+ postMessage(msg);
698
+ }
699
+ },
700
+ });
701
+ if (!pageTornDown) {
702
+ streamLeader.start();
703
+ if (pageSuspended) streamLeader.suspend();
704
+ }
705
+ }
706
+
707
+ async function loadHistory(request) {
708
+ breaker.assertClosed("loadHistory");
709
+ const state = fillState?.done ? fillState : await withFiles("readonly", get => get(FILL));
710
+ if (held(state) && (!state.type || !request.type || state.type === request.type)) {
711
+ return { ok: true, applied: 0, has_more: false };
712
+ }
713
+ const params = new URLSearchParams();
714
+ if (request.type) params.set("type", request.type);
715
+ if (request.search) params.set("search", request.search);
716
+ if (request.before) {
717
+ params.set("before_created_at", request.before.created_at);
718
+ params.set("before_id", request.before.id);
719
+ params.set("limit", String(request.limit));
720
+ }
721
+ if (request.partition != null) params.set("partition", request.partition);
722
+ return loadHistoryQuery(params.toString());
723
+ }
724
+
725
+ function scheduleFill(delay = fillDelayMs) {
726
+ if (!isLeaderOrStandalone() || breaker.isOpen()) return;
727
+ clearTimeout(fillTimer);
728
+ fillTimer = setTimeout(runFill, delay);
729
+ }
730
+
731
+ async function fillStep() {
732
+ if (breaker.isOpen()) return false;
733
+ fillState = await withFiles("readonly", get => get(FILL));
734
+ if (!fillState || !fillState.type) return false;
735
+ announceFill();
736
+ if (fillState.done || fillState.full) return false;
737
+ if (effectiveSimulation().offline || draining || (kickTimer && !kickHeld) || branches.isActive()) return true;
738
+
739
+ const key = query(fillState, fillState.pageSize);
740
+ const revision = localRevision;
741
+ const reply = await fetchReply("GET", "/records?" + key);
742
+ if (reply.status !== 200) {
743
+ fillDelayMs = Math.min(Math.max(fillDelayMs, 1000) * 2, FILL_RETRY_CAP_MS);
744
+ return true;
745
+ }
746
+ const page = JSON.parse(reply.text);
747
+ const applied = await withDb("readwrite", (save, put) => {
748
+ if (revision !== localRevision) return false;
749
+ host.history(key, reply.text);
750
+ const dbBytes = host.databaseSize();
751
+ const budget = storage?.fillBudgetBytes ?? (24 * 1024 * 1024);
752
+ fillState = advance(fillState, page, dbBytes, budget);
753
+ localRevision++;
754
+ put(FILL, fillState);
755
+ save();
756
+ return true;
757
+ });
758
+ if (!applied) return true;
759
+ fillDelayMs = FILL_PAUSE_MS;
760
+ announceFill();
761
+ const more = !(fillState.done || fillState.full);
762
+ if (!more) emitRecordsChanged(null);
763
+ return more;
764
+ }
765
+
766
+ async function runFill() {
767
+ if (!isLeaderOrStandalone() || fillInFlight || breaker.isOpen()) return;
768
+ fillInFlight = true;
769
+ let more = true;
770
+ try {
771
+ more = await fillStep();
772
+ } catch (error) {
773
+ if (breaker.isOpen() || error instanceof WasmFaultError) {
774
+ more = !breaker.isOpen();
775
+ } else {
776
+ fillDelayMs = Math.min(Math.max(fillDelayMs, 1000) * 2, FILL_RETRY_CAP_MS);
777
+ }
778
+ } finally {
779
+ fillInFlight = false;
780
+ }
781
+ if (more && isLeaderOrStandalone() && !breaker.isOpen()) {
782
+ scheduleFill(effectiveSimulation().offline ? 2000 : fillDelayMs);
783
+ }
784
+ }
785
+
786
+ async function loadHistoryQuery(key) {
787
+ let result;
788
+ for (let attempt = 0; attempt < 4; attempt++) {
789
+ const local = await withDb("readonly", () => host.history(key));
790
+ if (local.ok) return local;
791
+ const revision = localRevision;
792
+ const reply = await fetchReply("GET", "/records?" + key);
793
+ if (reply.status !== 200) return { ok: false, error: "History unavailable" };
794
+ result = await withDb("readwrite", save => {
795
+ if (revision !== localRevision) return { ok: false, busy: true };
796
+ const applied = host.history(key, reply.text);
797
+ localRevision++;
798
+ save();
799
+ return applied;
800
+ });
801
+ if (!result.busy) return result;
802
+ }
803
+ return result;
804
+ }
805
+
806
+ async function runRequest(method, render, { tabId = null } = {}) {
807
+ const writing = method !== "GET" && method !== "HEAD";
808
+ if (branches.isActive()) {
809
+ const result = render(branches.host());
810
+ const fault = result?.fault ?? result?.result?.fault ?? null;
811
+ if (writing && !fault) emitBranchState(branches.inspect());
812
+ return result;
813
+ }
814
+ const result = await withDb(writing ? "readwrite" : "readonly", save => {
815
+ const rendered = render(host);
816
+ const fault = rendered?.fault ?? rendered?.result?.fault ?? null;
817
+ if (fault) {
818
+ if (coordinator?.role === "standalone") snapshotRevision = Symbol("reload");
819
+ } else if (writing) {
820
+ localRevision++;
821
+ save();
822
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
823
+ applySyncSchedule(nextSyncAction(host.syncState(), QUIET_MS));
824
+ }
825
+ return rendered;
826
+ });
827
+ const fault = result?.fault ?? result?.result?.fault ?? null;
828
+ if (writing && !fault) {
829
+ // Peer tabs receive typed row deltas when the write recorded them,
830
+ // degrading cleanly to null (wildcard) when unlisted.
831
+ const deltaChanges = result?.notified ? result.changes : null;
832
+ emitRecordsChanged(deltaChanges, { excludeTabId: tabId });
833
+ }
834
+ return result;
835
+ }
836
+
837
+ function localRequest(method, path, options, targetHost = host) {
838
+ breaker.assertClosed("request");
839
+ const started = now();
840
+ const noticeRoute = matchSyncNoticeRoute(method, path, options?.body, options?.contentType);
841
+ const result = noticeRoute
842
+ ? handleSyncNoticeHttp(noticeRoute, options?.body, options?.contentType, targetHost)
843
+ : targetHost.request(method, path, options);
844
+ if (result.noticeResult && Array.isArray(result.noticeResult.notices)) {
845
+ emitSyncNotices(result.noticeResult.notices);
846
+ }
847
+ report({ kind: "local", method, path, status: result.fault ? "failed" : result.status, ms: Math.round(now() - started) });
848
+ return result;
849
+ }
850
+
851
+ function navigate({ method, path, body, contentType, headers }, targetHost = host) {
852
+ const started = now();
853
+ let result = localRequest(
854
+ method,
855
+ path,
856
+ { body: body ?? "", contentType: contentType || "application/x-www-form-urlencoded", headers },
857
+ targetHost,
858
+ );
859
+ const notified = result.notified;
860
+ const writeChanges = result.changes;
861
+ let redirected = false;
862
+ let finalPath = path;
863
+ const followHeaders = redirectHeaders(headers);
864
+ for (let hops = 0; hops < 5 && !result.fault && result.status >= 300 && result.status < 400; hops++) {
865
+ const location = result.headers.find(([name]) => name.toLowerCase() === "location")?.[1];
866
+ if (!location) break;
867
+ const next = new URL(location, origin);
868
+ finalPath = next.pathname + next.search;
869
+ redirected = true;
870
+ result = localRequest("GET", finalPath, { headers: followHeaders }, targetHost);
871
+ }
872
+ return { result: { ...result, ms: now() - started }, redirected, finalPath, notified, changes: writeChanges };
873
+ }
874
+
875
+ async function fetchShell(context, path, hasExistingDb) {
876
+ if (hasExistingDb || !shouldFetchShell({
877
+ path,
878
+ fingerprint: shellFingerprint,
879
+ always: shellAlways,
880
+ offline: effectiveSimulation().offline,
881
+ blocked: context ? !context.valid : false,
882
+ })) {
883
+ return null;
884
+ }
885
+ const started = now();
886
+ try {
887
+ const root = context?.shellPath ? serverRoot(syncEndpoint, mountPath) : syncEndpoint;
888
+ const grantPath = `${context?.shellPath || "/shell"}?fingerprint=${encodeURIComponent(shellFingerprint)}`;
889
+ const grant = await fetchReply("GET", grantPath, "", root);
890
+ if (grant.status !== 200) return null;
891
+ const parsed = parseShellGrant(grant.text);
892
+ if (!parsed) return null;
893
+ const response = await fetchImpl(root + parsed.path, {
894
+ headers: buildHeaders("GET"),
895
+ signal: AbortSignal.timeout(30000),
896
+ cache: "no-store",
897
+ });
898
+ if (!response.ok) return null;
899
+ const bytes = new Uint8Array(await response.arrayBuffer());
900
+ if (!isValidSqliteBytes(bytes)) return null;
901
+ return { bytes, cursor: parsed.cursor, identity: parsed.identity, fill: parsed.fill, ms: now() - started };
902
+ } catch {
903
+ return null;
904
+ }
905
+ }
906
+
907
+ async function earlyBootstrap(context, path, hasExistingMeta) {
908
+ if (hasExistingMeta || shouldFetchShell({
909
+ path,
910
+ fingerprint: shellFingerprint,
911
+ always: shellAlways,
912
+ offline: effectiveSimulation().offline,
913
+ blocked: context ? !context.valid : false,
914
+ })) {
915
+ return null;
916
+ }
917
+ try {
918
+ return await fetchReply("GET", "/bootstrap");
919
+ } catch {
920
+ return null;
921
+ }
922
+ }
923
+
924
+ async function openLeaderDatabase(module, { context, scope, path, promoted }) {
925
+ ensureSnapshotOpen(scope);
926
+ const storageStart = now();
927
+ storage = await openStorage(scope, {
928
+ storage: storageApi,
929
+ createFile: handle => new PagedSyncOPFSFile(handle),
930
+ });
931
+
932
+ const meta = await withFiles("readonly", async get => {
933
+ const [legacyBytes, version, revision, savedSecret, savedHistory, previousDigest, savedBackend, savedFill] = await Promise.all([
934
+ get(DATABASE), get(SCHEMA), get(REVISION), get("secret_key_base"),
935
+ get("migration_history"), get("schema_digest"), get(STORAGE_BACKEND), get(FILL),
936
+ ]);
937
+ return { legacyBytes, version, revision, savedSecret, savedHistory, previousDigest, savedBackend, savedFill };
938
+ });
939
+ const storageMs = now() - storageStart;
940
+
941
+ const orphanOpfs = storage.mode === "opfs" && storage.hasDatabase() &&
942
+ meta.version == null && meta.revision == null && meta.savedBackend == null;
943
+ if (orphanOpfs) storage.truncate(0);
944
+
945
+ const hasExistingDb = storage.mode === "opfs"
946
+ ? (storage.hasDatabase() || !!meta.legacyBytes)
947
+ : !!meta.legacyBytes;
948
+
949
+ // On failover promotion, the DB already exists — never fetch a fresh shell or bootstrap.
950
+ const shellFetch = promoted ? Promise.resolve(null) : fetchShell(context, path, hasExistingDb);
951
+ const bootstrapFetch = promoted ? Promise.resolve(null) : earlyBootstrap(context, path, hasExistingDb || meta.version != null);
952
+
953
+ let shell = await shellFetch;
954
+ let runtimeMs = 0;
955
+
956
+ const openOnce = async () => {
957
+ if (storage.mode === "opfs") {
958
+ let opfsHasBytes = storage.hasDatabase();
959
+ let migratedFromIdb = false;
960
+ let version = meta.version;
961
+ let previousDigest = meta.previousDigest;
962
+ let savedHistory = meta.savedHistory;
963
+
964
+ if (!opfsHasBytes && meta.legacyBytes) {
965
+ storage.writeAllBytes(meta.legacyBytes);
966
+ opfsHasBytes = true;
967
+ migratedFromIdb = true;
968
+ } else if (!opfsHasBytes && !meta.legacyBytes && meta.savedBackend === "opfs") {
969
+ // OPFS was cleared externally while IDB metadata remained; start cleanly.
970
+ version = null;
971
+ previousDigest = null;
972
+ savedHistory = null;
973
+ }
974
+
975
+ const existing = opfsHasBytes;
976
+ const secret = meta.savedSecret || randomHex(64);
977
+ const createHost = () => makeHost(module, { SECRET_KEY_BASE: secret });
978
+ const drift = detectSchemaDrift({
979
+ bytes: existing ? new Uint8Array([1]) : null,
980
+ version,
981
+ targetSchema,
982
+ legacySchema,
983
+ history: savedHistory,
984
+ migrationHistory,
985
+ previousDigest,
986
+ schemaDigest,
987
+ });
988
+
989
+ let candidate;
990
+ let restoredOpfs = existing;
991
+ let rehydrated = null;
992
+ let fromShell = !existing && !!shell;
993
+
994
+ const rehydrateOpfs = (oldBytes, reason) => {
995
+ shell = null;
996
+ fromShell = false;
997
+ const outcome = rehydrateFromBytes({
998
+ bytes: oldBytes,
999
+ reason,
1000
+ createHost,
1001
+ prepareFresh: freshHost => {
1002
+ storage.truncate(0);
1003
+ freshHost.mountDatabase(storage.file, targetSchema);
1004
+ },
1005
+ onReport: report,
1006
+ });
1007
+ candidate = outcome.host;
1008
+ runtimeMs = outcome.runtimeMs;
1009
+ restoredOpfs = false;
1010
+ rehydrated = outcome.rehydrated;
1011
+ };
1012
+
1013
+ if (drift) {
1014
+ rehydrateOpfs(existing ? storage.readAllBytes() : null, drift);
1015
+ } else {
1016
+ const previous = version ?? Number(legacySchema);
1017
+ candidate = createHost();
1018
+ // Back up bytes ONLY when a schema migration is about to mutate an existing OPFS DB.
1019
+ const migrationBackup = existing && previous < targetSchema ? storage.readAllBytes() : null;
1020
+ if (fromShell) storage.writeAllBytes(shell.bytes);
1021
+
1022
+ candidate.mountDatabase(storage.file, fromShell ? targetSchema : (existing ? previous : targetSchema));
1023
+ const initStart = now();
1024
+ try {
1025
+ candidate.ensureBooted();
1026
+ runtimeMs = now() - initStart;
1027
+ if (fromShell) {
1028
+ const state = candidate.syncState();
1029
+ if (!validateShellState(state, shell)) {
1030
+ throw new Error("The shell does not match its grant.");
1031
+ }
1032
+ if (shell.fill) fillState = fresh(shell.fill);
1033
+ } else {
1034
+ shell = null;
1035
+ if (meta.savedFill) fillState = meta.savedFill;
1036
+ }
1037
+ } catch (error) {
1038
+ if (existing) {
1039
+ try {
1040
+ rehydrateOpfs(migrationBackup || storage.readAllBytes(), "migration_failed");
1041
+ } catch (rehydrateError) {
1042
+ if (migrationBackup) storage.writeAllBytes(migrationBackup);
1043
+ throw rehydrateError;
1044
+ }
1045
+ } else {
1046
+ if (fromShell || !existing) storage.truncate(0);
1047
+ throw error;
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ candidate.flushDatabase();
1053
+ const needsMetaWrite = !meta.savedSecret || fromShell || !!rehydrated || version !== targetSchema ||
1054
+ !previousDigest || migratedFromIdb || meta.savedBackend !== "opfs";
1055
+
1056
+ snapshotRevision = meta.revision ?? 0;
1057
+ if (needsMetaWrite) {
1058
+ snapshotRevision = (meta.revision ?? 0) + 1;
1059
+ await withFiles("readwrite", async (_get, put, del) => {
1060
+ if (!meta.savedSecret) put("secret_key_base", secret);
1061
+ if (fromShell && shell.fill) put(FILL, fillState);
1062
+ put(REVISION, snapshotRevision);
1063
+ put(SCHEMA, targetSchema);
1064
+ put("migration_history", migrationHistory);
1065
+ put("schema_digest", schemaDigest);
1066
+ put(STORAGE_BACKEND, "opfs");
1067
+ if (rehydrated) put(FILL, null);
1068
+ // Reclaim legacy whole-file IDB snapshot once OPFS boot succeeds.
1069
+ if (migratedFromIdb || meta.legacyBytes) del(DATABASE);
1070
+ });
1071
+ }
1072
+ host = candidate;
1073
+ return { restored: restoredOpfs, rehydrated };
1074
+ }
1075
+
1076
+ // IndexedDB fallback path (whole-file transaction).
1077
+ return withFiles("readwrite", async (get, put) => {
1078
+ const [bytes, version, revision, savedSecret, savedHistory, previousDigest, savedFill] = await Promise.all([
1079
+ get(DATABASE), get(SCHEMA), get(REVISION), get("secret_key_base"),
1080
+ get("migration_history"), get("schema_digest"), get(FILL),
1081
+ ]);
1082
+ const secret = savedSecret || randomHex(64);
1083
+ if (!savedSecret) put("secret_key_base", secret);
1084
+ const outcome = openOrRehydrate({
1085
+ bytes,
1086
+ version,
1087
+ targetSchema,
1088
+ legacySchema,
1089
+ history: savedHistory,
1090
+ migrationHistory,
1091
+ previousDigest,
1092
+ schemaDigest,
1093
+ shell,
1094
+ createHost: () => makeHost(module, { SECRET_KEY_BASE: secret }),
1095
+ onReport: report,
1096
+ });
1097
+ const candidate = outcome.host;
1098
+ runtimeMs = outcome.runtimeMs;
1099
+ if (outcome.fromShell) {
1100
+ const state = candidate.syncState();
1101
+ if (!validateShellState(state, shell)) {
1102
+ throw new Error("The shell does not match its grant.");
1103
+ }
1104
+ if (shell.fill) {
1105
+ fillState = fresh(shell.fill);
1106
+ put(FILL, fillState);
1107
+ }
1108
+ } else {
1109
+ shell = null;
1110
+ if (savedFill) fillState = savedFill;
1111
+ }
1112
+ snapshotRevision = revision;
1113
+ if (outcome.fromShell || outcome.rehydrated || version !== targetSchema || !previousDigest) {
1114
+ snapshotRevision = (revision ?? 0) + 1;
1115
+ put(DATABASE, candidate.databaseBytes());
1116
+ put(REVISION, snapshotRevision);
1117
+ put(SCHEMA, targetSchema);
1118
+ put("migration_history", migrationHistory);
1119
+ put("schema_digest", schemaDigest);
1120
+ put(STORAGE_BACKEND, "indexeddb");
1121
+ if (outcome.rehydrated) put(FILL, null);
1122
+ }
1123
+ host = candidate;
1124
+ return { restored: outcome.restored, rehydrated: outcome.rehydrated };
1125
+ });
1126
+ };
1127
+
1128
+ let opened;
1129
+ try {
1130
+ try {
1131
+ opened = await openOnce();
1132
+ } catch (error) {
1133
+ if (!shell) throw error;
1134
+ report({ kind: "sync", method: "GET", path: "/shell", status: "rejected", ms: Math.round(shell.ms) });
1135
+ shell = null;
1136
+ breaker.reset();
1137
+ opened = await openOnce();
1138
+ }
1139
+ } catch (error) {
1140
+ // Release the OPFS sync handle if boot or schema validation fails.
1141
+ storage?.close();
1142
+ storage = null;
1143
+ throw error;
1144
+ }
1145
+
1146
+ const { restored, rehydrated } = opened;
1147
+ if (rehydrated) breaker.reset();
1148
+ if (recorder.enabled && !restored && !shell && host && typeof host.snapshotForRecorder === "function") {
1149
+ recorder.captureCheckpoint(host.snapshotForRecorder());
1150
+ }
1151
+ const bootstrapStart = now();
1152
+ if (!restored && !shell && !breaker.isOpen()) await drain(true, rehydrated ? null : await bootstrapFetch);
1153
+ if (restored && !breaker.isOpen()) {
1154
+ const state = host.syncState();
1155
+ if (!state.fault && (state.exit === undefined || state.exit === 0)) {
1156
+ applySyncSchedule(nextSyncAction(state, 0));
1157
+ }
1158
+ }
1159
+ ensureStreamLeader();
1160
+ if (!breaker.isOpen()) streamLeader?.setCanLead(true);
1161
+ const bootstrapMs = now() - bootstrapStart;
1162
+
1163
+ if (!breaker.isOpen() && fillState && fillState.type && !fillState.done && !fillState.full) {
1164
+ scheduleFill(fillInitialDelayMs);
1165
+ } else if (fillState) {
1166
+ announceFill();
1167
+ }
1168
+
1169
+ return {
1170
+ restored,
1171
+ rehydrated,
1172
+ storageMs,
1173
+ runtimeMs,
1174
+ bootstrapMs,
1175
+ storageMode: storage.mode,
1176
+ shell: shell ? { ms: shell.ms, bytes: shell.bytes.length, cursor: shell.cursor } : null,
1177
+ };
1178
+ }
1179
+
1180
+ async function preloadPathHistory(context) {
1181
+ if (!context?.valid) return;
1182
+ for (const id of context.lookupIds) {
1183
+ await loadHistoryQuery(new URLSearchParams({ id }).toString());
1184
+ }
1185
+ if (context.preloadBefore) {
1186
+ await loadHistory(context.preloadBefore);
1187
+ }
1188
+ }
1189
+
1190
+ async function handleServerRequest(payload) {
1191
+ const targetPath = resolveServerRequest(payload.path, origin);
1192
+ const method = (payload.method || "GET").toUpperCase();
1193
+ const pathname = new URL(targetPath, origin).pathname;
1194
+ if (manifest.mode === "island" && !isServerAllowed(manifest, method, pathname, syncEndpoint)) {
1195
+ throw new Error(`Disallowed server action: ${method} ${pathname}`);
1196
+ }
1197
+ const root = serverRoot(syncEndpoint, mountPath);
1198
+ const body = typeof payload.body === "string" ? payload.body : "";
1199
+ const reply = await fetchReply(method, targetPath, body, root, {}, payload.contentType ?? "");
1200
+ if (method !== "GET" && method !== "HEAD" && reply.status >= 200 && reply.status < 400) {
1201
+ streamLeader?.reconnect();
1202
+ }
1203
+ return reply;
1204
+ }
1205
+
1206
+ async function wipeLocalStorage() {
1207
+ streamLeader?.stop();
1208
+ streamLeader = null;
1209
+ clearTimeout(kickTimer);
1210
+ clearTimeout(fillTimer);
1211
+ kickTimer = null;
1212
+ kickHeld = false;
1213
+ fillTimer = null;
1214
+ host = null;
1215
+ if (storage) {
1216
+ await storage.wipe();
1217
+ storage = null;
1218
+ }
1219
+ coordinator?.close({ announceBye: true });
1220
+ return { ok: true };
1221
+ }
1222
+
1223
+ async function handleLeaderRpc(method, payload, { tabId }) {
1224
+ if (method === "boot_tab") {
1225
+ if (payload?.syncScope && !syncScope) syncScope = payload.syncScope;
1226
+ if (payload?.syncHeaders && typeof payload.syncHeaders === "object") {
1227
+ syncHeaders = { ...syncHeaders, ...payload.syncHeaders };
1228
+ }
1229
+ if (payload?.trace && !recorder.enabled) {
1230
+ recorder.configure({
1231
+ enabled: true,
1232
+ ...(typeof payload.trace === "object" ? payload.trace : {}),
1233
+ meta: traceMeta(),
1234
+ });
1235
+ if (host && typeof host.snapshotForRecorder === "function") {
1236
+ recorder.captureCheckpoint(host.snapshotForRecorder());
1237
+ }
1238
+ }
1239
+ const tabContext = payload?.path ? contextOf(payload.path) : syncContext;
1240
+ if (!breaker.isOpen()) await preloadPathHistory(tabContext);
1241
+ const first = payload?.path && !breaker.isOpen()
1242
+ ? await runRequest("GET", target => navigate({ method: "GET", path: payload.path, headers: payload.headers }, target), { tabId })
1243
+ : null;
1244
+ return {
1245
+ first,
1246
+ storageMode: storage?.mode || "indexeddb",
1247
+ fillState: fillState ? { done: fillState.done, full: fillState.full, rows: fillState.rows } : null,
1248
+ circuit: breaker.snapshot(),
1249
+ };
1250
+ }
1251
+ if (method === "configure_headers") {
1252
+ if (payload && typeof payload === "object") {
1253
+ syncHeaders = { ...syncHeaders, ...payload };
1254
+ }
1255
+ return { ok: true };
1256
+ }
1257
+ if (method === "navigate") {
1258
+ return runRequest(payload.method, target => navigate(payload, target), { tabId });
1259
+ }
1260
+ if (method === "request") {
1261
+ const started = now();
1262
+ const result = await runRequest(
1263
+ payload.method,
1264
+ target => localRequest(payload.method, payload.path, {
1265
+ body: payload.body ?? "",
1266
+ contentType: payload.contentType || "application/x-www-form-urlencoded",
1267
+ headers: payload.headers,
1268
+ }, target),
1269
+ { tabId },
1270
+ );
1271
+ return { ...result, ms: now() - started };
1272
+ }
1273
+ if (method === "branch.create") {
1274
+ const state = await withDb("readonly", () => branches.fork({
1275
+ name: payload?.name,
1276
+ mainHost: host,
1277
+ schemaVersion: targetSchema,
1278
+ createHost: (bytes, version, branchName) => {
1279
+ const staged = makeHost(host.module, { ...host.env, INSTANT_RECORD_BRANCH: branchName });
1280
+ staged.cookies = new Map(host.cookies);
1281
+ staged.restoreDatabase(bytes, version);
1282
+ return staged;
1283
+ },
1284
+ }));
1285
+ report({ kind: "branch", method: "FORK", path: state.name, status: "staged" });
1286
+ emitBranchState(state);
1287
+ return state;
1288
+ }
1289
+ if (method === "branch.status") {
1290
+ return branches.inspect();
1291
+ }
1292
+ if (method === "branch.approve") {
1293
+ const result = await branches.approve({
1294
+ conflict: payload?.conflict || "lww",
1295
+ onMain: (mutations, conflict) => withDb("readwrite", save => {
1296
+ const replay = host.branchReplay(mutations, { conflict });
1297
+ if (replay.applied > 0) {
1298
+ localRevision++;
1299
+ save();
1300
+ }
1301
+ return replay;
1302
+ }),
1303
+ });
1304
+ const postApproveState = host.syncState();
1305
+ if (result.applied > 0 || postApproveState.pending > 0 || postApproveState.nextReleaseMs != null) {
1306
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
1307
+ applySyncSchedule(nextSyncAction(result.applied > 0 ? { ...postApproveState, pending: Math.max(postApproveState.pending, 1) } : postApproveState, 0));
1308
+ }
1309
+ report({ kind: "branch", method: "APPROVE", path: `${result.name} (${result.applied} applied, ${result.skipped} skipped)`, status: 200 });
1310
+ emitBranchState({ active: false, lastAction: result });
1311
+ emitRecordsChanged(result.changes || null);
1312
+ return result;
1313
+ }
1314
+ if (method === "branch.discard") {
1315
+ const result = branches.discard();
1316
+ const postDiscardState = host.syncState();
1317
+ if (postDiscardState.pending > 0 || postDiscardState.nextReleaseMs != null) {
1318
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
1319
+ applySyncSchedule(nextSyncAction(postDiscardState, 0));
1320
+ }
1321
+ report({ kind: "branch", method: "DISCARD", path: `${result.name} (${result.dropped} dropped)`, status: 200 });
1322
+ emitBranchState({ active: false, lastAction: result });
1323
+ emitRecordsChanged(null);
1324
+ return result;
1325
+ }
1326
+ if (method === "fetch_history") {
1327
+ return loadHistory(payload);
1328
+ }
1329
+ if (method === "save") {
1330
+ return withDb("readwrite", save => save());
1331
+ }
1332
+ if (method === "sync") {
1333
+ return syncPass();
1334
+ }
1335
+ if (method === "notices") {
1336
+ return runNoticeAction(payload || { action: "list" });
1337
+ }
1338
+ if (method === "serverRequest") {
1339
+ return handleServerRequest(payload);
1340
+ }
1341
+ if (method === "wipe") {
1342
+ return wipeLocalStorage();
1343
+ }
1344
+ if (method === "reset_circuit") {
1345
+ breaker.reset();
1346
+ if (coordinator?.role === "standalone") snapshotRevision = Symbol("reload");
1347
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
1348
+ if (host?.poisoned) {
1349
+ const previous = host;
1350
+ if (storage?.mode === "opfs" && storage.file) {
1351
+ const fresh = makeHost(previous.module, previous.env);
1352
+ fresh.cookies = previous.cookies;
1353
+ fresh.mountDatabase(storage.file, targetSchema);
1354
+ fresh.ensureBooted();
1355
+ host = fresh;
1356
+ } else {
1357
+ const bytes = await withFiles("readonly", get => get(DATABASE));
1358
+ const fresh = makeHost(previous.module, previous.env);
1359
+ fresh.cookies = previous.cookies;
1360
+ if (bytes) fresh.restoreDatabase(bytes, targetSchema);
1361
+ fresh.ensureBooted();
1362
+ host = fresh;
1363
+ }
1364
+ }
1365
+ if (isLeaderOrStandalone()) {
1366
+ streamLeader?.setCanLead?.(true);
1367
+ streamLeader?.wake?.();
1368
+ }
1369
+ const result = { ok: true, circuit: breaker.snapshot() };
1370
+ emitToTabs({ type: "instant_record.circuit", circuit: result.circuit });
1371
+ return result;
1372
+ }
1373
+ if (method === "trace.configure") {
1374
+ const options = payload || {};
1375
+ const wasEnabled = recorder.enabled;
1376
+ const status = recorder.configure({ ...options, meta: traceMeta() });
1377
+ if (!wasEnabled && recorder.enabled && host && typeof host.snapshotForRecorder === "function") {
1378
+ recorder.captureCheckpoint(host.snapshotForRecorder());
1379
+ }
1380
+ return status;
1381
+ }
1382
+ if (method === "trace.status") {
1383
+ return recorder.status();
1384
+ }
1385
+ if (method === "trace.clear") {
1386
+ recorder.clear();
1387
+ if (recorder.enabled && host && typeof host.snapshotForRecorder === "function") {
1388
+ recorder.captureCheckpoint(host.snapshotForRecorder());
1389
+ }
1390
+ return recorder.status();
1391
+ }
1392
+ if (method === "trace.export") {
1393
+ const options = payload || {};
1394
+ return recorder.exportTrace({
1395
+ redact: options.redact !== false,
1396
+ includeUnredactedDatabase: !!options.includeUnredactedDatabase,
1397
+ meta: traceMeta(),
1398
+ circuit: breaker.snapshot(),
1399
+ });
1400
+ }
1401
+ throw new Error("Unknown leader RPC method: " + method);
1402
+ }
1403
+
1404
+ async function boot(payload = {}) {
1405
+ savedBootPayload = payload;
1406
+ syncContext = contextOf(payload.path || "/");
1407
+ currentScope = syncContext ? syncContext.storageKey : "";
1408
+ syncScope = typeof payload.scope === "string" ? payload.scope : "";
1409
+ syncHeaders = {
1410
+ ...(syncContext?.headers || {}),
1411
+ ...(payload.syncHeaders && typeof payload.syncHeaders === "object" ? payload.syncHeaders : {}),
1412
+ };
1413
+ if (typeof payload.visible === "boolean") pageVisible = payload.visible;
1414
+ if (payload.trace) {
1415
+ recorder.configure({
1416
+ enabled: true,
1417
+ ...(typeof payload.trace === "object" ? payload.trace : {}),
1418
+ meta: traceMeta(),
1419
+ });
1420
+ }
1421
+
1422
+ const started = now();
1423
+ savedModule = payload.module || await compileWasm(wasmUrl);
1424
+ const compiled = now();
1425
+
1426
+ ensureStreamLeader();
1427
+
1428
+ coordinator = createCoordinator({
1429
+ scope: currentScope,
1430
+ sourceVersion,
1431
+ targetSchema,
1432
+ locks,
1433
+ ...(createChannel ? { createChannel } : {}),
1434
+ onBecomeLeader: async ({ promoted }) => {
1435
+ return openLeaderDatabase(savedModule, {
1436
+ context: syncContext,
1437
+ scope: currentScope,
1438
+ path: savedBootPayload?.path || "/",
1439
+ promoted,
1440
+ });
1441
+ },
1442
+ onRpc: handleLeaderRpc,
1443
+ onLeaderMessage: (msg, { reply }) => {
1444
+ if (msg.type === "clear_log") {
1445
+ history.length = 0;
1446
+ } else if (msg.type === "simulate" && msg.backlog) {
1447
+ reply?.({ type: "instant_record.debug_backlog", entries: history, streamOpen });
1448
+ }
1449
+ },
1450
+ onLeaderSimulationChange: (next, prev) => {
1451
+ streamLeader?.setOfflineSimulated(!!next.offline);
1452
+ if (host && prev.offline && !next.offline && !breaker.isOpen()) {
1453
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
1454
+ kickSync(0);
1455
+ if (fillState && fillState.type && !fillState.done && !fillState.full) scheduleFill(0);
1456
+ }
1457
+ },
1458
+ onFollowerPush: msg => {
1459
+ if (msg) postMessage(msg);
1460
+ },
1461
+ onRoleChange: nextRole => {
1462
+ postMessage({ type: "instant_record.role", role: nextRole });
1463
+ if ((nextRole === "leader" || nextRole === "standalone") && !breaker.isOpen()) streamLeader?.wake();
1464
+ },
1465
+ });
1466
+
1467
+ // Apply any simulation settings that arrived before boot.
1468
+ coordinator.updateSimulation(localSimulation);
1469
+
1470
+ const startedRole = await coordinator.start();
1471
+
1472
+ if (startedRole.role === "leader" || startedRole.role === "standalone") {
1473
+ const bootInfo = startedRole.bootResult;
1474
+ if (!breaker.isOpen()) await preloadPathHistory(syncContext);
1475
+ const first = payload.path && !breaker.isOpen()
1476
+ ? await runRequest("GET", target => navigate({ method: "GET", path: payload.path, headers: payload.headers }, target), { tabId: coordinator.workerId })
1477
+ : null;
1478
+ if (!breaker.isOpen() && host && typeof host.notices === "function") {
1479
+ const state = host.syncState();
1480
+ if (!state.fault && (state.exit === undefined || state.exit === 0) && state.notices > 0) {
1481
+ emitSyncNotices(host.notices({ action: "list" }).notices);
1482
+ }
1483
+ }
1484
+ return {
1485
+ compileMs: compiled - started,
1486
+ restored: bootInfo.restored,
1487
+ rehydrated: bootInfo.rehydrated,
1488
+ storageMs: bootInfo.storageMs,
1489
+ runtimeMs: bootInfo.runtimeMs,
1490
+ bootstrapMs: bootInfo.bootstrapMs,
1491
+ first,
1492
+ circuit: breaker.snapshot(),
1493
+ shell: bootInfo.shell,
1494
+ role: startedRole.role,
1495
+ storageMode: bootInfo.storageMode,
1496
+ };
1497
+ }
1498
+
1499
+ // Follower path: leader already owns the hot AppHost and storage.
1500
+ const tabBoot = await coordinator.call("boot_tab", { path: payload.path, syncScope, syncHeaders, headers: payload.headers, trace: payload.trace }, { idempotent: true });
1501
+ if (tabBoot.fillState) {
1502
+ postMessage({ type: "instant_record.history", state: tabBoot.fillState });
1503
+ }
1504
+ return {
1505
+ compileMs: compiled - started,
1506
+ restored: true,
1507
+ storageMs: 0,
1508
+ runtimeMs: 0,
1509
+ bootstrapMs: 0,
1510
+ first: tabBoot.first,
1511
+ circuit: tabBoot.circuit || breaker.snapshot(),
1512
+ shell: null,
1513
+ role: "follower",
1514
+ storageMode: tabBoot.storageMode,
1515
+ };
1516
+ }
1517
+
1518
+ function shutdown({ announceBye = true } = {}) {
1519
+ streamLeader?.stop();
1520
+ streamLeader = null;
1521
+ clearTimeout(kickTimer);
1522
+ clearTimeout(fillTimer);
1523
+ kickTimer = null;
1524
+ kickHeld = false;
1525
+ fillTimer = null;
1526
+ if (storage) {
1527
+ storage.close();
1528
+ storage = null;
1529
+ }
1530
+ host = null;
1531
+ coordinator?.close({ announceBye });
1532
+ }
1533
+
1534
+ async function handleMessage(event) {
1535
+ const { id, type, payload } = event.data;
1536
+ try {
1537
+ if (type === "instant_record.visibility") {
1538
+ pageVisible = !!event.data.visible;
1539
+ streamLeader?.setVisible(pageVisible);
1540
+ return;
1541
+ }
1542
+ if (type === "instant_record.pagehide") {
1543
+ pageVisible = false;
1544
+ if (event.data.persisted) {
1545
+ pageSuspended = true;
1546
+ streamLeader?.suspend();
1547
+ } else {
1548
+ pageTornDown = true;
1549
+ shutdown({ announceBye: true });
1550
+ }
1551
+ return;
1552
+ }
1553
+ if (type === "instant_record.pageshow") {
1554
+ pageSuspended = false;
1555
+ pageVisible = !!event.data.visible;
1556
+ streamLeader?.resume(pageVisible);
1557
+ return;
1558
+ }
1559
+ if (type === "instant_record.bye") {
1560
+ shutdown({ announceBye: true });
1561
+ return;
1562
+ }
1563
+ if (type === "instant_record.clear_log") {
1564
+ history.length = 0;
1565
+ coordinator?.clearLog();
1566
+ return;
1567
+ }
1568
+ if (type === "instant_record.reset_circuit") {
1569
+ const result = coordinator
1570
+ ? await coordinator.call("reset_circuit", null, { idempotent: true })
1571
+ : await handleLeaderRpc("reset_circuit", null, { tabId: null });
1572
+ if (id != null) return postMessage({ id, result });
1573
+ return;
1574
+ }
1575
+ if (type === "instant_record.trace.configure") {
1576
+ const options = payload || event.data.options || {};
1577
+ const result = coordinator
1578
+ ? await coordinator.call("trace.configure", options, { idempotent: true })
1579
+ : await handleLeaderRpc("trace.configure", options, { tabId: null });
1580
+ if (id != null) return postMessage({ id, result });
1581
+ return;
1582
+ }
1583
+ if (type === "instant_record.trace.status") {
1584
+ const result = coordinator
1585
+ ? await coordinator.call("trace.status", null, { idempotent: true })
1586
+ : await handleLeaderRpc("trace.status", null, { tabId: null });
1587
+ if (id != null) return postMessage({ id, result });
1588
+ return;
1589
+ }
1590
+ if (type === "instant_record.trace.clear") {
1591
+ const result = coordinator
1592
+ ? await coordinator.call("trace.clear", null, { idempotent: true })
1593
+ : await handleLeaderRpc("trace.clear", null, { tabId: null });
1594
+ if (id != null) return postMessage({ id, result });
1595
+ return;
1596
+ }
1597
+ if (type === "instant_record.trace.export") {
1598
+ const options = payload || event.data.options || {};
1599
+ const trace = coordinator
1600
+ ? await coordinator.call("trace.export", options, { idempotent: true })
1601
+ : await handleLeaderRpc("trace.export", options, { tabId: null });
1602
+ if (id != null) return postMessage({ id, result: trace });
1603
+ postMessage({ type: "instant_record.trace.exported", trace });
1604
+ return;
1605
+ }
1606
+ if (type === "instant_record.configure_headers") {
1607
+ if (payload && typeof payload === "object") {
1608
+ syncHeaders = { ...syncHeaders, ...payload };
1609
+ if (coordinator && coordinator.role === "follower") {
1610
+ await coordinator.call("configure_headers", payload, { idempotent: true });
1611
+ }
1612
+ }
1613
+ return;
1614
+ }
1615
+ if (type === "instant_record.simulate") {
1616
+ const previous = localSimulation;
1617
+ localSimulation = {
1618
+ offline: !!event.data.settings?.offline,
1619
+ latencyMs: Number(event.data.settings?.latencyMs) || 0,
1620
+ report: !!event.data.settings?.report,
1621
+ };
1622
+ if (coordinator) {
1623
+ coordinator.updateSimulation(localSimulation, { backlog: !!event.data.backlog });
1624
+ } else if (event.data.backlog) {
1625
+ postMessage({ type: "instant_record.debug_backlog", entries: history, streamOpen });
1626
+ }
1627
+ streamLeader?.setOfflineSimulated(!!effectiveSimulation().offline);
1628
+ if (isLeaderOrStandalone() && host && previous.offline && !localSimulation.offline && !effectiveSimulation().offline && !breaker.isOpen()) {
1629
+ drainRetry.delayMs = DRAIN_RETRY_BASE_MS;
1630
+ kickSync(0);
1631
+ }
1632
+ return;
1633
+ }
1634
+ if (type === "instant_record.fetch_history") {
1635
+ const port = event.ports[0];
1636
+ try {
1637
+ if (!coordinator) throw new Error("Worker not booted");
1638
+ const reply = await coordinator.call("fetch_history", event.data.request, { idempotent: true });
1639
+ port.postMessage(reply);
1640
+ } catch (error) {
1641
+ port.postMessage({ ok: false, error: error.message });
1642
+ }
1643
+ return;
1644
+ }
1645
+ if (type === "serverRequest") {
1646
+ const idempotent = payload.method === "GET" || payload.method === "HEAD";
1647
+ const reply = coordinator
1648
+ ? await coordinator.call("serverRequest", payload, { idempotent })
1649
+ : await handleServerRequest(payload);
1650
+ return postMessage({ id, result: reply });
1651
+ }
1652
+ if (type === "boot") return postMessage({ id, result: await boot(payload) });
1653
+ if (type === "navigate") {
1654
+ const idempotent = payload.method === "GET" || payload.method === "HEAD";
1655
+ return postMessage({ id, result: await coordinator.call("navigate", payload, { idempotent }) });
1656
+ }
1657
+ if (type === "request") {
1658
+ const idempotent = payload.method === "GET" || payload.method === "HEAD";
1659
+ return postMessage({ id, result: await coordinator.call("request", payload, { idempotent }) });
1660
+ }
1661
+ if (type === "save") return postMessage({ id, result: await coordinator.call("save", null, { idempotent: true }) });
1662
+ if (type === "sync") return postMessage({ id, result: await coordinator.call("sync", null, { idempotent: true }) });
1663
+ if (type === "notices") {
1664
+ const action = payload?.action || "list";
1665
+ return postMessage({ id, result: await coordinator.call("notices", payload || { action: "list" }, { idempotent: action === "list" }) });
1666
+ }
1667
+ if (type === "wipe") return postMessage({ id, result: await coordinator.call("wipe", null, { idempotent: true }) });
1668
+ if (type === "branch.create") return postMessage({ id, result: await coordinator.call("branch.create", payload, { idempotent: false }) });
1669
+ if (type === "branch.status") return postMessage({ id, result: await coordinator.call("branch.status", payload, { idempotent: true }) });
1670
+ if (type === "branch.approve") return postMessage({ id, result: await coordinator.call("branch.approve", payload, { idempotent: false }) });
1671
+ if (type === "branch.discard") return postMessage({ id, result: await coordinator.call("branch.discard", payload, { idempotent: false }) });
1672
+ } catch (error) {
1673
+ postMessage({ id, error: String(error && error.message ? error.message : error) });
1674
+ }
1675
+ }
1676
+
1677
+ return {
1678
+ boot,
1679
+ handleMessage,
1680
+ handleOnline,
1681
+ handleOffline,
1682
+ shutdown,
1683
+ fillStep,
1684
+ syncPass,
1685
+ get role() { return coordinator?.role || "idle"; },
1686
+ get storageMode() { return storage?.mode || coordinator?.storageMode || null; },
1687
+ get fillState() { return fillState; },
1688
+ get streamOpen() { return streamOpen; },
1689
+ get breaker() { return breaker; },
1690
+ get recorder() { return recorder; },
1691
+ };
1692
+ }