@syncular/server 0.1.3 → 0.2.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 (758) hide show
  1. package/README.md +773 -13
  2. package/dist/admin.d.ts +136 -0
  3. package/dist/admin.js +168 -0
  4. package/dist/blob-handlers.d.ts +69 -0
  5. package/dist/blob-handlers.js +245 -0
  6. package/dist/blob-store.d.ts +111 -0
  7. package/dist/blob-store.js +0 -0
  8. package/dist/content-encoding.d.ts +27 -0
  9. package/dist/content-encoding.js +69 -0
  10. package/dist/context.d.ts +151 -0
  11. package/dist/context.js +21 -0
  12. package/dist/crdt-merger.d.ts +28 -0
  13. package/dist/crdt-merger.js +11 -0
  14. package/dist/d1-storage.d.ts +50 -0
  15. package/dist/d1-storage.js +0 -0
  16. package/dist/errors.d.ts +35 -9
  17. package/dist/errors.js +220 -11
  18. package/dist/events-ring.d.ts +55 -0
  19. package/dist/events-ring.js +96 -0
  20. package/dist/events.d.ts +231 -0
  21. package/dist/events.js +22 -0
  22. package/dist/frame-bytes.d.ts +20 -0
  23. package/dist/frame-bytes.js +75 -0
  24. package/dist/handler.d.ts +9 -0
  25. package/dist/handler.js +490 -0
  26. package/dist/index.d.ts +42 -33
  27. package/dist/index.js +45 -27
  28. package/dist/lease-store.d.ts +50 -0
  29. package/dist/lease-store.js +0 -0
  30. package/dist/pg-executor-pglite.d.ts +27 -0
  31. package/dist/pg-executor-pglite.js +33 -0
  32. package/dist/pg-executor.d.ts +67 -0
  33. package/dist/pg-executor.js +56 -0
  34. package/dist/postgres-fanout.d.ts +83 -0
  35. package/dist/postgres-fanout.js +71 -0
  36. package/dist/postgres-storage.d.ts +69 -0
  37. package/dist/postgres-storage.js +766 -0
  38. package/dist/prune.d.ts +24 -39
  39. package/dist/prune.js +44 -146
  40. package/dist/pull.d.ts +42 -67
  41. package/dist/pull.js +387 -1187
  42. package/dist/push.d.ts +31 -66
  43. package/dist/push.js +406 -655
  44. package/dist/realtime.d.ts +197 -0
  45. package/dist/realtime.js +848 -0
  46. package/dist/relational-rows.d.ts +229 -0
  47. package/dist/relational-rows.js +514 -0
  48. package/dist/s3-blob-store.d.ts +142 -0
  49. package/dist/s3-blob-store.js +458 -0
  50. package/dist/s3-segment-store.d.ts +95 -0
  51. package/dist/s3-segment-store.js +380 -0
  52. package/dist/schema.d.ts +82 -286
  53. package/dist/schema.js +133 -9
  54. package/dist/scopes.d.ts +48 -0
  55. package/dist/scopes.js +98 -0
  56. package/dist/segment-download.d.ts +14 -0
  57. package/dist/segment-download.js +125 -0
  58. package/dist/segment-store.d.ts +81 -0
  59. package/dist/segment-store.js +63 -0
  60. package/dist/signed-url.d.ts +139 -0
  61. package/dist/signed-url.js +143 -0
  62. package/dist/sigv4.d.ts +97 -0
  63. package/dist/sigv4.js +161 -0
  64. package/dist/sqlite-blob-store.d.ts +22 -0
  65. package/dist/sqlite-blob-store.js +86 -0
  66. package/dist/sqlite-dialect.d.ts +101 -0
  67. package/dist/sqlite-dialect.js +250 -0
  68. package/dist/sqlite-image.d.ts +27 -0
  69. package/dist/sqlite-image.js +83 -0
  70. package/dist/sqlite-lease-store.d.ts +21 -0
  71. package/dist/sqlite-lease-store.js +94 -0
  72. package/dist/sqlite-segment-store.d.ts +25 -0
  73. package/dist/sqlite-segment-store.js +115 -0
  74. package/dist/sqlite-storage.d.ts +47 -0
  75. package/dist/sqlite-storage.js +477 -0
  76. package/dist/storage.d.ts +252 -0
  77. package/dist/storage.js +1 -0
  78. package/dist/validate.d.ts +83 -0
  79. package/dist/validate.js +44 -0
  80. package/package.json +17 -325
  81. package/src/admin.ts +312 -0
  82. package/src/blob-handlers.ts +340 -0
  83. package/src/blob-store.ts +0 -0
  84. package/src/content-encoding.ts +94 -0
  85. package/src/context.ts +176 -0
  86. package/src/crdt-merger.ts +33 -0
  87. package/src/d1-storage.ts +0 -0
  88. package/src/errors.ts +241 -19
  89. package/src/events-ring.ts +116 -0
  90. package/src/events.ts +291 -0
  91. package/src/frame-bytes.ts +94 -0
  92. package/src/handler.ts +678 -0
  93. package/src/index.ts +44 -27
  94. package/src/lease-store.ts +0 -0
  95. package/src/pg-executor-pglite.ts +63 -0
  96. package/src/pg-executor.ts +87 -0
  97. package/src/postgres-fanout.ts +143 -0
  98. package/src/postgres-storage.ts +1182 -0
  99. package/src/prune.ts +63 -289
  100. package/src/pull.ts +505 -1805
  101. package/src/push.ts +623 -1006
  102. package/src/realtime.ts +1082 -0
  103. package/src/relational-rows.ts +633 -0
  104. package/src/s3-blob-store.ts +616 -0
  105. package/src/s3-segment-store.ts +519 -0
  106. package/src/schema.ts +242 -281
  107. package/src/scopes.ts +127 -0
  108. package/src/segment-download.ts +169 -0
  109. package/src/segment-store.ts +154 -0
  110. package/src/signed-url.ts +308 -0
  111. package/src/sigv4.ts +267 -0
  112. package/src/sqlite-blob-store.ts +125 -0
  113. package/src/sqlite-dialect.ts +337 -0
  114. package/src/sqlite-image.ts +124 -0
  115. package/src/sqlite-lease-store.ts +144 -0
  116. package/src/sqlite-segment-store.ts +204 -0
  117. package/src/sqlite-storage.ts +792 -0
  118. package/src/storage.ts +316 -0
  119. package/src/validate.ts +123 -0
  120. package/dist/auth-leases.d.ts +0 -85
  121. package/dist/auth-leases.d.ts.map +0 -1
  122. package/dist/auth-leases.js +0 -368
  123. package/dist/auth-leases.js.map +0 -1
  124. package/dist/better-sqlite3.d.ts +0 -22
  125. package/dist/better-sqlite3.d.ts.map +0 -1
  126. package/dist/better-sqlite3.js +0 -16
  127. package/dist/better-sqlite3.js.map +0 -1
  128. package/dist/blobs/access.d.ts +0 -35
  129. package/dist/blobs/access.d.ts.map +0 -1
  130. package/dist/blobs/access.js +0 -149
  131. package/dist/blobs/access.js.map +0 -1
  132. package/dist/blobs/adapters/database.d.ts +0 -100
  133. package/dist/blobs/adapters/database.d.ts.map +0 -1
  134. package/dist/blobs/adapters/database.js +0 -247
  135. package/dist/blobs/adapters/database.js.map +0 -1
  136. package/dist/blobs/index.d.ts +0 -9
  137. package/dist/blobs/index.d.ts.map +0 -1
  138. package/dist/blobs/index.js +0 -9
  139. package/dist/blobs/index.js.map +0 -1
  140. package/dist/blobs/manager.d.ts +0 -220
  141. package/dist/blobs/manager.d.ts.map +0 -1
  142. package/dist/blobs/manager.js +0 -625
  143. package/dist/blobs/manager.js.map +0 -1
  144. package/dist/blobs/migrate.d.ts +0 -27
  145. package/dist/blobs/migrate.d.ts.map +0 -1
  146. package/dist/blobs/migrate.js +0 -127
  147. package/dist/blobs/migrate.js.map +0 -1
  148. package/dist/blobs/types.d.ts +0 -58
  149. package/dist/blobs/types.d.ts.map +0 -1
  150. package/dist/blobs/types.js +0 -5
  151. package/dist/blobs/types.js.map +0 -1
  152. package/dist/bun-sqlite.d.ts +0 -19
  153. package/dist/bun-sqlite.d.ts.map +0 -1
  154. package/dist/bun-sqlite.js +0 -19
  155. package/dist/bun-sqlite.js.map +0 -1
  156. package/dist/clients.d.ts +0 -15
  157. package/dist/clients.d.ts.map +0 -1
  158. package/dist/clients.js +0 -7
  159. package/dist/clients.js.map +0 -1
  160. package/dist/cloudflare/durable-object.d.ts +0 -93
  161. package/dist/cloudflare/durable-object.d.ts.map +0 -1
  162. package/dist/cloudflare/durable-object.js +0 -210
  163. package/dist/cloudflare/durable-object.js.map +0 -1
  164. package/dist/cloudflare/index.d.ts +0 -22
  165. package/dist/cloudflare/index.d.ts.map +0 -1
  166. package/dist/cloudflare/index.js +0 -22
  167. package/dist/cloudflare/index.js.map +0 -1
  168. package/dist/cloudflare/r2.d.ts +0 -180
  169. package/dist/cloudflare/r2.d.ts.map +0 -1
  170. package/dist/cloudflare/r2.js +0 -258
  171. package/dist/cloudflare/r2.js.map +0 -1
  172. package/dist/cloudflare/scope-cache.d.ts +0 -54
  173. package/dist/cloudflare/scope-cache.d.ts.map +0 -1
  174. package/dist/cloudflare/scope-cache.js +0 -223
  175. package/dist/cloudflare/scope-cache.js.map +0 -1
  176. package/dist/cloudflare/sentry.d.ts +0 -47
  177. package/dist/cloudflare/sentry.d.ts.map +0 -1
  178. package/dist/cloudflare/sentry.js +0 -163
  179. package/dist/cloudflare/sentry.js.map +0 -1
  180. package/dist/cloudflare/worker.d.ts +0 -46
  181. package/dist/cloudflare/worker.d.ts.map +0 -1
  182. package/dist/cloudflare/worker.js +0 -63
  183. package/dist/cloudflare/worker.js.map +0 -1
  184. package/dist/commit-integrity.d.ts +0 -38
  185. package/dist/commit-integrity.d.ts.map +0 -1
  186. package/dist/commit-integrity.js +0 -260
  187. package/dist/commit-integrity.js.map +0 -1
  188. package/dist/compaction.d.ts +0 -27
  189. package/dist/compaction.d.ts.map +0 -1
  190. package/dist/compaction.js +0 -49
  191. package/dist/compaction.js.map +0 -1
  192. package/dist/crdt-yjs/index.d.ts +0 -99
  193. package/dist/crdt-yjs/index.d.ts.map +0 -1
  194. package/dist/crdt-yjs/index.js +0 -629
  195. package/dist/crdt-yjs/index.js.map +0 -1
  196. package/dist/d1.d.ts +0 -13
  197. package/dist/d1.d.ts.map +0 -1
  198. package/dist/d1.js +0 -14
  199. package/dist/d1.js.map +0 -1
  200. package/dist/dialect/base.d.ts +0 -93
  201. package/dist/dialect/base.d.ts.map +0 -1
  202. package/dist/dialect/base.js +0 -181
  203. package/dist/dialect/base.js.map +0 -1
  204. package/dist/dialect/helpers.d.ts +0 -16
  205. package/dist/dialect/helpers.d.ts.map +0 -1
  206. package/dist/dialect/helpers.js +0 -83
  207. package/dist/dialect/helpers.js.map +0 -1
  208. package/dist/dialect/index.d.ts +0 -7
  209. package/dist/dialect/index.d.ts.map +0 -1
  210. package/dist/dialect/index.js +0 -7
  211. package/dist/dialect/index.js.map +0 -1
  212. package/dist/dialect/types.d.ts +0 -187
  213. package/dist/dialect/types.d.ts.map +0 -1
  214. package/dist/dialect/types.js +0 -8
  215. package/dist/dialect/types.js.map +0 -1
  216. package/dist/encrypted-crdt.d.ts +0 -67
  217. package/dist/encrypted-crdt.d.ts.map +0 -1
  218. package/dist/encrypted-crdt.js +0 -426
  219. package/dist/encrypted-crdt.js.map +0 -1
  220. package/dist/errors.d.ts.map +0 -1
  221. package/dist/errors.js.map +0 -1
  222. package/dist/filesystem/index.d.ts +0 -44
  223. package/dist/filesystem/index.d.ts.map +0 -1
  224. package/dist/filesystem/index.js +0 -164
  225. package/dist/filesystem/index.js.map +0 -1
  226. package/dist/handlers/collection.d.ts +0 -20
  227. package/dist/handlers/collection.d.ts.map +0 -1
  228. package/dist/handlers/collection.js +0 -42
  229. package/dist/handlers/collection.js.map +0 -1
  230. package/dist/handlers/create-handler.d.ts +0 -156
  231. package/dist/handlers/create-handler.d.ts.map +0 -1
  232. package/dist/handlers/create-handler.js +0 -626
  233. package/dist/handlers/create-handler.js.map +0 -1
  234. package/dist/handlers/index.d.ts +0 -4
  235. package/dist/handlers/index.d.ts.map +0 -1
  236. package/dist/handlers/index.js +0 -4
  237. package/dist/handlers/index.js.map +0 -1
  238. package/dist/handlers/types.d.ts +0 -295
  239. package/dist/handlers/types.d.ts.map +0 -1
  240. package/dist/handlers/types.js +0 -2
  241. package/dist/handlers/types.js.map +0 -1
  242. package/dist/helpers/conflict.d.ts +0 -52
  243. package/dist/helpers/conflict.d.ts.map +0 -1
  244. package/dist/helpers/conflict.js +0 -49
  245. package/dist/helpers/conflict.js.map +0 -1
  246. package/dist/helpers/emitted-change.d.ts +0 -56
  247. package/dist/helpers/emitted-change.d.ts.map +0 -1
  248. package/dist/helpers/emitted-change.js +0 -46
  249. package/dist/helpers/emitted-change.js.map +0 -1
  250. package/dist/helpers/index.d.ts +0 -12
  251. package/dist/helpers/index.d.ts.map +0 -1
  252. package/dist/helpers/index.js +0 -12
  253. package/dist/helpers/index.js.map +0 -1
  254. package/dist/helpers/paginate.d.ts +0 -49
  255. package/dist/helpers/paginate.d.ts.map +0 -1
  256. package/dist/helpers/paginate.js +0 -54
  257. package/dist/helpers/paginate.js.map +0 -1
  258. package/dist/helpers/scope-authorization.d.ts +0 -7
  259. package/dist/helpers/scope-authorization.d.ts.map +0 -1
  260. package/dist/helpers/scope-authorization.js +0 -19
  261. package/dist/helpers/scope-authorization.js.map +0 -1
  262. package/dist/helpers/scope-commit-index.d.ts +0 -12
  263. package/dist/helpers/scope-commit-index.d.ts.map +0 -1
  264. package/dist/helpers/scope-commit-index.js +0 -35
  265. package/dist/helpers/scope-commit-index.js.map +0 -1
  266. package/dist/helpers/scope-strings.d.ts +0 -74
  267. package/dist/helpers/scope-strings.d.ts.map +0 -1
  268. package/dist/helpers/scope-strings.js +0 -82
  269. package/dist/helpers/scope-strings.js.map +0 -1
  270. package/dist/hono/api-key-auth.d.ts +0 -49
  271. package/dist/hono/api-key-auth.d.ts.map +0 -1
  272. package/dist/hono/api-key-auth.js +0 -108
  273. package/dist/hono/api-key-auth.js.map +0 -1
  274. package/dist/hono/audit-redaction.d.ts +0 -20
  275. package/dist/hono/audit-redaction.d.ts.map +0 -1
  276. package/dist/hono/audit-redaction.js +0 -85
  277. package/dist/hono/audit-redaction.js.map +0 -1
  278. package/dist/hono/blobs.d.ts +0 -75
  279. package/dist/hono/blobs.d.ts.map +0 -1
  280. package/dist/hono/blobs.js +0 -586
  281. package/dist/hono/blobs.js.map +0 -1
  282. package/dist/hono/console/gateway.d.ts +0 -42
  283. package/dist/hono/console/gateway.d.ts.map +0 -1
  284. package/dist/hono/console/gateway.js +0 -2158
  285. package/dist/hono/console/gateway.js.map +0 -1
  286. package/dist/hono/console/live-auth.d.ts +0 -7
  287. package/dist/hono/console/live-auth.d.ts.map +0 -1
  288. package/dist/hono/console/live-auth.js +0 -39
  289. package/dist/hono/console/live-auth.js.map +0 -1
  290. package/dist/hono/console/route-descriptor.d.ts +0 -6
  291. package/dist/hono/console/route-descriptor.d.ts.map +0 -1
  292. package/dist/hono/console/route-descriptor.js +0 -16
  293. package/dist/hono/console/route-descriptor.js.map +0 -1
  294. package/dist/hono/console/routes/api-keys.d.ts +0 -8
  295. package/dist/hono/console/routes/api-keys.d.ts.map +0 -1
  296. package/dist/hono/console/routes/api-keys.js +0 -575
  297. package/dist/hono/console/routes/api-keys.js.map +0 -1
  298. package/dist/hono/console/routes/clients.d.ts +0 -8
  299. package/dist/hono/console/routes/clients.d.ts.map +0 -1
  300. package/dist/hono/console/routes/clients.js +0 -322
  301. package/dist/hono/console/routes/clients.js.map +0 -1
  302. package/dist/hono/console/routes/commits.d.ts +0 -8
  303. package/dist/hono/console/routes/commits.d.ts.map +0 -1
  304. package/dist/hono/console/routes/commits.js +0 -882
  305. package/dist/hono/console/routes/commits.js.map +0 -1
  306. package/dist/hono/console/routes/context.d.ts +0 -188
  307. package/dist/hono/console/routes/context.d.ts.map +0 -1
  308. package/dist/hono/console/routes/context.js +0 -633
  309. package/dist/hono/console/routes/context.js.map +0 -1
  310. package/dist/hono/console/routes/events.d.ts +0 -8
  311. package/dist/hono/console/routes/events.d.ts.map +0 -1
  312. package/dist/hono/console/routes/events.js +0 -501
  313. package/dist/hono/console/routes/events.js.map +0 -1
  314. package/dist/hono/console/routes/maintenance.d.ts +0 -8
  315. package/dist/hono/console/routes/maintenance.d.ts.map +0 -1
  316. package/dist/hono/console/routes/maintenance.js +0 -341
  317. package/dist/hono/console/routes/maintenance.js.map +0 -1
  318. package/dist/hono/console/routes/shared.d.ts +0 -174
  319. package/dist/hono/console/routes/shared.d.ts.map +0 -1
  320. package/dist/hono/console/routes/shared.js +0 -583
  321. package/dist/hono/console/routes/shared.js.map +0 -1
  322. package/dist/hono/console/routes/stats.d.ts +0 -8
  323. package/dist/hono/console/routes/stats.d.ts.map +0 -1
  324. package/dist/hono/console/routes/stats.js +0 -295
  325. package/dist/hono/console/routes/stats.js.map +0 -1
  326. package/dist/hono/console/routes/storage.d.ts +0 -8
  327. package/dist/hono/console/routes/storage.d.ts.map +0 -1
  328. package/dist/hono/console/routes/storage.js +0 -121
  329. package/dist/hono/console/routes/storage.js.map +0 -1
  330. package/dist/hono/console/routes.d.ts +0 -36
  331. package/dist/hono/console/routes.d.ts.map +0 -1
  332. package/dist/hono/console/routes.js +0 -112
  333. package/dist/hono/console/routes.js.map +0 -1
  334. package/dist/hono/console/schema-errors.d.ts +0 -2
  335. package/dist/hono/console/schema-errors.d.ts.map +0 -1
  336. package/dist/hono/console/schema-errors.js +0 -17
  337. package/dist/hono/console/schema-errors.js.map +0 -1
  338. package/dist/hono/console/schemas.d.ts +0 -1515
  339. package/dist/hono/console/schemas.d.ts.map +0 -1
  340. package/dist/hono/console/schemas.js +0 -661
  341. package/dist/hono/console/schemas.js.map +0 -1
  342. package/dist/hono/console/types.d.ts +0 -213
  343. package/dist/hono/console/types.d.ts.map +0 -1
  344. package/dist/hono/console/types.js +0 -2
  345. package/dist/hono/console/types.js.map +0 -1
  346. package/dist/hono/console/ui.d.ts +0 -38
  347. package/dist/hono/console/ui.d.ts.map +0 -1
  348. package/dist/hono/console/ui.js +0 -43
  349. package/dist/hono/console/ui.js.map +0 -1
  350. package/dist/hono/create-server.d.ts +0 -71
  351. package/dist/hono/create-server.d.ts.map +0 -1
  352. package/dist/hono/create-server.js +0 -121
  353. package/dist/hono/create-server.js.map +0 -1
  354. package/dist/hono/errors.d.ts +0 -13
  355. package/dist/hono/errors.d.ts.map +0 -1
  356. package/dist/hono/errors.js +0 -21
  357. package/dist/hono/errors.js.map +0 -1
  358. package/dist/hono/index.d.ts +0 -20
  359. package/dist/hono/index.d.ts.map +0 -1
  360. package/dist/hono/index.js +0 -31
  361. package/dist/hono/index.js.map +0 -1
  362. package/dist/hono/openapi.d.ts +0 -72
  363. package/dist/hono/openapi.d.ts.map +0 -1
  364. package/dist/hono/openapi.js +0 -99
  365. package/dist/hono/openapi.js.map +0 -1
  366. package/dist/hono/proxy/connection-manager.d.ts +0 -78
  367. package/dist/hono/proxy/connection-manager.d.ts.map +0 -1
  368. package/dist/hono/proxy/connection-manager.js +0 -251
  369. package/dist/hono/proxy/connection-manager.js.map +0 -1
  370. package/dist/hono/proxy/index.d.ts +0 -8
  371. package/dist/hono/proxy/index.d.ts.map +0 -1
  372. package/dist/hono/proxy/index.js +0 -8
  373. package/dist/hono/proxy/index.js.map +0 -1
  374. package/dist/hono/proxy/routes.d.ts +0 -86
  375. package/dist/hono/proxy/routes.d.ts.map +0 -1
  376. package/dist/hono/proxy/routes.js +0 -183
  377. package/dist/hono/proxy/routes.js.map +0 -1
  378. package/dist/hono/rate-limit.d.ts +0 -101
  379. package/dist/hono/rate-limit.d.ts.map +0 -1
  380. package/dist/hono/rate-limit.js +0 -184
  381. package/dist/hono/rate-limit.js.map +0 -1
  382. package/dist/hono/realtime-sync-packs.d.ts +0 -43
  383. package/dist/hono/realtime-sync-packs.d.ts.map +0 -1
  384. package/dist/hono/realtime-sync-packs.js +0 -219
  385. package/dist/hono/realtime-sync-packs.js.map +0 -1
  386. package/dist/hono/routes/audit.d.ts +0 -12
  387. package/dist/hono/routes/audit.d.ts.map +0 -1
  388. package/dist/hono/routes/audit.js +0 -385
  389. package/dist/hono/routes/audit.js.map +0 -1
  390. package/dist/hono/routes/auth-leases.d.ts +0 -8
  391. package/dist/hono/routes/auth-leases.d.ts.map +0 -1
  392. package/dist/hono/routes/auth-leases.js +0 -88
  393. package/dist/hono/routes/auth-leases.js.map +0 -1
  394. package/dist/hono/routes/combined.d.ts +0 -8
  395. package/dist/hono/routes/combined.d.ts.map +0 -1
  396. package/dist/hono/routes/combined.js +0 -392
  397. package/dist/hono/routes/combined.js.map +0 -1
  398. package/dist/hono/routes/context.d.ts +0 -314
  399. package/dist/hono/routes/context.d.ts.map +0 -1
  400. package/dist/hono/routes/context.js +0 -1147
  401. package/dist/hono/routes/context.js.map +0 -1
  402. package/dist/hono/routes/health.d.ts +0 -8
  403. package/dist/hono/routes/health.d.ts.map +0 -1
  404. package/dist/hono/routes/health.js +0 -16
  405. package/dist/hono/routes/health.js.map +0 -1
  406. package/dist/hono/routes/realtime.d.ts +0 -9
  407. package/dist/hono/routes/realtime.d.ts.map +0 -1
  408. package/dist/hono/routes/realtime.js +0 -626
  409. package/dist/hono/routes/realtime.js.map +0 -1
  410. package/dist/hono/routes/shared.d.ts +0 -689
  411. package/dist/hono/routes/shared.d.ts.map +0 -1
  412. package/dist/hono/routes/shared.js +0 -972
  413. package/dist/hono/routes/shared.js.map +0 -1
  414. package/dist/hono/routes/snapshots.d.ts +0 -10
  415. package/dist/hono/routes/snapshots.d.ts.map +0 -1
  416. package/dist/hono/routes/snapshots.js +0 -281
  417. package/dist/hono/routes/snapshots.js.map +0 -1
  418. package/dist/hono/routes.d.ts +0 -19
  419. package/dist/hono/routes.d.ts.map +0 -1
  420. package/dist/hono/routes.js +0 -37
  421. package/dist/hono/routes.js.map +0 -1
  422. package/dist/hono/validation.d.ts +0 -5
  423. package/dist/hono/validation.d.ts.map +0 -1
  424. package/dist/hono/validation.js +0 -47
  425. package/dist/hono/validation.js.map +0 -1
  426. package/dist/hono/websocket-origin.d.ts +0 -9
  427. package/dist/hono/websocket-origin.d.ts.map +0 -1
  428. package/dist/hono/websocket-origin.js +0 -96
  429. package/dist/hono/websocket-origin.js.map +0 -1
  430. package/dist/hono/ws.d.ts +0 -341
  431. package/dist/hono/ws.d.ts.map +0 -1
  432. package/dist/hono/ws.js +0 -711
  433. package/dist/hono/ws.js.map +0 -1
  434. package/dist/index.d.ts.map +0 -1
  435. package/dist/index.js.map +0 -1
  436. package/dist/libsql.d.ts +0 -29
  437. package/dist/libsql.d.ts.map +0 -1
  438. package/dist/libsql.js +0 -25
  439. package/dist/libsql.js.map +0 -1
  440. package/dist/migrate.d.ts +0 -14
  441. package/dist/migrate.d.ts.map +0 -1
  442. package/dist/migrate.js +0 -13
  443. package/dist/migrate.js.map +0 -1
  444. package/dist/neon.d.ts +0 -21
  445. package/dist/neon.d.ts.map +0 -1
  446. package/dist/neon.js +0 -22
  447. package/dist/neon.js.map +0 -1
  448. package/dist/notify.d.ts +0 -77
  449. package/dist/notify.d.ts.map +0 -1
  450. package/dist/notify.js +0 -233
  451. package/dist/notify.js.map +0 -1
  452. package/dist/pglite.d.ts +0 -37
  453. package/dist/pglite.d.ts.map +0 -1
  454. package/dist/pglite.js +0 -37
  455. package/dist/pglite.js.map +0 -1
  456. package/dist/plugins/index.d.ts +0 -2
  457. package/dist/plugins/index.d.ts.map +0 -1
  458. package/dist/plugins/index.js +0 -2
  459. package/dist/plugins/index.js.map +0 -1
  460. package/dist/plugins/types.d.ts +0 -73
  461. package/dist/plugins/types.d.ts.map +0 -1
  462. package/dist/plugins/types.js +0 -30
  463. package/dist/plugins/types.js.map +0 -1
  464. package/dist/postgres/index.d.ts +0 -68
  465. package/dist/postgres/index.d.ts.map +0 -1
  466. package/dist/postgres/index.js +0 -924
  467. package/dist/postgres/index.js.map +0 -1
  468. package/dist/proxy/collection.d.ts +0 -7
  469. package/dist/proxy/collection.d.ts.map +0 -1
  470. package/dist/proxy/collection.js +0 -6
  471. package/dist/proxy/collection.js.map +0 -1
  472. package/dist/proxy/handler.d.ts +0 -42
  473. package/dist/proxy/handler.d.ts.map +0 -1
  474. package/dist/proxy/handler.js +0 -102
  475. package/dist/proxy/handler.js.map +0 -1
  476. package/dist/proxy/index.d.ts +0 -9
  477. package/dist/proxy/index.d.ts.map +0 -1
  478. package/dist/proxy/index.js +0 -14
  479. package/dist/proxy/index.js.map +0 -1
  480. package/dist/proxy/mutation-detector.d.ts +0 -35
  481. package/dist/proxy/mutation-detector.d.ts.map +0 -1
  482. package/dist/proxy/mutation-detector.js +0 -246
  483. package/dist/proxy/mutation-detector.js.map +0 -1
  484. package/dist/proxy/oplog.d.ts +0 -30
  485. package/dist/proxy/oplog.d.ts.map +0 -1
  486. package/dist/proxy/oplog.js +0 -137
  487. package/dist/proxy/oplog.js.map +0 -1
  488. package/dist/proxy/types.d.ts +0 -44
  489. package/dist/proxy/types.d.ts.map +0 -1
  490. package/dist/proxy/types.js +0 -7
  491. package/dist/proxy/types.js.map +0 -1
  492. package/dist/prune.d.ts.map +0 -1
  493. package/dist/prune.js.map +0 -1
  494. package/dist/pull.d.ts.map +0 -1
  495. package/dist/pull.js.map +0 -1
  496. package/dist/push.d.ts.map +0 -1
  497. package/dist/push.js.map +0 -1
  498. package/dist/realtime/in-memory.d.ts +0 -13
  499. package/dist/realtime/in-memory.d.ts.map +0 -1
  500. package/dist/realtime/in-memory.js +0 -28
  501. package/dist/realtime/in-memory.js.map +0 -1
  502. package/dist/realtime/index.d.ts +0 -4
  503. package/dist/realtime/index.d.ts.map +0 -1
  504. package/dist/realtime/index.js +0 -3
  505. package/dist/realtime/index.js.map +0 -1
  506. package/dist/realtime/types.d.ts +0 -62
  507. package/dist/realtime/types.d.ts.map +0 -1
  508. package/dist/realtime/types.js +0 -19
  509. package/dist/realtime/types.js.map +0 -1
  510. package/dist/relay/client-role/forward-engine.d.ts +0 -63
  511. package/dist/relay/client-role/forward-engine.d.ts.map +0 -1
  512. package/dist/relay/client-role/forward-engine.js +0 -267
  513. package/dist/relay/client-role/forward-engine.js.map +0 -1
  514. package/dist/relay/client-role/index.d.ts +0 -9
  515. package/dist/relay/client-role/index.d.ts.map +0 -1
  516. package/dist/relay/client-role/index.js +0 -9
  517. package/dist/relay/client-role/index.js.map +0 -1
  518. package/dist/relay/client-role/pull-engine.d.ts +0 -72
  519. package/dist/relay/client-role/pull-engine.d.ts.map +0 -1
  520. package/dist/relay/client-role/pull-engine.js +0 -249
  521. package/dist/relay/client-role/pull-engine.js.map +0 -1
  522. package/dist/relay/client-role/sequence-mapper.d.ts +0 -65
  523. package/dist/relay/client-role/sequence-mapper.d.ts.map +0 -1
  524. package/dist/relay/client-role/sequence-mapper.js +0 -161
  525. package/dist/relay/client-role/sequence-mapper.js.map +0 -1
  526. package/dist/relay/evaluation/relay-paths.d.ts +0 -41
  527. package/dist/relay/evaluation/relay-paths.d.ts.map +0 -1
  528. package/dist/relay/evaluation/relay-paths.js +0 -504
  529. package/dist/relay/evaluation/relay-paths.js.map +0 -1
  530. package/dist/relay/evaluation/rust-boundary.d.ts +0 -47
  531. package/dist/relay/evaluation/rust-boundary.d.ts.map +0 -1
  532. package/dist/relay/evaluation/rust-boundary.js +0 -220
  533. package/dist/relay/evaluation/rust-boundary.js.map +0 -1
  534. package/dist/relay/index.d.ts +0 -37
  535. package/dist/relay/index.d.ts.map +0 -1
  536. package/dist/relay/index.js +0 -44
  537. package/dist/relay/index.js.map +0 -1
  538. package/dist/relay/migrate.d.ts +0 -18
  539. package/dist/relay/migrate.d.ts.map +0 -1
  540. package/dist/relay/migrate.js +0 -99
  541. package/dist/relay/migrate.js.map +0 -1
  542. package/dist/relay/mode-manager.d.ts +0 -60
  543. package/dist/relay/mode-manager.d.ts.map +0 -1
  544. package/dist/relay/mode-manager.js +0 -114
  545. package/dist/relay/mode-manager.js.map +0 -1
  546. package/dist/relay/realtime.d.ts +0 -90
  547. package/dist/relay/realtime.d.ts.map +0 -1
  548. package/dist/relay/realtime.js +0 -147
  549. package/dist/relay/realtime.js.map +0 -1
  550. package/dist/relay/relay.d.ts +0 -190
  551. package/dist/relay/relay.d.ts.map +0 -1
  552. package/dist/relay/relay.js +0 -320
  553. package/dist/relay/relay.js.map +0 -1
  554. package/dist/relay/schema.d.ts +0 -158
  555. package/dist/relay/schema.d.ts.map +0 -1
  556. package/dist/relay/schema.js +0 -7
  557. package/dist/relay/schema.js.map +0 -1
  558. package/dist/relay/server-role/index.d.ts +0 -56
  559. package/dist/relay/server-role/index.d.ts.map +0 -1
  560. package/dist/relay/server-role/index.js +0 -193
  561. package/dist/relay/server-role/index.js.map +0 -1
  562. package/dist/relay/server-role/pull.d.ts +0 -27
  563. package/dist/relay/server-role/pull.d.ts.map +0 -1
  564. package/dist/relay/server-role/pull.js +0 -24
  565. package/dist/relay/server-role/pull.js.map +0 -1
  566. package/dist/relay/server-role/push.d.ts +0 -29
  567. package/dist/relay/server-role/push.d.ts.map +0 -1
  568. package/dist/relay/server-role/push.js +0 -122
  569. package/dist/relay/server-role/push.js.map +0 -1
  570. package/dist/s3/index.d.ts +0 -83
  571. package/dist/s3/index.d.ts.map +0 -1
  572. package/dist/s3/index.js +0 -223
  573. package/dist/s3/index.js.map +0 -1
  574. package/dist/schema.d.ts.map +0 -1
  575. package/dist/schema.js.map +0 -1
  576. package/dist/service-worker/index.d.ts +0 -114
  577. package/dist/service-worker/index.d.ts.map +0 -1
  578. package/dist/service-worker/index.js +0 -487
  579. package/dist/service-worker/index.js.map +0 -1
  580. package/dist/snapshot-artifacts/sqlite-bun.d.ts +0 -15
  581. package/dist/snapshot-artifacts/sqlite-bun.d.ts.map +0 -1
  582. package/dist/snapshot-artifacts/sqlite-bun.js +0 -128
  583. package/dist/snapshot-artifacts/sqlite-bun.js.map +0 -1
  584. package/dist/snapshot-artifacts.d.ts +0 -206
  585. package/dist/snapshot-artifacts.d.ts.map +0 -1
  586. package/dist/snapshot-artifacts.js +0 -545
  587. package/dist/snapshot-artifacts.js.map +0 -1
  588. package/dist/snapshot-chunks/db-metadata.d.ts +0 -56
  589. package/dist/snapshot-chunks/db-metadata.d.ts.map +0 -1
  590. package/dist/snapshot-chunks/db-metadata.js +0 -360
  591. package/dist/snapshot-chunks/db-metadata.js.map +0 -1
  592. package/dist/snapshot-chunks/index.d.ts +0 -8
  593. package/dist/snapshot-chunks/index.d.ts.map +0 -1
  594. package/dist/snapshot-chunks/index.js +0 -8
  595. package/dist/snapshot-chunks/index.js.map +0 -1
  596. package/dist/snapshot-chunks/types.d.ts +0 -80
  597. package/dist/snapshot-chunks/types.d.ts.map +0 -1
  598. package/dist/snapshot-chunks/types.js +0 -8
  599. package/dist/snapshot-chunks/types.js.map +0 -1
  600. package/dist/snapshot-chunks.d.ts +0 -90
  601. package/dist/snapshot-chunks.d.ts.map +0 -1
  602. package/dist/snapshot-chunks.js +0 -304
  603. package/dist/snapshot-chunks.js.map +0 -1
  604. package/dist/sqlite/index.d.ts +0 -53
  605. package/dist/sqlite/index.d.ts.map +0 -1
  606. package/dist/sqlite/index.js +0 -795
  607. package/dist/sqlite/index.js.map +0 -1
  608. package/dist/sqlite3.d.ts +0 -22
  609. package/dist/sqlite3.d.ts.map +0 -1
  610. package/dist/sqlite3.js +0 -99
  611. package/dist/sqlite3.js.map +0 -1
  612. package/dist/stats.d.ts +0 -28
  613. package/dist/stats.d.ts.map +0 -1
  614. package/dist/stats.js +0 -93
  615. package/dist/stats.js.map +0 -1
  616. package/dist/subscriptions/cache.d.ts +0 -58
  617. package/dist/subscriptions/cache.d.ts.map +0 -1
  618. package/dist/subscriptions/cache.js +0 -250
  619. package/dist/subscriptions/cache.js.map +0 -1
  620. package/dist/subscriptions/index.d.ts +0 -3
  621. package/dist/subscriptions/index.d.ts.map +0 -1
  622. package/dist/subscriptions/index.js +0 -3
  623. package/dist/subscriptions/index.js.map +0 -1
  624. package/dist/subscriptions/resolve.d.ts +0 -40
  625. package/dist/subscriptions/resolve.d.ts.map +0 -1
  626. package/dist/subscriptions/resolve.js +0 -275
  627. package/dist/subscriptions/resolve.js.map +0 -1
  628. package/dist/sync.d.ts +0 -24
  629. package/dist/sync.d.ts.map +0 -1
  630. package/dist/sync.js +0 -27
  631. package/dist/sync.js.map +0 -1
  632. package/src/auth-leases.ts +0 -649
  633. package/src/better-sqlite3.ts +0 -35
  634. package/src/blobs/access.ts +0 -244
  635. package/src/blobs/adapters/database.ts +0 -397
  636. package/src/blobs/index.ts +0 -9
  637. package/src/blobs/manager.ts +0 -901
  638. package/src/blobs/migrate.ts +0 -158
  639. package/src/blobs/types.ts +0 -74
  640. package/src/bun-sqlite-ambient.d.ts +0 -19
  641. package/src/bun-sqlite.ts +0 -27
  642. package/src/clients.ts +0 -22
  643. package/src/cloudflare/durable-object.ts +0 -289
  644. package/src/cloudflare/index.ts +0 -22
  645. package/src/cloudflare/r2.ts +0 -526
  646. package/src/cloudflare/scope-cache.ts +0 -341
  647. package/src/cloudflare/sentry.ts +0 -230
  648. package/src/cloudflare/worker.ts +0 -77
  649. package/src/commit-integrity.ts +0 -371
  650. package/src/compaction.ts +0 -77
  651. package/src/crdt-yjs/index.ts +0 -931
  652. package/src/d1.ts +0 -16
  653. package/src/dialect/base.ts +0 -360
  654. package/src/dialect/helpers.ts +0 -92
  655. package/src/dialect/index.ts +0 -7
  656. package/src/dialect/types.ts +0 -247
  657. package/src/encrypted-crdt.ts +0 -786
  658. package/src/filesystem/index.ts +0 -262
  659. package/src/handlers/collection.ts +0 -121
  660. package/src/handlers/create-handler.ts +0 -1134
  661. package/src/handlers/index.ts +0 -3
  662. package/src/handlers/types.ts +0 -403
  663. package/src/helpers/conflict.ts +0 -64
  664. package/src/helpers/emitted-change.ts +0 -69
  665. package/src/helpers/index.ts +0 -12
  666. package/src/helpers/paginate.ts +0 -82
  667. package/src/helpers/scope-authorization.ts +0 -27
  668. package/src/helpers/scope-commit-index.ts +0 -52
  669. package/src/helpers/scope-strings.ts +0 -101
  670. package/src/hono/api-key-auth.ts +0 -177
  671. package/src/hono/audit-redaction.ts +0 -135
  672. package/src/hono/blobs.ts +0 -851
  673. package/src/hono/console/gateway.ts +0 -3046
  674. package/src/hono/console/live-auth.ts +0 -46
  675. package/src/hono/console/route-descriptor.ts +0 -22
  676. package/src/hono/console/routes/api-keys.ts +0 -721
  677. package/src/hono/console/routes/clients.ts +0 -447
  678. package/src/hono/console/routes/commits.ts +0 -1137
  679. package/src/hono/console/routes/context.ts +0 -956
  680. package/src/hono/console/routes/events.ts +0 -669
  681. package/src/hono/console/routes/maintenance.ts +0 -461
  682. package/src/hono/console/routes/shared.ts +0 -816
  683. package/src/hono/console/routes/stats.ts +0 -392
  684. package/src/hono/console/routes/storage.ts +0 -159
  685. package/src/hono/console/routes.ts +0 -146
  686. package/src/hono/console/schema-errors.ts +0 -23
  687. package/src/hono/console/schemas.ts +0 -914
  688. package/src/hono/console/types.ts +0 -223
  689. package/src/hono/console/ui.ts +0 -100
  690. package/src/hono/create-server.ts +0 -230
  691. package/src/hono/errors.ts +0 -50
  692. package/src/hono/index.ts +0 -54
  693. package/src/hono/openapi.ts +0 -139
  694. package/src/hono/proxy/connection-manager.ts +0 -340
  695. package/src/hono/proxy/index.ts +0 -8
  696. package/src/hono/proxy/routes.ts +0 -272
  697. package/src/hono/rate-limit.ts +0 -319
  698. package/src/hono/realtime-sync-packs.ts +0 -354
  699. package/src/hono/routes/audit.ts +0 -499
  700. package/src/hono/routes/auth-leases.ts +0 -119
  701. package/src/hono/routes/combined.ts +0 -583
  702. package/src/hono/routes/context.ts +0 -1629
  703. package/src/hono/routes/health.ts +0 -26
  704. package/src/hono/routes/realtime.ts +0 -808
  705. package/src/hono/routes/shared.ts +0 -1626
  706. package/src/hono/routes/snapshots.ts +0 -345
  707. package/src/hono/routes.ts +0 -68
  708. package/src/hono/validation.ts +0 -81
  709. package/src/hono/websocket-origin.ts +0 -131
  710. package/src/hono/ws.ts +0 -1134
  711. package/src/libsql.ts +0 -51
  712. package/src/migrate.ts +0 -20
  713. package/src/neon.ts +0 -28
  714. package/src/notify.ts +0 -341
  715. package/src/pglite.ts +0 -68
  716. package/src/plugins/index.ts +0 -1
  717. package/src/plugins/types.ts +0 -144
  718. package/src/postgres/index.ts +0 -1291
  719. package/src/proxy/collection.ts +0 -17
  720. package/src/proxy/handler.ts +0 -159
  721. package/src/proxy/index.ts +0 -21
  722. package/src/proxy/mutation-detector.ts +0 -281
  723. package/src/proxy/oplog.ts +0 -181
  724. package/src/proxy/types.ts +0 -46
  725. package/src/realtime/in-memory.ts +0 -33
  726. package/src/realtime/index.ts +0 -7
  727. package/src/realtime/types.ts +0 -90
  728. package/src/relay/bun-types.d.ts +0 -50
  729. package/src/relay/client-role/forward-engine.ts +0 -355
  730. package/src/relay/client-role/index.ts +0 -9
  731. package/src/relay/client-role/pull-engine.ts +0 -329
  732. package/src/relay/client-role/sequence-mapper.ts +0 -201
  733. package/src/relay/evaluation/relay-paths.ts +0 -699
  734. package/src/relay/evaluation/rust-boundary.ts +0 -464
  735. package/src/relay/index.ts +0 -50
  736. package/src/relay/migrate.ts +0 -113
  737. package/src/relay/mode-manager.ts +0 -142
  738. package/src/relay/realtime.ts +0 -207
  739. package/src/relay/relay.ts +0 -431
  740. package/src/relay/schema.ts +0 -171
  741. package/src/relay/server-role/index.ts +0 -338
  742. package/src/relay/server-role/pull.ts +0 -43
  743. package/src/relay/server-role/push.ts +0 -164
  744. package/src/s3/index.ts +0 -346
  745. package/src/service-worker/index.ts +0 -773
  746. package/src/snapshot-artifacts/sqlite-bun.ts +0 -168
  747. package/src/snapshot-artifacts.ts +0 -896
  748. package/src/snapshot-chunks/db-metadata.ts +0 -537
  749. package/src/snapshot-chunks/index.ts +0 -8
  750. package/src/snapshot-chunks/types.ts +0 -105
  751. package/src/snapshot-chunks.ts +0 -453
  752. package/src/sqlite/index.ts +0 -1064
  753. package/src/sqlite3.ts +0 -137
  754. package/src/stats.ts +0 -180
  755. package/src/subscriptions/cache.ts +0 -376
  756. package/src/subscriptions/index.ts +0 -2
  757. package/src/subscriptions/resolve.ts +0 -357
  758. package/src/sync.ts +0 -111
