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
data/frontend/focus.js ADDED
@@ -0,0 +1,10 @@
1
+ // Where focus belongs in `ids`, given the row that had it and where that row
2
+ // last stood. A row that left the list (archived here, or by a teammate)
3
+ // hands focus to the row that took its place, never to the top.
4
+ export function resolveFocus(ids, id, index) {
5
+ if (!ids.length) return { id: null, index: 0 }
6
+ const at = ids.indexOf(id)
7
+ if (at >= 0) return { id, index: at }
8
+ const next = Math.min(Math.max(index, 0), ids.length - 1)
9
+ return { id: ids[next], index: next }
10
+ }
data/frontend/held.js ADDED
@@ -0,0 +1,192 @@
1
+ // Writes held for a moment so they can be taken back. No React here, so the
2
+ // tests import this file alone; undo.js wraps it in a hook.
3
+ //
4
+ // heldActions({ ms, onChange }) answers { hold, undo, flush, snapshot }.
5
+ //
6
+ // hold({ label, ids, commit, context })
7
+ // keeps an action for `ms`. Its ids count as held from now until its
8
+ // write has been answered, so whoever draws them can leave them out.
9
+ // undo()
10
+ // drops the newest held action without committing it, and answers it
11
+ // (its `context` says what to put back), or null.
12
+ // flush(options)
13
+ // commits everything held now, oldest first. `options` reach `commit`.
14
+ //
15
+ // `commit(options)` does the write and may answer a promise. The ids stay
16
+ // held until it settles, so a row cannot return between a write and the
17
+ // answer that drops it. Reporting a failure is commit's own job.
18
+ //
19
+ // `onChange({ pending, held })` is called whenever either changes: `pending`
20
+ // is the actions that can still be undone, newest last.
21
+ export function heldActions({ ms = 5000, onChange = () => {} } = {}) {
22
+ let pending = []
23
+ let next = 1
24
+ const committing = new Map()
25
+
26
+ const snapshot = () => ({
27
+ pending: pending.map(({ timer, ...entry }) => entry),
28
+ held: new Set([...pending.flatMap((entry) => entry.ids), ...committing.keys()]),
29
+ })
30
+ const changed = () => onChange(snapshot())
31
+
32
+ const count = (ids, by) => {
33
+ for (const id of ids) {
34
+ const left = (committing.get(id) || 0) + by
35
+ if (left > 0) committing.set(id, left)
36
+ else committing.delete(id)
37
+ }
38
+ }
39
+
40
+ const run = (entry, options) => {
41
+ count(entry.ids, 1)
42
+ let answer
43
+ try {
44
+ answer = entry.commit(options)
45
+ } catch (error) {
46
+ answer = Promise.reject(error)
47
+ }
48
+ return Promise.resolve(answer).catch(() => {}).then(() => {
49
+ count(entry.ids, -1)
50
+ changed()
51
+ })
52
+ }
53
+
54
+ const expire = (entry) => {
55
+ pending = pending.filter((other) => other !== entry)
56
+ run(entry)
57
+ changed()
58
+ }
59
+
60
+ return {
61
+ snapshot,
62
+
63
+ hold({ label, ids, commit, context }) {
64
+ const entry = { key: next++, label, ids, commit, context }
65
+ entry.timer = setTimeout(() => expire(entry), ms)
66
+ pending.push(entry)
67
+ changed()
68
+ return entry.key
69
+ },
70
+
71
+ undo() {
72
+ const entry = pending.pop()
73
+ if (!entry) return null
74
+ clearTimeout(entry.timer)
75
+ changed()
76
+ return entry
77
+ },
78
+
79
+ flush(options) {
80
+ if (!pending.length) return
81
+ const entries = pending
82
+ pending = []
83
+ for (const entry of entries) {
84
+ clearTimeout(entry.timer)
85
+ run(entry, options)
86
+ }
87
+ changed()
88
+ },
89
+ }
90
+ }
91
+
92
+ // Durable undo state backed by local SQLite OutboxMutation rows (`hold_for:`).
93
+ // Unlike `heldActions` (which keeps writes in JS memory for non-compiled
94
+ // server-rendered pages), the write is already in SQLite with a `release_at`
95
+ // timestamp: this tracks unexpired rows across reloads, clears each toast when
96
+ // its `release_at` passes, and delegates `undo()` to `onCancel(entry)` (which
97
+ // calls `InstantRecord.cancel_pending(mutation_id)`).
98
+ const MAX_TIMEOUT_MS = 2_147_483_647
99
+
100
+ export function durableHeldActions({ onChange = () => {}, onCancel = () => {}, now = Date.now } = {}) {
101
+ let pending = []
102
+ let timer = null
103
+
104
+ const parseRelease = (entry) => {
105
+ const raw = entry.releaseAt ?? entry.release_at
106
+ if (typeof raw === "number") return raw
107
+ if (raw instanceof Date) return raw.getTime()
108
+ const parsed = Date.parse(raw)
109
+ return Number.isNaN(parsed) ? 0 : parsed
110
+ }
111
+
112
+ const samePending = (a, b) =>
113
+ a.length === b.length &&
114
+ a.every((entry, i) =>
115
+ entry.key === b[i].key &&
116
+ entry.id === b[i].id &&
117
+ entry.label === b[i].label &&
118
+ entry._releaseMs === b[i]._releaseMs,
119
+ )
120
+
121
+ const snapshot = () => ({
122
+ pending: pending.map(({ _releaseMs, ...entry }) => entry),
123
+ held: new Set(),
124
+ })
125
+
126
+ const clearTimer = () => {
127
+ if (timer !== null) {
128
+ clearTimeout(timer)
129
+ timer = null
130
+ }
131
+ }
132
+
133
+ const schedule = () => {
134
+ clearTimer()
135
+ if (!pending.length) return
136
+ const nextMs = Math.min(...pending.map((entry) => entry._releaseMs))
137
+ const delay = Math.min(Math.max(0, nextMs - now()), MAX_TIMEOUT_MS)
138
+ timer = setTimeout(prune, delay)
139
+ }
140
+
141
+ const prune = () => {
142
+ const current = now()
143
+ const remaining = pending.filter((entry) => entry._releaseMs > current)
144
+ if (remaining.length !== pending.length) {
145
+ pending = remaining
146
+ onChange(snapshot())
147
+ }
148
+ schedule()
149
+ }
150
+
151
+ return {
152
+ snapshot,
153
+
154
+ sync(entries = []) {
155
+ const current = now()
156
+ const next = entries
157
+ .map((entry) => {
158
+ const releaseMs = parseRelease(entry)
159
+ return { ...entry, key: entry.key ?? entry.id, _releaseMs: releaseMs }
160
+ })
161
+ .filter((entry) => entry._releaseMs > current)
162
+ const changed = !samePending(pending, next)
163
+ pending = next
164
+ schedule()
165
+ if (changed) onChange(snapshot())
166
+ },
167
+
168
+ undo() {
169
+ const current = now()
170
+ const before = pending.length
171
+ pending = pending.filter((entry) => entry._releaseMs > current)
172
+ const entry = pending.pop()
173
+ if (!entry) {
174
+ schedule()
175
+ if (pending.length !== before) onChange(snapshot())
176
+ return null
177
+ }
178
+ schedule()
179
+ const { _releaseMs, ...plain } = entry
180
+ onChange(snapshot())
181
+ onCancel(plain)
182
+ return plain
183
+ },
184
+
185
+ // Durable writes are already persisted in SQLite; leaving the page needs no flush.
186
+ flush() {},
187
+
188
+ dispose() {
189
+ clearTimer()
190
+ },
191
+ }
192
+ }
data/frontend/http.js ADDED
@@ -0,0 +1,76 @@
1
+ // An HTTP client for Inertia that the local database answers.
2
+ //
3
+ // In the compiled runtime the app's controllers run in a worker in this tab.
4
+ // The page's `fetch` reaches them with full HTTP headers (X-Inertia,
5
+ // X-Inertia-Partial-Component, X-Inertia-Partial-Data, Accept, Referer, ...);
6
+ // XMLHttpRequest, which Inertia uses by default, does not. So this client sends
7
+ // each Inertia request through `fetch` with its real headers and lets the
8
+ // worker follow redirects like a browser.
9
+ import { HttpResponseError } from "@inertiajs/core"
10
+
11
+ const formBody = (data, verb) => {
12
+ const fields = new URLSearchParams()
13
+ const entries = data instanceof FormData ? [...data.entries()] : Object.entries(data || {})
14
+ for (const [key, value] of entries) if (value !== null && value !== undefined) fields.append(key, String(value))
15
+ if (verb !== "POST") fields.set("_method", verb)
16
+ return fields
17
+ }
18
+
19
+ const failure = (status, url, data = "", headers = {}) =>
20
+ new HttpResponseError(`Request failed with status ${status}`, { status, data, headers }, url)
21
+
22
+ const responseHeaders = (headers) => {
23
+ const result = {}
24
+ if (headers && typeof headers.forEach === "function") {
25
+ headers.forEach((value, key) => { result[key.toLowerCase()] = value })
26
+ }
27
+ return result
28
+ }
29
+
30
+ const xsrf = () => decodeURIComponent(document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/)?.[1] || "")
31
+
32
+ // A write that visits nothing: a form post that neither follows the app's
33
+ // redirect nor reloads a prop. A page sending several writes in a row sends
34
+ // each this way and reloads its props once at the end, where `router.post`
35
+ // would answer every one with the whole page.
36
+ //
37
+ // It reaches Rails with the token Inertia's own requests carry. Beside a
38
+ // local database it is the page's own `fetch`, which the worker answers.
39
+ // `keepalive` lets the browser finish the request after the page is gone.
40
+ export async function write(url, data, { keepalive = false } = {}) {
41
+ const headers = { "X-Requested-With": "XMLHttpRequest" }
42
+ const token = xsrf()
43
+ if (token) headers["X-XSRF-TOKEN"] = token
44
+ const sent = await fetch(new URL(url, window.location.href), {
45
+ method: "POST", body: formBody(data, "POST"), headers, redirect: "manual", keepalive, credentials: "same-origin",
46
+ })
47
+ // A redirect not followed is the app saying the write was taken.
48
+ if (!sent.ok && sent.type !== "opaqueredirect") throw failure(sent.status, url)
49
+ }
50
+
51
+ export const localHttpClient = {
52
+ async request({ method, url, data, params, headers, signal }) {
53
+ const target = new URL(url, window.location.href)
54
+ for (const [key, value] of Object.entries(params || {})) target.searchParams.set(key, String(value))
55
+ const verb = method.toUpperCase()
56
+ const requestHeaders = {}
57
+ for (const [key, value] of Object.entries(headers || {})) {
58
+ if (value === null || value === undefined) continue
59
+ if (verb !== "GET" && verb !== "HEAD" && key.toLowerCase() === "content-type") continue
60
+ requestHeaders[key] = String(value)
61
+ }
62
+
63
+ const init = {
64
+ method: verb === "GET" || verb === "HEAD" ? verb : "POST",
65
+ headers: requestHeaders,
66
+ signal,
67
+ }
68
+ if (verb !== "GET" && verb !== "HEAD") init.body = formBody(data, verb)
69
+
70
+ const response = await fetch(target, init)
71
+ const text = await response.text()
72
+ const replyHeaders = responseHeaders(response.headers)
73
+ if (!response.ok) throw failure(response.status, url, text, replyHeaders)
74
+ return { status: response.status, data: text, headers: replyHeaders }
75
+ },
76
+ }
data/frontend/index.js ADDED
@@ -0,0 +1,53 @@
1
+ // InstantRecord for an Inertia page in React. It ships in the gem:
2
+ //
3
+ // npm install "$(bundle show instant_record)/frontend"
4
+ //
5
+ // import { instantRecord } from "instant_record"
6
+ // createInertiaApp({ ...instantRecord(), resolve, setup })
7
+ //
8
+ // The page stays an ordinary Inertia page: props in, visits out. These make
9
+ // its live props follow the local database and, in the compiled runtime, let
10
+ // that database answer its visits.
11
+ //
12
+ // Beside those are the pieces a list page is built from, none of which knows
13
+ // what the rows are: LiveList and useLiveWindow (a virtual list that widens
14
+ // with the scroll), useKeyboardNavigation (a focused row), useShortcuts (one
15
+ // table of key bindings), useSelection (rows picked, with ranges),
16
+ // useUndoable (writes held so they can be taken back) and write (a form post
17
+ // that visits nothing).
18
+ //
19
+ // And fileStore with useFile: the bytes of records that declare `sync_file`,
20
+ // kept in this browser, sent to the server in the background and fetched from
21
+ // it when asked for. It needs neither Inertia nor a local database.
22
+ import { localHttpClient, write } from "./http.js"
23
+ import { affectsReads, applyRowDeltas, createLiveTransport, filterChanges, liveTransport, patchProp } from "./live.js"
24
+ import { local } from "./window.js"
25
+
26
+ // InstantRecord's Inertia pages place the first page in an attribute
27
+ // of the root element, where plain escaping is enough. Apps using
28
+ // inertia_rails's script element leave data-page absent and fall through.
29
+ const pageInAttribute = (id = "app") => {
30
+ const page = document.getElementById(id)?.dataset.page
31
+ return page ? { page: JSON.parse(page) } : {}
32
+ }
33
+
34
+ export const instantRecord = (options) => ({
35
+ live: options ? createLiveTransport(options) : liveTransport,
36
+ ...pageInAttribute(),
37
+ ...(local() ? { http: localHttpClient } : {}),
38
+ })
39
+
40
+ export { affectsReads, applyRowDeltas, createLiveTransport, filterChanges, liveTransport, localHttpClient, patchProp, write }
41
+ export { local, useHistory, useLiveParam, useLiveSearch, useLiveWindow, useStableRows, widenWindow } from "./window.js"
42
+ export { resolveFocus } from "./focus.js"
43
+ export { useKeyboardNavigation } from "./keyboard.js"
44
+ export { chord, keycaps, match } from "./chord.js"
45
+ export { useShortcuts } from "./shortcuts.js"
46
+ export { rangeBetween } from "./range.js"
47
+ export { useSelection } from "./selection.js"
48
+ export { durableHeldActions, heldActions } from "./held.js"
49
+ export { useUndoable } from "./undo.js"
50
+ export { default as LiveList } from "./LiveList.js"
51
+ export { DEFAULT_CHUNK_SIZE, FileMissing, FileStore, NoRoom, fileStore } from "./files.js"
52
+ export { useFile } from "./file.js"
53
+ export { SYNC_NOTICES_EVENT, createSyncNoticesStore, diffNotice, useSyncNotices } from "./notices.js"
@@ -0,0 +1,56 @@
1
+ // Keyboard navigation for one list: a focused row, a registry the virtual
2
+ // list answers so a row it has not drawn can be scrolled into view, and focus
3
+ // that survives whatever redraws the list. The keys themselves are bindings
4
+ // (shortcuts.js): bind j to `move(1)` and k to `move(-1)`.
5
+ import { useCallback, useEffect, useRef, useState } from "react"
6
+ import { resolveFocus } from "./focus.js"
7
+
8
+ // useKeyboardNavigation({ ids, startAt, more, onNeed })
9
+ //
10
+ // ids the list's row ids, in order
11
+ // startAt the row to start on (the one the address names)
12
+ // more whether rows exist past the end of `ids`
13
+ // onNeed called with an index past the end, to load that far
14
+ //
15
+ // Answers { focusedId, focusedIndex, focus, move, register }.
16
+ export function useKeyboardNavigation({ ids, startAt, more, onNeed }) {
17
+ const [focused, setFocused] = useState(() => ({ id: startAt || null, index: Math.max(ids.indexOf(startAt), 0) }))
18
+ const scroller = useRef(null)
19
+ const live = useRef({})
20
+ live.current = { ids, focused, more, onNeed }
21
+
22
+ // Whatever redraws the list, focus stays on its row, or passes to the row
23
+ // that took its place.
24
+ useEffect(() => {
25
+ const next = resolveFocus(ids, focused.id, focused.index)
26
+ if (next.id !== focused.id || next.index !== focused.index) setFocused(next)
27
+ }, [ids, focused])
28
+
29
+ // The virtual list registers how to bring a row into view.
30
+ const register = useCallback((scrollTo) => {
31
+ scroller.current = scrollTo
32
+ return () => {
33
+ if (scroller.current === scrollTo) scroller.current = null
34
+ }
35
+ }, [])
36
+
37
+ const focus = useCallback((id) => {
38
+ const at = live.current.ids.indexOf(id)
39
+ if (at < 0) return
40
+ setFocused({ id, index: at })
41
+ scroller.current?.(at)
42
+ }, [])
43
+
44
+ const move = useCallback((step) => {
45
+ const { ids, focused, more, onNeed } = live.current
46
+ if (!ids.length) return null
47
+ const wanted = focused.index + step
48
+ if (wanted >= ids.length && more) onNeed?.(wanted)
49
+ const at = Math.min(Math.max(wanted, 0), ids.length - 1)
50
+ setFocused({ id: ids[at], index: at })
51
+ scroller.current?.(at)
52
+ return ids[at]
53
+ }, [])
54
+
55
+ return { focusedId: focused.id, focusedIndex: focused.index, focus, move, register }
56
+ }
data/frontend/live.js ADDED
@@ -0,0 +1,298 @@
1
+ // InstantRecord as a transport for Inertia's live props.
2
+ //
3
+ // A page object names, under `liveProps`, the events each prop listens for,
4
+ // and Inertia reloads a prop when one of its events arrives: a partial
5
+ // reload, throttled, paused while the tab is hidden, and repeated for every
6
+ // live prop when a dropped connection returns.
7
+ //
8
+ // Here an event is a synced model's name (`live: { mail: MailEntry }` in
9
+ // Ruby). The runtime dispatches "instant-record:records-changed" on the window
10
+ // whenever sync, a local write, or a peer tab touched the local database, with
11
+ // structured row deltas as `detail.changes` ({ type, id, op, changed_columns,
12
+ // attrs } each) and optional read tracking as `detail.reads` ({ tables, models,
13
+ // partitions }).
14
+ //
15
+ // Two fast paths avoid unnecessary reloads:
16
+ // 1. Table/partition skipping: when structured deltas only touch unaffected
17
+ // models/tables or non-matching partitions, the handler is not invoked.
18
+ // 2. Surgical row patching: when a patcher is registered (via
19
+ // `createLiveTransport({ patch })` or `liveTransport.registerPatcher`),
20
+ // deltas can update rows in place via `applyRowDeltas` / `patchProp` and
21
+ // return true to suppress Inertia's partial reload. When any delta is
22
+ // unpatchable (wildcard, omitted large column, or filtered create), the
23
+ // transport falls back to `handler({ changes })`.
24
+ //
25
+ // Served by Rails alone there is no local database and so no signal: a slow
26
+ // poll stands in for it, and the reload goes to the server.
27
+
28
+ const CHANGED = "instant-record:records-changed"
29
+ const POLL_MS = 4000
30
+
31
+ const isLocal = () => typeof window !== "undefined" && !!window.__spinel
32
+
33
+ function matchesPartitions(delta, constraints) {
34
+ if (!constraints || typeof constraints !== "object") return true
35
+ const attrs = delta?.attrs
36
+ if (!attrs || typeof attrs !== "object") return true
37
+ const changedCols = Array.isArray(delta.changed_columns) ? delta.changed_columns : []
38
+
39
+ for (const [col, allowed] of Object.entries(constraints)) {
40
+ // On an update where the partition column itself changed, the row may have
41
+ // entered or left this partition — conservatively treat it as affecting the read.
42
+ if (delta.op === "update" && changedCols.includes(col)) continue
43
+ if (!Object.prototype.hasOwnProperty.call(attrs, col)) continue
44
+ const val = attrs[col]
45
+ if (val === null || val === undefined) continue
46
+ const list = Array.isArray(allowed) ? allowed.map(String) : [String(allowed)]
47
+ if (!list.includes(String(val))) return false
48
+ }
49
+ return true
50
+ }
51
+
52
+ // Sound check: returns true if any delta in `changes` could affect `reads`
53
+ // ({ tables, models, partitions }). Wildcard `changes` (null) or missing `reads`
54
+ // conservatively return true.
55
+ export function affectsReads(changes, reads) {
56
+ if (!changes || !reads) return true
57
+ if (changes.length === 0) return false
58
+
59
+ const models = Array.isArray(reads.models) ? reads.models : []
60
+ const tables = Array.isArray(reads.tables) ? reads.tables : []
61
+ if (models.length === 0 && tables.length === 0) return false
62
+
63
+ const partitions = reads.partitions && typeof reads.partitions === "object" ? reads.partitions : {}
64
+
65
+ return changes.some((delta) => {
66
+ if (!delta || typeof delta !== "object") return true
67
+ const type = delta.type || ""
68
+ const table = delta.table || ""
69
+ let matchedKey = null
70
+ if (type && models.includes(type)) matchedKey = type
71
+ else if (table && tables.includes(table)) matchedKey = table
72
+ if (!matchedKey) return false
73
+
74
+ const constraints = partitions[matchedKey] || (table ? partitions[table] : null)
75
+ return matchesPartitions(delta, constraints)
76
+ })
77
+ }
78
+
79
+ // Filter structured deltas for a single subscribed model, respecting optional
80
+ // page/prop read tracking and explicit channel partitions.
81
+ //
82
+ // Returns:
83
+ // null -> wildcard (anything may have changed; caller must reload)
84
+ // [] -> unaffected (skip reload)
85
+ // Delta[] -> matching deltas for this model/partition
86
+ export function filterChanges(changes, { model, reads = null, partitions = null } = {}) {
87
+ if (!changes) return null
88
+ if (!Array.isArray(changes) || changes.length === 0) return []
89
+
90
+ const modelDeltas = changes.filter((delta) => {
91
+ if (!delta || typeof delta !== "object") return false
92
+ return delta.type === model || (delta.table && delta.table === model)
93
+ })
94
+ if (modelDeltas.length === 0) return []
95
+
96
+ return modelDeltas.filter((delta) => {
97
+ if (partitions && !matchesPartitions(delta, partitions)) return false
98
+ if (reads) {
99
+ const models = Array.isArray(reads.models) ? reads.models : []
100
+ const tables = Array.isArray(reads.tables) ? reads.tables : []
101
+ const hasAnyScope = models.length > 0 || tables.length > 0
102
+ if (hasAnyScope) {
103
+ const table = delta.table || ""
104
+ const inModels = delta.type && models.includes(delta.type)
105
+ const inTables = table && tables.includes(table)
106
+ if (!inModels && !inTables) return false
107
+ } else {
108
+ // Explicit empty read set: nothing was read from the database.
109
+ return false
110
+ }
111
+ const readPartitions = reads.partitions?.[delta.type] || (delta.table ? reads.partitions?.[delta.table] : null)
112
+ if (readPartitions && !matchesPartitions(delta, readPartitions)) return false
113
+ }
114
+ return true
115
+ })
116
+ }
117
+
118
+ // Apply structured row deltas surgically to an array of rows, preserving object
119
+ // identity (`===`) for untouched rows.
120
+ //
121
+ // Returns:
122
+ // { patched: true, rows, changed } when every delta applied cleanly
123
+ // { patched: false, reason } when any delta requires a full reload
124
+ export function applyRowDeltas(rows, deltas, options = {}) {
125
+ if (!Array.isArray(rows)) return { patched: false, reason: "rows_not_array" }
126
+ if (!Array.isArray(deltas)) return { patched: false, reason: "wildcard" }
127
+ if (deltas.length === 0) return { patched: true, rows, changed: false }
128
+
129
+ const {
130
+ idKey = "id",
131
+ getId = (row) => (row && typeof row === "object" ? String(row[idKey]) : null),
132
+ create = null,
133
+ update = null,
134
+ matches = null,
135
+ insertAt = "start",
136
+ allowCreate = true,
137
+ allowUpdate = true,
138
+ allowDestroy = true,
139
+ missingUpdate = "ignore",
140
+ } = options
141
+
142
+ let next = rows.slice()
143
+ let changed = false
144
+
145
+ for (const delta of deltas) {
146
+ if (!delta || typeof delta !== "object" || !delta.op) {
147
+ return { patched: false, reason: "untyped_delta" }
148
+ }
149
+ const id = String(delta.id)
150
+ const idx = next.findIndex((row) => getId(row) === id)
151
+ const attrs = delta.attrs && typeof delta.attrs === "object" ? delta.attrs : {}
152
+ const changedCols = Array.isArray(delta.changed_columns) ? delta.changed_columns : []
153
+
154
+ if (delta.op === "destroy") {
155
+ if (!allowDestroy) return { patched: false, reason: "destroy_disallowed" }
156
+ if (idx !== -1) {
157
+ next.splice(idx, 1)
158
+ changed = true
159
+ }
160
+ continue
161
+ }
162
+
163
+ if (delta.op === "create") {
164
+ if (!allowCreate) return { patched: false, reason: "create_disallowed" }
165
+ // If a column changed but was omitted from attrs (e.g. byte cap), reload.
166
+ if (changedCols.some((col) => !Object.prototype.hasOwnProperty.call(attrs, col))) {
167
+ return { patched: false, reason: "incomplete_attrs" }
168
+ }
169
+ if (matches && !matches(attrs, delta)) continue
170
+ const built = create ? create(delta) : (Object.keys(attrs).length ? { id, ...attrs } : null)
171
+ if (!built) return { patched: false, reason: "cannot_build_row" }
172
+
173
+ if (idx !== -1) {
174
+ next[idx] = built
175
+ } else if (typeof insertAt === "function") {
176
+ next = insertAt(next, built, delta)
177
+ } else if (insertAt === "end") {
178
+ next.push(built)
179
+ } else {
180
+ next.unshift(built)
181
+ }
182
+ changed = true
183
+ continue
184
+ }
185
+
186
+ if (delta.op === "update") {
187
+ if (!allowUpdate) return { patched: false, reason: "update_disallowed" }
188
+ if (changedCols.some((col) => !Object.prototype.hasOwnProperty.call(attrs, col))) {
189
+ return { patched: false, reason: "incomplete_attrs" }
190
+ }
191
+ if (idx === -1) {
192
+ if (missingUpdate === "reload") return { patched: false, reason: "missing_row" }
193
+ continue
194
+ }
195
+ const existing = next[idx]
196
+ const updated = update ? update(existing, delta) : { ...existing, ...attrs }
197
+ if (!updated) return { patched: false, reason: "cannot_update_row" }
198
+ if (matches && !matches(updated, delta)) {
199
+ next.splice(idx, 1)
200
+ changed = true
201
+ continue
202
+ }
203
+ next[idx] = updated
204
+ changed = true
205
+ continue
206
+ }
207
+
208
+ return { patched: false, reason: "unknown_op" }
209
+ }
210
+
211
+ return { patched: true, rows: changed ? next : rows, changed }
212
+ }
213
+
214
+ // Convenience wrapper that patches either a plain array prop `[row, ...]` or a
215
+ // windowed prop `{ rows: [...], ... }` (preserving sibling keys like `more` / `limit`).
216
+ export function patchProp(propValue, deltas, options = {}) {
217
+ if (Array.isArray(propValue)) {
218
+ const result = applyRowDeltas(propValue, deltas, options)
219
+ return result.patched ? { patched: true, value: result.rows, changed: result.changed } : result
220
+ }
221
+ if (propValue && typeof propValue === "object" && Array.isArray(propValue.rows)) {
222
+ const result = applyRowDeltas(propValue.rows, deltas, options)
223
+ if (!result.patched) return result
224
+ return {
225
+ patched: true,
226
+ value: result.changed ? { ...propValue, rows: result.rows } : propValue,
227
+ changed: result.changed,
228
+ }
229
+ }
230
+ return { patched: false, reason: "unsupported_prop_shape" }
231
+ }
232
+
233
+ export function createLiveTransport(options = {}) {
234
+ const patchers = new Map()
235
+ if (options.patch && typeof options.patch === "object") {
236
+ for (const [model, fn] of Object.entries(options.patch)) {
237
+ if (typeof fn === "function") patchers.set(model, fn)
238
+ }
239
+ }
240
+ const defaultPatch = typeof options.patch === "function" ? options.patch : null
241
+ const getReads = typeof options.reads === "function" ? options.reads : null
242
+ const onSkip = typeof options.onSkip === "function" ? options.onSkip : null
243
+
244
+ return {
245
+ registerPatcher(model, patcher) {
246
+ patchers.set(model, patcher)
247
+ return () => {
248
+ if (patchers.get(model) === patcher) patchers.delete(model)
249
+ }
250
+ },
251
+
252
+ subscribe(channel, model, handler) {
253
+ if (!channel || channel.name !== "instant_record") return () => {}
254
+
255
+ const changed = (event) => {
256
+ const changes = event?.detail?.changes ?? null
257
+ const reads = event?.detail?.reads ?? getReads?.() ?? channel.reads ?? (typeof window !== "undefined" ? window.__spinel?.reads ?? null : null)
258
+ const partitions = channel.partitions ?? null
259
+
260
+ const mine = filterChanges(changes, { model, reads, partitions })
261
+ if (mine === null) return handler({ changes: null })
262
+ if (mine.length === 0) {
263
+ onSkip?.({ model, channel, changes, reads })
264
+ return
265
+ }
266
+
267
+ const patcher = patchers.get(model) || defaultPatch
268
+ if (patcher) {
269
+ const applied = patcher(mine, { model, channel, reads, applyRowDeltas, patchProp })
270
+ if (applied === true || applied?.patched === true) return
271
+ }
272
+
273
+ handler({ changes: mine })
274
+ }
275
+
276
+ window.addEventListener(CHANGED, changed)
277
+ const poll = isLocal() ? null : setInterval(() => navigator.onLine && changed(), POLL_MS)
278
+ return () => {
279
+ window.removeEventListener(CHANGED, changed)
280
+ if (poll) clearInterval(poll)
281
+ }
282
+ },
283
+
284
+ onStatusChange(callback) {
285
+ const up = () => callback(true)
286
+ const down = () => callback(false)
287
+ window.addEventListener("online", up)
288
+ window.addEventListener("offline", down)
289
+ callback(navigator.onLine)
290
+ return () => {
291
+ window.removeEventListener("online", up)
292
+ window.removeEventListener("offline", down)
293
+ }
294
+ },
295
+ }
296
+ }
297
+
298
+ export const liveTransport = createLiveTransport()