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,17 @@
1
+ {
2
+ "name": "web",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "keywords": [],
10
+ "author": "",
11
+ "license": "ISC",
12
+ "type": "module",
13
+ "dependencies": {
14
+ "@bjorn3/browser_wasi_shim": "^0.4.2",
15
+ "vite": "^8.3.8"
16
+ }
17
+ }
@@ -0,0 +1,556 @@
1
+ // Core AppHost factory (zero external dependencies) so both the browser bundle
2
+ // (via @bjorn3/browser_wasi_shim in app-host.js) and Node replay/tests share
3
+ // the exact same WASI host, OPFS/IndexedDB storage mount, fault detection,
4
+ // notification bridge, and flight recorder integration.
5
+ import { parseReads, readNotice } from "./changes.js";
6
+ import { WasmFaultError, buildFault, isTrapExit, readEvents } from "./faults.js";
7
+ import { buildHttpRequest } from "./http-headers.js";
8
+
9
+ const encoder = new TextEncoder();
10
+ const decoder = new TextDecoder();
11
+
12
+ export function createAppHostClass({ WASI, File, OpenFile, Directory, PreopenDirectory, ConsoleStdout }) {
13
+ class ResponseFile extends File {
14
+ constructor(host) {
15
+ super(new Uint8Array());
16
+ this.host = host;
17
+ }
18
+
19
+ path_open(oflags, rights, fdFlags) {
20
+ const reqFile = this.host.hostDir.contents.get("request") || this.host.requestFile;
21
+ const text = decoder.decode(reqFile.data);
22
+ const newline = text.indexOf("\n");
23
+ const firstLine = newline < 0 ? text : text.slice(0, newline);
24
+ const [method, url] = firstLine.split(" ");
25
+ let rest = newline < 0 ? "" : text.slice(newline + 1);
26
+ const headers = {};
27
+ const split = rest.indexOf("\n\n");
28
+ if (split >= 0) {
29
+ const candidate = rest.slice(0, split).split("\n");
30
+ if (candidate.every(line => /^[A-Za-z0-9-]+: /.test(line))) {
31
+ for (const line of candidate) {
32
+ const colon = line.indexOf(": ");
33
+ headers[line.slice(0, colon)] = line.slice(colon + 2);
34
+ }
35
+ rest = rest.slice(split + 2);
36
+ }
37
+ }
38
+ let status = 0;
39
+ let body = "";
40
+ try {
41
+ ({ status, body } = this.host.exchange(method, url, rest, headers));
42
+ } catch {
43
+ status = 0; // offline: the gem's transport raises Transport::Error and the outbox keeps the write
44
+ }
45
+ this.host.exchanges.push(`${method} ${url} -> ${status}`);
46
+ const record = {
47
+ method,
48
+ url,
49
+ requestBody: rest,
50
+ status,
51
+ responseBody: body == null ? "" : String(body),
52
+ };
53
+ if (Object.keys(headers).length > 0) record.requestHeaders = headers;
54
+ this.host.exchangeRecords.push(record);
55
+ this.data = encoder.encode(`${status}\n${body ?? ""}`);
56
+ return super.path_open(oflags, rights, fdFlags);
57
+ }
58
+ }
59
+
60
+ return class AppHost {
61
+ // exchange(method, url, body, headers) -> { status, body }, synchronous.
62
+ constructor(module, { exchange, env = {}, onFault = null, onEvents = null, onSuccess = null, recorder = null, clock = () => Date.now() } = {}) {
63
+ this.module = module;
64
+ this.exchange = exchange;
65
+ this.onFault = onFault;
66
+ this.onEvents = onEvents;
67
+ this.onSuccess = onSuccess;
68
+ this.recorder = recorder;
69
+ this.clock = clock;
70
+ this.env = {
71
+ SPINEL_GC_SLAB_MB: "8",
72
+ DATABASE_POOL_SIZE: "1",
73
+ RAILS_ENV: "production",
74
+ SECRET_KEY_BASE: randomHex(64),
75
+ ...env,
76
+ };
77
+ this.storage = new Directory(new Map());
78
+ this.inFile = new File(new Uint8Array());
79
+ this.outFile = new File(new Uint8Array());
80
+ this.requestFile = new File(new Uint8Array());
81
+ this.notifyFile = new File(new Uint8Array());
82
+ this.eventsFile = new File(new Uint8Array());
83
+ this.hostDir = new Directory(new Map([
84
+ ["in", this.inFile],
85
+ ["out", this.outFile],
86
+ ["request", this.requestFile],
87
+ ["response", new ResponseFile(this)],
88
+ ["notify", this.notifyFile],
89
+ ["events", this.eventsFile],
90
+ ]));
91
+ this.root = new Map([
92
+ ["storage", this.storage],
93
+ ["tmp", new Directory(new Map())],
94
+ ["host", this.hostDir],
95
+ ]);
96
+ this.cookies = new Map();
97
+ this.exchanges = [];
98
+ this.exchangeRecords = [];
99
+ this.errors = [];
100
+ this.schemaVersion = 0;
101
+ this.instance = null;
102
+ this.poisoned = false;
103
+ this.lastFault = null;
104
+ }
105
+
106
+ // The SQLite file's byte length without copying its contents.
107
+ databaseSize() {
108
+ const file = this.storage.contents.get("development.sqlite3");
109
+ if (!file) return 0;
110
+ if (typeof file.byteLength === "function") return file.byteLength();
111
+ if (file.data) return file.data.byteLength;
112
+ if (file.size !== undefined) return Number(file.size);
113
+ return 0;
114
+ }
115
+
116
+ // The SQLite file's bytes, for persisting between page loads (null before the first run).
117
+ databaseBytes() {
118
+ const file = this.storage.contents.get("development.sqlite3");
119
+ if (!file) return null;
120
+ if (typeof file.readAll === "function") return file.readAll();
121
+ return file.data ?? null;
122
+ }
123
+
124
+ // Flush dirty pages when backed by a page-level OPFS sync handle.
125
+ flushDatabase() {
126
+ const file = this.storage.contents.get("development.sqlite3");
127
+ if (file && typeof file.flush === "function") file.flush();
128
+ }
129
+
130
+ // Mount an existing WASI Inode (such as PagedSyncOPFSFile) at /storage/development.sqlite3.
131
+ mountDatabase(inode, schemaVersion = 0) {
132
+ this.schemaVersion = Number(schemaVersion) || 0;
133
+ this.storage.contents.set("development.sqlite3", inode);
134
+ this.hostDir.contents.set("schema_version", new File(encoder.encode(String(this.schemaVersion).padStart(20, "0"))));
135
+ if (this.recorder?.enabled) {
136
+ this.recorder.captureCheckpoint(this.snapshotForRecorder());
137
+ }
138
+ }
139
+
140
+ // Independent copy-on-write snapshot of the live SQLite bytes for staging branches.
141
+ cloneDatabaseBytes() {
142
+ const bytes = this.databaseBytes();
143
+ return bytes ? new Uint8Array(bytes) : null;
144
+ }
145
+
146
+ restoreDatabase(bytes, schemaVersion = 0) {
147
+ const copy = bytes instanceof Uint8Array ? bytes.slice() : new Uint8Array(bytes);
148
+ this.mountDatabase(new File(copy), schemaVersion);
149
+ }
150
+
151
+ restoreForOutboxExtraction(bytes) {
152
+ const copy = bytes instanceof Uint8Array ? bytes.slice() : new Uint8Array(bytes);
153
+ this.storage.contents.set("development.sqlite3", new File(copy));
154
+ this.hostDir.contents.set("recovery", new File(encoder.encode("extract_outbox")));
155
+ }
156
+
157
+ extractOutbox(bytes) {
158
+ if (!bytes || !bytes.length) return [];
159
+ this.restoreForOutboxExtraction(bytes);
160
+ const result = this.call("wasm_export_outbox", new Uint8Array());
161
+ if (result.exit !== 0) {
162
+ throw new WasmFaultError(
163
+ result.fault || buildFault({ exportName: "wasm_export_outbox", exit: result.exit, errors: result.errors, at: this.clock() }),
164
+ );
165
+ }
166
+ const parsed = JSON.parse(decoder.decode(result.out) || "[]");
167
+ return Array.isArray(parsed) ? parsed : [];
168
+ }
169
+
170
+ importOutbox(rows) {
171
+ if (!Array.isArray(rows) || rows.length === 0) return { imported: 0 };
172
+ const result = this.call("wasm_import_outbox", encoder.encode(JSON.stringify(rows)));
173
+ if (result.exit !== 0) {
174
+ throw new WasmFaultError(
175
+ result.fault || buildFault({ exportName: "wasm_import_outbox", exit: result.exit, errors: result.errors, at: this.clock() }),
176
+ );
177
+ }
178
+ return JSON.parse(decoder.decode(result.out) || '{"imported":0}');
179
+ }
180
+
181
+ snapshotForRecorder() {
182
+ return {
183
+ dbBytes: this.databaseBytes(),
184
+ schemaVersion: this.schemaVersion,
185
+ env: this.env,
186
+ cookies: this.cookies,
187
+ };
188
+ }
189
+
190
+ // Lazily instantiate and boot the WASI reactor once (after restoreDatabase/mountDatabase
191
+ // has placed any saved SQLite file into /storage).
192
+ ensureBooted() {
193
+ if (this.instance) return;
194
+ if (this.poisoned) {
195
+ throw new WasmFaultError(
196
+ this.lastFault ||
197
+ buildFault({
198
+ exportName: "wasm_boot",
199
+ exit: "trap: instance poisoned",
200
+ trapped: true,
201
+ fatal: true,
202
+ at: this.clock(),
203
+ }),
204
+ );
205
+ }
206
+ this.errors = [];
207
+ const fds = [
208
+ new OpenFile(new File(new Uint8Array())),
209
+ new OpenFile(new File(new Uint8Array())),
210
+ ConsoleStdout.lineBuffered((line) => this.errors.push(line)),
211
+ new PreopenDirectory("/", this.root),
212
+ ];
213
+ const wasi = new WASI(
214
+ ["app"],
215
+ Object.entries(this.env).map(([key, value]) => `${key}=${value}`),
216
+ fds,
217
+ { debug: false },
218
+ );
219
+ const imports = { ...wasi.wasiImport };
220
+ for (const name of ["sock_accept", "sock_recv", "sock_send", "sock_shutdown"]) imports[name] = () => 58; // ENOTSUP
221
+ const instance = new WebAssembly.Instance(this.module, { wasi_snapshot_preview1: imports });
222
+ wasi.initialize(instance);
223
+ try {
224
+ instance.exports.wasm_boot();
225
+ } catch (error) {
226
+ this.poisoned = true;
227
+ const fault = buildFault({
228
+ exportName: "wasm_boot",
229
+ exit: `trap: ${error?.message || String(error)}`,
230
+ errors: this.errors.slice(),
231
+ trapped: true,
232
+ fatal: true,
233
+ stack: error?.stack || null,
234
+ at: this.clock(),
235
+ });
236
+ this.lastFault = fault;
237
+ this.onFault?.(fault);
238
+ throw new WasmFaultError(fault, { cause: error });
239
+ }
240
+ this.instance = instance;
241
+ }
242
+
243
+ call(exportName, inputBytes) {
244
+ const payload = inputBytes instanceof Uint8Array ? inputBytes : new Uint8Array(inputBytes || 0);
245
+ this.errors = [];
246
+ this.exchangeRecords = [];
247
+ this.eventsFile.data = new Uint8Array();
248
+ this.hostDir.contents.set("events", this.eventsFile);
249
+
250
+ if (this.poisoned) {
251
+ const fault = buildFault({
252
+ exportName,
253
+ exit: "trap: instance poisoned after previous fatal trap",
254
+ errors: this.lastFault?.errors || [],
255
+ trapped: true,
256
+ fatal: true,
257
+ at: this.clock(),
258
+ });
259
+ this.lastFault = fault;
260
+ this.onFault?.(fault);
261
+ return { exit: fault.exit, out: new Uint8Array(), errors: fault.errors.slice(), events: [], trapped: true, fault };
262
+ }
263
+
264
+ this.ensureBooted();
265
+
266
+ const preCallSnapshot = this.recorder?.enabled ? this.snapshotForRecorder() : null;
267
+
268
+ this.inFile.data = payload;
269
+ this.hostDir.contents.set("in", this.inFile);
270
+ this.outFile.data = new Uint8Array();
271
+ this.hostDir.contents.set("out", this.outFile);
272
+
273
+ let exit;
274
+ let trapped = false;
275
+ let stack = null;
276
+ try {
277
+ exit = this.instance.exports[exportName]();
278
+ } catch (error) {
279
+ trapped = true;
280
+ this.poisoned = true;
281
+ exit = `trap: ${error?.message || String(error)}`;
282
+ stack = error?.stack || null;
283
+ }
284
+
285
+ const outEntry = this.hostDir.contents.get("out") || this.outFile;
286
+ const eventsEntry = this.hostDir.contents.get("events") || this.eventsFile;
287
+ const events = readEvents(decoder.decode(eventsEntry.data));
288
+ const errors = this.errors.slice();
289
+ const fault = exit === 0
290
+ ? null
291
+ : buildFault({
292
+ exportName,
293
+ exit,
294
+ errors,
295
+ trapped: trapped || isTrapExit(exit),
296
+ fatal: trapped || isTrapExit(exit),
297
+ stack,
298
+ at: this.clock(),
299
+ });
300
+
301
+ if (events.length > 0) this.onEvents?.(events, exportName);
302
+ if (fault) {
303
+ this.lastFault = fault;
304
+ this.onFault?.(fault);
305
+ } else {
306
+ this.onSuccess?.(exportName);
307
+ }
308
+
309
+ const outcome = { exit, out: outEntry.data, errors, events, trapped: !!fault?.trapped, fault };
310
+ if (this.recorder?.enabled) {
311
+ this.recorder.recordStep({
312
+ exportName,
313
+ inputBytes: payload,
314
+ exchanges: this.exchangeRecords,
315
+ outcome,
316
+ preCallSnapshot,
317
+ });
318
+ }
319
+ return outcome;
320
+ }
321
+
322
+ // One HTTP request through the app's own router and controllers.
323
+ request(method, path, { body = "", contentType, headers = {} } = {}) {
324
+ const input = buildHttpRequest(method, path, { body, contentType, headers, cookies: this.cookies });
325
+
326
+ this.notifyFile.data = new Uint8Array();
327
+ this.hostDir.contents.set("notify", this.notifyFile);
328
+ const result = this.call("wasm_request", input);
329
+ const text = decoder.decode(result.out);
330
+ const split = text.indexOf("\n\n");
331
+ const lines = (split < 0 ? text : text.slice(0, split)).split("\n");
332
+ const responseHeaders = [];
333
+ let reads = null;
334
+ for (const line of lines.slice(1)) {
335
+ const colon = line.indexOf(": ");
336
+ if (colon < 0) continue;
337
+ const name = line.slice(0, colon);
338
+ const value = line.slice(colon + 2);
339
+ const lower = name.toLowerCase();
340
+ if (lower === "set-cookie") {
341
+ const pair = value.split(";")[0];
342
+ const equals = pair.indexOf("=");
343
+ if (/max-age=0/i.test(value)) this.cookies.delete(pair.slice(0, equals));
344
+ else this.cookies.set(pair.slice(0, equals), pair.slice(equals + 1));
345
+ } else {
346
+ if (lower === "x-instant-record-reads") reads = parseReads(value);
347
+ responseHeaders.push([name, value]);
348
+ }
349
+ }
350
+ const status = Number(lines[0]) || 500;
351
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
352
+ return {
353
+ status,
354
+ headers: responseHeaders,
355
+ body: split < 0 ? "" : text.slice(split + 2),
356
+ reads,
357
+ ...readNotice(decoder.decode(notifyEntry.data)),
358
+ exit: result.exit,
359
+ errors: result.errors,
360
+ events: result.events,
361
+ fault: result.fault,
362
+ };
363
+ }
364
+
365
+ // One pass of the gem's own sync loop (InstantRecord::Client.sync_pass).
366
+ syncPlan() {
367
+ const result = this.call("wasm_sync_plan", new Uint8Array());
368
+ if (result.exit !== 0) {
369
+ throw new WasmFaultError(
370
+ result.fault || buildFault({ exportName: "wasm_sync_plan", exit: result.exit, errors: result.errors, at: this.clock() }),
371
+ );
372
+ }
373
+ return JSON.parse(decoder.decode(result.out));
374
+ }
375
+
376
+ sync(endpoint, exchange = this.exchange) {
377
+ this.notifyFile.data = new Uint8Array();
378
+ this.hostDir.contents.set("notify", this.notifyFile);
379
+ this.exchanges = [];
380
+ const previousExchange = this.exchange;
381
+ let result;
382
+ try {
383
+ this.exchange = exchange;
384
+ result = this.call("wasm_sync", encoder.encode(endpoint || ""));
385
+ } finally {
386
+ this.exchange = previousExchange;
387
+ }
388
+ const text = decoder.decode(result.out);
389
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
390
+ const nextRelease = /next_release_ms=(\d+)/.exec(text);
391
+ return {
392
+ changed: result.exit === 0 && text.startsWith("changed"),
393
+ pending: result.exit === 0 ? Number(/pending=(\d+)/.exec(text)?.[1] ?? -1) : -1,
394
+ held: result.exit === 0 ? Number(/held=(\d+)/.exec(text)?.[1] ?? 0) : 0,
395
+ nextReleaseMs: result.exit === 0 && nextRelease ? Number(nextRelease[1]) : null,
396
+ cursor: result.exit === 0 ? Number(/cursor=(\d+)/.exec(text)?.[1] ?? 0) : 0,
397
+ ...readNotice(decoder.decode(notifyEntry.data)),
398
+ exchanges: this.exchanges,
399
+ exit: result.exit,
400
+ errors: result.errors,
401
+ events: result.events,
402
+ fault: result.fault,
403
+ };
404
+ }
405
+
406
+ // Merge pre-fetched push/bootstrap responses into SQLite by mutation_id
407
+ // without discarding acks when newer local edits landed during the fetch.
408
+ applySync(endpoint, { push = null, bootstrap = null } = {}) {
409
+ this.notifyFile.data = new Uint8Array();
410
+ this.hostDir.contents.set("notify", this.notifyFile);
411
+ this.exchanges = [];
412
+ const payload = JSON.stringify({
413
+ endpoint: endpoint || "",
414
+ push,
415
+ bootstrap,
416
+ });
417
+ const result = this.call("wasm_sync", encoder.encode(payload));
418
+ if (result.exit !== 0) {
419
+ throw new WasmFaultError(
420
+ result.fault || buildFault({ exportName: "wasm_sync", exit: result.exit, errors: result.errors, at: this.clock() }),
421
+ );
422
+ }
423
+ const text = decoder.decode(result.out);
424
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
425
+ const nextRelease = /next_release_ms=(\d+)/.exec(text);
426
+ return {
427
+ changed: text.startsWith("changed"),
428
+ pending: Number(/pending=(\d+)/.exec(text)?.[1] ?? -1),
429
+ held: Number(/held=(\d+)/.exec(text)?.[1] ?? 0),
430
+ nextReleaseMs: nextRelease ? Number(nextRelease[1]) : null,
431
+ cursor: Number(/cursor=(\d+)/.exec(text)?.[1] ?? 0),
432
+ progressed: /progressed=1\b/.test(text),
433
+ failed: /failed=1\b/.test(text),
434
+ quarantined: Number(/quarantined=(\d+)/.exec(text)?.[1] ?? 0),
435
+ ...readNotice(decoder.decode(notifyEntry.data)),
436
+ exchanges: this.exchanges,
437
+ exit: result.exit,
438
+ errors: result.errors,
439
+ events: result.events,
440
+ fault: result.fault,
441
+ };
442
+ }
443
+
444
+ // Feed an SSE batch fetched asynchronously by the worker into InstantRecord::Client.consume_stream.
445
+ consumeStream(chunk) {
446
+ this.notifyFile.data = new Uint8Array();
447
+ this.hostDir.contents.set("notify", this.notifyFile);
448
+ const result = this.call("wasm_stream", encoder.encode(chunk));
449
+ const text = decoder.decode(result.out);
450
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
451
+ return {
452
+ applied: result.exit === 0 ? Number(/applied=(\d+)/.exec(text)?.[1] ?? 0) : 0,
453
+ cursor: result.exit === 0 ? Number(/cursor=(\d+)/.exec(text)?.[1] ?? 0) : 0,
454
+ bootstrapped: result.exit === 0 ? !text.includes("bootstrap=needed") : true,
455
+ ...readNotice(decoder.decode(notifyEntry.data)),
456
+ exit: result.exit,
457
+ errors: result.errors,
458
+ events: result.events,
459
+ fault: result.fault,
460
+ };
461
+ }
462
+
463
+ history(key, response = "") {
464
+ const result = this.call("wasm_history", encoder.encode(JSON.stringify({ key, response })));
465
+ if (result.exit !== 0) {
466
+ throw new WasmFaultError(
467
+ result.fault || buildFault({ exportName: "wasm_history", exit: result.exit, errors: result.errors, at: this.clock() }),
468
+ );
469
+ }
470
+ return JSON.parse(decoder.decode(result.out));
471
+ }
472
+
473
+ notices(request = { action: "list" }) {
474
+ this.notifyFile.data = new Uint8Array();
475
+ this.hostDir.contents.set("notify", this.notifyFile);
476
+ const result = this.call("wasm_notices", encoder.encode(JSON.stringify(request)));
477
+ if (result.exit !== 0) {
478
+ throw new WasmFaultError(
479
+ result.fault || buildFault({ exportName: "wasm_notices", exit: result.exit, errors: result.errors, at: this.clock() }),
480
+ );
481
+ }
482
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
483
+ return {
484
+ ...JSON.parse(decoder.decode(result.out)),
485
+ ...readNotice(decoder.decode(notifyEntry.data)),
486
+ exit: result.exit,
487
+ errors: result.errors,
488
+ events: result.events,
489
+ fault: result.fault,
490
+ };
491
+ }
492
+
493
+ // Extract OutboxMutations recorded after `excludeIds` on the active SQLite database.
494
+ branchOutbox(excludeIds = []) {
495
+ const result = this.call("wasm_branch_outbox", encoder.encode(JSON.stringify({ exclude_ids: excludeIds })));
496
+ if (result.exit !== 0) {
497
+ throw new WasmFaultError(
498
+ result.fault || buildFault({ exportName: "wasm_branch_outbox", exit: result.exit, errors: result.errors, at: this.clock() }),
499
+ );
500
+ }
501
+ return JSON.parse(decoder.decode(result.out));
502
+ }
503
+
504
+ // Safely replay extracted branch OutboxMutations onto the active (`main`) SQLite database.
505
+ branchReplay(mutations, { conflict = "lww" } = {}) {
506
+ this.notifyFile.data = new Uint8Array();
507
+ this.hostDir.contents.set("notify", this.notifyFile);
508
+ const result = this.call("wasm_branch_replay", encoder.encode(JSON.stringify({ mutations, conflict })));
509
+ if (result.exit !== 0) {
510
+ throw new WasmFaultError(
511
+ result.fault || buildFault({ exportName: "wasm_branch_replay", exit: result.exit, errors: result.errors, at: this.clock() }),
512
+ );
513
+ }
514
+ const parsed = JSON.parse(decoder.decode(result.out));
515
+ const notifyEntry = this.hostDir.contents.get("notify") || this.notifyFile;
516
+ return {
517
+ ...parsed,
518
+ ...readNotice(decoder.decode(notifyEntry.data)),
519
+ exit: result.exit,
520
+ errors: result.errors,
521
+ events: result.events,
522
+ fault: result.fault,
523
+ };
524
+ }
525
+
526
+ syncState() {
527
+ const result = this.call("wasm_cursor", new Uint8Array());
528
+ const text = decoder.decode(result.out);
529
+ const nextRelease = /next_release_ms=(\d+)/.exec(text);
530
+ return {
531
+ bootstrapped: result.exit === 0 && text.includes("bootstrap=ready"),
532
+ cursor: result.exit === 0 ? Number(/cursor=(\d+)/.exec(text)?.[1] ?? 0) : 0,
533
+ pending: result.exit === 0 ? Number(/pending=(\d+)/.exec(text)?.[1] ?? 0) : -1,
534
+ held: result.exit === 0 ? Number(/held=(\d+)/.exec(text)?.[1] ?? 0) : 0,
535
+ nextReleaseMs: result.exit === 0 && nextRelease ? Number(nextRelease[1]) : null,
536
+ notices: result.exit === 0 ? Number(/notices=(\d+)/.exec(text)?.[1] ?? 0) : 0,
537
+ // The name the server gave whoever this browser synced as, when it tells people apart.
538
+ identity: result.exit === 0 ? (/identity=(\S+)/.exec(text)?.[1] ?? "") : "",
539
+ exit: result.exit,
540
+ errors: result.errors,
541
+ events: result.events,
542
+ fault: result.fault,
543
+ };
544
+ }
545
+ };
546
+ }
547
+
548
+ function randomHex(bytes) {
549
+ const buffer = new Uint8Array(bytes);
550
+ if (globalThis.crypto?.getRandomValues) {
551
+ globalThis.crypto.getRandomValues(buffer);
552
+ } else {
553
+ for (let i = 0; i < buffer.length; i++) buffer[i] = Math.floor(Math.random() * 256);
554
+ }
555
+ return [...buffer].map((byte) => byte.toString(16).padStart(2, "0")).join("");
556
+ }
@@ -0,0 +1,16 @@
1
+ // Host for the compiled app (hand-written). Boots the WASI reactor wasm module ONCE per worker
2
+ // lifetime on an in-memory or OPFS-backed WASI filesystem, keeping the Spinel GC slab and SQLite
3
+ // connection live across requests and sync passes:
4
+ // /storage the app's SQLite file (and its secret key)
5
+ // /host in / out request/sync input and output buffers
6
+ // request the gem writes "METHOD URL\nbody"
7
+ // response opening it makes the host perform that request, synchronously
8
+ // notify the gem writes "records_changed" when a sync pass moved rows,
9
+ // and the records it can list after it (changes.js)
10
+ // events the gem writes bridged ActiveSupport::Notifications JSON
11
+ // Works the same in Node (tests / replay) and in a browser worker; only `exchange` differs.
12
+ import { WASI, File, OpenFile, Directory, PreopenDirectory, ConsoleStdout } from "@bjorn3/browser_wasi_shim";
13
+ import { createAppHostClass } from "./app-host-core.js";
14
+
15
+ export { WasmFaultError } from "./faults.js";
16
+ export const AppHost = createAppHostClass({ WASI, File, OpenFile, Directory, PreopenDirectory, ConsoleStdout });