@@ -1,1626 +0,0 @@
1
- /**
2
- * Shared private helpers, constants, option types, and zod schemas used by the
3
- * sync route modules. Extracted verbatim from routes.ts.
4
- */
5
-
6
- import {
7
- collectScopeVars,
8
- createSyncularErrorResponse,
9
- type ScopeValues,
10
- ScopeValuesSchema,
11
- type StoredScopes,
12
- SYNC_AUTH_LEASE_CODE_EXPIRED,
13
- SYNC_AUTH_LEASE_CODE_INVALID,
14
- SYNC_AUTH_LEASE_CODE_MISSING,
15
- type SyncAuthLeaseCapabilities,
16
- } from '@syncular/core';
17
- import type {
18
- ScopeCacheBackend,
19
- ServerSnapshotBinaryMetadata,
20
- ServerSyncDialect,
21
- ServerTableHandler,
22
- SnapshotArtifactStorage,
23
- SnapshotChunkStorage,
24
- SqlFamily,
25
- SyncCoreDb,
26
- SyncRealtimeBroadcaster,
27
- SyncServerAuth,
28
- SyncServerPushPlugin,
29
- } from '@syncular/server';
30
- import {
31
- type AuthLeaseSigner,
32
- type CompactOptions,
33
- coerceNumber,
34
- type PruneOptions,
35
- type PullResult,
36
- parseJsonValue,
37
- } from '@syncular/server';
38
- import type { Context, Hono } from 'hono';
39
- import type { UpgradeWebSocket } from 'hono/ws';
40
- import { type Kysely, sql } from 'kysely';
41
- import { z } from 'zod';
42
- import { syncErrorResponse, syncLimitExceeded } from '../errors';
43
- import type { SyncRateLimitConfig } from '../rate-limit';
44
- import { resolveAllowedOriginFromPatterns } from '../websocket-origin';
45
- import type {
46
- WebSocketConnectionManager,
47
- WebSocketRealtimeSubscription,
48
- } from '../ws';
49
-
50
- /**
51
- * WeakMaps for storing Hono-instance-specific data without augmenting the type.
52
- */
53
- const wsConnectionManagerMap = new WeakMap<Hono, WebSocketConnectionManager>();
54
- const realtimeUnsubscribeMap = new WeakMap<Hono, () => void>();
55
-
56
- export { realtimeUnsubscribeMap, wsConnectionManagerMap };
57
-
58
- export interface SyncAuthResult extends SyncServerAuth {}
59
-
60
- /**
61
- * WebSocket configuration for realtime sync.
62
- */
63
- export interface SyncWebSocketConfig {
64
- enabled?: boolean;
65
- /**
66
- * Runtime-provided WebSocket upgrader (e.g. from `hono/bun`'s `createBunWebSocket()`).
67
- */
68
- upgradeWebSocket?: UpgradeWebSocket;
69
- heartbeatIntervalMs?: number;
70
- /**
71
- * Maximum number of concurrent WebSocket connections across the entire process.
72
- * Default: 5000
73
- */
74
- maxConnectionsTotal?: number;
75
- /**
76
- * Maximum number of concurrent WebSocket connections per clientId.
77
- * Default: 3
78
- */
79
- maxConnectionsPerClient?: number;
80
- /**
81
- * Maximum inbound websocket message size in bytes.
82
- * Default: 1 MiB.
83
- */
84
- maxMessageBytes?: number;
85
- /**
86
- * Maximum encoded sync-pack size sent directly over a websocket frame.
87
- * Larger payloads fall back to explicit HTTP pull recovery.
88
- * Default: 64 KiB.
89
- */
90
- maxSyncPackBytes?: number;
91
- /**
92
- * Maximum inbound websocket messages allowed per connection within one window.
93
- * Default: 120 messages.
94
- * Set to 0 or a negative value to disable rate limiting.
95
- */
96
- maxMessagesPerWindow?: number;
97
- /**
98
- * Maximum outbound sync notifications allowed without a newer client ACK.
99
- * When exceeded, the server sends cursor-only resync-required frames until
100
- * the client ACKs a caught-up cursor. Set to 0 to disable.
101
- * Default: 64.
102
- */
103
- maxInFlightSyncsPerConnection?: number;
104
- /**
105
- * Recent outbound scope notifications retained for websocket reconnect
106
- * replay before falling back to HTTP pull recovery. Set to 0 to disable.
107
- * Default: 64.
108
- */
109
- replayWindowSize?: number;
110
- /**
111
- * Window size in milliseconds for inbound websocket message rate limiting.
112
- * Default: 10000 ms.
113
- */
114
- messageRateWindowMs?: number;
115
- /**
116
- * Optional list of allowed websocket origins.
117
- * - undefined: allow same-origin browser upgrades and origin-less non-browser clients
118
- * - '*': allow all origins
119
- * - string[]: exact origin match (scheme + host + port)
120
- */
121
- allowedOrigins?: string[] | '*';
122
- }
123
-
124
- export type SyncCorsOriginResolver = (
125
- origin: string | undefined,
126
- context: Context
127
- ) =>
128
- | boolean
129
- | string
130
- | null
131
- | undefined
132
- | Promise<boolean | string | null | undefined>;
133
-
134
- export type SyncCorsOrigin = string | string[] | '*' | SyncCorsOriginResolver;
135
-
136
- export interface SyncCorsOptions {
137
- /**
138
- * Hono-style origin config.
139
- * - string / string[]: exact or wildcard origin patterns
140
- * - '*': allow all origins
141
- * - function: dynamic allow/deny decision
142
- */
143
- origin?: SyncCorsOrigin;
144
- /**
145
- * Additional request headers to allow. These are appended to the built-in
146
- * Syncular transport and tracing headers, not used as a replacement.
147
- */
148
- allowHeaders?: string[];
149
- /**
150
- * Additional response headers exposed to the browser.
151
- */
152
- exposeHeaders?: string[];
153
- }
154
-
155
- export interface SyncRoutesConfigWithRateLimit {
156
- /**
157
- * Optional browser CORS handling for sync routes.
158
- * When configured, sync route responses and preflights include matching
159
- * CORS headers directly from the generated sync app.
160
- */
161
- cors?: SyncCorsOrigin | SyncCorsOptions;
162
- /**
163
- * Max commits per pull request.
164
- * Default: 100
165
- */
166
- maxPullLimitCommits?: number;
167
- /**
168
- * Max subscriptions per pull request.
169
- * Default: 200
170
- */
171
- maxSubscriptionsPerPull?: number;
172
- /**
173
- * Max snapshot rows per snapshot page.
174
- * Default: 5000
175
- */
176
- maxPullLimitSnapshotRows?: number;
177
- /**
178
- * Max snapshot pages per subscription per pull response.
179
- * Default: 50
180
- */
181
- maxPullMaxSnapshotPages?: number;
182
- /**
183
- * Gzip compression level for generated snapshot chunks.
184
- *
185
- * Default: 1, range: 0-9. Lower values reduce CPU and browser inflate time
186
- * but increase response size.
187
- */
188
- snapshotChunkGzipLevel?: number;
189
- /**
190
- * Max operations per pushed commit.
191
- * Default: 200
192
- */
193
- maxOperationsPerPush?: number;
194
- /**
195
- * Maximum JSON request body accepted by POST /.
196
- * Default: 4 MiB.
197
- */
198
- maxSyncRequestJsonBytes?: number;
199
- /**
200
- * Maximum binary sync-pack response body emitted by POST /.
201
- * Default: 16 MiB.
202
- */
203
- maxSyncBinaryPackBytes?: number;
204
- /**
205
- * Maximum snapshot chunk body emitted by GET /snapshot-chunks/:chunkId.
206
- * Default: 64 MiB.
207
- */
208
- maxSnapshotChunkResponseBytes?: number;
209
- /**
210
- * Maximum snapshot artifact body emitted by GET /snapshot-artifacts/:artifactId.
211
- * Default: 256 MiB.
212
- */
213
- maxSnapshotArtifactResponseBytes?: number;
214
- /**
215
- * Request/response payload snapshots recorded for console inspection.
216
- */
217
- requestPayloadSnapshots?: {
218
- /**
219
- * Enable payload snapshot storage in `sync_request_payloads`.
220
- * Default: false (opt-in).
221
- */
222
- enabled?: boolean;
223
- /**
224
- * Max serialized payload size in bytes per request/response snapshot.
225
- * Larger payloads are truncated with metadata.
226
- * Default: 128 KiB.
227
- */
228
- maxBytes?: number;
229
- };
230
- /**
231
- * Minimum Syncular client schema version accepted by this server.
232
- * Clients with an older runtime must upgrade before continuing sync.
233
- */
234
- requiredSchemaVersion?: number;
235
- /**
236
- * Latest Syncular client schema version known by this server.
237
- * Newer values are informational and should not block older compatible
238
- * clients.
239
- */
240
- latestSchemaVersion?: number;
241
- /**
242
- * Rate limiting configuration.
243
- * Set to false to disable all rate limiting.
244
- */
245
- rateLimit?: SyncRateLimitConfig | false;
246
- /**
247
- * WebSocket realtime configuration.
248
- */
249
- websocket?: SyncWebSocketConfig;
250
-
251
- /**
252
- * Optional pruning configuration. When enabled, the server periodically prunes
253
- * old commit history based on active client cursors.
254
- */
255
- prune?: {
256
- /** Minimum time between prune runs. Default: 5 minutes. */
257
- minIntervalMs?: number;
258
- /** Pruning watermark options. */
259
- options?: PruneOptions;
260
- };
261
-
262
- /**
263
- * Optional compaction configuration. When enabled, the server periodically
264
- * compacts older change history to reduce storage.
265
- */
266
- compact?: {
267
- /** Minimum time between compaction runs. Default: 30 minutes. */
268
- minIntervalMs?: number;
269
- /** Compaction options. */
270
- options?: CompactOptions;
271
- };
272
-
273
- /**
274
- * Optional multi-instance realtime broadcaster.
275
- * When provided, instances publish/subscribe commit wakeups via the broadcaster.
276
- */
277
- realtime?: {
278
- broadcaster: SyncRealtimeBroadcaster;
279
- /** Optional stable instance id (useful in tests). */
280
- instanceId?: string;
281
- };
282
- }
283
-
284
- export interface SyncAuthLeaseRoutesConfig<
285
- Auth extends SyncAuthResult = SyncAuthResult,
286
- > {
287
- /**
288
- * Set false to keep route config around without exposing the issue endpoint.
289
- * Providing this config enables POST /auth-leases/issue by default.
290
- */
291
- enabled?: boolean;
292
- issuer: string;
293
- audience: string;
294
- kid: string;
295
- signer: AuthLeaseSigner;
296
- publicKey: CryptoKey;
297
- ttlMs?: number;
298
- maxTtlMs?: number;
299
- maxClockSkewMs?: number;
300
- capabilities?: SyncAuthLeaseCapabilities;
301
- nowMs?: () => number;
302
- leaseId?: () => string;
303
- subject?: (
304
- auth: Auth
305
- ) => Record<string, unknown> | Promise<Record<string, unknown>>;
306
- }
307
-
308
- export interface CreateSyncRoutesOptions<
309
- DB extends SyncCoreDb = SyncCoreDb,
310
- Auth extends SyncAuthResult = SyncAuthResult,
311
- F extends SqlFamily = SqlFamily,
312
- > {
313
- db: Kysely<DB>;
314
- dialect: ServerSyncDialect<F>;
315
- handlers: ServerTableHandler<DB, Auth>[];
316
- snapshotBinary?: ServerSnapshotBinaryMetadata;
317
- plugins?: SyncServerPushPlugin<DB, Auth>[];
318
- authenticate: (c: Context) => Promise<Auth | null>;
319
- sync?: SyncRoutesConfigWithRateLimit;
320
- authLeases?: SyncAuthLeaseRoutesConfig<Auth>;
321
- wsConnectionManager?: WebSocketConnectionManager;
322
- /**
323
- * Optional snapshot chunk storage adapter.
324
- * When provided, stores snapshot chunk bodies in external storage
325
- * (S3, R2, etc.) instead of inline in the database.
326
- */
327
- chunkStorage?: SnapshotChunkStorage;
328
- /**
329
- * Optional scoped snapshot artifact body storage adapter.
330
- * Artifact metadata is stored in SQL; bodies are always external.
331
- */
332
- snapshotArtifactStorage?: SnapshotArtifactStorage;
333
- /**
334
- * Optional scope cache backend for resolveScopes() results.
335
- * Request-local memoization is always applied for every pull.
336
- */
337
- scopeCache?: ScopeCacheBackend;
338
- /**
339
- * Optional live emitter for console websocket activity feed.
340
- * When provided, sync lifecycle events are published to `/console/events/live`.
341
- */
342
- consoleLiveEmitter?: {
343
- emit(event: {
344
- type: 'sync' | 'push' | 'pull' | 'commit' | 'client_update';
345
- timestamp: string;
346
- data: Record<string, unknown>;
347
- }): void;
348
- };
349
- /**
350
- * Optional console schema readiness promise.
351
- * When provided, request-event recording waits for this promise before writing.
352
- */
353
- consoleSchemaReady?: Promise<void>;
354
- }
355
-
356
- // ============================================================================
357
- // Route Schemas
358
- // ============================================================================
359
-
360
- export const snapshotChunkParamsSchema = z.object({
361
- chunkId: z.string().min(1),
362
- });
363
- export const snapshotArtifactParamsSchema = z.object({
364
- artifactId: z.string().min(1),
365
- });
366
- export const snapshotChunkQuerySchema = z.object({
367
- scopes: z.string().optional(),
368
- });
369
-
370
- export const auditCommitListQuerySchema = z.object({
371
- limit: z.coerce.number().int().min(1).max(200).optional(),
372
- beforeCommitSeq: z.coerce.number().int().min(1).optional(),
373
- actorId: z.string().min(1).optional(),
374
- table: z.string().min(1).optional(),
375
- from: z.string().datetime().optional(),
376
- to: z.string().datetime().optional(),
377
- });
378
-
379
- export const auditCommitParamsSchema = z.object({
380
- commitSeq: z.coerce.number().int().min(1),
381
- });
382
-
383
- export const auditRowHistoryParamsSchema = z.object({
384
- table: z.string().min(1),
385
- rowId: z.string().min(1),
386
- });
387
-
388
- export const auditRowHistoryQuerySchema = z
389
- .object({
390
- limit: z.coerce.number().int().min(1).max(200).optional(),
391
- beforeCommitSeq: z.coerce.number().int().min(1).optional(),
392
- afterCommitSeq: z.coerce.number().int().min(1).optional(),
393
- })
394
- .refine(
395
- (query) =>
396
- query.beforeCommitSeq === undefined ||
397
- query.afterCommitSeq === undefined ||
398
- query.afterCommitSeq < query.beforeCommitSeq,
399
- {
400
- message: 'afterCommitSeq must be lower than beforeCommitSeq',
401
- path: ['afterCommitSeq'],
402
- }
403
- );
404
-
405
- export const auditDebugExportQuerySchema = z.object({
406
- limitCommits: z.coerce.number().int().min(1).max(200).default(50),
407
- limitEvents: z.coerce.number().int().min(1).max(500).default(100),
408
- from: z.string().datetime().optional(),
409
- to: z.string().datetime().optional(),
410
- });
411
-
412
- const auditCommitSummarySchema = z.object({
413
- commitSeq: z.number().int(),
414
- actorId: z.string(),
415
- clientId: z.string(),
416
- clientCommitId: z.string(),
417
- createdAt: z.string(),
418
- changeCount: z.number().int(),
419
- affectedTables: z.array(z.string()),
420
- });
421
-
422
- export const auditCommitListResponseSchema = z.object({
423
- ok: z.literal(true),
424
- commits: z.array(auditCommitSummarySchema),
425
- nextCursor: z.number().int().nullable(),
426
- });
427
-
428
- const auditChangeKindSchema = z.enum([
429
- 'app_row',
430
- 'delete',
431
- 'blob_reference',
432
- 'encrypted_field_envelope',
433
- 'encrypted_crdt_update',
434
- 'encrypted_crdt_checkpoint',
435
- ]);
436
-
437
- const auditChangeRedactionSchema = z.object({
438
- payload: z.literal('omitted'),
439
- reason: z.literal('audit_redacted_by_default'),
440
- });
441
-
442
- const auditChangeSchema = z.object({
443
- changeId: z.number().int(),
444
- table: z.string(),
445
- rowId: z.string(),
446
- op: z.enum(['upsert', 'delete']),
447
- rowVersion: z.number().int().nullable(),
448
- fields: z.array(z.string()),
449
- scopeFields: z.array(z.string()),
450
- changeKind: auditChangeKindSchema,
451
- sensitiveFields: z.array(z.string()),
452
- redaction: auditChangeRedactionSchema,
453
- });
454
-
455
- export const auditCommitDetailResponseSchema = z.object({
456
- ok: z.literal(true),
457
- commit: auditCommitSummarySchema,
458
- changes: z.array(auditChangeSchema),
459
- });
460
-
461
- const auditDebugExportCommitSchema = auditCommitSummarySchema.extend({
462
- changes: z.array(auditChangeSchema),
463
- });
464
-
465
- const auditDebugExportEventSchema = z.object({
466
- eventId: z.number().int(),
467
- partitionId: z.string(),
468
- requestId: z.string(),
469
- traceId: z.string().nullable(),
470
- spanId: z.string().nullable(),
471
- eventType: z.enum(['sync', 'push', 'pull']),
472
- syncPath: z.enum(['http-combined', 'ws-push']),
473
- transportPath: z.enum(['direct', 'relay']),
474
- actorId: z.string(),
475
- clientId: z.string(),
476
- statusCode: z.number().int(),
477
- outcome: z.string(),
478
- responseStatus: z.string(),
479
- errorCode: z.string().nullable(),
480
- durationMs: z.number().int(),
481
- commitSeq: z.number().int().nullable(),
482
- operationCount: z.number().int().nullable(),
483
- rowCount: z.number().int().nullable(),
484
- subscriptionCount: z.number().int().nullable(),
485
- scopesSummary: z
486
- .record(z.string(), z.union([z.string(), z.array(z.string())]))
487
- .nullable(),
488
- tables: z.array(z.string()),
489
- createdAt: z.string(),
490
- });
491
-
492
- export const auditDebugExportResponseSchema = z.object({
493
- ok: z.literal(true),
494
- generatedAt: z.string(),
495
- partitionId: z.string(),
496
- limits: z.object({
497
- commits: z.number().int(),
498
- requestEvents: z.number().int(),
499
- }),
500
- truncated: z.object({
501
- commits: z.boolean(),
502
- requestEvents: z.boolean(),
503
- }),
504
- commits: z.array(auditDebugExportCommitSchema),
505
- requestEvents: z.array(auditDebugExportEventSchema),
506
- });
507
-
508
- const auditRowHistoryEntrySchema = z.object({
509
- commitSeq: z.number().int(),
510
- actorId: z.string(),
511
- clientId: z.string(),
512
- clientCommitId: z.string(),
513
- createdAt: z.string(),
514
- changeId: z.number().int(),
515
- table: z.string(),
516
- rowId: z.string(),
517
- op: z.enum(['upsert', 'delete']),
518
- rowVersion: z.number().int().nullable(),
519
- fields: z.array(z.string()),
520
- scopeFields: z.array(z.string()),
521
- changeKind: auditChangeKindSchema,
522
- sensitiveFields: z.array(z.string()),
523
- redaction: auditChangeRedactionSchema,
524
- });
525
-
526
- export const auditRowHistoryResponseSchema = z.object({
527
- ok: z.literal(true),
528
- table: z.string(),
529
- rowId: z.string(),
530
- history: z.array(auditRowHistoryEntrySchema),
531
- nextCursor: z.number().int().nullable(),
532
- });
533
-
534
- export type AuditChangeResponse = z.infer<typeof auditChangeSchema>;
535
- export type AuditDebugExportEvent = z.infer<typeof auditDebugExportEventSchema>;
536
-
537
- export const DEFAULT_REQUEST_PAYLOAD_SNAPSHOT_MAX_BYTES = 128 * 1024;
538
- export const DEFAULT_MAX_SYNC_REQUEST_JSON_BYTES = 4 * 1024 * 1024;
539
- export const DEFAULT_MAX_SYNC_BINARY_PACK_BYTES = 16 * 1024 * 1024;
540
- export const DEFAULT_MAX_SNAPSHOT_CHUNK_RESPONSE_BYTES = 64 * 1024 * 1024;
541
- export const DEFAULT_MAX_SNAPSHOT_ARTIFACT_RESPONSE_BYTES = 256 * 1024 * 1024;
542
- const SNAPSHOT_SCOPES_HEADER = 'x-syncular-snapshot-scopes';
543
- const SYNC_CLIENT_ID_HEADER = 'x-syncular-client-id';
544
-
545
- export type TraceContext = {
546
- traceId: string | null;
547
- spanId: string | null;
548
- };
549
-
550
- const DEFAULT_SYNC_CORS_ALLOW_HEADERS = [
551
- 'Content-Type',
552
- 'Authorization',
553
- 'Cache-Control',
554
- 'x-syncular-publishable-key',
555
- 'x-syncular-schema-version',
556
- SNAPSHOT_SCOPES_HEADER,
557
- 'x-syncular-sync-attempt-id',
558
- 'x-syncular-transport-path',
559
- SYNC_CLIENT_ID_HEADER,
560
- 'sentry-trace',
561
- 'baggage',
562
- 'traceparent',
563
- 'tracestate',
564
- ];
565
-
566
- const DEFAULT_SYNC_CORS_ALLOW_METHODS = [
567
- 'GET',
568
- 'POST',
569
- 'PUT',
570
- 'DELETE',
571
- 'OPTIONS',
572
- ];
573
-
574
- const DEFAULT_SYNC_CORS_EXPOSE_HEADERS: string[] = [];
575
-
576
- export type NormalizedSyncCorsConfig = {
577
- resolveOrigin: (
578
- origin: string | undefined,
579
- context: Context
580
- ) => Promise<string | null>;
581
- staticAllowedOrigins?: string[] | '*';
582
- allowHeaders: string[];
583
- exposeHeaders: string[];
584
- allowMethods: string[];
585
- allowCredentials: boolean;
586
- maxAgeSeconds: number;
587
- };
588
-
589
- export function applySyncCorsHeaders(args: {
590
- headers: Headers;
591
- allowedOrigin: string;
592
- allowCredentials: boolean;
593
- allowHeaders: string[];
594
- exposeHeaders: string[];
595
- allowMethods: string[];
596
- maxAgeSeconds: number;
597
- }): void {
598
- args.headers.set('Access-Control-Allow-Origin', args.allowedOrigin);
599
- args.headers.set(
600
- 'Access-Control-Allow-Headers',
601
- args.allowHeaders.join(', ')
602
- );
603
- args.headers.set(
604
- 'Access-Control-Allow-Methods',
605
- args.allowMethods.join(', ')
606
- );
607
- args.headers.set('Access-Control-Max-Age', String(args.maxAgeSeconds));
608
- if (args.exposeHeaders.length > 0) {
609
- args.headers.set(
610
- 'Access-Control-Expose-Headers',
611
- args.exposeHeaders.join(', ')
612
- );
613
- }
614
- if (args.allowedOrigin !== '*') {
615
- args.headers.append('Vary', 'Origin');
616
- if (args.allowCredentials) {
617
- args.headers.set('Access-Control-Allow-Credentials', 'true');
618
- }
619
- }
620
- }
621
-
622
- export function createSyncCorsOriginDeniedResponse(origin: string): Response {
623
- return syncErrorResponse(
624
- 403,
625
- 'sync.forbidden',
626
- `Origin ${origin} is not allowed for sync access.`
627
- );
628
- }
629
-
630
- function mergeUniqueHeaders(...lists: Array<string[] | undefined>): string[] {
631
- const seen = new Set<string>();
632
- const merged: string[] = [];
633
- for (const list of lists) {
634
- for (const header of list ?? []) {
635
- const trimmed = header.trim();
636
- if (trimmed.length === 0) continue;
637
- const key = trimmed.toLowerCase();
638
- if (seen.has(key)) continue;
639
- seen.add(key);
640
- merged.push(trimmed);
641
- }
642
- }
643
- return merged;
644
- }
645
-
646
- function normalizeOriginResolver(
647
- resolver: SyncCorsOriginResolver
648
- ): NormalizedSyncCorsConfig['resolveOrigin'] {
649
- return async (origin, context) => {
650
- const resolved = await resolver(origin, context);
651
- if (resolved === true) {
652
- return origin ?? null;
653
- }
654
- if (resolved === false || resolved == null) {
655
- return null;
656
- }
657
- return resolved;
658
- };
659
- }
660
-
661
- function createStaticOriginResolver(
662
- allowedOrigins: string[] | '*'
663
- ): NormalizedSyncCorsConfig['resolveOrigin'] {
664
- return async (origin) => {
665
- if (allowedOrigins === '*') {
666
- return '*';
667
- }
668
- return resolveAllowedOriginFromPatterns(origin, allowedOrigins);
669
- };
670
- }
671
-
672
- function toStaticAllowedOrigins(
673
- origin: string | string[] | '*'
674
- ): string[] | '*' {
675
- return origin === '*' ? '*' : typeof origin === 'string' ? [origin] : origin;
676
- }
677
-
678
- export function normalizeSyncCorsConfig(
679
- config: SyncRoutesConfigWithRateLimit['cors']
680
- ): NormalizedSyncCorsConfig | null {
681
- if (!config) {
682
- return null;
683
- }
684
-
685
- if (
686
- typeof config === 'string' ||
687
- Array.isArray(config) ||
688
- typeof config === 'function'
689
- ) {
690
- const originResolver =
691
- typeof config === 'function'
692
- ? normalizeOriginResolver(config)
693
- : createStaticOriginResolver(toStaticAllowedOrigins(config));
694
- const staticAllowedOrigins =
695
- typeof config === 'function' ? undefined : toStaticAllowedOrigins(config);
696
- return {
697
- resolveOrigin: originResolver,
698
- staticAllowedOrigins,
699
- allowHeaders: [...DEFAULT_SYNC_CORS_ALLOW_HEADERS],
700
- exposeHeaders: [...DEFAULT_SYNC_CORS_EXPOSE_HEADERS],
701
- allowMethods: [...DEFAULT_SYNC_CORS_ALLOW_METHODS],
702
- allowCredentials: true,
703
- maxAgeSeconds: 86_400,
704
- };
705
- }
706
-
707
- const staticOrigin = config.origin;
708
- const resolveOrigin =
709
- typeof staticOrigin === 'function'
710
- ? normalizeOriginResolver(staticOrigin)
711
- : staticOrigin
712
- ? createStaticOriginResolver(toStaticAllowedOrigins(staticOrigin))
713
- : async () => null;
714
- const staticAllowedOrigins =
715
- typeof staticOrigin === 'function'
716
- ? undefined
717
- : staticOrigin
718
- ? toStaticAllowedOrigins(staticOrigin)
719
- : undefined;
720
- return {
721
- resolveOrigin,
722
- staticAllowedOrigins,
723
- allowHeaders: mergeUniqueHeaders(
724
- DEFAULT_SYNC_CORS_ALLOW_HEADERS,
725
- config.allowHeaders
726
- ),
727
- exposeHeaders: mergeUniqueHeaders(
728
- DEFAULT_SYNC_CORS_EXPOSE_HEADERS,
729
- config.exposeHeaders
730
- ),
731
- allowMethods: [...DEFAULT_SYNC_CORS_ALLOW_METHODS],
732
- allowCredentials: true,
733
- maxAgeSeconds: 86_400,
734
- };
735
- }
736
-
737
- export function createOpaqueId(prefix: string): string {
738
- const randomPart =
739
- typeof crypto !== 'undefined' && 'randomUUID' in crypto
740
- ? crypto.randomUUID()
741
- : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
742
- return `${prefix}-${randomPart}`;
743
- }
744
-
745
- export function readOriginHeader(c: Context): string | undefined {
746
- return c.req.raw.headers.get('origin') ?? c.req.header('origin');
747
- }
748
-
749
- export function readRequestId(c: Context): string {
750
- const headerRequestId = c.req.header('x-request-id')?.trim();
751
- if (headerRequestId) return headerRequestId;
752
- return createOpaqueId('req');
753
- }
754
-
755
- export function readClientIdHint(c: Context): string {
756
- return c.req.header(SYNC_CLIENT_ID_HEADER)?.trim() || 'unknown';
757
- }
758
-
759
- function parseW3cTraceparent(
760
- traceparent: string | null | undefined
761
- ): TraceContext | null {
762
- if (!traceparent) return null;
763
- const parsed = traceparent.trim();
764
- const match = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i.exec(parsed);
765
- if (!match) return null;
766
- const traceId = match[1]?.toLowerCase() ?? null;
767
- const spanId = match[2]?.toLowerCase() ?? null;
768
- if (!traceId || !spanId) return null;
769
- return { traceId, spanId };
770
- }
771
-
772
- function parseSentryTraceHeader(
773
- sentryTrace: string | null | undefined
774
- ): TraceContext | null {
775
- if (!sentryTrace) return null;
776
- const parsed = sentryTrace.trim();
777
- const match = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-[01])?$/i.exec(parsed);
778
- if (!match) return null;
779
- const traceId = match[1]?.toLowerCase() ?? null;
780
- const spanId = match[2]?.toLowerCase() ?? null;
781
- if (!traceId || !spanId) return null;
782
- return { traceId, spanId };
783
- }
784
-
785
- export function readPositiveInteger(
786
- value: number | undefined,
787
- fallback: number
788
- ): number {
789
- if (typeof value !== 'number' || !Number.isFinite(value)) {
790
- return fallback;
791
- }
792
- if (value <= 0) {
793
- return fallback;
794
- }
795
- return Math.floor(value);
796
- }
797
-
798
- export function readOptionalPositiveInteger(
799
- value: number | undefined
800
- ): number | undefined {
801
- if (typeof value !== 'number' || !Number.isFinite(value)) {
802
- return undefined;
803
- }
804
- if (value <= 0) {
805
- return undefined;
806
- }
807
- return Math.floor(value);
808
- }
809
-
810
- class SyncJsonBodyLimitError extends Error {
811
- constructor(
812
- public readonly limit: string,
813
- public readonly observed: number,
814
- public readonly max: number
815
- ) {
816
- super(`${limit} exceeded: ${observed} bytes > ${max} bytes`);
817
- this.name = 'SyncJsonBodyLimitError';
818
- }
819
- }
820
-
821
- export function isSyncJsonBodyLimitError(
822
- error: unknown
823
- ): error is SyncJsonBodyLimitError {
824
- return (
825
- typeof error === 'object' &&
826
- error !== null &&
827
- (error as { name?: string }).name === 'SyncJsonBodyLimitError'
828
- );
829
- }
830
-
831
- export function readRequestContentLength(
832
- c: Context
833
- ): number | null | 'invalid' {
834
- const header = c.req.header('Content-Length');
835
- if (!header) return null;
836
- const value = Number(header);
837
- if (!Number.isFinite(value) || value < 0) return 'invalid';
838
- return Math.floor(value);
839
- }
840
-
841
- export async function readRequestBodyBytesWithLimit(
842
- request: Request,
843
- args: { maxBytes: number; limit: string }
844
- ): Promise<Uint8Array> {
845
- const body = request.body;
846
- if (!body) return new Uint8Array();
847
-
848
- const reader = body.getReader();
849
- const chunks: Uint8Array[] = [];
850
- let totalBytes = 0;
851
-
852
- while (true) {
853
- const { done, value } = await reader.read();
854
- if (done) break;
855
- if (!value || value.length === 0) continue;
856
-
857
- totalBytes += value.length;
858
- if (totalBytes > args.maxBytes) {
859
- throw new SyncJsonBodyLimitError(args.limit, totalBytes, args.maxBytes);
860
- }
861
- chunks.push(value);
862
- }
863
-
864
- const merged = new Uint8Array(totalBytes);
865
- let offset = 0;
866
- for (const chunk of chunks) {
867
- merged.set(chunk, offset);
868
- offset += chunk.length;
869
- }
870
- return merged;
871
- }
872
-
873
- export function responseBodyOverLimit(
874
- c: Context,
875
- args: { limit: string; observed: number; max: number; message?: string }
876
- ): Response | null {
877
- if (args.observed <= args.max) return null;
878
- return syncLimitExceeded(c, args);
879
- }
880
-
881
- export function syncValidationError(
882
- c: Context,
883
- target: string,
884
- issues: readonly { path?: unknown; message?: unknown }[]
885
- ): Response {
886
- return c.json(
887
- createSyncularErrorResponse('sync.invalid_request', {
888
- message: 'Invalid request.',
889
- details: {
890
- target,
891
- issues: issues.map((issue) => ({
892
- message:
893
- typeof issue.message === 'string'
894
- ? issue.message
895
- : 'Validation failed.',
896
- path: Array.isArray(issue.path)
897
- ? issue.path.map((segment) => String(segment))
898
- : [],
899
- })),
900
- },
901
- }),
902
- 400
903
- );
904
- }
905
-
906
- export function readTraceContext(c: Context): TraceContext {
907
- const traceparent = parseW3cTraceparent(c.req.header('traceparent'));
908
- if (traceparent) return traceparent;
909
-
910
- const sentryTrace = parseSentryTraceHeader(c.req.header('sentry-trace'));
911
- if (sentryTrace) return sentryTrace;
912
-
913
- return { traceId: null, spanId: null };
914
- }
915
-
916
- function readStringField(
917
- data: Record<string, unknown>,
918
- key: string
919
- ): string | null {
920
- const value = data[key];
921
- if (typeof value !== 'string') return null;
922
- const trimmed = value.trim();
923
- return trimmed.length > 0 ? trimmed : null;
924
- }
925
-
926
- export function readTraceContextFromMessage(
927
- msg: Record<string, unknown>
928
- ): TraceContext {
929
- const directTraceId =
930
- readStringField(msg, 'traceId') ?? readStringField(msg, 'trace_id');
931
- const directSpanId =
932
- readStringField(msg, 'spanId') ?? readStringField(msg, 'span_id');
933
- if (directTraceId || directSpanId) {
934
- return { traceId: directTraceId, spanId: directSpanId };
935
- }
936
-
937
- const traceparent =
938
- readStringField(msg, 'traceparent') ?? readStringField(msg, 'traceParent');
939
- const parsedTraceparent = parseW3cTraceparent(traceparent);
940
- if (parsedTraceparent) return parsedTraceparent;
941
-
942
- const sentryTrace =
943
- readStringField(msg, 'sentry-trace') ??
944
- readStringField(msg, 'sentryTrace') ??
945
- readStringField(msg, 'sentry_trace');
946
- const parsedSentryTrace = parseSentryTraceHeader(sentryTrace);
947
- if (parsedSentryTrace) return parsedSentryTrace;
948
-
949
- return { traceId: null, spanId: null };
950
- }
951
-
952
- export function normalizeResponseStatus(
953
- statusCode: number,
954
- outcome: string
955
- ): string {
956
- if (statusCode >= 500) return 'server_error';
957
- if (statusCode >= 400) return 'client_error';
958
- if (statusCode >= 300) return 'redirect';
959
- if (statusCode >= 200) {
960
- if (outcome === 'error' || outcome === 'rejected') return 'failure';
961
- return 'success';
962
- }
963
- return 'unknown';
964
- }
965
-
966
- export function firstPushErrorCode(results: unknown): string | null {
967
- if (!Array.isArray(results)) return null;
968
- for (const result of results) {
969
- if (!result || typeof result !== 'object') continue;
970
- const status = Reflect.get(result, 'status');
971
- if (status !== 'error') continue;
972
- const code = Reflect.get(result, 'code');
973
- if (typeof code === 'string' && code.length > 0) {
974
- return code;
975
- }
976
- }
977
- return null;
978
- }
979
-
980
- export function summarizeScopeValues(
981
- scopes: Record<string, string | string[]>
982
- ): Record<string, string | string[]> | null {
983
- const summary: Record<string, string | string[]> = {};
984
- for (const [key, value] of Object.entries(scopes)) {
985
- if (typeof value === 'string') {
986
- summary[key] = value;
987
- continue;
988
- }
989
-
990
- if (Array.isArray(value)) {
991
- const normalized = value
992
- .filter((entry): entry is string => typeof entry === 'string')
993
- .slice(0, 20);
994
- summary[key] = normalized;
995
- }
996
- }
997
-
998
- return Object.keys(summary).length > 0 ? summary : null;
999
- }
1000
-
1001
- export function summarizePullResponse(response: PullResult['response']): {
1002
- subscriptions: Array<{
1003
- id: string;
1004
- status: 'active' | 'revoked';
1005
- bootstrap: boolean;
1006
- nextCursor: number;
1007
- commitCount: number;
1008
- changeCount: number;
1009
- snapshotCount: number;
1010
- snapshotRowCount: number;
1011
- }>;
1012
- } {
1013
- return {
1014
- subscriptions: response.subscriptions.map((subscription) => {
1015
- const changeCount = subscription.commits.reduce(
1016
- (totalChanges, commit) => totalChanges + commit.changes.length,
1017
- 0
1018
- );
1019
- const snapshotCount = subscription.snapshots?.length ?? 0;
1020
- const snapshotRowCount =
1021
- subscription.snapshots?.reduce(
1022
- (totalRows, snapshot) => totalRows + snapshot.rows.length,
1023
- 0
1024
- ) ?? 0;
1025
-
1026
- return {
1027
- id: subscription.id,
1028
- status: subscription.status,
1029
- bootstrap: subscription.bootstrap,
1030
- nextCursor: subscription.nextCursor,
1031
- commitCount: subscription.commits.length,
1032
- changeCount,
1033
- snapshotCount,
1034
- snapshotRowCount,
1035
- };
1036
- }),
1037
- };
1038
- }
1039
-
1040
- export function summarizePullResponseForRequestEvent(
1041
- response: PullResult['response']
1042
- ): {
1043
- subscriptionCount: number;
1044
- activeSubscriptionCount: number;
1045
- revokedSubscriptionCount: number;
1046
- bootstrapSubscriptionCount: number;
1047
- commitCount: number;
1048
- changeCount: number;
1049
- snapshotPageCount: number;
1050
- snapshotInlineRowCount: number;
1051
- snapshotChunkCount: number;
1052
- snapshotChunkBytes: number;
1053
- snapshotArtifactCount: number;
1054
- snapshotArtifactBytes: number;
1055
- } {
1056
- let activeSubscriptionCount = 0;
1057
- let revokedSubscriptionCount = 0;
1058
- let bootstrapSubscriptionCount = 0;
1059
- let commitCount = 0;
1060
- let changeCount = 0;
1061
- let snapshotPageCount = 0;
1062
- let snapshotInlineRowCount = 0;
1063
- let snapshotChunkCount = 0;
1064
- let snapshotChunkBytes = 0;
1065
- let snapshotArtifactCount = 0;
1066
- let snapshotArtifactBytes = 0;
1067
-
1068
- for (const subscription of response.subscriptions) {
1069
- if (subscription.status === 'revoked') {
1070
- revokedSubscriptionCount += 1;
1071
- } else {
1072
- activeSubscriptionCount += 1;
1073
- }
1074
- if (subscription.bootstrap) {
1075
- bootstrapSubscriptionCount += 1;
1076
- }
1077
- commitCount += subscription.commits.length;
1078
- changeCount += subscription.commits.reduce(
1079
- (totalChanges, commit) => totalChanges + commit.changes.length,
1080
- 0
1081
- );
1082
- for (const snapshot of subscription.snapshots ?? []) {
1083
- snapshotPageCount += 1;
1084
- snapshotInlineRowCount += snapshot.rows.length;
1085
- for (const chunk of snapshot.chunks ?? []) {
1086
- snapshotChunkCount += 1;
1087
- snapshotChunkBytes += chunk.byteLength;
1088
- }
1089
- for (const artifact of snapshot.artifacts ?? []) {
1090
- snapshotArtifactCount += 1;
1091
- snapshotArtifactBytes += artifact.byteLength;
1092
- }
1093
- }
1094
- }
1095
-
1096
- return {
1097
- subscriptionCount: response.subscriptions.length,
1098
- activeSubscriptionCount,
1099
- revokedSubscriptionCount,
1100
- bootstrapSubscriptionCount,
1101
- commitCount,
1102
- changeCount,
1103
- snapshotPageCount,
1104
- snapshotInlineRowCount,
1105
- snapshotChunkCount,
1106
- snapshotChunkBytes,
1107
- snapshotArtifactCount,
1108
- snapshotArtifactBytes,
1109
- };
1110
- }
1111
-
1112
- export function countPullRows(response: PullResult['response']): number {
1113
- return response.subscriptions.reduce((totalRows, subscription) => {
1114
- const commitRows = subscription.commits.reduce(
1115
- (totalChanges, commit) => totalChanges + commit.changes.length,
1116
- 0
1117
- );
1118
- const snapshotRows =
1119
- subscription.snapshots?.reduce(
1120
- (totalSnapshotRows, snapshot) =>
1121
- totalSnapshotRows + snapshot.rows.length,
1122
- 0
1123
- ) ?? 0;
1124
- return totalRows + commitRows + snapshotRows;
1125
- }, 0);
1126
- }
1127
-
1128
- export function readSnapshotScopeValues(
1129
- c: Context,
1130
- queryScopes: string | undefined
1131
- ): Record<string, string | string[]> | null {
1132
- const rawValue = queryScopes ?? c.req.header(SNAPSHOT_SCOPES_HEADER);
1133
- if (!rawValue) return null;
1134
- const parsed = parseJsonValue(rawValue);
1135
- const validated = ScopeValuesSchema.safeParse(parsed);
1136
- if (!validated.success) return null;
1137
- return validated.data;
1138
- }
1139
-
1140
- export function parseScopesSummary(
1141
- value: unknown
1142
- ): Record<string, string | string[]> | null {
1143
- const parsed = parseJsonValue(value);
1144
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1145
- return null;
1146
- }
1147
-
1148
- const summary: Record<string, string | string[]> = {};
1149
- for (const [key, entry] of Object.entries(parsed)) {
1150
- if (typeof entry === 'string') {
1151
- summary[key] = entry;
1152
- continue;
1153
- }
1154
- if (!Array.isArray(entry)) continue;
1155
- summary[key] = entry.filter(
1156
- (value): value is string => typeof value === 'string'
1157
- );
1158
- }
1159
-
1160
- return Object.keys(summary).length > 0 ? summary : null;
1161
- }
1162
-
1163
- export function normalizeRequestEventType(
1164
- value: unknown
1165
- ): 'sync' | 'push' | 'pull' {
1166
- if (value === 'sync' || value === 'push' || value === 'pull') {
1167
- return value;
1168
- }
1169
- return 'pull';
1170
- }
1171
-
1172
- export function isMissingRequestEventsTableError(error: unknown): boolean {
1173
- const visited = new Set<Error>();
1174
- let current: unknown = error;
1175
-
1176
- while (current instanceof Error && !visited.has(current)) {
1177
- visited.add(current);
1178
- const message = current.message.toLowerCase();
1179
- if (
1180
- message.includes('sync_request_events') &&
1181
- (message.includes('no such table') ||
1182
- message.includes('does not exist') ||
1183
- message.includes('unknown table'))
1184
- ) {
1185
- return true;
1186
- }
1187
- current = current.cause;
1188
- }
1189
-
1190
- return false;
1191
- }
1192
-
1193
- const SENSITIVE_PAYLOAD_KEYS = new Set([
1194
- 'accesstoken',
1195
- 'apikey',
1196
- 'authorization',
1197
- 'clientsecret',
1198
- 'cookie',
1199
- 'idtoken',
1200
- 'passcode',
1201
- 'passphrase',
1202
- 'password',
1203
- 'privatekey',
1204
- 'refreshtoken',
1205
- 'secret',
1206
- 'secretkey',
1207
- 'sessiontoken',
1208
- 'setcookie',
1209
- 'token',
1210
- 'xapikey',
1211
- ]);
1212
- const REDACTED_PAYLOAD_VALUE = '[redacted]';
1213
-
1214
- function normalizePayloadKey(key: string): string {
1215
- return key.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
1216
- }
1217
-
1218
- function payloadSnapshotReplacer(key: string, value: unknown): unknown {
1219
- if (key !== '' && SENSITIVE_PAYLOAD_KEYS.has(normalizePayloadKey(key))) {
1220
- return REDACTED_PAYLOAD_VALUE;
1221
- }
1222
- return value;
1223
- }
1224
-
1225
- export function encodePayloadSnapshot(
1226
- value: unknown,
1227
- maxBytes: number
1228
- ): string {
1229
- try {
1230
- const serialized = JSON.stringify(value, payloadSnapshotReplacer);
1231
- if (serialized.length <= maxBytes) {
1232
- return serialized;
1233
- }
1234
- return JSON.stringify({
1235
- truncated: true,
1236
- originalSizeBytes: serialized.length,
1237
- preview: serialized.slice(0, maxBytes),
1238
- });
1239
- } catch {
1240
- return JSON.stringify({
1241
- truncated: false,
1242
- serializationError: 'Could not serialize payload snapshot',
1243
- });
1244
- }
1245
- }
1246
-
1247
- export function emitConsoleLiveEvent(
1248
- emitter:
1249
- | {
1250
- emit(event: {
1251
- type: 'sync' | 'push' | 'pull' | 'commit' | 'client_update';
1252
- timestamp: string;
1253
- data: Record<string, unknown>;
1254
- }): void;
1255
- }
1256
- | undefined,
1257
- type: 'sync' | 'push' | 'pull' | 'commit' | 'client_update',
1258
- data: Record<string, unknown> | (() => Record<string, unknown>)
1259
- ): void {
1260
- if (!emitter) return;
1261
- emitter.emit({
1262
- type,
1263
- timestamp: new Date().toISOString(),
1264
- data: typeof data === 'function' ? data() : data,
1265
- });
1266
- }
1267
-
1268
- export function isAuthLeaseRefreshRetriable(code: string): boolean {
1269
- return (
1270
- code === SYNC_AUTH_LEASE_CODE_MISSING ||
1271
- code === SYNC_AUTH_LEASE_CODE_INVALID ||
1272
- code === SYNC_AUTH_LEASE_CODE_EXPIRED
1273
- );
1274
- }
1275
-
1276
- export type RequestPayloadSnapshot = {
1277
- request: unknown;
1278
- response: unknown;
1279
- };
1280
-
1281
- export function clampInt(value: number, min: number, max: number): number {
1282
- return Math.max(min, Math.min(max, value));
1283
- }
1284
-
1285
- export function measureWebSocketMessageBytes(data: unknown): number {
1286
- if (typeof data === 'string') {
1287
- return new TextEncoder().encode(data).byteLength;
1288
- }
1289
- if (data instanceof ArrayBuffer) {
1290
- return data.byteLength;
1291
- }
1292
- if (ArrayBuffer.isView(data)) {
1293
- return data.byteLength;
1294
- }
1295
- if (typeof Blob !== 'undefined' && data instanceof Blob) {
1296
- return data.size;
1297
- }
1298
- return new TextEncoder().encode(String(data)).byteLength;
1299
- }
1300
-
1301
- export function readTransportPath(
1302
- c: Context,
1303
- queryValue?: string | null
1304
- ): 'direct' | 'relay' {
1305
- if (queryValue === 'relay' || queryValue === 'direct') {
1306
- return queryValue;
1307
- }
1308
-
1309
- const headerValue = c.req.header('x-syncular-transport-path');
1310
- if (headerValue === 'relay' || headerValue === 'direct') {
1311
- return headerValue;
1312
- }
1313
-
1314
- return 'direct';
1315
- }
1316
-
1317
- export function scopeValuesToScopeKeys(scopes: unknown): string[] {
1318
- if (!scopes || typeof scopes !== 'object') return [];
1319
- const scopeKeys = new Set<string>();
1320
-
1321
- for (const [key, value] of Object.entries(scopes)) {
1322
- if (!value) continue;
1323
- const prefix = key.replace(/_id$/, '');
1324
-
1325
- if (Array.isArray(value)) {
1326
- for (const v of value) {
1327
- if (typeof v !== 'string') continue;
1328
- if (!v) continue;
1329
- scopeKeys.add(`${prefix}:${v}`);
1330
- }
1331
- continue;
1332
- }
1333
-
1334
- if (typeof value === 'string') {
1335
- if (!value) continue;
1336
- scopeKeys.add(`${prefix}:${value}`);
1337
- continue;
1338
- }
1339
-
1340
- // Best-effort: stringify scalars.
1341
- if (typeof value === 'number' || typeof value === 'bigint') {
1342
- scopeKeys.add(`${prefix}:${String(value)}`);
1343
- }
1344
- }
1345
-
1346
- return Array.from(scopeKeys);
1347
- }
1348
-
1349
- export function selectRequiredAuditScopes(
1350
- scopePatterns: readonly string[],
1351
- allowedScopes: ScopeValues
1352
- ): ScopeValues | null {
1353
- const requiredScopeKeys = Array.from(collectScopeVars(scopePatterns));
1354
- if (requiredScopeKeys.length === 0) {
1355
- return {};
1356
- }
1357
-
1358
- const auditScopes: ScopeValues = {};
1359
- for (const key of requiredScopeKeys) {
1360
- const value = allowedScopes[key];
1361
- if (value === undefined) {
1362
- return null;
1363
- }
1364
- if (Array.isArray(value) && value.length === 0) {
1365
- return null;
1366
- }
1367
- auditScopes[key] = value;
1368
- }
1369
- return auditScopes;
1370
- }
1371
-
1372
- export function parseStoredAuditScopes(value: unknown): StoredScopes {
1373
- const parsed = parseJsonValue(value);
1374
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1375
- return {};
1376
- }
1377
-
1378
- const scopes: StoredScopes = {};
1379
- for (const [key, scopeValue] of Object.entries(parsed)) {
1380
- if (typeof scopeValue === 'string') {
1381
- scopes[key] = scopeValue;
1382
- }
1383
- }
1384
- return scopes;
1385
- }
1386
-
1387
- function partitionScopeKey(partitionId: string, scopeKey: string): string {
1388
- return `${partitionId}::${scopeKey}`;
1389
- }
1390
-
1391
- export function applyPartitionToScopeKeys(
1392
- partitionId: string,
1393
- scopeKeys: readonly string[]
1394
- ): string[] {
1395
- const prefixed = new Set<string>();
1396
- for (const scopeKey of scopeKeys) {
1397
- if (!scopeKey) continue;
1398
- if (scopeKey.startsWith(`${partitionId}::`)) {
1399
- prefixed.add(scopeKey);
1400
- continue;
1401
- }
1402
- prefixed.add(partitionScopeKey(partitionId, scopeKey));
1403
- }
1404
- return Array.from(prefixed);
1405
- }
1406
-
1407
- export function uniqueScopeKeys(scopeKeys: readonly string[]): string[] {
1408
- return Array.from(
1409
- new Set(scopeKeys.filter((scopeKey) => scopeKey.length > 0))
1410
- );
1411
- }
1412
-
1413
- function parseRealtimeSubscriptionScopes(
1414
- value: unknown
1415
- ): Record<string, string | string[]> {
1416
- const parsed = parseJsonValue(value);
1417
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1418
- return {};
1419
- }
1420
-
1421
- const scopes: Record<string, string | string[]> = {};
1422
- for (const [key, scopeValue] of Object.entries(
1423
- parsed as Record<string, unknown>
1424
- )) {
1425
- if (typeof scopeValue === 'string' && scopeValue.length > 0) {
1426
- scopes[key] = scopeValue;
1427
- continue;
1428
- }
1429
- if (Array.isArray(scopeValue)) {
1430
- const values = scopeValue.filter(
1431
- (item): item is string => typeof item === 'string' && item.length > 0
1432
- );
1433
- if (values.length > 0) {
1434
- scopes[key] = values;
1435
- }
1436
- }
1437
- }
1438
- return scopes;
1439
- }
1440
-
1441
- export function parsePersistedRealtimeSubscriptions(
1442
- value: unknown,
1443
- partitionId: string
1444
- ): WebSocketRealtimeSubscription[] {
1445
- const parsed = parseJsonValue(value);
1446
- if (!Array.isArray(parsed)) return [];
1447
-
1448
- const subscriptions: WebSocketRealtimeSubscription[] = [];
1449
- for (const entry of parsed) {
1450
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
1451
- const record = entry as Record<string, unknown>;
1452
- const id = typeof record.id === 'string' ? record.id : '';
1453
- const table = typeof record.table === 'string' ? record.table : '';
1454
- if (!id || !table) continue;
1455
-
1456
- const scopes = parseRealtimeSubscriptionScopes(record.scopes);
1457
- const scopeKeys = applyPartitionToScopeKeys(
1458
- partitionId,
1459
- scopeValuesToScopeKeys(scopes)
1460
- );
1461
- if (scopeKeys.length === 0) continue;
1462
-
1463
- const cursor = coerceNumber(record.cursor);
1464
- subscriptions.push({
1465
- id,
1466
- table,
1467
- scopes,
1468
- scopeKeys,
1469
- cursor: cursor === null ? -1 : Math.max(-1, cursor),
1470
- verifiedRoot:
1471
- typeof record.verifiedRoot === 'string' &&
1472
- record.verifiedRoot.length > 0
1473
- ? record.verifiedRoot
1474
- : null,
1475
- });
1476
- }
1477
- return subscriptions;
1478
- }
1479
-
1480
- export function normalizeScopeKeyForPartition(
1481
- partitionId: string,
1482
- scopeKey: string
1483
- ): string {
1484
- if (scopeKey.startsWith(`${partitionId}::`)) return scopeKey;
1485
- if (scopeKey.includes('::')) return '';
1486
- return partitionScopeKey(partitionId, scopeKey);
1487
- }
1488
-
1489
- export async function readCommitScopeKeys<DB extends SyncCoreDb>(
1490
- db: Kysely<DB>,
1491
- commitSeq: number,
1492
- partitionId: string
1493
- ): Promise<string[]> {
1494
- const indexedRows = await sql<{ scope_key: string }>`
1495
- select distinct scope_key
1496
- from ${sql.table('sync_scope_commits')}
1497
- where commit_seq = ${commitSeq}
1498
- and partition_id = ${partitionId}
1499
- `.execute(db);
1500
- const indexedScopeKeys = indexedRows.rows
1501
- .map((row) => row.scope_key)
1502
- .filter(
1503
- (scopeKey): scopeKey is string =>
1504
- typeof scopeKey === 'string' && scopeKey.length > 0
1505
- );
1506
- return applyPartitionToScopeKeys(partitionId, indexedScopeKeys);
1507
- }
1508
-
1509
- export async function readClientState<DB extends SyncCoreDb>(
1510
- db: Kysely<DB>,
1511
- partitionId: string,
1512
- clientId: string
1513
- ): Promise<{
1514
- ownerActorId: string | null;
1515
- effectiveScopes: unknown;
1516
- realtimeSubscriptions: unknown;
1517
- cursor: number | null;
1518
- latestCommitSeq: number;
1519
- hasConflict: boolean;
1520
- }> {
1521
- const result = await sql<{
1522
- cursor_actor_id: string | null;
1523
- effective_scopes: unknown;
1524
- realtime_subscriptions: unknown;
1525
- cursor: number | string | null;
1526
- latest_client_actor_id: string | null;
1527
- latest_commit_seq: number | string | null;
1528
- }>`
1529
- SELECT
1530
- cc.actor_id AS cursor_actor_id,
1531
- cc.effective_scopes,
1532
- cc.realtime_subscriptions,
1533
- cc.cursor,
1534
- (
1535
- SELECT actor_id
1536
- FROM sync_commits
1537
- WHERE partition_id = ${partitionId} AND client_id = ${clientId}
1538
- ORDER BY commit_seq DESC
1539
- LIMIT 1
1540
- ) AS latest_client_actor_id,
1541
- (
1542
- SELECT COALESCE(MAX(commit_seq), 0)
1543
- FROM sync_commits
1544
- WHERE partition_id = ${partitionId}
1545
- ) AS latest_commit_seq
1546
- FROM (SELECT 1) AS realtime_state
1547
- LEFT JOIN sync_client_cursors AS cc
1548
- ON cc.partition_id = ${partitionId} AND cc.client_id = ${clientId}
1549
- LIMIT 1
1550
- `.execute(db);
1551
- const cursorRow = result.rows[0];
1552
-
1553
- // Cursor state reflects the current authenticated owner for a clientId.
1554
- // Commit history is only used to seed ownership before the first pull.
1555
- const ownerActorId =
1556
- cursorRow?.cursor_actor_id ?? cursorRow?.latest_client_actor_id ?? null;
1557
- const cursor =
1558
- cursorRow?.cursor === null || cursorRow?.cursor === undefined
1559
- ? null
1560
- : Number(cursorRow.cursor);
1561
- const latestCommitSeq =
1562
- cursorRow?.latest_commit_seq === null ||
1563
- cursorRow?.latest_commit_seq === undefined
1564
- ? 0
1565
- : Number(cursorRow.latest_commit_seq);
1566
-
1567
- return {
1568
- ownerActorId,
1569
- effectiveScopes: cursorRow?.effective_scopes ?? null,
1570
- realtimeSubscriptions: cursorRow?.realtime_subscriptions ?? null,
1571
- cursor: Number.isFinite(cursor) ? cursor : null,
1572
- latestCommitSeq: Number.isFinite(latestCommitSeq) ? latestCommitSeq : 0,
1573
- hasConflict: false,
1574
- };
1575
- }
1576
-
1577
- export async function recordRealtimeAck<DB extends SyncCoreDb>(args: {
1578
- db: Kysely<DB>;
1579
- dialect: ServerSyncDialect;
1580
- partitionId: string;
1581
- actorId: string;
1582
- clientId: string;
1583
- cursor: number;
1584
- realtimeSubscriptions?: unknown;
1585
- }): Promise<void> {
1586
- const now = new Date().toISOString();
1587
- const realtimeSubscriptionsJson =
1588
- args.realtimeSubscriptions === undefined
1589
- ? null
1590
- : JSON.stringify(args.realtimeSubscriptions);
1591
- const realtimeSubscriptionsSet =
1592
- args.dialect.family === 'postgres'
1593
- ? sql`realtime_subscriptions = ${realtimeSubscriptionsJson}::jsonb,`
1594
- : sql`realtime_subscriptions = ${realtimeSubscriptionsJson},`;
1595
- await sql`
1596
- UPDATE sync_client_cursors
1597
- SET
1598
- cursor = CASE
1599
- WHEN cursor < ${args.cursor}
1600
- AND cursor < (
1601
- SELECT COALESCE(MAX(commit_seq), 0)
1602
- FROM sync_commits
1603
- WHERE partition_id = ${args.partitionId}
1604
- )
1605
- THEN CASE
1606
- WHEN ${args.cursor} < (
1607
- SELECT COALESCE(MAX(commit_seq), 0)
1608
- FROM sync_commits
1609
- WHERE partition_id = ${args.partitionId}
1610
- )
1611
- THEN ${args.cursor}
1612
- ELSE (
1613
- SELECT COALESCE(MAX(commit_seq), 0)
1614
- FROM sync_commits
1615
- WHERE partition_id = ${args.partitionId}
1616
- )
1617
- END
1618
- ELSE cursor
1619
- END,
1620
- ${realtimeSubscriptionsSet}
1621
- updated_at = ${now}
1622
- WHERE partition_id = ${args.partitionId}
1623
- AND client_id = ${args.clientId}
1624
- AND actor_id = ${args.actorId}
1625
- `.execute(args.db);
1626
- }