@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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 (283) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +201 -0
  3. package/README.md +233 -2
  4. package/bin/ui-kit.js +12 -0
  5. package/dist/alchemy/app.d.ts +34 -0
  6. package/dist/alchemy/app.js +88 -0
  7. package/dist/alchemy/index.d.ts +11 -0
  8. package/dist/alchemy/index.js +11 -0
  9. package/dist/alchemy/live-rooms.d.ts +21 -0
  10. package/dist/alchemy/live-rooms.js +31 -0
  11. package/dist/alchemy/migrations.d.ts +28 -0
  12. package/dist/alchemy/migrations.js +56 -0
  13. package/dist/alchemy/stage.d.ts +20 -0
  14. package/dist/alchemy/stage.js +20 -0
  15. package/dist/alchemy/wrangler-config.d.ts +76 -0
  16. package/dist/alchemy/wrangler-config.js +82 -0
  17. package/dist/build/app-modules.d.ts +11 -0
  18. package/dist/build/app-modules.js +40 -0
  19. package/dist/build/check.d.ts +4 -0
  20. package/dist/build/check.js +170 -0
  21. package/dist/build/cli.d.ts +1 -0
  22. package/dist/build/cli.js +79 -0
  23. package/dist/build/feature.d.ts +8 -0
  24. package/dist/build/feature.js +24 -0
  25. package/dist/build/index.d.ts +13 -0
  26. package/dist/build/index.js +13 -0
  27. package/dist/build/measure-cpu.d.ts +2 -0
  28. package/dist/build/measure-cpu.js +196 -0
  29. package/dist/build/prerender.d.ts +5 -0
  30. package/dist/build/prerender.js +109 -0
  31. package/dist/build/preview.d.ts +7 -0
  32. package/dist/build/preview.js +41 -0
  33. package/dist/build/seo-files.d.ts +27 -0
  34. package/dist/build/seo-files.js +24 -0
  35. package/dist/client/head-swap.d.ts +45 -0
  36. package/dist/client/head-swap.js +183 -0
  37. package/dist/client/hydration-pass.d.ts +56 -0
  38. package/dist/client/hydration-pass.js +186 -0
  39. package/dist/client/hydration-reset.d.ts +82 -0
  40. package/dist/client/hydration-reset.js +154 -0
  41. package/dist/client/index.d.ts +37 -0
  42. package/dist/client/index.js +65 -0
  43. package/dist/client/nav-client.d.ts +35 -0
  44. package/dist/client/nav-client.js +371 -0
  45. package/dist/live/collab/doc-provider.d.ts +74 -0
  46. package/dist/live/collab/doc-provider.js +412 -0
  47. package/dist/live/collab/index.d.ts +51 -0
  48. package/dist/live/collab/index.jsx +142 -0
  49. package/dist/live/collab-status.d.ts +25 -0
  50. package/dist/live/collab-status.js +17 -0
  51. package/dist/live/cursors/cursor-engine.d.ts +57 -0
  52. package/dist/live/cursors/cursor-engine.js +243 -0
  53. package/dist/live/cursors/index.d.ts +46 -0
  54. package/dist/live/cursors/index.jsx +110 -0
  55. package/dist/live/declaration.d.ts +113 -0
  56. package/dist/live/declaration.js +94 -0
  57. package/dist/live/index.d.ts +8 -0
  58. package/dist/live/index.js +8 -0
  59. package/dist/live/protocol.d.ts +224 -0
  60. package/dist/live/protocol.js +272 -0
  61. package/dist/live/server/doc-store.d.ts +68 -0
  62. package/dist/live/server/doc-store.js +187 -0
  63. package/dist/live/server/index.d.ts +60 -0
  64. package/dist/live/server/index.js +77 -0
  65. package/dist/live/server/room-presence.d.ts +24 -0
  66. package/dist/live/server/room-presence.js +123 -0
  67. package/dist/live/server/room-sockets.d.ts +65 -0
  68. package/dist/live/server/room-sockets.js +97 -0
  69. package/dist/live/server/room.d.ts +20 -0
  70. package/dist/live/server/room.js +348 -0
  71. package/dist/live/server/route.d.ts +56 -0
  72. package/dist/live/server/route.js +159 -0
  73. package/dist/live/server/types.d.ts +163 -0
  74. package/dist/live/server/types.js +2 -0
  75. package/dist/logic/agent-actions.d.ts +133 -0
  76. package/dist/logic/agent-actions.js +150 -0
  77. package/dist/logic/command-types.d.ts +53 -0
  78. package/dist/logic/command-types.js +0 -0
  79. package/dist/logic/dev.d.ts +9 -0
  80. package/dist/logic/dev.js +10 -0
  81. package/dist/logic/draft-rebase.d.ts +59 -0
  82. package/dist/logic/draft-rebase.js +71 -0
  83. package/dist/logic/form-state.d.ts +105 -0
  84. package/dist/logic/form-state.js +93 -0
  85. package/dist/logic/head.d.ts +145 -0
  86. package/dist/logic/head.js +140 -0
  87. package/dist/logic/index.d.ts +27 -0
  88. package/dist/logic/index.js +25 -0
  89. package/dist/logic/island-def.d.ts +89 -0
  90. package/dist/logic/island-def.js +59 -0
  91. package/dist/logic/kit-commands.d.ts +104 -0
  92. package/dist/logic/kit-commands.js +72 -0
  93. package/dist/logic/kit-errors.d.ts +25 -0
  94. package/dist/logic/kit-errors.js +6 -0
  95. package/dist/logic/listen.d.ts +99 -0
  96. package/dist/logic/listen.js +92 -0
  97. package/dist/logic/mutation-def.d.ts +65 -0
  98. package/dist/logic/mutation-def.js +43 -0
  99. package/dist/logic/navigation-data.d.ts +50 -0
  100. package/dist/logic/navigation-data.js +55 -0
  101. package/dist/logic/navigation-policy.d.ts +74 -0
  102. package/dist/logic/navigation-policy.js +127 -0
  103. package/dist/logic/page-model-def.d.ts +108 -0
  104. package/dist/logic/page-model-def.js +31 -0
  105. package/dist/logic/path.d.ts +31 -0
  106. package/dist/logic/path.js +48 -0
  107. package/dist/logic/query-def.d.ts +56 -0
  108. package/dist/logic/query-def.js +37 -0
  109. package/dist/logic/query-key.d.ts +24 -0
  110. package/dist/logic/query-key.js +35 -0
  111. package/dist/logic/query-types.d.ts +28 -0
  112. package/dist/logic/query-types.js +2 -0
  113. package/dist/logic/resources.d.ts +163 -0
  114. package/dist/logic/resources.js +62 -0
  115. package/dist/logic/result.d.ts +30 -0
  116. package/dist/logic/result.js +23 -0
  117. package/dist/logic/route-model.d.ts +139 -0
  118. package/dist/logic/route-model.js +207 -0
  119. package/dist/logic/route-params.d.ts +80 -0
  120. package/dist/logic/route-params.js +114 -0
  121. package/dist/logic/route-table.d.ts +308 -0
  122. package/dist/logic/route-table.js +206 -0
  123. package/dist/logic/seo.d.ts +61 -0
  124. package/dist/logic/seo.js +101 -0
  125. package/dist/logic/site.d.ts +12 -0
  126. package/dist/logic/site.js +0 -0
  127. package/dist/logic/subscriptions.d.ts +177 -0
  128. package/dist/logic/subscriptions.js +152 -0
  129. package/dist/render/index.d.ts +32 -0
  130. package/dist/render/index.js +52 -0
  131. package/dist/runtime/island-wake.d.ts +38 -0
  132. package/dist/runtime/island-wake.js +147 -0
  133. package/dist/runtime/query-scope.d.ts +224 -0
  134. package/dist/runtime/query-scope.js +222 -0
  135. package/dist/runtime/room-hub.d.ts +107 -0
  136. package/dist/runtime/room-hub.js +307 -0
  137. package/dist/runtime/subscription-runner.d.ts +71 -0
  138. package/dist/runtime/subscription-runner.js +240 -0
  139. package/dist/server/bindings.d.ts +41 -0
  140. package/dist/server/bindings.js +74 -0
  141. package/dist/server/browser.d.ts +9 -0
  142. package/dist/server/browser.js +9 -0
  143. package/dist/server/edge-cache.d.ts +28 -0
  144. package/dist/server/edge-cache.js +35 -0
  145. package/dist/server/errors.d.ts +45 -0
  146. package/dist/server/errors.js +36 -0
  147. package/dist/server/form-actions-setup.d.ts +1 -0
  148. package/dist/server/form-actions-setup.js +15 -0
  149. package/dist/server/form-actions.d.ts +121 -0
  150. package/dist/server/form-actions.js +211 -0
  151. package/dist/server/index.d.ts +36 -0
  152. package/dist/server/index.js +35 -0
  153. package/dist/server/inputs.d.ts +45 -0
  154. package/dist/server/inputs.js +77 -0
  155. package/dist/server/rate-limit.d.ts +29 -0
  156. package/dist/server/rate-limit.js +32 -0
  157. package/dist/server/read-cache.d.ts +74 -0
  158. package/dist/server/read-cache.js +58 -0
  159. package/dist/server/request-info.d.ts +17 -0
  160. package/dist/server/request-info.js +11 -0
  161. package/dist/server/request.d.ts +52 -0
  162. package/dist/server/request.js +73 -0
  163. package/dist/server/response-cookies.d.ts +23 -0
  164. package/dist/server/response-cookies.js +24 -0
  165. package/dist/server/run-effect.d.ts +42 -0
  166. package/dist/server/run-effect.js +92 -0
  167. package/dist/server/run.d.ts +63 -0
  168. package/dist/server/run.js +66 -0
  169. package/dist/server/session.d.ts +125 -0
  170. package/dist/server/session.js +247 -0
  171. package/dist/test/fake-bindings.d.ts +32 -0
  172. package/dist/test/fake-bindings.js +108 -0
  173. package/dist/test/fake-room.d.ts +66 -0
  174. package/dist/test/fake-room.js +216 -0
  175. package/dist/test/index.d.ts +19 -0
  176. package/dist/test/index.js +44 -0
  177. package/dist/test/probe.d.ts +11 -0
  178. package/dist/test/probe.js +11 -0
  179. package/dist/test/solid-jsx.d.ts +23 -0
  180. package/dist/test/solid-jsx.js +28 -0
  181. package/dist/test/solid-preload.d.ts +1 -0
  182. package/dist/test/solid-preload.js +29 -0
  183. package/dist/ui/code-editor/index.d.ts +21 -0
  184. package/dist/ui/code-editor/index.jsx +286 -0
  185. package/dist/ui/collab-text/index.d.ts +29 -0
  186. package/dist/ui/collab-text/index.jsx +96 -0
  187. package/dist/ui/components/controls.d.ts +69 -0
  188. package/dist/ui/components/controls.jsx +81 -0
  189. package/dist/ui/components/feedback.d.ts +26 -0
  190. package/dist/ui/components/feedback.jsx +80 -0
  191. package/dist/ui/components/layout.d.ts +74 -0
  192. package/dist/ui/components/layout.jsx +146 -0
  193. package/dist/ui/components/lists.d.ts +69 -0
  194. package/dist/ui/components/lists.jsx +133 -0
  195. package/dist/ui/components/navigation.d.ts +73 -0
  196. package/dist/ui/components/navigation.jsx +112 -0
  197. package/dist/ui/components/text.d.ts +34 -0
  198. package/dist/ui/components/text.jsx +163 -0
  199. package/dist/ui/index.d.ts +7 -0
  200. package/dist/ui/index.js +7 -0
  201. package/dist/ui/jsx-runtime.d.ts +19 -0
  202. package/dist/ui/jsx-runtime.js +0 -0
  203. package/dist/ui/list-keys.d.ts +31 -0
  204. package/dist/ui/list-keys.js +45 -0
  205. package/dist/ui/styles/base.css +38 -0
  206. package/dist/ui/styles/components.css +608 -0
  207. package/dist/ui/styles/tokens.css +27 -0
  208. package/dist/ui/styles/transitions.css +23 -0
  209. package/dist/ui/styles/workbench.css +428 -0
  210. package/dist/ui/styles.css +9 -0
  211. package/dist/view/agent-actions-view.d.ts +30 -0
  212. package/dist/view/agent-actions-view.js +27 -0
  213. package/dist/view/agent-surface.d.ts +42 -0
  214. package/dist/view/agent-surface.js +123 -0
  215. package/dist/view/app-scope.d.ts +51 -0
  216. package/dist/view/app-scope.js +75 -0
  217. package/dist/view/boundary.d.ts +18 -0
  218. package/dist/view/boundary.jsx +26 -0
  219. package/dist/view/command-runner.d.ts +16 -0
  220. package/dist/view/command-runner.js +245 -0
  221. package/dist/view/form.d.ts +82 -0
  222. package/dist/view/form.jsx +109 -0
  223. package/dist/view/head-view.d.ts +31 -0
  224. package/dist/view/head-view.js +46 -0
  225. package/dist/view/index.d.ts +41 -0
  226. package/dist/view/index.js +40 -0
  227. package/dist/view/island-root.d.ts +30 -0
  228. package/dist/view/island-root.js +36 -0
  229. package/dist/view/island.d.ts +102 -0
  230. package/dist/view/island.jsx +154 -0
  231. package/dist/view/match.d.ts +41 -0
  232. package/dist/view/match.js +111 -0
  233. package/dist/view/model.d.ts +92 -0
  234. package/dist/view/model.js +162 -0
  235. package/dist/view/navigation-head.d.ts +29 -0
  236. package/dist/view/navigation-head.jsx +38 -0
  237. package/dist/view/page-model.d.ts +46 -0
  238. package/dist/view/page-model.js +146 -0
  239. package/dist/view/query-effects.d.ts +87 -0
  240. package/dist/view/query-effects.js +147 -0
  241. package/dist/view/query-ok.d.ts +45 -0
  242. package/dist/view/query-ok.js +96 -0
  243. package/dist/view/query.d.ts +115 -0
  244. package/dist/view/query.jsx +179 -0
  245. package/dist/view/result-view.d.ts +14 -0
  246. package/dist/view/result-view.jsx +15 -0
  247. package/dist/view/route-pages.d.ts +43 -0
  248. package/dist/view/route-pages.js +59 -0
  249. package/dist/view/router.d.ts +44 -0
  250. package/dist/view/router.js +123 -0
  251. package/dist/vite/dev-middleware.d.ts +12 -0
  252. package/dist/vite/dev-middleware.js +39 -0
  253. package/dist/vite/dev-objects.d.ts +25 -0
  254. package/dist/vite/dev-objects.js +127 -0
  255. package/dist/vite/dev-platform.d.ts +19 -0
  256. package/dist/vite/dev-platform.js +77 -0
  257. package/dist/vite/dev-seo-files.d.ts +11 -0
  258. package/dist/vite/dev-seo-files.js +40 -0
  259. package/dist/vite/index.d.ts +53 -0
  260. package/dist/vite/index.js +148 -0
  261. package/dist/vite/local-config.d.ts +34 -0
  262. package/dist/vite/local-config.js +72 -0
  263. package/dist/vite/worker-build.d.ts +24 -0
  264. package/dist/vite/worker-build.js +84 -0
  265. package/dist/worker/create-worker.d.ts +52 -0
  266. package/dist/worker/create-worker.js +90 -0
  267. package/dist/worker/index.d.ts +12 -0
  268. package/dist/worker/index.js +12 -0
  269. package/dist/worker/page-routes.d.ts +88 -0
  270. package/dist/worker/page-routes.js +100 -0
  271. package/dist/worker/page-status.d.ts +41 -0
  272. package/dist/worker/page-status.js +23 -0
  273. package/dist/worker/request-prelude.d.ts +69 -0
  274. package/dist/worker/request-prelude.js +107 -0
  275. package/dist/worker/security.d.ts +76 -0
  276. package/dist/worker/security.js +137 -0
  277. package/dist/worker/server-app.d.ts +54 -0
  278. package/dist/worker/server-app.js +76 -0
  279. package/guards/browser-only.js +5 -0
  280. package/guards/node-only.js +6 -0
  281. package/guards/server-only.js +5 -0
  282. package/migrations/0001-sessions.sql +22 -0
  283. package/package.json +233 -5
