@powersync/service-core 0.0.2

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 (412) hide show
  1. package/.probes/.gitkeep +0 -0
  2. package/CHANGELOG.md +13 -0
  3. package/LICENSE +67 -0
  4. package/README.md +3 -0
  5. package/dist/api/api-index.d.ts +2 -0
  6. package/dist/api/api-index.js +3 -0
  7. package/dist/api/api-index.js.map +1 -0
  8. package/dist/api/diagnostics.d.ts +21 -0
  9. package/dist/api/diagnostics.js +183 -0
  10. package/dist/api/diagnostics.js.map +1 -0
  11. package/dist/api/schema.d.ts +5 -0
  12. package/dist/api/schema.js +88 -0
  13. package/dist/api/schema.js.map +1 -0
  14. package/dist/auth/CachedKeyCollector.d.ts +46 -0
  15. package/dist/auth/CachedKeyCollector.js +116 -0
  16. package/dist/auth/CachedKeyCollector.js.map +1 -0
  17. package/dist/auth/CompoundKeyCollector.d.ts +8 -0
  18. package/dist/auth/CompoundKeyCollector.js +23 -0
  19. package/dist/auth/CompoundKeyCollector.js.map +1 -0
  20. package/dist/auth/JwtPayload.d.ts +10 -0
  21. package/dist/auth/JwtPayload.js +2 -0
  22. package/dist/auth/JwtPayload.js.map +1 -0
  23. package/dist/auth/KeyCollector.d.ts +24 -0
  24. package/dist/auth/KeyCollector.js +2 -0
  25. package/dist/auth/KeyCollector.js.map +1 -0
  26. package/dist/auth/KeySpec.d.ts +26 -0
  27. package/dist/auth/KeySpec.js +49 -0
  28. package/dist/auth/KeySpec.js.map +1 -0
  29. package/dist/auth/KeyStore.d.ts +39 -0
  30. package/dist/auth/KeyStore.js +131 -0
  31. package/dist/auth/KeyStore.js.map +1 -0
  32. package/dist/auth/LeakyBucket.d.ts +39 -0
  33. package/dist/auth/LeakyBucket.js +57 -0
  34. package/dist/auth/LeakyBucket.js.map +1 -0
  35. package/dist/auth/RemoteJWKSCollector.d.ts +24 -0
  36. package/dist/auth/RemoteJWKSCollector.js +106 -0
  37. package/dist/auth/RemoteJWKSCollector.js.map +1 -0
  38. package/dist/auth/StaticKeyCollector.d.ts +14 -0
  39. package/dist/auth/StaticKeyCollector.js +19 -0
  40. package/dist/auth/StaticKeyCollector.js.map +1 -0
  41. package/dist/auth/SupabaseKeyCollector.d.ts +22 -0
  42. package/dist/auth/SupabaseKeyCollector.js +61 -0
  43. package/dist/auth/SupabaseKeyCollector.js.map +1 -0
  44. package/dist/auth/auth-index.d.ts +10 -0
  45. package/dist/auth/auth-index.js +11 -0
  46. package/dist/auth/auth-index.js.map +1 -0
  47. package/dist/db/db-index.d.ts +1 -0
  48. package/dist/db/db-index.js +2 -0
  49. package/dist/db/db-index.js.map +1 -0
  50. package/dist/db/mongo.d.ts +29 -0
  51. package/dist/db/mongo.js +65 -0
  52. package/dist/db/mongo.js.map +1 -0
  53. package/dist/entry/cli-entry.d.ts +15 -0
  54. package/dist/entry/cli-entry.js +36 -0
  55. package/dist/entry/cli-entry.js.map +1 -0
  56. package/dist/entry/commands/config-command.d.ts +10 -0
  57. package/dist/entry/commands/config-command.js +21 -0
  58. package/dist/entry/commands/config-command.js.map +1 -0
  59. package/dist/entry/commands/migrate-action.d.ts +2 -0
  60. package/dist/entry/commands/migrate-action.js +18 -0
  61. package/dist/entry/commands/migrate-action.js.map +1 -0
  62. package/dist/entry/commands/start-action.d.ts +3 -0
  63. package/dist/entry/commands/start-action.js +15 -0
  64. package/dist/entry/commands/start-action.js.map +1 -0
  65. package/dist/entry/commands/teardown-action.d.ts +2 -0
  66. package/dist/entry/commands/teardown-action.js +17 -0
  67. package/dist/entry/commands/teardown-action.js.map +1 -0
  68. package/dist/entry/entry-index.d.ts +5 -0
  69. package/dist/entry/entry-index.js +6 -0
  70. package/dist/entry/entry-index.js.map +1 -0
  71. package/dist/index.d.ts +24 -0
  72. package/dist/index.js +26 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/metrics/metrics.d.ts +16 -0
  75. package/dist/metrics/metrics.js +139 -0
  76. package/dist/metrics/metrics.js.map +1 -0
  77. package/dist/migrations/db/migrations/1684951997326-init.d.ts +3 -0
  78. package/dist/migrations/db/migrations/1684951997326-init.js +31 -0
  79. package/dist/migrations/db/migrations/1684951997326-init.js.map +1 -0
  80. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.d.ts +2 -0
  81. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js +5 -0
  82. package/dist/migrations/db/migrations/1688556755264-initial-sync-rules.js.map +1 -0
  83. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.d.ts +3 -0
  84. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js +54 -0
  85. package/dist/migrations/db/migrations/1702295701188-sync-rule-state.js.map +1 -0
  86. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.d.ts +3 -0
  87. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js +27 -0
  88. package/dist/migrations/db/migrations/1711543888062-write-checkpoint-index.js.map +1 -0
  89. package/dist/migrations/db/store.d.ts +3 -0
  90. package/dist/migrations/db/store.js +10 -0
  91. package/dist/migrations/db/store.js.map +1 -0
  92. package/dist/migrations/migrations.d.ts +10 -0
  93. package/dist/migrations/migrations.js +94 -0
  94. package/dist/migrations/migrations.js.map +1 -0
  95. package/dist/replication/ErrorRateLimiter.d.ts +17 -0
  96. package/dist/replication/ErrorRateLimiter.js +42 -0
  97. package/dist/replication/ErrorRateLimiter.js.map +1 -0
  98. package/dist/replication/PgRelation.d.ts +16 -0
  99. package/dist/replication/PgRelation.js +26 -0
  100. package/dist/replication/PgRelation.js.map +1 -0
  101. package/dist/replication/WalConnection.d.ts +34 -0
  102. package/dist/replication/WalConnection.js +190 -0
  103. package/dist/replication/WalConnection.js.map +1 -0
  104. package/dist/replication/WalStream.d.ts +58 -0
  105. package/dist/replication/WalStream.js +517 -0
  106. package/dist/replication/WalStream.js.map +1 -0
  107. package/dist/replication/WalStreamManager.d.ts +30 -0
  108. package/dist/replication/WalStreamManager.js +199 -0
  109. package/dist/replication/WalStreamManager.js.map +1 -0
  110. package/dist/replication/WalStreamRunner.d.ts +38 -0
  111. package/dist/replication/WalStreamRunner.js +155 -0
  112. package/dist/replication/WalStreamRunner.js.map +1 -0
  113. package/dist/replication/replication-index.d.ts +7 -0
  114. package/dist/replication/replication-index.js +8 -0
  115. package/dist/replication/replication-index.js.map +1 -0
  116. package/dist/replication/util.d.ts +9 -0
  117. package/dist/replication/util.js +62 -0
  118. package/dist/replication/util.js.map +1 -0
  119. package/dist/routes/admin.d.ts +7 -0
  120. package/dist/routes/admin.js +192 -0
  121. package/dist/routes/admin.js.map +1 -0
  122. package/dist/routes/auth.d.ts +58 -0
  123. package/dist/routes/auth.js +182 -0
  124. package/dist/routes/auth.js.map +1 -0
  125. package/dist/routes/checkpointing.d.ts +3 -0
  126. package/dist/routes/checkpointing.js +30 -0
  127. package/dist/routes/checkpointing.js.map +1 -0
  128. package/dist/routes/dev.d.ts +6 -0
  129. package/dist/routes/dev.js +163 -0
  130. package/dist/routes/dev.js.map +1 -0
  131. package/dist/routes/route-generators.d.ts +15 -0
  132. package/dist/routes/route-generators.js +32 -0
  133. package/dist/routes/route-generators.js.map +1 -0
  134. package/dist/routes/router-socket.d.ts +10 -0
  135. package/dist/routes/router-socket.js +5 -0
  136. package/dist/routes/router-socket.js.map +1 -0
  137. package/dist/routes/router.d.ts +13 -0
  138. package/dist/routes/router.js +2 -0
  139. package/dist/routes/router.js.map +1 -0
  140. package/dist/routes/routes-index.d.ts +4 -0
  141. package/dist/routes/routes-index.js +5 -0
  142. package/dist/routes/routes-index.js.map +1 -0
  143. package/dist/routes/socket-route.d.ts +2 -0
  144. package/dist/routes/socket-route.js +119 -0
  145. package/dist/routes/socket-route.js.map +1 -0
  146. package/dist/routes/sync-rules.d.ts +6 -0
  147. package/dist/routes/sync-rules.js +182 -0
  148. package/dist/routes/sync-rules.js.map +1 -0
  149. package/dist/routes/sync-stream.d.ts +5 -0
  150. package/dist/routes/sync-stream.js +74 -0
  151. package/dist/routes/sync-stream.js.map +1 -0
  152. package/dist/runner/teardown.d.ts +2 -0
  153. package/dist/runner/teardown.js +79 -0
  154. package/dist/runner/teardown.js.map +1 -0
  155. package/dist/storage/BucketStorage.d.ts +298 -0
  156. package/dist/storage/BucketStorage.js +25 -0
  157. package/dist/storage/BucketStorage.js.map +1 -0
  158. package/dist/storage/MongoBucketStorage.d.ts +51 -0
  159. package/dist/storage/MongoBucketStorage.js +388 -0
  160. package/dist/storage/MongoBucketStorage.js.map +1 -0
  161. package/dist/storage/SourceTable.d.ts +39 -0
  162. package/dist/storage/SourceTable.js +50 -0
  163. package/dist/storage/SourceTable.js.map +1 -0
  164. package/dist/storage/mongo/MongoBucketBatch.d.ts +48 -0
  165. package/dist/storage/mongo/MongoBucketBatch.js +584 -0
  166. package/dist/storage/mongo/MongoBucketBatch.js.map +1 -0
  167. package/dist/storage/mongo/MongoIdSequence.d.ts +12 -0
  168. package/dist/storage/mongo/MongoIdSequence.js +21 -0
  169. package/dist/storage/mongo/MongoIdSequence.js.map +1 -0
  170. package/dist/storage/mongo/MongoPersistedSyncRules.d.ts +9 -0
  171. package/dist/storage/mongo/MongoPersistedSyncRules.js +9 -0
  172. package/dist/storage/mongo/MongoPersistedSyncRules.js.map +1 -0
  173. package/dist/storage/mongo/MongoPersistedSyncRulesContent.d.ts +20 -0
  174. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js +26 -0
  175. package/dist/storage/mongo/MongoPersistedSyncRulesContent.js.map +1 -0
  176. package/dist/storage/mongo/MongoSyncBucketStorage.d.ts +27 -0
  177. package/dist/storage/mongo/MongoSyncBucketStorage.js +379 -0
  178. package/dist/storage/mongo/MongoSyncBucketStorage.js.map +1 -0
  179. package/dist/storage/mongo/MongoSyncRulesLock.d.ts +16 -0
  180. package/dist/storage/mongo/MongoSyncRulesLock.js +65 -0
  181. package/dist/storage/mongo/MongoSyncRulesLock.js.map +1 -0
  182. package/dist/storage/mongo/OperationBatch.d.ts +26 -0
  183. package/dist/storage/mongo/OperationBatch.js +101 -0
  184. package/dist/storage/mongo/OperationBatch.js.map +1 -0
  185. package/dist/storage/mongo/PersistedBatch.d.ts +42 -0
  186. package/dist/storage/mongo/PersistedBatch.js +200 -0
  187. package/dist/storage/mongo/PersistedBatch.js.map +1 -0
  188. package/dist/storage/mongo/db.d.ts +23 -0
  189. package/dist/storage/mongo/db.js +34 -0
  190. package/dist/storage/mongo/db.js.map +1 -0
  191. package/dist/storage/mongo/models.d.ts +137 -0
  192. package/dist/storage/mongo/models.js +27 -0
  193. package/dist/storage/mongo/models.js.map +1 -0
  194. package/dist/storage/mongo/util.d.ts +26 -0
  195. package/dist/storage/mongo/util.js +81 -0
  196. package/dist/storage/mongo/util.js.map +1 -0
  197. package/dist/storage/storage-index.d.ts +14 -0
  198. package/dist/storage/storage-index.js +15 -0
  199. package/dist/storage/storage-index.js.map +1 -0
  200. package/dist/sync/BroadcastIterable.d.ts +38 -0
  201. package/dist/sync/BroadcastIterable.js +153 -0
  202. package/dist/sync/BroadcastIterable.js.map +1 -0
  203. package/dist/sync/LastValueSink.d.ts +25 -0
  204. package/dist/sync/LastValueSink.js +84 -0
  205. package/dist/sync/LastValueSink.js.map +1 -0
  206. package/dist/sync/merge.d.ts +39 -0
  207. package/dist/sync/merge.js +175 -0
  208. package/dist/sync/merge.js.map +1 -0
  209. package/dist/sync/safeRace.d.ts +1 -0
  210. package/dist/sync/safeRace.js +91 -0
  211. package/dist/sync/safeRace.js.map +1 -0
  212. package/dist/sync/sync-index.d.ts +6 -0
  213. package/dist/sync/sync-index.js +7 -0
  214. package/dist/sync/sync-index.js.map +1 -0
  215. package/dist/sync/sync.d.ts +18 -0
  216. package/dist/sync/sync.js +248 -0
  217. package/dist/sync/sync.js.map +1 -0
  218. package/dist/sync/util.d.ts +26 -0
  219. package/dist/sync/util.js +73 -0
  220. package/dist/sync/util.js.map +1 -0
  221. package/dist/system/CorePowerSyncSystem.d.ts +18 -0
  222. package/dist/system/CorePowerSyncSystem.js +28 -0
  223. package/dist/system/CorePowerSyncSystem.js.map +1 -0
  224. package/dist/util/Mutex.d.ts +47 -0
  225. package/dist/util/Mutex.js +132 -0
  226. package/dist/util/Mutex.js.map +1 -0
  227. package/dist/util/PgManager.d.ts +24 -0
  228. package/dist/util/PgManager.js +55 -0
  229. package/dist/util/PgManager.js.map +1 -0
  230. package/dist/util/alerting.d.ts +4 -0
  231. package/dist/util/alerting.js +14 -0
  232. package/dist/util/alerting.js.map +1 -0
  233. package/dist/util/config/collectors/config-collector.d.ts +29 -0
  234. package/dist/util/config/collectors/config-collector.js +116 -0
  235. package/dist/util/config/collectors/config-collector.js.map +1 -0
  236. package/dist/util/config/collectors/impl/base64-config-collector.d.ts +6 -0
  237. package/dist/util/config/collectors/impl/base64-config-collector.js +15 -0
  238. package/dist/util/config/collectors/impl/base64-config-collector.js.map +1 -0
  239. package/dist/util/config/collectors/impl/fallback-config-collector.d.ts +11 -0
  240. package/dist/util/config/collectors/impl/fallback-config-collector.js +19 -0
  241. package/dist/util/config/collectors/impl/fallback-config-collector.js.map +1 -0
  242. package/dist/util/config/collectors/impl/filesystem-config-collector.d.ts +6 -0
  243. package/dist/util/config/collectors/impl/filesystem-config-collector.js +35 -0
  244. package/dist/util/config/collectors/impl/filesystem-config-collector.js.map +1 -0
  245. package/dist/util/config/compound-config-collector.d.ts +32 -0
  246. package/dist/util/config/compound-config-collector.js +126 -0
  247. package/dist/util/config/compound-config-collector.js.map +1 -0
  248. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.d.ts +7 -0
  249. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js +17 -0
  250. package/dist/util/config/sync-rules/impl/base64-sync-rules-collector.js.map +1 -0
  251. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.d.ts +7 -0
  252. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js +21 -0
  253. package/dist/util/config/sync-rules/impl/filesystem-sync-rules-collector.js.map +1 -0
  254. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.d.ts +7 -0
  255. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js +17 -0
  256. package/dist/util/config/sync-rules/impl/inline-sync-rules-collector.js.map +1 -0
  257. package/dist/util/config/sync-rules/sync-collector.d.ts +6 -0
  258. package/dist/util/config/sync-rules/sync-collector.js +3 -0
  259. package/dist/util/config/sync-rules/sync-collector.js.map +1 -0
  260. package/dist/util/config/types.d.ts +53 -0
  261. package/dist/util/config/types.js +7 -0
  262. package/dist/util/config/types.js.map +1 -0
  263. package/dist/util/config.d.ts +7 -0
  264. package/dist/util/config.js +35 -0
  265. package/dist/util/config.js.map +1 -0
  266. package/dist/util/env.d.ts +10 -0
  267. package/dist/util/env.js +25 -0
  268. package/dist/util/env.js.map +1 -0
  269. package/dist/util/memory-tracking.d.ts +7 -0
  270. package/dist/util/memory-tracking.js +58 -0
  271. package/dist/util/memory-tracking.js.map +1 -0
  272. package/dist/util/migration_lib.d.ts +11 -0
  273. package/dist/util/migration_lib.js +64 -0
  274. package/dist/util/migration_lib.js.map +1 -0
  275. package/dist/util/pgwire_utils.d.ts +24 -0
  276. package/dist/util/pgwire_utils.js +117 -0
  277. package/dist/util/pgwire_utils.js.map +1 -0
  278. package/dist/util/populate_test_data.d.ts +8 -0
  279. package/dist/util/populate_test_data.js +65 -0
  280. package/dist/util/populate_test_data.js.map +1 -0
  281. package/dist/util/protocol-types.d.ts +178 -0
  282. package/dist/util/protocol-types.js +38 -0
  283. package/dist/util/protocol-types.js.map +1 -0
  284. package/dist/util/secs.d.ts +2 -0
  285. package/dist/util/secs.js +49 -0
  286. package/dist/util/secs.js.map +1 -0
  287. package/dist/util/util-index.d.ts +22 -0
  288. package/dist/util/util-index.js +23 -0
  289. package/dist/util/util-index.js.map +1 -0
  290. package/dist/util/utils.d.ts +14 -0
  291. package/dist/util/utils.js +75 -0
  292. package/dist/util/utils.js.map +1 -0
  293. package/package.json +55 -0
  294. package/src/api/api-index.ts +2 -0
  295. package/src/api/diagnostics.ts +221 -0
  296. package/src/api/schema.ts +99 -0
  297. package/src/auth/CachedKeyCollector.ts +132 -0
  298. package/src/auth/CompoundKeyCollector.ts +33 -0
  299. package/src/auth/JwtPayload.ts +11 -0
  300. package/src/auth/KeyCollector.ts +27 -0
  301. package/src/auth/KeySpec.ts +67 -0
  302. package/src/auth/KeyStore.ts +156 -0
  303. package/src/auth/LeakyBucket.ts +66 -0
  304. package/src/auth/RemoteJWKSCollector.ts +130 -0
  305. package/src/auth/StaticKeyCollector.ts +21 -0
  306. package/src/auth/SupabaseKeyCollector.ts +67 -0
  307. package/src/auth/auth-index.ts +10 -0
  308. package/src/db/db-index.ts +1 -0
  309. package/src/db/mongo.ts +72 -0
  310. package/src/entry/cli-entry.ts +41 -0
  311. package/src/entry/commands/config-command.ts +36 -0
  312. package/src/entry/commands/migrate-action.ts +25 -0
  313. package/src/entry/commands/start-action.ts +24 -0
  314. package/src/entry/commands/teardown-action.ts +23 -0
  315. package/src/entry/entry-index.ts +5 -0
  316. package/src/index.ts +37 -0
  317. package/src/metrics/metrics.ts +169 -0
  318. package/src/migrations/db/migrations/1684951997326-init.ts +33 -0
  319. package/src/migrations/db/migrations/1688556755264-initial-sync-rules.ts +5 -0
  320. package/src/migrations/db/migrations/1702295701188-sync-rule-state.ts +99 -0
  321. package/src/migrations/db/migrations/1711543888062-write-checkpoint-index.ts +32 -0
  322. package/src/migrations/db/store.ts +11 -0
  323. package/src/migrations/migrations.ts +122 -0
  324. package/src/replication/ErrorRateLimiter.ts +49 -0
  325. package/src/replication/PgRelation.ts +42 -0
  326. package/src/replication/WalConnection.ts +227 -0
  327. package/src/replication/WalStream.ts +626 -0
  328. package/src/replication/WalStreamManager.ts +214 -0
  329. package/src/replication/WalStreamRunner.ts +180 -0
  330. package/src/replication/replication-index.ts +7 -0
  331. package/src/replication/util.ts +76 -0
  332. package/src/routes/admin.ts +229 -0
  333. package/src/routes/auth.ts +209 -0
  334. package/src/routes/checkpointing.ts +38 -0
  335. package/src/routes/dev.ts +194 -0
  336. package/src/routes/route-generators.ts +39 -0
  337. package/src/routes/router-socket.ts +13 -0
  338. package/src/routes/router.ts +17 -0
  339. package/src/routes/routes-index.ts +5 -0
  340. package/src/routes/socket-route.ts +131 -0
  341. package/src/routes/sync-rules.ts +210 -0
  342. package/src/routes/sync-stream.ts +92 -0
  343. package/src/runner/teardown.ts +91 -0
  344. package/src/storage/BucketStorage.ts +386 -0
  345. package/src/storage/MongoBucketStorage.ts +493 -0
  346. package/src/storage/SourceTable.ts +60 -0
  347. package/src/storage/mongo/MongoBucketBatch.ts +756 -0
  348. package/src/storage/mongo/MongoIdSequence.ts +24 -0
  349. package/src/storage/mongo/MongoPersistedSyncRules.ts +16 -0
  350. package/src/storage/mongo/MongoPersistedSyncRulesContent.ts +47 -0
  351. package/src/storage/mongo/MongoSyncBucketStorage.ts +517 -0
  352. package/src/storage/mongo/MongoSyncRulesLock.ts +81 -0
  353. package/src/storage/mongo/OperationBatch.ts +115 -0
  354. package/src/storage/mongo/PersistedBatch.ts +245 -0
  355. package/src/storage/mongo/db.ts +69 -0
  356. package/src/storage/mongo/models.ts +157 -0
  357. package/src/storage/mongo/util.ts +88 -0
  358. package/src/storage/storage-index.ts +15 -0
  359. package/src/sync/BroadcastIterable.ts +161 -0
  360. package/src/sync/LastValueSink.ts +100 -0
  361. package/src/sync/merge.ts +200 -0
  362. package/src/sync/safeRace.ts +99 -0
  363. package/src/sync/sync-index.ts +6 -0
  364. package/src/sync/sync.ts +312 -0
  365. package/src/sync/util.ts +98 -0
  366. package/src/system/CorePowerSyncSystem.ts +43 -0
  367. package/src/util/Mutex.ts +159 -0
  368. package/src/util/PgManager.ts +64 -0
  369. package/src/util/alerting.ts +17 -0
  370. package/src/util/config/collectors/config-collector.ts +141 -0
  371. package/src/util/config/collectors/impl/base64-config-collector.ts +18 -0
  372. package/src/util/config/collectors/impl/fallback-config-collector.ts +22 -0
  373. package/src/util/config/collectors/impl/filesystem-config-collector.ts +41 -0
  374. package/src/util/config/compound-config-collector.ts +171 -0
  375. package/src/util/config/sync-rules/impl/base64-sync-rules-collector.ts +21 -0
  376. package/src/util/config/sync-rules/impl/filesystem-sync-rules-collector.ts +26 -0
  377. package/src/util/config/sync-rules/impl/inline-sync-rules-collector.ts +21 -0
  378. package/src/util/config/sync-rules/sync-collector.ts +8 -0
  379. package/src/util/config/types.ts +60 -0
  380. package/src/util/config.ts +39 -0
  381. package/src/util/env.ts +28 -0
  382. package/src/util/memory-tracking.ts +67 -0
  383. package/src/util/migration_lib.ts +79 -0
  384. package/src/util/pgwire_utils.ts +139 -0
  385. package/src/util/populate_test_data.ts +78 -0
  386. package/src/util/protocol-types.ts +223 -0
  387. package/src/util/secs.ts +54 -0
  388. package/src/util/util-index.ts +25 -0
  389. package/src/util/utils.ts +102 -0
  390. package/test/src/__snapshots__/pg_test.test.ts.snap +256 -0
  391. package/test/src/__snapshots__/sync.test.ts.snap +235 -0
  392. package/test/src/auth.test.ts +340 -0
  393. package/test/src/broadcast_iterable.test.ts +156 -0
  394. package/test/src/data_storage.test.ts +1176 -0
  395. package/test/src/env.ts +8 -0
  396. package/test/src/large_batch.test.ts +194 -0
  397. package/test/src/merge_iterable.test.ts +355 -0
  398. package/test/src/pg_test.test.ts +432 -0
  399. package/test/src/schema_changes.test.ts +545 -0
  400. package/test/src/slow_tests.test.ts +257 -0
  401. package/test/src/sql_functions.test.ts +254 -0
  402. package/test/src/sql_operators.test.ts +132 -0
  403. package/test/src/sync.test.ts +293 -0
  404. package/test/src/sync_rules.test.ts +1051 -0
  405. package/test/src/util.ts +67 -0
  406. package/test/src/validation.test.ts +63 -0
  407. package/test/src/wal_stream.test.ts +310 -0
  408. package/test/src/wal_stream_utils.ts +147 -0
  409. package/test/tsconfig.json +20 -0
  410. package/tsconfig.json +20 -0
  411. package/tsconfig.tsbuildinfo +1 -0
  412. package/vitest.config.ts +11 -0
