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,118 @@
1
+ // React hook for InstantRecord::SyncNotice quarantine items.
2
+ //
3
+ // In the compiled browser runtime it talks to the worker's `notices` bridge
4
+ // and listens for `instant-record:sync-notices` events. Against a Rails server
5
+ // it falls back to the mounted engine's `/instant_record/sync_notices` JSON
6
+ // endpoints.
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
8
+ import { SYNC_NOTICES_EVENT, createSyncNoticesStore, diffNotice } from "./sync-notices.js"
9
+ import { local } from "./window.js"
10
+
11
+ const xsrf = () =>
12
+ typeof document === "undefined"
13
+ ? ""
14
+ : decodeURIComponent(document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]*)/)?.[1] || "")
15
+
16
+ function workerTransport() {
17
+ return {
18
+ list: () => window.__spinel.call("notices", { action: "list" }),
19
+ resolve: ({ action, id, overrides }) =>
20
+ window.__spinel.call("notices", { action, id, overrides }),
21
+ }
22
+ }
23
+
24
+ function httpTransport(endpoint) {
25
+ const base = endpoint.replace(/\/+$/, "")
26
+ const jsonHeaders = () => {
27
+ const headers = { Accept: "application/json", "Content-Type": "application/json" }
28
+ const token = xsrf()
29
+ if (token) headers["X-XSRF-TOKEN"] = token
30
+ return headers
31
+ }
32
+
33
+ return {
34
+ async list() {
35
+ const response = await fetch(`${base}.json`, {
36
+ headers: { Accept: "application/json" },
37
+ credentials: "same-origin",
38
+ })
39
+ if (!response.ok) return { ok: false, error: `Request failed (${response.status})` }
40
+ return response.json()
41
+ },
42
+
43
+ async resolve({ action, id, overrides }) {
44
+ const response = await fetch(`${base}/${encodeURIComponent(id)}/${action}.json`, {
45
+ method: "POST",
46
+ headers: jsonHeaders(),
47
+ body: JSON.stringify({ overrides: overrides || {} }),
48
+ credentials: "same-origin",
49
+ })
50
+ const data = await response.json().catch(() => ({}))
51
+ if (!response.ok) return { ok: false, error: data.error || `Request failed (${response.status})`, notices: data.notices }
52
+ return data
53
+ },
54
+ }
55
+ }
56
+
57
+ export function useSyncNotices({
58
+ endpoint = "/instant_record/sync_notices",
59
+ recordType = null,
60
+ recordId = null,
61
+ } = {}) {
62
+ const isLocal = local()
63
+ const initial = isLocal && Array.isArray(window.__spinel?.notices) ? window.__spinel.notices : []
64
+ const transport = useMemo(
65
+ () => (isLocal ? workerTransport() : httpTransport(endpoint)),
66
+ [isLocal, endpoint],
67
+ )
68
+ const storeRef = useRef(null)
69
+ const [state, setState] = useState(() => {
70
+ const store = createSyncNoticesStore({ transport, initial, recordType, recordId })
71
+ return store.snapshot()
72
+ })
73
+
74
+ useEffect(() => {
75
+ const store = createSyncNoticesStore({
76
+ transport,
77
+ initial: isLocal && Array.isArray(window.__spinel?.notices) ? window.__spinel.notices : [],
78
+ recordType,
79
+ recordId,
80
+ onChange: setState,
81
+ })
82
+ storeRef.current = store
83
+ setState(store.snapshot())
84
+ store.refresh()
85
+
86
+ if (!isLocal || typeof window === "undefined") return undefined
87
+ const onNotices = (event) => {
88
+ store.setNotices(event?.detail?.notices || [])
89
+ }
90
+ const onRecordsChanged = () => {
91
+ store.refresh()
92
+ }
93
+ window.addEventListener(SYNC_NOTICES_EVENT, onNotices)
94
+ window.addEventListener("instant-record:records-changed", onRecordsChanged)
95
+ return () => {
96
+ window.removeEventListener(SYNC_NOTICES_EVENT, onNotices)
97
+ window.removeEventListener("instant-record:records-changed", onRecordsChanged)
98
+ }
99
+ }, [transport, isLocal, recordType, recordId])
100
+
101
+ const refresh = useCallback(() => storeRef.current?.refresh(), [])
102
+ const retry = useCallback((id, overrides = {}) => storeRef.current?.retry(id, overrides), [])
103
+ const fork = useCallback((id, overrides = {}) => storeRef.current?.fork(id, overrides), [])
104
+ const dismiss = useCallback((id) => storeRef.current?.dismiss(id), [])
105
+
106
+ return {
107
+ notices: state.notices,
108
+ count: state.count,
109
+ loading: state.loading,
110
+ error: state.error,
111
+ refresh,
112
+ retry,
113
+ fork,
114
+ dismiss,
115
+ }
116
+ }
117
+
118
+ export { SYNC_NOTICES_EVENT, createSyncNoticesStore, diffNotice }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "instant_record",
3
+ "version": "0.3.0",
4
+ "description": "InstantRecord for an Inertia page in React: live props from the local database, the list and keyboard pieces built on them, and a record's file kept in the browser",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": { ".": "./index.js", "./files": "./files.js" },
9
+ "peerDependencies": {
10
+ "@inertiajs/core": "^3.11.0",
11
+ "@inertiajs/react": "^3.11.0",
12
+ "react": "^19.0.0",
13
+ "react-virtuoso": "^4.18.0"
14
+ }
15
+ }
data/frontend/range.js ADDED
@@ -0,0 +1,10 @@
1
+ // The ids from `anchorId` to `cursorId` in `ids`, both included, in list
2
+ // order whichever way the range runs. An anchor that left the list leaves
3
+ // only the cursor's row.
4
+ export function rangeBetween(ids, anchorId, cursorId) {
5
+ const cursor = ids.indexOf(cursorId)
6
+ if (cursor < 0) return []
7
+ const anchor = ids.indexOf(anchorId)
8
+ if (anchor < 0) return [cursorId]
9
+ return ids.slice(Math.min(anchor, cursor), Math.max(anchor, cursor) + 1)
10
+ }
@@ -0,0 +1,47 @@
1
+ // A selected set over a list of ids, with the anchor a range grows from.
2
+ // What a selection means (archive it, mark it) is the page's business.
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
4
+ import { rangeBetween } from "./range.js"
5
+
6
+ const NONE = { selected: new Set(), anchor: null }
7
+
8
+ // useSelection(ids) answers { selected, anchor, toggle, extendTo, all, clear }.
9
+ //
10
+ // toggle(id) selects or deselects one row, and anchors there
11
+ // extendTo(id, from) replaces the selection with the range from the anchor
12
+ // to `id`, so a range shrinks as well as grows. With
13
+ // nothing anchored yet, `from` is the anchor.
14
+ // all() every id in the list
15
+ //
16
+ // An id that leaves the list leaves the selection.
17
+ export function useSelection(ids) {
18
+ const [state, setState] = useState(NONE)
19
+ const live = useRef(ids)
20
+ live.current = ids
21
+
22
+ useEffect(() => {
23
+ setState((state) => {
24
+ if (!state.selected.size) return state
25
+ const here = new Set(ids)
26
+ const selected = new Set([...state.selected].filter((id) => here.has(id)))
27
+ if (selected.size === state.selected.size) return state
28
+ return selected.size ? { ...state, selected } : NONE
29
+ })
30
+ }, [ids])
31
+
32
+ const toggle = useCallback((id) => setState((state) => {
33
+ const selected = new Set(state.selected)
34
+ if (!selected.delete(id)) selected.add(id)
35
+ return selected.size ? { selected, anchor: id } : NONE
36
+ }), [])
37
+
38
+ const extendTo = useCallback((id, from) => setState((state) => {
39
+ const anchor = state.anchor ?? from ?? id
40
+ return { selected: new Set(rangeBetween(live.current, anchor, id)), anchor }
41
+ }), [])
42
+
43
+ const all = useCallback(() => setState({ selected: new Set(live.current), anchor: live.current[0] ?? null }), [])
44
+ const clear = useCallback(() => setState(NONE), [])
45
+
46
+ return useMemo(() => ({ ...state, toggle, extendTo, all, clear }), [state, toggle, extendTo, all, clear])
47
+ }
@@ -0,0 +1,25 @@
1
+ // One keydown listener for a page, run from a table of bindings (chord.js
2
+ // says what a binding is). Keys belong to the text while a field has focus,
3
+ // unless a binding says otherwise, and Escape hands them back.
4
+ import { useEffect, useRef } from "react"
5
+ import { match, place } from "./chord.js"
6
+
7
+ export function useShortcuts(bindings) {
8
+ const live = useRef(bindings)
9
+ live.current = bindings
10
+
11
+ useEffect(() => {
12
+ const press = (event) => {
13
+ if (event.defaultPrevented) return
14
+ const binding = match(live.current, event, event.target)
15
+ if (!binding) {
16
+ if (event.key === "Escape" && place(event.target).typing) event.target.blur()
17
+ return
18
+ }
19
+ event.preventDefault()
20
+ binding.run(event)
21
+ }
22
+ window.addEventListener("keydown", press)
23
+ return () => window.removeEventListener("keydown", press)
24
+ }, [])
25
+ }
@@ -0,0 +1,130 @@
1
+ // Pure state and diff helpers for InstantRecord::SyncNotice quarantine items.
2
+ // Kept framework-free so the logic tests directly under Node without React.
3
+
4
+ const BOOKKEEPING = new Set(["id", "server_version", "sync_state", "created_at", "updated_at"])
5
+
6
+ export const SYNC_NOTICES_EVENT = "instant-record:sync-notices"
7
+
8
+ // Compute field-level differences between a notice's attempted local changes
9
+ // and the winning server attributes, skipping gem bookkeeping columns.
10
+ export function diffNotice(notice) {
11
+ if (!notice || typeof notice !== "object") return []
12
+ const attempted = notice.attempted_changes && typeof notice.attempted_changes === "object"
13
+ ? notice.attempted_changes
14
+ : {}
15
+ const server = notice.server_attributes && typeof notice.server_attributes === "object"
16
+ ? notice.server_attributes
17
+ : {}
18
+ const serverKeys = Object.keys(server)
19
+ const keys = (notice.operation === "destroy" ? serverKeys : Object.keys(attempted))
20
+ .filter((key) => !BOOKKEEPING.has(key))
21
+
22
+ const diffs = []
23
+ for (const field of keys) {
24
+ const local = notice.operation === "destroy" ? null : attempted[field]
25
+ const remote = server[field]
26
+ if (serverKeys.length > 0 && local === remote) continue
27
+ diffs.push({ field, local, server: remote })
28
+ }
29
+ return diffs
30
+ }
31
+
32
+ export function filterNotices(notices, { recordType = null, recordId = null } = {}) {
33
+ const list = Array.isArray(notices) ? notices : []
34
+ return list.filter((notice) => {
35
+ if (recordType && notice.record_type !== recordType) return false
36
+ if (recordId && notice.record_id !== recordId) return false
37
+ return true
38
+ })
39
+ }
40
+
41
+ // Framework-free controller driving useSyncNotices. `transport` abstracts the
42
+ // compiled browser worker (`window.__spinel.call("notices", ...)`) vs server
43
+ // HTTP requests so tests can exercise every resolution path directly.
44
+ export function createSyncNoticesStore({
45
+ transport,
46
+ initial = [],
47
+ recordType = null,
48
+ recordId = null,
49
+ onChange = () => {},
50
+ } = {}) {
51
+ let state = {
52
+ all: Array.isArray(initial) ? initial : [],
53
+ notices: filterNotices(initial, { recordType, recordId }),
54
+ loading: false,
55
+ error: null,
56
+ }
57
+
58
+ const emit = (patch) => {
59
+ const all = patch.all !== undefined ? patch.all : state.all
60
+ state = {
61
+ ...state,
62
+ ...patch,
63
+ all,
64
+ notices: filterNotices(all, { recordType, recordId }),
65
+ }
66
+ onChange(snapshot())
67
+ }
68
+
69
+ const snapshot = () => ({
70
+ notices: state.notices,
71
+ count: state.notices.length,
72
+ loading: state.loading,
73
+ error: state.error,
74
+ })
75
+
76
+ const setNotices = (list) => {
77
+ emit({ all: Array.isArray(list) ? list : [], error: null })
78
+ }
79
+
80
+ const refresh = async () => {
81
+ emit({ loading: true, error: null })
82
+ try {
83
+ const reply = await transport.list()
84
+ if (!reply || reply.ok === false) {
85
+ emit({ loading: false, error: reply?.error || "Could not load sync notices" })
86
+ return reply || { ok: false, error: "Could not load sync notices" }
87
+ }
88
+ emit({ all: reply.notices || [], loading: false, error: null })
89
+ return reply
90
+ } catch (err) {
91
+ const message = err?.message || String(err)
92
+ emit({ loading: false, error: message })
93
+ return { ok: false, error: message }
94
+ }
95
+ }
96
+
97
+ const act = async (action, id, overrides = {}) => {
98
+ emit({ loading: true, error: null })
99
+ try {
100
+ const reply = await transport.resolve({ action, id, overrides })
101
+ if (!reply || reply.ok === false) {
102
+ const message = reply?.error || `Could not ${action} sync notice`
103
+ emit({
104
+ all: Array.isArray(reply?.notices) ? reply.notices : state.all,
105
+ loading: false,
106
+ error: message,
107
+ })
108
+ return reply || { ok: false, error: message }
109
+ }
110
+ const next = Array.isArray(reply.notices)
111
+ ? reply.notices
112
+ : state.all.filter((notice) => notice.id !== id)
113
+ emit({ all: next, loading: false, error: null })
114
+ return reply
115
+ } catch (err) {
116
+ const message = err?.message || String(err)
117
+ emit({ loading: false, error: message })
118
+ return { ok: false, error: message }
119
+ }
120
+ }
121
+
122
+ return {
123
+ snapshot,
124
+ setNotices,
125
+ refresh,
126
+ retry: (id, overrides = {}) => act("retry", id, overrides),
127
+ fork: (id, overrides = {}) => act("fork", id, overrides),
128
+ dismiss: (id) => act("dismiss", id),
129
+ }
130
+ }
data/frontend/undo.js ADDED
@@ -0,0 +1,48 @@
1
+ // Undo for a page's writes:
2
+ // - On compiled local-SQLite pages that pass `durable` (held OutboxMutation
3
+ // descriptors with `release_at`) and `onCancel`, tracks durable SQLite holds
4
+ // across reloads without flushing on pagehide.
5
+ // - On non-compiled server-rendered pages (or when `durable` is omitted), holds
6
+ // writes in memory for `ms` and flushes with `{ keepalive: true }` on leave.
7
+ import { useEffect, useMemo, useRef, useState } from "react"
8
+ import { durableHeldActions, heldActions } from "./held.js"
9
+ import { local } from "./window.js"
10
+
11
+ const NOTHING = { pending: [], held: new Set() }
12
+
13
+ // useUndoable({ ms, durable, onCancel }) answers { pending, held, hold, undo, flush }:
14
+ // held.js says what each is. `held` is the ids to leave out of what is drawn.
15
+ export function useUndoable({ ms = 5000, durable, onCancel } = {}) {
16
+ const isDurable = local() && Array.isArray(durable)
17
+ const [state, setState] = useState(NOTHING)
18
+ const cancelRef = useRef(onCancel)
19
+ cancelRef.current = onCancel
20
+
21
+ const volatile = useRef(null)
22
+ const persistent = useRef(null)
23
+ if (!isDurable) volatile.current ||= heldActions({ ms, onChange: setState })
24
+ if (isDurable) persistent.current ||= durableHeldActions({ onChange: setState, onCancel: (entry) => cancelRef.current?.(entry) })
25
+
26
+ useEffect(() => {
27
+ if (!isDurable) return
28
+ persistent.current.sync(durable)
29
+ return () => persistent.current.dispose()
30
+ }, [isDurable, durable])
31
+
32
+ useEffect(() => {
33
+ if (isDurable) return
34
+ const leave = () => volatile.current.flush({ keepalive: true })
35
+ window.addEventListener("pagehide", leave)
36
+ return () => {
37
+ window.removeEventListener("pagehide", leave)
38
+ leave()
39
+ }
40
+ }, [isDurable])
41
+
42
+ return useMemo(() => ({
43
+ ...state,
44
+ hold: (action) => (isDurable ? action?.commit?.() : volatile.current.hold(action)),
45
+ undo: () => (isDurable ? persistent.current.undo() : volatile.current.undo()),
46
+ flush: (options) => (isDurable ? persistent.current.flush(options) : volatile.current.flush(options)),
47
+ }), [state, isDurable])
48
+ }
@@ -0,0 +1,181 @@
1
+ // What a page asks of InstantRecord beyond what Inertia already gives it.
2
+ // Nothing here knows about mail: it is written to move into the gem.
3
+ import { router, usePage } from "@inertiajs/react"
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react"
5
+
6
+ // True where the page runs beside a local database (the compiled runtime).
7
+ export const local = () => typeof window !== "undefined" && !!window.__spinel
8
+ // True where every row is at hand: no local database, or one whose fill is done.
9
+ // Out here because useLiveWindow has a `window` of its own.
10
+ const whole = () => !local() || window.__spinel.history?.done === true
11
+
12
+ // The local database holds a window of each model. This asks the worker to
13
+ // widen it past `before`, and answers { ok, has_more }. With no local
14
+ // database the server already has everything, so there is nothing to widen.
15
+ export function widenWindow(request) {
16
+ const worker = local() && window.__spinel.worker
17
+ if (!worker) return Promise.resolve({ ok: true })
18
+ return new Promise((resolve) => {
19
+ const channel = new MessageChannel()
20
+ const timer = setTimeout(() => resolve({ ok: false, busy: true, error: "history request timed out" }), 15000)
21
+ channel.port1.onmessage = (event) => {
22
+ clearTimeout(timer)
23
+ resolve(event.data || { ok: false, error: "empty reply" })
24
+ }
25
+ worker.postMessage({ type: "instant_record.fetch_history", request }, [channel.port2])
26
+ })
27
+ }
28
+
29
+ // How much of a model's history the local database holds, as the worker's
30
+ // background fill reports it: { done, full, rows }. `done` says the beginning
31
+ // is here, so every read and every count is whole. With no local database the
32
+ // server answers and everything is whole already.
33
+ export function useHistory() {
34
+ const [state, setState] = useState(() => (local() ? window.__spinel.history || { done: false } : { done: true }))
35
+ useEffect(() => {
36
+ if (!local()) return
37
+ const update = (event) => setState(event.detail)
38
+ window.addEventListener("instant-record:history", update)
39
+ if (window.__spinel.history) setState(window.__spinel.history)
40
+ return () => window.removeEventListener("instant-record:history", update)
41
+ }, [])
42
+ return state
43
+ }
44
+
45
+ // useLiveSearch widens a search past what the local database holds. The page
46
+ // has already answered `term` from that database. This asks the sync server
47
+ // for the matches it holds beyond it, and reloads `only` when some arrive and
48
+ // the reader is still on the same term. Answers { waiting, partial }: partial
49
+ // says the server could not be asked, so what is shown is this device's part.
50
+ export function useLiveSearch(term, { only, model }) {
51
+ const [state, setState] = useState({ waiting: false, partial: false })
52
+ const current = useRef(term)
53
+ current.current = term
54
+
55
+ useEffect(() => {
56
+ if (!term || !local()) return setState({ waiting: false, partial: false })
57
+ setState({ waiting: true, partial: false })
58
+ widenWindow({ type: model, search: term }).then((reply) => {
59
+ if (current.current !== term) return
60
+ setState({ waiting: false, partial: !reply.ok })
61
+ if (reply.ok && reply.applied > 0) router.reload({ only })
62
+ })
63
+ }, [term, model])
64
+ return state
65
+ }
66
+
67
+ // useLiveParam keeps one query parameter of the address at `value` and the
68
+ // props that depend on it answered for it.
69
+ //
70
+ // only the props to reload when the value changes
71
+ // answered the value the props on the page were answered for
72
+ // omit (value) => true where the address should not carry it
73
+ //
74
+ // The address changes first, with a client-side visit, and the partial
75
+ // reload follows. Every reload, this one or one Inertia starts for a live
76
+ // prop, reads the address as it stands, so none can answer for an older
77
+ // value and put it back. An answer that still arrives for another value is
78
+ // asked for once more.
79
+ export function useLiveParam(name, value, { only, answered, omit }) {
80
+ const { url } = usePage()
81
+ const asked = useRef(null)
82
+
83
+ useEffect(() => {
84
+ if (value === null || value === undefined) return
85
+ const want = String(value)
86
+ const address = new URL(url, window.location.origin)
87
+ const current = address.searchParams.get(name)
88
+ const stale = String(answered) !== want && asked.current !== `${want}:${answered}`
89
+ const reload = () => {
90
+ if (!stale) return
91
+ asked.current = `${want}:${answered}`
92
+ router.reload({ only })
93
+ }
94
+ if (current === want || (current === null && omit?.(value))) return reload()
95
+
96
+ if (omit?.(value)) address.searchParams.delete(name)
97
+ else address.searchParams.set(name, want)
98
+ router.replace({ url: address.pathname + address.search, preserveState: true, preserveScroll: true, onFinish: reload })
99
+ }, [name, value, answered, url])
100
+ }
101
+
102
+ // useLiveWindow grows a list prop with the reader's scroll.
103
+ //
104
+ // prop the prop's name, to reload it alone
105
+ // window the prop itself: { rows, more, limit }, the rows, whether this
106
+ // database holds more, and the limit the answer was made for
107
+ // model the synced model the rows are, by name
108
+ // cursor (row) => { created_at, id } of a row, to ask for what is older
109
+ // search the term the list is narrowed by, if any, so older pages are too
110
+ //
111
+ // Answers { more, older, failed }. `older(upTo)` loads the next page, or as
112
+ // far as index `upTo`: first into the local database where there is one, then
113
+ // into the prop, by a wider `limit` in the address. The list stays one prop
114
+ // however long it gets, so a live reload keeps all of it current and a
115
+ // reload of the page returns to the same depth.
116
+ export function useLiveWindow({ prop, window, model, cursor, search = "", pageSize = 50 }) {
117
+ const [limit, setLimit] = useState(window.limit)
118
+ const [exhausted, setExhausted] = useState(false)
119
+ const [failed, setFailed] = useState(false)
120
+ const only = useMemo(() => [prop], [prop])
121
+ useLiveParam("limit", limit, { only, answered: window.limit, omit: (value) => value <= pageSize })
122
+ // Beside a local database, older rows may still be on the sync server.
123
+ const more = window.more || (local() && !exhausted)
124
+ const busy = useRef(false)
125
+ const now = useRef({})
126
+ now.current = { window, more, limit, search }
127
+ // Another search is another list: start it at the first page. The search
128
+ // the page arrived with keeps the depth its address asked for.
129
+ const searched = useRef(search)
130
+ useEffect(() => {
131
+ if (searched.current === search) return
132
+ searched.current = search
133
+ setExhausted(false)
134
+ setLimit(pageSize)
135
+ }, [search, pageSize])
136
+
137
+ const older = useCallback(async (upTo = 0) => {
138
+ const { window, more, limit, search } = now.current
139
+ // One step at a time: wait for the answer to the last one.
140
+ if (busy.current || !more || window.limit < limit) return
141
+ busy.current = true
142
+ try {
143
+ const last = window.rows.at(-1)
144
+ // Until the whole history is here, rows the database holds further down
145
+ // may lie past a gap (a search brought them in), so the page below the
146
+ // last row is asked for even when there are local rows to show. A page
147
+ // asked for before is answered by the worker without the server.
148
+ if (last && (!window.more || !whole())) {
149
+ const reply = await widenWindow({ type: model, before: cursor(last), limit: pageSize, ...(search ? { search } : {}) })
150
+ if (!reply.ok) throw new Error(reply.error)
151
+ if (reply.has_more === false) setExhausted(true)
152
+ }
153
+ setFailed(false)
154
+ setLimit(Math.max(window.limit + pageSize, Math.ceil((upTo + 1) / pageSize) * pageSize))
155
+ } catch {
156
+ setFailed(true)
157
+ } finally {
158
+ busy.current = false
159
+ }
160
+ }, [model, cursor, pageSize])
161
+
162
+ return { more, older, failed }
163
+ }
164
+
165
+ // Turns each raw row of a prop into an object once, and hands back the same
166
+ // object for as long as the row's data is unchanged, so a memoized row
167
+ // component redraws only when its own record did.
168
+ export function useStableRows(raw, build) {
169
+ const kept = useRef(new Map())
170
+ return useMemo(() => {
171
+ const next = new Map()
172
+ const rows = raw.map((fields) => {
173
+ const key = JSON.stringify(fields)
174
+ const row = kept.current.get(key) || build(fields)
175
+ next.set(key, row)
176
+ return row
177
+ })
178
+ kept.current = next
179
+ return rows
180
+ }, [raw, build])
181
+ }
@@ -2,50 +2,38 @@ require "rails/generators"
2
2
 