@@ -0,0 +1,412 @@
1
+ /**
2
+ * The kit's Yjs doc provider: one doc socket
3
+ * (`/live/room/<type>/<key>/doc/<doc>`) speaking the y-websocket wire
4
+ * format (sync 0, awareness 1, auth 2, query-awareness 3) that the room
5
+ * object serves. Used by the collab part (`collab-text.tsx`); no Solid and
6
+ * no DOM beyond `WebSocket` / `document.visibilityState` (injectable), so it
7
+ * is unit-tested with a fake socket and real Yjs.
8
+ *
9
+ * Why not the stock `y-websocket` client: it closes and reconnects any
10
+ * socket that received nothing for 30 s (a lone, idle editor: one Durable
11
+ * Object request every 30 s for nothing), re-broadcasts awareness forever,
12
+ * and knows nothing of hidden tabs or Readers. The client contract
13
+ * (`docs/guides/ui-kit-live-rooms.md`, "Client") asks for:
14
+ *
15
+ * - **No idle traffic.** No liveness timer. A `ping` (auto-answered by the
16
+ * runtime without waking the room) is sent only when the viewer edits
17
+ * after `PING_MS` of silence from the server; no answer within
18
+ * `PONG_TIMEOUT_MS` means a dead socket, which reconnects. A lone idle
19
+ * editor sends nothing at all.
20
+ * - **Awareness renewals stop when idle.** Real awareness changes (caret,
21
+ * selection, name) are sent at once; `Awareness`'s 15 s renewals are sent
22
+ * only within `AWARENESS_IDLE_MS` of the last local edit or selection
23
+ * change. Peers then drop this caret after their 30 s timeout.
24
+ * - **Hidden tabs go quiet.** On hide, the local awareness is cleared at
25
+ * once (peers stop drawing this caret) and the socket closes after
26
+ * `DOC_HIDDEN_CLOSE_MS`. On show, it reconnects (sync step 1 catches up)
27
+ * and the awareness comes back.
28
+ * - **Readers never write.** Without edit access the provider answers the
29
+ * room's sync step 1 with nothing and sends no updates (the room would
30
+ * refuse them anyway: `permission-denied`).
31
+ * - Reconnects with the kit's jittered backoff; close code 4403 (access
32
+ * changed) reconnects at once.
33
+ */
34
+ import * as decoding from 'lib0/decoding';
35
+ import * as encoding from 'lib0/encoding';
36
+ import * as authProtocol from 'y-protocols/auth';
37
+ import * as awarenessProtocol from 'y-protocols/awareness';
38
+ import * as syncProtocol from 'y-protocols/sync';
39
+ import { jitteredDelay, socketUrl, STABLE_OPEN_MS, } from '../../runtime/subscription-runner.js';
40
+ import { LIVE_CLOSE, LIVE_PING, LIVE_TIMING } from '../protocol.js';
41
+ const MSG_SYNC = 0;
42
+ const MSG_AWARENESS = 1;
43
+ const MSG_AUTH = 2;
44
+ const MSG_QUERY_AWARENESS = 3;
45
+ /** How long a `ping` may go unanswered before the socket counts as dead. */
46
+ export const PONG_TIMEOUT_MS = 10_000;
47
+ const OPEN = 1;
48
+ function browserDeps() {
49
+ return {
50
+ openSocket: (path) => new WebSocket(socketUrl(path)),
51
+ setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
52
+ clearTimeout: (h) => globalThis.clearTimeout(h),
53
+ now: () => Date.now(),
54
+ random: () => Math.random(),
55
+ isHidden: () => document.visibilityState === 'hidden',
56
+ onVisibility: (fn) => {
57
+ document.addEventListener('visibilitychange', fn);
58
+ return () => document.removeEventListener('visibilitychange', fn);
59
+ },
60
+ onOnline: (fn) => {
61
+ window.addEventListener('online', fn);
62
+ return () => window.removeEventListener('online', fn);
63
+ },
64
+ };
65
+ }
66
+ function closeCodeOf(event) {
67
+ const code = event?.code;
68
+ return typeof code === 'number' ? code : undefined;
69
+ }
70
+ /**
71
+ * Connects `doc` (and its `awareness`) to a room doc socket. Starts at
72
+ * once (call it after hydration settles); `destroy()` ends it.
73
+ *
74
+ * @example
75
+ * ```ts
76
+ * const doc = new Y.Doc();
77
+ * const awareness = new Awareness(doc);
78
+ * const provider = createDocProvider({
79
+ * path: notes.path, doc, awareness,
80
+ * canWrite: () => access === "Editor",
81
+ * onConnection: (c) => console.log(c),
82
+ * });
83
+ * provider.setLocalState({ user: { name: "Alice", color: "#f80" } });
84
+ * ```
85
+ */
86
+ export function createDocProvider(options, deps = browserDeps()) {
87
+ const { doc, awareness } = options;
88
+ let socket;
89
+ let destroyed = false;
90
+ /** Closed on purpose (hidden for long): reconnect on show, not on a timer. */
91
+ let parked = false;
92
+ let synced = false;
93
+ let everSynced = false;
94
+ let connection;
95
+ let step = LIVE_TIMING.RECONNECT_MIN_MS;
96
+ let retry;
97
+ let stable;
98
+ let hiddenClose;
99
+ let pongWait;
100
+ let lastReceived = deps.now();
101
+ let lastActivity = Number.NEGATIVE_INFINITY;
102
+ let awarenessChanged = false;
103
+ /** What to announce while visible; cleared from `awareness` when hidden. */
104
+ let wanted = null;
105
+ let opened = 0;
106
+ let sentFrames = 0;
107
+ let pings = 0;
108
+ const report = (next) => {
109
+ if (next === connection)
110
+ return;
111
+ connection = next;
112
+ options.onConnection(next);
113
+ };
114
+ const isOpen = () => socket !== undefined && socket.readyState === OPEN;
115
+ const sendBinary = (bytes) => {
116
+ if (!socket || !isOpen())
117
+ return;
118
+ socket.send(bytes);
119
+ sentFrames += 1;
120
+ };
121
+ const frame = (write) => {
122
+ const encoder = encoding.createEncoder();
123
+ write(encoder);
124
+ return encoding.toUint8Array(encoder);
125
+ };
126
+ const sendOwnAwareness = () => {
127
+ if (awareness.getLocalState() === null)
128
+ return;
129
+ sendBinary(frame((e) => {
130
+ encoding.writeVarUint(e, MSG_AWARENESS);
131
+ encoding.writeVarUint8Array(e, awarenessProtocol.encodeAwarenessUpdate(awareness, [
132
+ doc.clientID,
133
+ ]));
134
+ }));
135
+ };
136
+ const clearTimer = (handle) => {
137
+ if (handle !== undefined)
138
+ deps.clearTimeout(handle);
139
+ };
140
+ const removeRemoteAwareness = () => {
141
+ const others = [...awareness.getStates().keys()].filter((id) => id !== doc.clientID);
142
+ if (others.length > 0)
143
+ awarenessProtocol.removeAwarenessStates(awareness, others, provider);
144
+ };
145
+ /** Ping only when the viewer acts after a quiet spell: dead-socket detection without idle traffic. */
146
+ const checkAlive = () => {
147
+ if (!socket || !isOpen() || pongWait !== undefined)
148
+ return;
149
+ if (deps.now() - lastReceived < LIVE_TIMING.PING_MS)
150
+ return;
151
+ socket.send(LIVE_PING.request);
152
+ pings += 1;
153
+ const ws = socket;
154
+ pongWait = deps.setTimeout(() => {
155
+ pongWait = undefined;
156
+ if (socket === ws) {
157
+ // Dead: drop it and reconnect like any other close.
158
+ handleClose(ws, undefined);
159
+ }
160
+ }, PONG_TIMEOUT_MS);
161
+ };
162
+ const onMessage = (ws, data) => {
163
+ if (socket !== ws || destroyed)
164
+ return;
165
+ lastReceived = deps.now();
166
+ clearTimer(pongWait);
167
+ pongWait = undefined;
168
+ if (typeof data === 'string')
169
+ return; // `pong`
170
+ const bytes = data instanceof Uint8Array
171
+ ? data
172
+ : new Uint8Array(data);
173
+ const decoder = decoding.createDecoder(bytes);
174
+ const type = decoding.readVarUint(decoder);
175
+ switch (type) {
176
+ case MSG_SYNC: {
177
+ const encoder = encoding.createEncoder();
178
+ encoding.writeVarUint(encoder, MSG_SYNC);
179
+ const syncType = syncProtocol.readSyncMessage(decoder, encoder, doc, provider);
180
+ // A Reader answers the room's step 1 with nothing: it never writes.
181
+ if (syncType === syncProtocol.messageYjsSyncStep1 &&
182
+ options.canWrite() &&
183
+ encoding.length(encoder) > 1) {
184
+ sendBinary(encoding.toUint8Array(encoder));
185
+ }
186
+ if (syncType === syncProtocol.messageYjsSyncStep2 && !synced) {
187
+ synced = true;
188
+ everSynced = true;
189
+ report('Synced');
190
+ }
191
+ return;
192
+ }
193
+ case MSG_AWARENESS:
194
+ awarenessProtocol.applyAwarenessUpdate(awareness, decoding.readVarUint8Array(decoder), provider);
195
+ return;
196
+ case MSG_AUTH:
197
+ authProtocol.readAuthMessage(decoder, doc, (_doc, reason) => options.onDenied?.(reason));
198
+ return;
199
+ case MSG_QUERY_AWARENESS:
200
+ // The room is stateless: each client answers for itself only.
201
+ sendOwnAwareness();
202
+ return;
203
+ default:
204
+ return;
205
+ }
206
+ };
207
+ function handleClose(ws, event) {
208
+ if (socket !== ws)
209
+ return;
210
+ socket = undefined;
211
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
212
+ try {
213
+ ws.close();
214
+ }
215
+ catch {
216
+ // Already closed.
217
+ }
218
+ synced = false;
219
+ clearTimer(stable);
220
+ clearTimer(pongWait);
221
+ stable = pongWait = undefined;
222
+ removeRemoteAwareness();
223
+ if (destroyed)
224
+ return;
225
+ report(everSynced ? 'Offline' : 'Connecting');
226
+ if (parked)
227
+ return;
228
+ if (closeCodeOf(event) === LIVE_CLOSE.ACCESS_CHANGED) {
229
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
230
+ retry = deps.setTimeout(connect, 0);
231
+ return;
232
+ }
233
+ retry = deps.setTimeout(connect, jitteredDelay(step, deps.random()));
234
+ step = Math.min(step * 2, LIVE_TIMING.RECONNECT_MAX_MS);
235
+ }
236
+ function connect() {
237
+ retry = undefined;
238
+ if (destroyed || parked || socket)
239
+ return;
240
+ if (!everSynced)
241
+ report('Connecting');
242
+ let ws;
243
+ try {
244
+ ws = deps.openSocket(options.path);
245
+ }
246
+ catch (error) {
247
+ console.error(`[collab] doc ${options.path} failed to open:`, error);
248
+ retry = deps.setTimeout(connect, jitteredDelay(step, deps.random()));
249
+ step = Math.min(step * 2, LIVE_TIMING.RECONNECT_MAX_MS);
250
+ return;
251
+ }
252
+ opened += 1;
253
+ ws.binaryType = 'arraybuffer';
254
+ socket = ws;
255
+ lastReceived = deps.now();
256
+ ws.onopen = () => {
257
+ if (socket !== ws || destroyed)
258
+ return;
259
+ stable = deps.setTimeout(() => {
260
+ stable = undefined;
261
+ if (socket === ws)
262
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
263
+ }, STABLE_OPEN_MS);
264
+ // Ask for what we miss (the room sends its own step 1; an Editor answers it with ours).
265
+ sendBinary(frame((e) => {
266
+ encoding.writeVarUint(e, MSG_SYNC);
267
+ syncProtocol.writeSyncStep1(e, doc);
268
+ }));
269
+ sendOwnAwareness();
270
+ };
271
+ ws.onmessage = (event) => onMessage(ws, event.data);
272
+ ws.onerror = () => { };
273
+ ws.onclose = (event) => handleClose(ws, event);
274
+ }
275
+ const onDocUpdate = (update, origin) => {
276
+ if (origin === provider || destroyed)
277
+ return;
278
+ lastActivity = deps.now();
279
+ if (!options.canWrite())
280
+ return;
281
+ sendBinary(frame((e) => {
282
+ encoding.writeVarUint(e, MSG_SYNC);
283
+ syncProtocol.writeUpdate(e, update);
284
+ }));
285
+ checkAlive();
286
+ };
287
+ const onAwarenessChange = (_changes, origin) => {
288
+ if (origin !== 'local')
289
+ return;
290
+ awarenessChanged = true;
291
+ lastActivity = deps.now();
292
+ };
293
+ const onAwarenessUpdate = (changes, origin) => {
294
+ if (origin !== 'local')
295
+ return;
296
+ const changed = awarenessChanged;
297
+ awarenessChanged = false;
298
+ // A renewal (same state, re-sent by `Awareness` every 15 s): only while active.
299
+ if (!changed &&
300
+ deps.now() - lastActivity >= LIVE_TIMING.AWARENESS_IDLE_MS)
301
+ return;
302
+ const clients = [
303
+ ...changes.added,
304
+ ...changes.updated,
305
+ ...changes.removed,
306
+ ];
307
+ sendBinary(frame((e) => {
308
+ encoding.writeVarUint(e, MSG_AWARENESS);
309
+ encoding.writeVarUint8Array(e, awarenessProtocol.encodeAwarenessUpdate(awareness, clients));
310
+ }));
311
+ };
312
+ const onVisibility = () => {
313
+ if (destroyed)
314
+ return;
315
+ if (deps.isHidden()) {
316
+ if (awareness.getLocalState() !== null)
317
+ awareness.setLocalState(null);
318
+ clearTimer(hiddenClose);
319
+ hiddenClose = deps.setTimeout(() => {
320
+ hiddenClose = undefined;
321
+ if (!deps.isHidden() || !socket)
322
+ return;
323
+ parked = true;
324
+ const ws = socket;
325
+ handleClose(ws, undefined);
326
+ }, LIVE_TIMING.DOC_HIDDEN_CLOSE_MS);
327
+ return;
328
+ }
329
+ clearTimer(hiddenClose);
330
+ hiddenClose = undefined;
331
+ if (wanted !== null)
332
+ awareness.setLocalState(wanted);
333
+ if (parked) {
334
+ parked = false;
335
+ clearTimer(retry);
336
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
337
+ connect();
338
+ return;
339
+ }
340
+ checkAlive();
341
+ };
342
+ const onOnline = () => {
343
+ if (destroyed || parked)
344
+ return;
345
+ if (!socket) {
346
+ clearTimer(retry);
347
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
348
+ connect();
349
+ return;
350
+ }
351
+ checkAlive();
352
+ };
353
+ const provider = {
354
+ reconnect: () => {
355
+ if (destroyed)
356
+ return;
357
+ for (const handle of [retry, stable, pongWait])
358
+ clearTimer(handle);
359
+ retry = stable = pongWait = undefined;
360
+ step = LIVE_TIMING.RECONNECT_MIN_MS;
361
+ const ws = socket;
362
+ if (ws) {
363
+ socket = undefined;
364
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
365
+ ws.close();
366
+ synced = false;
367
+ removeRemoteAwareness();
368
+ }
369
+ if (!parked)
370
+ connect();
371
+ },
372
+ setLocalState: (state) => {
373
+ wanted = state;
374
+ if (!deps.isHidden())
375
+ awareness.setLocalState(state);
376
+ },
377
+ destroy: () => {
378
+ if (destroyed)
379
+ return;
380
+ // Tell peers this caret is gone while the socket is still open.
381
+ if (awareness.getLocalState() !== null)
382
+ awareness.setLocalState(null);
383
+ destroyed = true;
384
+ for (const handle of [retry, stable, hiddenClose, pongWait])
385
+ clearTimer(handle);
386
+ doc.off('update', onDocUpdate);
387
+ awareness.off('change', onAwarenessChange);
388
+ awareness.off('update', onAwarenessUpdate);
389
+ stopVisibility();
390
+ stopOnline();
391
+ const ws = socket;
392
+ socket = undefined;
393
+ if (ws) {
394
+ ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
395
+ ws.close();
396
+ }
397
+ },
398
+ stats: () => ({ opened, sentFrames, pings }),
399
+ };
400
+ // Start quiet: nothing to announce until the host says who we are.
401
+ awareness.setLocalState(null);
402
+ doc.on('update', onDocUpdate);
403
+ awareness.on('change', onAwarenessChange);
404
+ awareness.on('update', onAwarenessUpdate);
405
+ const stopVisibility = deps.onVisibility(onVisibility);
406
+ const stopOnline = deps.onOnline(onOnline);
407
+ connect();
408
+ // Opened in a background tab: the same 30 s grace as hiding it.
409
+ if (deps.isHidden())
410
+ onVisibility();
411
+ return provider;
412
+ }
@@ -0,0 +1,51 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ /**
3
+ * The kit's collab part (`@alecsibilia/ui-kit/live/collab`): a Yjs doc of a live room,
4
+ * bound to the `@alecsibilia/ui-kit/ui` CodeMirror surface, inside an island. Client only:
5
+ * an app renders it from a client-only island module (`*-island.lazy.tsx`,
6
+ * loaded by a nested `<Island load>` whose `fallback` is the doc's
7
+ * persisted text from a `<Query>`, so JS-off readers and first paint see
8
+ * the saved text).
9
+ *
10
+ * ```tsx
11
+ * // src/islands/plan-notes-editor-island.lazy.tsx
12
+ * export default function PlanNotesEditor(props: IslandComponentProps<{ doc: DocRef }, PlanNotesMsg>) {
13
+ * return <CollabText doc={props.doc} send={props.send} label="Plan notes" placeholder="..." readOnlyPlaceholder="..." />;
14
+ * }
15
+ * ```
16
+ *
17
+ * What it does:
18
+ * - owns the `Y.Doc` and its awareness (an external store: the document
19
+ * never enters a model). The host model gets only
20
+ * `{ _tag: "CollabStatusChanged", status }` Messages
21
+ * (`Connecting | Synced | ReadOnly | Offline`);
22
+ * - opens the doc socket with the kit's provider (`doc-provider.ts`: no
23
+ * idle traffic, awareness cleared when hidden, socket closed after 30 s
24
+ * hidden, renewals stop after 30 s idle);
25
+ * - reads access from the room's `welcome` frame on the page's shared room
26
+ * socket (the same one `presence(...)` and `<LiveCursors>` use): the
27
+ * editor is read-only for Readers, and becomes so the moment the room
28
+ * refuses a write. When the room socket comes back as someone else
29
+ * (sign-in / sign-out in any tab, a 4403), the doc socket reconnects too;
30
+ * - names this viewer's caret from the room's presence list (name, hue).
31
+ *
32
+ * Refetching the persisted copy after a `saved` frame is the host model's
33
+ * job (`roomSaved(...)` subscription + `Refetch`): the part never touches
34
+ * queries.
35
+ */
36
+ import { type Element as SolidElement } from 'solid-js';
37
+ import { type CollabStatusChanged } from '../collab-status.ts';
38
+ import type { DocRef } from '../protocol.ts';
39
+ export { collabStatusOf, type CollabStatus, type CollabStatusChanged, } from '../collab-status.ts';
40
+ export interface CollabTextProps {
41
+ /** A declared doc of a declared room (`docRef(LIVE_ROOMS, room, "notes")`). */
42
+ readonly doc: DocRef;
43
+ /** The host model's `send` (the island's `props.send`). */
44
+ readonly send: (msg: CollabStatusChanged) => void;
45
+ /** Accessible name of the editor. */
46
+ readonly label: string;
47
+ readonly placeholder: string;
48
+ readonly readOnlyPlaceholder: string;
49
+ readonly testId?: string;
50
+ }
51
+ export declare function CollabText(props: CollabTextProps): SolidElement;
@@ -0,0 +1,142 @@
1
+ /** @jsxImportSource @solidjs/web */
2
+ import { isServer } from '@solidjs/web';
3
+ /**
4
+ * The kit's collab part (`@alecsibilia/ui-kit/live/collab`): a Yjs doc of a live room,
5
+ * bound to the `@alecsibilia/ui-kit/ui` CodeMirror surface, inside an island. Client only:
6
+ * an app renders it from a client-only island module (`*-island.lazy.tsx`,
7
+ * loaded by a nested `<Island load>` whose `fallback` is the doc's
8
+ * persisted text from a `<Query>`, so JS-off readers and first paint see
9
+ * the saved text).
10
+ *
11
+ * ```tsx
12
+ * // src/islands/plan-notes-editor-island.lazy.tsx
13
+ * export default function PlanNotesEditor(props: IslandComponentProps<{ doc: DocRef }, PlanNotesMsg>) {
14
+ * return <CollabText doc={props.doc} send={props.send} label="Plan notes" placeholder="..." readOnlyPlaceholder="..." />;
15
+ * }
16
+ * ```
17
+ *
18
+ * What it does:
19
+ * - owns the `Y.Doc` and its awareness (an external store: the document
20
+ * never enters a model). The host model gets only
21
+ * `{ _tag: "CollabStatusChanged", status }` Messages
22
+ * (`Connecting | Synced | ReadOnly | Offline`);
23
+ * - opens the doc socket with the kit's provider (`doc-provider.ts`: no
24
+ * idle traffic, awareness cleared when hidden, socket closed after 30 s
25
+ * hidden, renewals stop after 30 s idle);
26
+ * - reads access from the room's `welcome` frame on the page's shared room
27
+ * socket (the same one `presence(...)` and `<LiveCursors>` use): the
28
+ * editor is read-only for Readers, and becomes so the moment the room
29
+ * refuses a write. When the room socket comes back as someone else
30
+ * (sign-in / sign-out in any tab, a 4403), the doc socket reconnects too;
31
+ * - names this viewer's caret from the room's presence list (name, hue).
32
+ *
33
+ * Refetching the persisted copy after a `saved` frame is the host model's
34
+ * job (`roomSaved(...)` subscription + `Refetch`): the part never touches
35
+ * queries.
36
+ */
37
+ import { createSignal, onCleanup, onSettled, untrack, } from 'solid-js';
38
+ import { Awareness } from 'y-protocols/awareness';
39
+ import * as Y from 'yjs';
40
+ import { createDocProvider, } from './doc-provider.js';
41
+ import { CollabTextSurface } from '../../ui/collab-text/index.jsx';
42
+ import { useKitScope } from '../../view/app-scope.js';
43
+ import { collabStatusOf, } from '../collab-status.js';
44
+ export { collabStatusOf, } from '../collab-status.js';
45
+ export function CollabText(props) {
46
+ const scope = useKitScope();
47
+ const ydoc = new Y.Doc();
48
+ const awareness = new Awareness(ydoc);
49
+ // One doc per part for its life (props are island JSON, captured once).
50
+ const text = ydoc.getText(untrack(() => props.doc.doc));
51
+ const [editable, setEditable] = createSignal(false);
52
+ let connection = 'Connecting';
53
+ let welcomed = false;
54
+ let access = 'Reader';
55
+ let refused = false;
56
+ let reported;
57
+ const report = () => {
58
+ const status = collabStatusOf(connection, welcomed, access, refused);
59
+ if (status === reported)
60
+ return;
61
+ reported = status;
62
+ props.send({ _tag: 'CollabStatusChanged', status });
63
+ };
64
+ onSettled(() => {
65
+ if (isServer || !scope)
66
+ return;
67
+ const handle = scope.rooms().acquire(props.doc.room.path);
68
+ let identity;
69
+ // Assigned once below; the handlers above it read it first.
70
+ // oxlint-disable-next-line prefer-const
71
+ let provider;
72
+ const announce = () => {
73
+ if (!provider)
74
+ return;
75
+ if (access !== 'Editor' || refused) {
76
+ provider.setLocalState(null);
77
+ return;
78
+ }
79
+ const welcome = handle.welcome();
80
+ const me = handle
81
+ .presence()
82
+ ?.peers.find((peer) => peer.id === welcome?.self);
83
+ if (!me)
84
+ return;
85
+ provider.setLocalState({
86
+ user: {
87
+ name: me.name,
88
+ color: `hsl(${me.hue} 80% 55%)`,
89
+ colorLight: `hsl(${me.hue} 80% 55% / 0.25)`,
90
+ },
91
+ });
92
+ };
93
+ const onWelcome = (welcome) => {
94
+ const next = `${welcome.self}|${welcome.access}`;
95
+ const someoneElse = identity !== undefined && identity !== next;
96
+ identity = next;
97
+ welcomed = true;
98
+ access = welcome.access;
99
+ refused = false;
100
+ setEditable(access === 'Editor');
101
+ // A new identity at the room (viewer changed, 4403): the doc socket must re-identify too.
102
+ if (someoneElse)
103
+ provider?.reconnect();
104
+ announce();
105
+ report();
106
+ };
107
+ provider = createDocProvider({
108
+ path: props.doc.path,
109
+ doc: ydoc,
110
+ awareness,
111
+ canWrite: () => access === 'Editor' && !refused,
112
+ onConnection: (next) => {
113
+ connection = next;
114
+ report();
115
+ },
116
+ onDenied: () => {
117
+ refused = true;
118
+ setEditable(false);
119
+ announce();
120
+ report();
121
+ },
122
+ });
123
+ const welcome = handle.welcome();
124
+ if (welcome)
125
+ onWelcome(welcome);
126
+ handle.onFrame((frame) => {
127
+ if (frame.t === 'welcome')
128
+ onWelcome(frame);
129
+ else if (frame.t === 'presence')
130
+ announce();
131
+ });
132
+ return () => {
133
+ provider?.destroy();
134
+ handle.release();
135
+ };
136
+ });
137
+ onCleanup(() => {
138
+ awareness.destroy();
139
+ ydoc.destroy();
140
+ });
141
+ return (<CollabTextSurface text={text} awareness={awareness} editable={editable()} label={props.label} placeholder={props.placeholder} readOnlyPlaceholder={props.readOnlyPlaceholder} testId={props.testId}/>);
142
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * What the kit's collab part (`<CollabText>`, `@alecsibilia/ui-kit/live/collab`) tells the
3
+ * model that hosts it: only the editor's status, never the document. Pure
4
+ * types (a `.model.ts` imports them through `@alecsibilia/ui-kit/logic`).
5
+ */
6
+ /**
7
+ * - `Connecting`: the doc socket is opening, or has not synced yet.
8
+ * - `Synced`: in sync with the room, and the viewer may edit.
9
+ * - `ReadOnly`: in sync, but the room says the viewer may only read
10
+ * (`authorize(user, room, "edit")` was false, or the room refused a write).
11
+ * - `Offline`: the socket dropped after a sync (or the tab has been hidden
12
+ * for 30 s); edits made meanwhile stay in the tab and merge on reconnect.
13
+ */
14
+ export type CollabStatus = 'Connecting' | 'Synced' | 'ReadOnly' | 'Offline';
15
+ /** The one Message the collab part sends to its host model (through the island's `send`). */
16
+ export interface CollabStatusChanged {
17
+ readonly _tag: 'CollabStatusChanged';
18
+ readonly status: CollabStatus;
19
+ }
20
+ /**
21
+ * The status the host model sees, from the doc socket's state, whether the
22
+ * room's `welcome` has said who we are, the room's access, and whether the
23
+ * room refused a write. Kit-internal (exported for tests).
24
+ */
25
+ export declare function collabStatusOf(connection: 'Connecting' | 'Synced' | 'Offline', welcomed: boolean, access: 'Editor' | 'Reader', refused: boolean): CollabStatus;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * What the kit's collab part (`<CollabText>`, `@alecsibilia/ui-kit/live/collab`) tells the
3
+ * model that hosts it: only the editor's status, never the document. Pure
4
+ * types (a `.model.ts` imports them through `@alecsibilia/ui-kit/logic`).
5
+ */
6
+ /**
7
+ * The status the host model sees, from the doc socket's state, whether the
8
+ * room's `welcome` has said who we are, the room's access, and whether the
9
+ * room refused a write. Kit-internal (exported for tests).
10
+ */
11
+ export function collabStatusOf(connection, welcomed, access, refused) {
12
+ if (connection !== 'Synced')
13
+ return connection;
14
+ if (!welcomed)
15
+ return 'Connecting';
16
+ return access === 'Editor' && !refused ? 'Synced' : 'ReadOnly';
17
+ }