@@ -0,0 +1,192 @@
1
+ import * as micro from '@journeyapps-platform/micro';
2
+ import { SqlSyncRules, StaticSchema, isJsonValue, toSyncRulesValue } from '@powersync/service-sync-rules';
3
+ import { internal_routes } from '@powersync/service-types';
4
+ import * as api from '../api/api-index.js';
5
+ import * as util from '../util/util-index.js';
6
+ import { authApi } from './auth.js';
7
+ const demoCredentials = (router) => router.post('/api/admin/v1/demo-credentials', {
8
+ authorize: authApi,
9
+ validator: micro.schema.createTsCodecValidator(internal_routes.DemoCredentialsRequest, { allowAdditional: true }),
10
+ handler: async (payload) => {
11
+ const connection = payload.context.system.config.connection;
12
+ if (connection == null || !connection.demo_database) {
13
+ return internal_routes.DemoCredentialsResponse.encode({});
14
+ }
15
+ const uri = util.buildDemoPgUri(connection);
16
+ return internal_routes.DemoCredentialsResponse.encode({
17
+ credentials: {
18
+ postgres_uri: uri
19
+ }
20
+ });
21
+ }
22
+ });
23
+ export const executeSql = (router) => router.post('/api/admin/v1/execute-sql', {
24
+ authorize: authApi,
25
+ validator: micro.schema.createTsCodecValidator(internal_routes.ExecuteSqlRequest, { allowAdditional: true }),
26
+ handler: async (payload) => {
27
+ const connection = payload.context.system.config.connection;
28
+ if (connection == null || !connection.debug_api) {
29
+ return internal_routes.ExecuteSqlResponse.encode({
30
+ results: {
31
+ columns: [],
32
+ rows: []
33
+ },
34
+ success: false,
35
+ error: 'SQL querying is not enabled'
36
+ });
37
+ }
38
+ const pool = payload.context.system.requirePgPool();
39
+ const { query, args } = payload.params.sql;
40
+ try {
41
+ const result = await pool.query({
42
+ statement: query,
43
+ params: args.map(util.autoParameter)
44
+ });
45
+ return internal_routes.ExecuteSqlResponse.encode({
46
+ success: true,
47
+ results: {
48
+ columns: result.columns.map((c) => c.name),
49
+ rows: result.rows.map((row) => {
50
+ return row.map((value) => mapColumnValue(toSyncRulesValue(value)));
51
+ })
52
+ }
53
+ });
54
+ }
55
+ catch (e) {
56
+ return internal_routes.ExecuteSqlResponse.encode({
57
+ results: {
58
+ columns: [],
59
+ rows: []
60
+ },
61
+ success: false,
62
+ error: e.message
63
+ });
64
+ }
65
+ }
66
+ });
67
+ export const diagnostics = (router) => router.post('/api/admin/v1/diagnostics', {
68
+ authorize: authApi,
69
+ validator: micro.schema.createTsCodecValidator(internal_routes.DiagnosticsRequest, { allowAdditional: true }),
70
+ handler: async (payload) => {
71
+ const include_content = payload.params.sync_rules_content ?? false;
72
+ const system = payload.context.system;
73
+ const status = await api.getConnectionStatus(system);
74
+ if (status == null) {
75
+ return internal_routes.DiagnosticsResponse.encode({
76
+ connections: []
77
+ });
78
+ }
79
+ const { storage } = system;
80
+ const active = await storage.getActiveSyncRulesContent();
81
+ const next = await storage.getNextSyncRulesContent();
82
+ const active_status = await api.getSyncRulesStatus(active, system, {
83
+ include_content,
84
+ check_connection: status.connected,
85
+ live_status: true
86
+ });
87
+ const next_status = await api.getSyncRulesStatus(next, system, {
88
+ include_content,
89
+ check_connection: status.connected,
90
+ live_status: true
91
+ });
92
+ return internal_routes.DiagnosticsResponse.encode({
93
+ connections: [status],
94
+ active_sync_rules: active_status,
95
+ deploying_sync_rules: next_status
96
+ });
97
+ }
98
+ });
99
+ export const getSchema = (router) => router.post('/api/admin/v1/schema', {
100
+ authorize: authApi,
101
+ validator: micro.schema.createTsCodecValidator(internal_routes.GetSchemaRequest, { allowAdditional: true }),
102
+ handler: async (payload) => {
103
+ const system = payload.context.system;
104
+ return internal_routes.GetSchemaResponse.encode(await api.getConnectionsSchema(system));
105
+ }
106
+ });
107
+ export const reprocess = (router) => router.post('/api/admin/v1/reprocess', {
108
+ authorize: authApi,
109
+ validator: micro.schema.createTsCodecValidator(internal_routes.ReprocessRequest, { allowAdditional: true }),
110
+ handler: async (payload) => {
111
+ const system = payload.context.system;
112
+ const storage = system.storage;
113
+ const next = await storage.getNextSyncRules();
114
+ if (next != null) {
115
+ throw new Error(`Busy processing sync rules - cannot reprocess`);
116
+ }
117
+ const active = await storage.getActiveSyncRules();
118
+ if (active == null) {
119
+ throw new micro.errors.JourneyError({
120
+ status: 422,
121
+ code: 'NO_SYNC_RULES',
122
+ description: 'No active sync rules'
123
+ });
124
+ }
125
+ const new_rules = await storage.updateSyncRules({
126
+ content: active.sync_rules.content
127
+ });
128
+ return internal_routes.ReprocessResponse.encode({
129
+ connections: [
130
+ {
131
+ tag: system.config.connection.tag,
132
+ id: system.config.connection.id,
133
+ slot_name: new_rules.slot_name
134
+ }
135
+ ]
136
+ });
137
+ }
138
+ });
139
+ export const validate = (router) => router.post('/api/admin/v1/validate', {
140
+ authorize: authApi,
141
+ validator: micro.schema.createTsCodecValidator(internal_routes.ValidateRequest, { allowAdditional: true }),
142
+ handler: async (payload) => {
143
+ const system = payload.context.system;
144
+ const content = payload.params.sync_rules;
145
+ const schemaData = await api.getConnectionsSchema(system);
146
+ const schema = new StaticSchema(schemaData.connections);
147
+ const sync_rules = {
148
+ // Dummy values
149
+ id: 0,
150
+ slot_name: '',
151
+ parsed() {
152
+ return {
153
+ ...this,
154
+ sync_rules: SqlSyncRules.fromYaml(content, { throwOnError: false, schema })
155
+ };
156
+ },
157
+ sync_rules_content: content,
158
+ async lock() {
159
+ throw new Error('Lock not implemented');
160
+ }
161
+ };
162
+ const connectionStatus = await api.getConnectionStatus(system);
163
+ if (connectionStatus == null) {
164
+ return internal_routes.ValidateResponse.encode({
165
+ errors: [{ level: 'fatal', message: 'No connection configured' }],
166
+ connections: []
167
+ });
168
+ }
169
+ const status = (await api.getSyncRulesStatus(sync_rules, system, {
170
+ include_content: false,
171
+ check_connection: connectionStatus?.connected,
172
+ live_status: false
173
+ }));
174
+ if (connectionStatus == null) {
175
+ status.errors.push({ level: 'fatal', message: 'No connection configured' });
176
+ }
177
+ return internal_routes.ValidateResponse.encode(status);
178
+ }
179
+ });
180
+ function mapColumnValue(value) {
181
+ if (typeof value == 'bigint') {
182
+ return Number(value);
183
+ }
184
+ else if (isJsonValue(value)) {
185
+ return value;
186
+ }
187
+ else {
188
+ return null;
189
+ }
190
+ }
191
+ export const admin_routes = [demoCredentials, executeSql, diagnostics, getSchema, reprocess, validate];
192
+ //# sourceMappingURL=admin.js.map
@@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gBAAgB,EAAE,SAAS;YAC7C,WAAW,EAAE,KAAK;SACnB,CAAC,CAAE,CAAC;QAEL,IAAI,gBAAgB,IAAI,IAAI,EAAE,CAAC;YAC7B,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,0BAA0B,EAAE,CAAC,CAAC;QAC9E,CAAC;QAED,OAAO,eAAe,CAAC,gBAAgB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;CACF,CAAC,CAAC;AAEL,SAAS,cAAc,CAAC,KAAkB;IACxC,IAAI,OAAO,KAAK,IAAI,QAAQ,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;SAAM,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,KAAK,CAAC;IACf,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,eAAe,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC"}
@@ -0,0 +1,58 @@
1
+ import * as micro from '@journeyapps-platform/micro';
2
+ import { FastifyRequest } from 'fastify';
3
+ import * as auth from '../auth/auth-index.js';
4
+ import * as util from '../util/util-index.js';
5
+ import { Context } from './router.js';
6
+ import { CorePowerSyncSystem } from '../system/CorePowerSyncSystem.js';
7
+ export declare function endpoint(req: FastifyRequest): string;
8
+ /**
9
+ * @deprecated
10
+ *
11
+ * Will be replaced by temporary tokens issued by PowerSync Management service.
12
+ */
13
+ export declare function issueDevToken(req: FastifyRequest, user_id: string, config: util.ResolvedPowerSyncConfig): Promise<string>;
14
+ /** @deprecated */
15
+ export declare function issueLegacyDevToken(req: FastifyRequest, user_id: string, config: util.ResolvedPowerSyncConfig): Promise<string>;
16
+ export declare function issuePowerSyncToken(req: FastifyRequest, user_id: string, config: util.ResolvedPowerSyncConfig): Promise<string>;
17
+ export declare function getTokenFromHeader(authHeader?: string): string | null;
18
+ export declare const authUser: (payload: micro.fastify.FastifyHandlerPayload<any, Context>) => Promise<{
19
+ authorized: boolean;
20
+ errors: any[];
21
+ } | {
22
+ authorized: boolean;
23
+ errors?: undefined;
24
+ }>;
25
+ export declare function authorizeUser(context: Context, authHeader?: string): Promise<{
26
+ authorized: boolean;
27
+ errors: any[];
28
+ } | {
29
+ authorized: boolean;
30
+ errors?: undefined;
31
+ }>;
32
+ export declare function generateContext(system: CorePowerSyncSystem, token: string): Promise<{
33
+ context: {
34
+ user_id: string;
35
+ token_payload: auth.JwtPayload;
36
+ };
37
+ errors?: undefined;
38
+ } | {
39
+ context: null;
40
+ errors: any[];
41
+ }>;
42
+ /**
43
+ * @deprecated
44
+ */
45
+ export declare const authDevUser: (payload: micro.fastify.FastifyHandlerPayload<any, Context>) => Promise<{
46
+ authorized: boolean;
47
+ errors: any[];
48
+ } | {
49
+ authorized: boolean;
50
+ errors?: undefined;
51
+ }>;
52
+ export declare const authApi: (payload: micro.fastify.FastifyHandlerPayload<any, Context>) => {
53
+ authorized: boolean;
54
+ errors: string[];
55
+ } | {
56
+ authorized: boolean;
57
+ errors?: undefined;
58
+ };
@@ -0,0 +1,182 @@
1
+ import * as jose from 'jose';
2
+ export function endpoint(req) {
3
+ const protocol = req.headers['x-forwarded-proto'] ?? req.protocol;
4
+ const host = req.hostname;
5
+ return `${protocol}://${host}`;
6
+ }
7
+ function devAudience(req) {
8
+ return `${endpoint(req)}/dev`;
9
+ }
10
+ /**
11
+ * @deprecated
12
+ *
13
+ * Will be replaced by temporary tokens issued by PowerSync Management service.
14
+ */
15
+ export async function issueDevToken(req, user_id, config) {
16
+ const iss = devAudience(req);
17
+ const aud = devAudience(req);
18
+ const key = config.dev.dev_key;
19
+ if (key == null) {
20
+ throw new Error('Auth disabled');
21
+ }
22
+ return await new jose.SignJWT({})
23
+ .setProtectedHeader({ alg: key.source.alg, kid: key.kid })
24
+ .setSubject(user_id)
25
+ .setIssuedAt()
26
+ .setIssuer(iss)
27
+ .setAudience(aud)
28
+ .setExpirationTime('30d')
29
+ .sign(key.key);
30
+ }
31
+ /** @deprecated */
32
+ export async function issueLegacyDevToken(req, user_id, config) {
33
+ const iss = devAudience(req);
34
+ const aud = config.jwt_audiences[0];
35
+ const key = config.dev.dev_key;
36
+ if (key == null || aud == null) {
37
+ throw new Error('Auth disabled');
38
+ }
39
+ return await new jose.SignJWT({})
40
+ .setProtectedHeader({ alg: key.source.alg, kid: key.kid })
41
+ .setSubject(user_id)
42
+ .setIssuedAt()
43
+ .setIssuer(iss)
44
+ .setAudience(aud)
45
+ .setExpirationTime('60m')
46
+ .sign(key.key);
47
+ }
48
+ export async function issuePowerSyncToken(req, user_id, config) {
49
+ const iss = devAudience(req);
50
+ const aud = config.jwt_audiences[0];
51
+ const key = config.dev.dev_key;
52
+ if (key == null || aud == null) {
53
+ throw new Error('Auth disabled');
54
+ }
55
+ const jwt = await new jose.SignJWT({})
56
+ .setProtectedHeader({ alg: key.source.alg, kid: key.kid })
57
+ .setSubject(user_id)
58
+ .setIssuedAt()
59
+ .setIssuer(iss)
60
+ .setAudience(aud)
61
+ .setExpirationTime('5m')
62
+ .sign(key.key);
63
+ return jwt;
64
+ }
65
+ export function getTokenFromHeader(authHeader = '') {
66
+ const tokenMatch = /^(Token|Bearer) (\S+)$/.exec(authHeader);
67
+ if (!tokenMatch) {
68
+ return null;
69
+ }
70
+ const token = tokenMatch[2];
71
+ return token ?? null;
72
+ }
73
+ export const authUser = async (payload) => {
74
+ return authorizeUser(payload.context, payload.request.headers.authorization);
75
+ };
76
+ export async function authorizeUser(context, authHeader = '') {
77
+ const token = getTokenFromHeader(authHeader);
78
+ if (token == null) {
79
+ return {
80
+ authorized: false,
81
+ errors: ['Authentication required']
82
+ };
83
+ }
84
+ const { context: tokenContext, errors } = await generateContext(context.system, token);
85
+ if (!tokenContext) {
86
+ return {
87
+ authorized: false,
88
+ errors
89
+ };
90
+ }
91
+ Object.assign(context, tokenContext);
92
+ return { authorized: true };
93
+ }
94
+ export async function generateContext(system, token) {
95
+ const config = system.config;
96
+ let tokenPayload;
97
+ try {
98
+ const maxAge = config.token_max_expiration;
99
+ tokenPayload = await system.client_keystore.verifyJwt(token, {
100
+ defaultAudiences: config.jwt_audiences,
101
+ maxAge: maxAge
102
+ });
103
+ return {
104
+ context: {
105
+ user_id: tokenPayload.sub,
106
+ token_payload: tokenPayload
107
+ }
108
+ };
109
+ }
110
+ catch (err) {
111
+ return {
112
+ context: null,
113
+ errors: [err.message]
114
+ };
115
+ }
116
+ }
117
+ /**
118
+ * @deprecated
119
+ */
120
+ export const authDevUser = async (payload) => {
121
+ const context = payload.context;
122
+ const token = getTokenFromHeader(payload.request.headers.authorization);
123
+ if (!context.system.config.dev.demo_auth) {
124
+ return {
125
+ authorized: false,
126
+ errors: ['Authentication disabled']
127
+ };
128
+ }
129
+ if (token == null) {
130
+ return {
131
+ authorized: false,
132
+ errors: ['Authentication required']
133
+ };
134
+ }
135
+ // Different from the configured audience.
136
+ // Should also not be changed by keys
137
+ const audience = [devAudience(payload.request)];
138
+ let tokenPayload;
139
+ try {
140
+ tokenPayload = await context.system.dev_client_keystore.verifyJwt(token, {
141
+ defaultAudiences: audience,
142
+ maxAge: '31d'
143
+ });
144
+ }
145
+ catch (err) {
146
+ return {
147
+ authorized: false,
148
+ errors: [err.message]
149
+ };
150
+ }
151
+ payload.context.user_id = tokenPayload.sub;
152
+ return { authorized: true };
153
+ };
154
+ export const authApi = (payload) => {
155
+ const context = payload.context;
156
+ const api_keys = context.system.config.api_tokens;
157
+ if (api_keys.length == 0) {
158
+ return {
159
+ authorized: false,
160
+ errors: ['Authentication disabled']
161
+ };
162
+ }
163
+ const auth = payload.request.headers.authorization ?? '';
164
+ const tokenMatch = /^(Token|Bearer) (\S+)$/.exec(auth);
165
+ if (!tokenMatch) {
166
+ return {
167
+ authorized: false,
168
+ errors: ['Authentication required']
169
+ };
170
+ }
171
+ const token = tokenMatch[2];
172
+ if (api_keys.includes(token)) {
173
+ return { authorized: true };
174
+ }
175
+ else {
176
+ return {
177
+ authorized: false,
178
+ errors: ['Authentication failed']
179
+ };
180
+ }
181
+ };
182
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/routes/auth.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAO7B,MAAM,UAAU,QAAQ,CAAC,GAAmB;IAC1C,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,mBAAmB,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC;IAClE,MAAM,IAAI,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC1B,OAAO,GAAG,QAAQ,MAAM,IAAI,EAAE,CAAC;AACjC,CAAC;AAED,SAAS,WAAW,CAAC,GAAmB;IACtC,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;AAChC,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,GAAmB,EAAE,OAAe,EAAE,MAAoC;IAC5G,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IAE7B,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC;IAC/B,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;IACnC,CAAC;IAED,OAAO,MAAM,IAAI,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;SAC9B,kBAAkB,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,CAAC,GAAI,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC;SAC1D,UAAU,CAAC,OAAO,CAAC;SACn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IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,aAAa,IAAI,EAAE,CAAC;IAEzD,MAAM,UAAU,GAAG,wBAAwB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO;YACL,UAAU,EAAE,KAAK;YACjB,MAAM,EAAE,CAAC,yBAAyB,CAAC;SACpC,CAAC;IACJ,CAAC;IACD,MAAM,KAAK,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;IAC5B,IAAI,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;IAC9B,CAAC;SAAM,CAAC;QACN,OAAO;YACL,UAAU,EAAE,KAAK;YACjB,MAAM,EAAE,CAAC,uBAAuB,CAAC;SAClC,CAAC;IACJ,CAAC;AACH,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { RouteGenerator } from './router.js';
2
+ export declare const writeCheckpoint: RouteGenerator;
3
+ export declare const writeCheckpoint2: RouteGenerator;
@@ -0,0 +1,30 @@
1
+ import * as t from 'ts-codec';
2
+ import * as micro from '@journeyapps-platform/micro';
3
+ import * as util from '../util/util-index.js';
4
+ import { authUser } from './auth.js';
5
+ const WriteCheckpointRequest = t.object({});
6
+ export const writeCheckpoint = (router) => router.get('/write-checkpoint.json', {
7
+ authorize: authUser,
8
+ validator: micro.schema.createTsCodecValidator(WriteCheckpointRequest, { allowAdditional: true }),
9
+ handler: async (payload) => {
10
+ const system = payload.context.system;
11
+ const storage = system.storage;
12
+ const checkpoint = await util.getClientCheckpoint(system.requirePgPool(), storage);
13
+ return {
14
+ checkpoint
15
+ };
16
+ }
17
+ });
18
+ export const writeCheckpoint2 = (router) => router.get('/write-checkpoint2.json', {
19
+ authorize: authUser,
20
+ validator: micro.schema.createTsCodecValidator(WriteCheckpointRequest, { allowAdditional: true }),
21
+ handler: async (payload) => {
22
+ const { user_id, system } = payload.context;
23
+ const storage = system.storage;
24
+ const write_checkpoint = await util.createWriteCheckpoint(system.requirePgPool(), storage, user_id);
25
+ return {
26
+ write_checkpoint: String(write_checkpoint)
27
+ };
28
+ }
29
+ });
30
+ //# sourceMappingURL=checkpointing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkpointing.js","sourceRoot":"","sources":["../../src/routes/checkpointing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAC9B,OAAO,KAAK,KAAK,MAAM,6BAA6B,CAAC;AAErD,OAAO,KAAK,IAAI,MAAM,sBAAsB,CAAC;AAE7C,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAGrC,MAAM,sBAAsB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAE5C,MAAM,CAAC,MAAM,eAAe,GAAmB,CAAC,MAAM,EAAE,EAAE,CACxD,MAAM,CAAC,GAAG,CAAC,wBAAwB,EAAE;IACnC,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,sBAAsB,CAAC,sBAAsB,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC;IACjG,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QACzB,MAAM,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC;QACtC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAE/B,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,aAAa,EAAE,EAAE,OAAO,CAAC,CAAC;QACnF,OAAO;YACL,UAAU;SACX,CAAC;IACJ,CAAC;CACF,CAAC,CAAC;AAEL,MAAM,CAAC,MAAM,gBAAgB,GAAmB,CAAC,MAAM,EAAE,EAAE,CACzD,MAAM,CAAC,GAAG,CAAC,yBAAyB,EAAE;IACpC,SAAS,EAAE,QAAQ;IACnB,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,sBAAsB,CAAC,sBAAsB,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC;IACjG,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;QACzB,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC;QAC5C,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;QAC/B,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,aAAa,EAAE,EAAE,OAAO,EAAE,OAAQ,CAAC,CAAC;QACrG,OAAO;YACL,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,CAAC;SAC3C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { RouteGenerator } from './router.js';
2
+ export declare const auth: RouteGenerator;
3
+ export declare const auth2: RouteGenerator;
4
+ export declare const token: RouteGenerator;
5
+ export declare const crud: RouteGenerator;
6
+ export declare const dev_routes: RouteGenerator[];
@@ -0,0 +1,163 @@
1
+ import * as t from 'ts-codec';
2
+ import * as micro from '@journeyapps-platform/micro';
3
+ import * as util from '../util/util-index.js';
4
+ import { authDevUser, authUser, endpoint, issueDevToken, issueLegacyDevToken, issuePowerSyncToken } from './auth.js';
5
+ const AuthParams = t.object({
6
+ user: t.string,
7
+ password: t.string
8
+ });
9
+ // For legacy web client only. Remove soon.
10
+ export const auth = (router) => router.post('/auth.json', {
11
+ validator: micro.schema.createTsCodecValidator(AuthParams, { allowAdditional: true }),
12
+ handler: async (payload) => {
13
+ const { user, password } = payload.params;
14
+ const config = payload.context.system.config;
15
+ if (config.dev.demo_auth == false || config.dev.demo_password == null) {
16
+ throw new micro.errors.AuthorizationError(['Demo auth disabled']);
17
+ }
18
+ if (password == config.dev.demo_password) {
19
+ const token = await issueLegacyDevToken(payload.request, user, payload.context.system.config);
20
+ return { token, user_id: user, endpoint: endpoint(payload.request) };
21
+ }
22
+ else {
23
+ throw new micro.errors.AuthorizationError(['Authentication failed']);
24
+ }
25
+ }
26
+ });
27
+ export const auth2 = (router) => router.post('/dev/auth.json', {
28
+ validator: micro.schema.createTsCodecValidator(AuthParams, { allowAdditional: true }),
29
+ handler: async (payload) => {
30
+ const { user, password } = payload.params;
31
+ const config = payload.context.system.config;
32
+ if (config.dev.demo_auth == false || config.dev.demo_password == null) {
33
+ throw new micro.errors.AuthorizationError(['Demo auth disabled']);
34
+ }
35
+ if (password == config.dev.demo_password) {
36
+ const token = await issueDevToken(payload.request, user, payload.context.system.config);
37
+ return { token, user_id: user };
38
+ }
39
+ else {
40
+ throw new micro.errors.AuthorizationError(['Authentication failed']);
41
+ }
42
+ }
43
+ });
44
+ const TokenParams = t.object({});
45
+ export const token = (router) => router.post('/dev/token.json', {
46
+ validator: micro.schema.createTsCodecValidator(TokenParams, { allowAdditional: true }),
47
+ authorize: authDevUser,
48
+ handler: async (payload) => {
49
+ const { user_id } = payload.context;
50
+ const outToken = await issuePowerSyncToken(payload.request, user_id, payload.context.system.config);
51
+ return { token: outToken, user_id: user_id, endpoint: endpoint(payload.request) };
52
+ }
53
+ });
54
+ const OpType = {
55
+ PUT: 'PUT',
56
+ PATCH: 'PATCH',
57
+ DELETE: 'DELETE'
58
+ };
59
+ const CrudEntry = t.object({
60
+ op: t.Enum(OpType),
61
+ type: t.string,
62
+ id: t.string,
63
+ op_id: t.number.optional(),
64
+ data: t.any.optional()
65
+ });
66
+ const CrudRequest = t.object({
67
+ data: t.array(CrudEntry),
68
+ write_checkpoint: t.boolean.optional()
69
+ });
70
+ export const crud = (router) => router.post('/crud.json', {
71
+ validator: micro.schema.createTsCodecValidator(CrudRequest, { allowAdditional: true }),
72
+ authorize: authUser,
73
+ handler: async (payload) => {
74
+ const { user_id, system } = payload.context;
75
+ const pool = system.requirePgPool();
76
+ if (!system.config.dev.crud_api) {
77
+ throw new Error('CRUD api disabled');
78
+ }
79
+ const params = payload.params;
80
+ let statements = [];
81
+ // Implementation note:
82
+ // Postgres does automatic "assigment cast" for query literals,
83
+ // e.g. a string literal to uuid. However, the same doesn't apply
84
+ // to query parameters.
85
+ // To handle those automatically, we use `json_populate_record`
86
+ // to automatically cast to the correct types.
87
+ for (let op of params.data) {
88
+ const table = util.escapeIdentifier(op.type);
89
+ if (op.op == 'PUT') {
90
+ const data = op.data;
91
+ const with_id = { ...data, id: op.id };
92
+ const columnsEscaped = Object.keys(with_id).map(util.escapeIdentifier);
93
+ const columnsJoined = columnsEscaped.join(', ');
94
+ let updateClauses = [];
95
+ for (let key of Object.keys(data)) {
96
+ updateClauses.push(`${util.escapeIdentifier(key)} = EXCLUDED.${util.escapeIdentifier(key)}`);
97
+ }
98
+ const updateClause = updateClauses.length > 0 ? `DO UPDATE SET ${updateClauses.join(', ')}` : `DO NOTHING`;
99
+ const statement = `
100
+ WITH data_row AS (
101
+ SELECT (json_populate_record(null::${table}, $1::json)).*
102
+ )
103
+ INSERT INTO ${table} (${columnsJoined})
104
+ SELECT ${columnsJoined} FROM data_row
105
+ ON CONFLICT(id) ${updateClause}`;
106
+ statements.push({
107
+ statement: statement,
108
+ params: [{ type: 'varchar', value: JSON.stringify(with_id) }]
109
+ });
110
+ }
111
+ else if (op.op == 'PATCH') {
112
+ const data = op.data;
113
+ const with_id = { ...data, id: op.id };
114
+ let updateClauses = [];
115
+ for (let key of Object.keys(data)) {
116
+ updateClauses.push(`${util.escapeIdentifier(key)} = data_row.${util.escapeIdentifier(key)}`);
117
+ }
118
+ const statement = `
119
+ WITH data_row AS (
120
+ SELECT (json_populate_record(null::${table}, $1::json)).*
121
+ )
122
+ UPDATE ${table}
123
+ SET ${updateClauses.join(', ')}
124
+ FROM data_row
125
+ WHERE ${table}.id = data_row.id`;
126
+ statements.push({
127
+ statement: statement,
128
+ params: [{ type: 'varchar', value: JSON.stringify(with_id) }]
129
+ });
130
+ }
131
+ else if (op.op == 'DELETE') {
132
+ statements.push({
133
+ statement: `
134
+ WITH data_row AS (
135
+ SELECT (json_populate_record(null::${table}, $1::json)).*
136
+ )
137
+ DELETE FROM ${table}
138
+ USING data_row
139
+ WHERE ${table}.id = data_row.id`,
140
+ params: [{ type: 'varchar', value: JSON.stringify({ id: op.id }) }]
141
+ });
142
+ }
143
+ }
144
+ await pool.query(...statements);
145
+ const storage = system.storage;
146
+ if (payload.params.write_checkpoint === true) {
147
+ const write_checkpoint = await util.createWriteCheckpoint(pool, storage, payload.context.user_id);
148
+ return { write_checkpoint: String(write_checkpoint) };
149
+ }
150
+ else if (payload.params.write_checkpoint === false) {
151
+ return {};
152
+ }
153
+ else {
154
+ // Legacy
155
+ const checkpoint = await util.getClientCheckpoint(pool, storage);
156
+ return {
157
+ checkpoint
158
+ };
159
+ }
160
+ }
161
+ });
162
+ export const dev_routes = [auth, auth2, token, crud];
163
+ //# sourceMappingURL=dev.js.map