3
3
  module InstantRecord
4
4
  module Generators
5
- # Prepares a Rails app for InstantRecord's browser runtime:
6
- # wasmify environment, PGlite database config, and a PWA shell
7
- # wired with the InstantRecord sync driver.
8
5
  class InstallGenerator < Rails::Generators::Base
9
6
  source_root File.expand_path("templates", __dir__)
10
7
 
11
- def run_wasmify_install
12
- rake "wasmify:install"
8
+ def self.source_paths
9
+ [source_root, File.expand_path("../../../../compiled", __dir__)]
13
10
  end
14
11
 
15
- def generate_pwa_shell
16
- rake "wasmify:pwa"
12
+ def install_toolchain_config
13
+ copy_file "toolchain.env.example", "config/instant_record_toolchain.env"
17
14
  end
18
15
 
19
- def configure_pglite_database
20
- gsub_file "config/database.yml", '{ "nulldb" }', '{ "pglite" }'
21
- inject_into_file "config/database.yml", " js_interface: pglite4rails\n",
22
- after: /^wasm:\n adapter: .*\n/
23
- end
24
-
25
- def install_sync_driver
26
- copy_file "rails.sw.js", "pwa/rails.sw.js", force: true
27
- copy_file "database.js", "pwa/database.js", force: true
28
- # Auto-booting splash: registers the worker and reloads into the app.
29
- # (wasmify's boot.html stays available as a debug page.)
30
- copy_file "index.html", "pwa/index.html", force: true
31
- end
32
-
33
- def use_pglite_in_pwa
34
- gsub_file "pwa/package.json", /"wasmify-rails": "\^[\d.]+"/, '"wasmify-rails": "^0.2.3"'
35
- gsub_file "pwa/package.json", %r{"@sqlite\.org/sqlite-wasm": "[^"]+"}, '"@electric-sql/pglite": "^0.3.0"'
36
- gsub_file "pwa/vite.config.js", %r{exclude: \["@sqlite\.org/sqlite-wasm"\]}, 'exclude: ["@electric-sql/pglite"]'
16
+ def install_initializer
17
+ copy_file "instant_record.rb", "config/initializers/instant_record.rb"
37
18
  end
38
19
 
39
20
  def show_next_steps
40
21
  say <<~MSG
41
22
 
42
- InstantRecord is set up. Next:
23
+ Next steps for InstantRecord:
43
24
 
44
- 1. Mark the gems your app needs in the browser with `group: [:default, :wasm]` in the Gemfile
45
- 2. bin/rails db:migrate # engine tables (outbox, change log, ...)
46
- 3. bin/rails instant_record:build # compile + pack the browser bundle
47
- 4. cd pwa && yarn install && yarn dev # boot it
25
+ 1. Fill in tool paths in config/instant_record_toolchain.env
26
+ (see compiled/README.md for Roundhouse, Spinel, WASI SDK, SQLite, and npm setup).
27
+ 2. Include InstantRecord::Syncable in your synced models. Each table needs:
28
+ id: :string, server_version: :integer (default: 0, null: false),
29
+ sync_state: :string (default: "synced", null: false)
30
+ 3. Run migrations, check your toolchain, and compile:
31
+ bin/rails db:migrate
32
+ bin/rails instant_record:doctor
33
+ bin/rails instant_record:compile
48
34
 
35
+ The browser site is written to tmp/instant_record/compiled/web/dist.
36
+ Review config/initializers/instant_record.rb to configure scoping, file storage, or hosting.
49
37
  MSG
50
38
  end
51
39
  end