@astrogate/sdk 0.0.0-stage → 0.1.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 (440) hide show
  1. package/README.md +6 -2
  2. package/THIRD_PARTY_NOTICES.md +17 -0
  3. package/dist/browser.d.ts +85 -0
  4. package/dist/browser.js +16 -0
  5. package/dist/database-binding.d.ts +7 -0
  6. package/dist/database-binding.js +11 -0
  7. package/dist/hosted-session.d.ts +1 -0
  8. package/dist/hosted-session.js +11 -0
  9. package/dist/http.d.ts +24 -0
  10. package/dist/http.js +92 -0
  11. package/dist/inventory.d.ts +7 -0
  12. package/dist/inventory.js +18 -0
  13. package/dist/management-read.d.ts +17 -0
  14. package/dist/management-read.js +104 -0
  15. package/dist/management.d.ts +347 -0
  16. package/dist/management.js +137 -0
  17. package/dist/operator.d.ts +136 -0
  18. package/dist/operator.js +53 -0
  19. package/dist/react.d.ts +16 -0
  20. package/dist/react.js +10 -0
  21. package/dist/server.d.ts +27 -0
  22. package/dist/server.js +30 -0
  23. package/dist/services.d.ts +7 -0
  24. package/dist/services.js +53 -0
  25. package/dist/storage.d.ts +68 -0
  26. package/dist/storage.js +30 -0
  27. package/dist/tasks.d.ts +42 -0
  28. package/dist/tasks.js +24 -0
  29. package/dist/wire.gen.d.ts +7107 -0
  30. package/dist/wire.gen.js +5 -0
  31. package/native-provenance.json +15 -0
  32. package/node_modules/@instantdb/admin/LICENSE +202 -0
  33. package/node_modules/@instantdb/admin/dist/esm/index.d.ts +607 -0
  34. package/node_modules/@instantdb/admin/dist/esm/index.js +1036 -0
  35. package/node_modules/@instantdb/admin/dist/esm/polyfill.d.ts +16 -0
  36. package/node_modules/@instantdb/admin/dist/esm/polyfill.js +21 -0
  37. package/node_modules/@instantdb/admin/dist/esm/subscribe.d.ts +38 -0
  38. package/node_modules/@instantdb/admin/dist/esm/subscribe.js +301 -0
  39. package/node_modules/@instantdb/admin/dist/esm/version.d.ts +2 -0
  40. package/node_modules/@instantdb/admin/dist/esm/version.js +2 -0
  41. package/node_modules/@instantdb/admin/package.json +23 -0
  42. package/node_modules/@instantdb/core/LICENSE +202 -0
  43. package/node_modules/@instantdb/core/dist/esm/Connection.d.ts +92 -0
  44. package/node_modules/@instantdb/core/dist/esm/Connection.js +188 -0
  45. package/node_modules/@instantdb/core/dist/esm/InMemoryStorage.d.ts +10 -0
  46. package/node_modules/@instantdb/core/dist/esm/InMemoryStorage.js +25 -0
  47. package/node_modules/@instantdb/core/dist/esm/IndexedDBStorage.d.ts +17 -0
  48. package/node_modules/@instantdb/core/dist/esm/IndexedDBStorage.js +309 -0
  49. package/node_modules/@instantdb/core/dist/esm/InstantError.d.ts +6 -0
  50. package/node_modules/@instantdb/core/dist/esm/InstantError.js +23 -0
  51. package/node_modules/@instantdb/core/dist/esm/Reactor.d.ts +430 -0
  52. package/node_modules/@instantdb/core/dist/esm/Reactor.js +2369 -0
  53. package/node_modules/@instantdb/core/dist/esm/StorageAPI.d.ts +39 -0
  54. package/node_modules/@instantdb/core/dist/esm/StorageAPI.js +65 -0
  55. package/node_modules/@instantdb/core/dist/esm/Stream.d.ts +120 -0
  56. package/node_modules/@instantdb/core/dist/esm/Stream.js +811 -0
  57. package/node_modules/@instantdb/core/dist/esm/SyncTable.d.ts +144 -0
  58. package/node_modules/@instantdb/core/dist/esm/SyncTable.js +523 -0
  59. package/node_modules/@instantdb/core/dist/esm/WindowNetworkListener.d.ts +4 -0
  60. package/node_modules/@instantdb/core/dist/esm/WindowNetworkListener.js +19 -0
  61. package/node_modules/@instantdb/core/dist/esm/attrTypes.d.ts +25 -0
  62. package/node_modules/@instantdb/core/dist/esm/attrTypes.js +1 -0
  63. package/node_modules/@instantdb/core/dist/esm/authAPI.d.ts +64 -0
  64. package/node_modules/@instantdb/core/dist/esm/authAPI.js +103 -0
  65. package/node_modules/@instantdb/core/dist/esm/clientTypes.d.ts +40 -0
  66. package/node_modules/@instantdb/core/dist/esm/clientTypes.js +1 -0
  67. package/node_modules/@instantdb/core/dist/esm/coreTypes.d.ts +33 -0
  68. package/node_modules/@instantdb/core/dist/esm/coreTypes.js +1 -0
  69. package/node_modules/@instantdb/core/dist/esm/createRouteHandler.d.ts +7 -0
  70. package/node_modules/@instantdb/core/dist/esm/createRouteHandler.js +51 -0
  71. package/node_modules/@instantdb/core/dist/esm/datalog.d.ts +7 -0
  72. package/node_modules/@instantdb/core/dist/esm/datalog.js +99 -0
  73. package/node_modules/@instantdb/core/dist/esm/devtool.d.ts +3 -0
  74. package/node_modules/@instantdb/core/dist/esm/devtool.js +144 -0
  75. package/node_modules/@instantdb/core/dist/esm/framework.d.ts +80 -0
  76. package/node_modules/@instantdb/core/dist/esm/framework.js +243 -0
  77. package/node_modules/@instantdb/core/dist/esm/helperTypes.d.ts +75 -0
  78. package/node_modules/@instantdb/core/dist/esm/helperTypes.js +1 -0
  79. package/node_modules/@instantdb/core/dist/esm/index.d.ts +597 -0
  80. package/node_modules/@instantdb/core/dist/esm/index.js +649 -0
  81. package/node_modules/@instantdb/core/dist/esm/infiniteQuery.d.ts +25 -0
  82. package/node_modules/@instantdb/core/dist/esm/infiniteQuery.js +430 -0
  83. package/node_modules/@instantdb/core/dist/esm/instaml.d.ts +17 -0
  84. package/node_modules/@instantdb/core/dist/esm/instaml.js +576 -0
  85. package/node_modules/@instantdb/core/dist/esm/instaql.d.ts +12 -0
  86. package/node_modules/@instantdb/core/dist/esm/instaql.js +632 -0
  87. package/node_modules/@instantdb/core/dist/esm/instatx.d.ts +127 -0
  88. package/node_modules/@instantdb/core/dist/esm/instatx.js +93 -0
  89. package/node_modules/@instantdb/core/dist/esm/model/instaqlResult.d.ts +7 -0
  90. package/node_modules/@instantdb/core/dist/esm/model/instaqlResult.js +24 -0
  91. package/node_modules/@instantdb/core/dist/esm/parseSchemaFromJSON.d.ts +2 -0
  92. package/node_modules/@instantdb/core/dist/esm/parseSchemaFromJSON.js +142 -0
  93. package/node_modules/@instantdb/core/dist/esm/presence.d.ts +50 -0
  94. package/node_modules/@instantdb/core/dist/esm/presence.js +50 -0
  95. package/node_modules/@instantdb/core/dist/esm/presenceTypes.d.ts +9 -0
  96. package/node_modules/@instantdb/core/dist/esm/presenceTypes.js +3 -0
  97. package/node_modules/@instantdb/core/dist/esm/queryTypes.d.ts +271 -0
  98. package/node_modules/@instantdb/core/dist/esm/queryTypes.js +3 -0
  99. package/node_modules/@instantdb/core/dist/esm/queryValidation.d.ts +5 -0
  100. package/node_modules/@instantdb/core/dist/esm/queryValidation.js +287 -0
  101. package/node_modules/@instantdb/core/dist/esm/reactorTypes.d.ts +29 -0
  102. package/node_modules/@instantdb/core/dist/esm/reactorTypes.js +1 -0
  103. package/node_modules/@instantdb/core/dist/esm/routeHandlerProtocol.d.ts +19 -0
  104. package/node_modules/@instantdb/core/dist/esm/routeHandlerProtocol.js +1 -0
  105. package/node_modules/@instantdb/core/dist/esm/rulesTypes.d.ts +85 -0
  106. package/node_modules/@instantdb/core/dist/esm/rulesTypes.js +1 -0
  107. package/node_modules/@instantdb/core/dist/esm/sanityCheckQueries.d.ts +18 -0
  108. package/node_modules/@instantdb/core/dist/esm/sanityCheckQueries.js +152 -0
  109. package/node_modules/@instantdb/core/dist/esm/schema.d.ts +72 -0
  110. package/node_modules/@instantdb/core/dist/esm/schema.js +128 -0
  111. package/node_modules/@instantdb/core/dist/esm/schemaTypes.d.ts +244 -0
  112. package/node_modules/@instantdb/core/dist/esm/schemaTypes.js +106 -0
  113. package/node_modules/@instantdb/core/dist/esm/store.d.ts +89 -0
  114. package/node_modules/@instantdb/core/dist/esm/store.js +722 -0
  115. package/node_modules/@instantdb/core/dist/esm/transactionValidation.d.ts +7 -0
  116. package/node_modules/@instantdb/core/dist/esm/transactionValidation.js +130 -0
  117. package/node_modules/@instantdb/core/dist/esm/utils/Deferred.d.ts +8 -0
  118. package/node_modules/@instantdb/core/dist/esm/utils/Deferred.js +17 -0
  119. package/node_modules/@instantdb/core/dist/esm/utils/PersistedObject.d.ts +80 -0
  120. package/node_modules/@instantdb/core/dist/esm/utils/PersistedObject.js +448 -0
  121. package/node_modules/@instantdb/core/dist/esm/utils/dates.d.ts +1 -0
  122. package/node_modules/@instantdb/core/dist/esm/utils/dates.js +211 -0
  123. package/node_modules/@instantdb/core/dist/esm/utils/error.d.ts +2 -0
  124. package/node_modules/@instantdb/core/dist/esm/utils/error.js +8 -0
  125. package/node_modules/@instantdb/core/dist/esm/utils/fetch.d.ts +125 -0
  126. package/node_modules/@instantdb/core/dist/esm/utils/fetch.js +31 -0
  127. package/node_modules/@instantdb/core/dist/esm/utils/flags.d.ts +4 -0
  128. package/node_modules/@instantdb/core/dist/esm/utils/flags.js +10 -0
  129. package/node_modules/@instantdb/core/dist/esm/utils/id.d.ts +3 -0
  130. package/node_modules/@instantdb/core/dist/esm/utils/id.js +25 -0
  131. package/node_modules/@instantdb/core/dist/esm/utils/linkIndex.d.ts +7 -0
  132. package/node_modules/@instantdb/core/dist/esm/utils/linkIndex.js +17 -0
  133. package/node_modules/@instantdb/core/dist/esm/utils/log.d.ts +6 -0
  134. package/node_modules/@instantdb/core/dist/esm/utils/log.js +13 -0
  135. package/node_modules/@instantdb/core/dist/esm/utils/object.d.ts +16 -0
  136. package/node_modules/@instantdb/core/dist/esm/utils/object.js +143 -0
  137. package/node_modules/@instantdb/core/dist/esm/utils/pgtime.d.ts +197 -0
  138. package/node_modules/@instantdb/core/dist/esm/utils/pgtime.js +197 -0
  139. package/node_modules/@instantdb/core/dist/esm/utils/pick.d.ts +1 -0
  140. package/node_modules/@instantdb/core/dist/esm/utils/pick.js +9 -0
  141. package/node_modules/@instantdb/core/dist/esm/utils/strings.d.ts +1 -0
  142. package/node_modules/@instantdb/core/dist/esm/utils/strings.js +15 -0
  143. package/node_modules/@instantdb/core/dist/esm/utils/weakHash.d.ts +15 -0
  144. package/node_modules/@instantdb/core/dist/esm/utils/weakHash.js +71 -0
  145. package/node_modules/@instantdb/core/dist/esm/utils/weakHashLegacy.d.ts +7 -0
  146. package/node_modules/@instantdb/core/dist/esm/utils/weakHashLegacy.js +72 -0
  147. package/node_modules/@instantdb/core/dist/esm/version.d.ts +2 -0
  148. package/node_modules/@instantdb/core/dist/esm/version.js +2 -0
  149. package/node_modules/@instantdb/core/dist/esm/warningToggle.d.ts +2 -0
  150. package/node_modules/@instantdb/core/dist/esm/warningToggle.js +4 -0
  151. package/node_modules/@instantdb/core/package.json +20 -0
  152. package/node_modules/@instantdb/eventsource/LICENSE +22 -0
  153. package/node_modules/@instantdb/eventsource/README.md +226 -0
  154. package/node_modules/@instantdb/eventsource/dist/index.cjs +279 -0
  155. package/node_modules/@instantdb/eventsource/dist/index.cjs.map +1 -0
  156. package/node_modules/@instantdb/eventsource/dist/index.d.cts +346 -0
  157. package/node_modules/@instantdb/eventsource/dist/index.d.ts +346 -0
  158. package/node_modules/@instantdb/eventsource/dist/index.js +279 -0
  159. package/node_modules/@instantdb/eventsource/dist/index.js.map +1 -0
  160. package/node_modules/@instantdb/eventsource/package.json +128 -0
  161. package/node_modules/@instantdb/eventsource/src/EventSource.ts +614 -0
  162. package/node_modules/@instantdb/eventsource/src/errors.ts +141 -0
  163. package/node_modules/@instantdb/eventsource/src/index.ts +3 -0
  164. package/node_modules/@instantdb/eventsource/src/types.ts +164 -0
  165. package/node_modules/@instantdb/react/LICENSE +202 -0
  166. package/node_modules/@instantdb/react/dist/esm/Cursors.d.ts +18 -0
  167. package/node_modules/@instantdb/react/dist/esm/Cursors.js +103 -0
  168. package/node_modules/@instantdb/react/dist/esm/InstantReactWebDatabase.d.ts +5 -0
  169. package/node_modules/@instantdb/react/dist/esm/InstantReactWebDatabase.js +5 -0
  170. package/node_modules/@instantdb/react/dist/esm/index.d.ts +6 -0
  171. package/node_modules/@instantdb/react/dist/esm/index.js +22 -0
  172. package/node_modules/@instantdb/react/dist/esm/init.d.ts +40 -0
  173. package/node_modules/@instantdb/react/dist/esm/init.js +49 -0
  174. package/node_modules/@instantdb/react/dist/esm/next-ssr/HydrationStreamProvider.d.ts +65 -0
  175. package/node_modules/@instantdb/react/dist/esm/next-ssr/HydrationStreamProvider.js +96 -0
  176. package/node_modules/@instantdb/react/dist/esm/next-ssr/InstantNextDatabase.d.ts +11 -0
  177. package/node_modules/@instantdb/react/dist/esm/next-ssr/InstantNextDatabase.js +31 -0
  178. package/node_modules/@instantdb/react/dist/esm/next-ssr/InstantSuspenseProvider.d.ts +24 -0
  179. package/node_modules/@instantdb/react/dist/esm/next-ssr/InstantSuspenseProvider.js +162 -0
  180. package/node_modules/@instantdb/react/dist/esm/next-ssr/getUserFromInstantCookie.d.ts +9 -0
  181. package/node_modules/@instantdb/react/dist/esm/next-ssr/getUserFromInstantCookie.js +16 -0
  182. package/node_modules/@instantdb/react/dist/esm/next-ssr/htmlescape.d.ts +2 -0
  183. package/node_modules/@instantdb/react/dist/esm/next-ssr/htmlescape.js +20 -0
  184. package/node_modules/@instantdb/react/dist/esm/next-ssr/index.d.ts +29 -0
  185. package/node_modules/@instantdb/react/dist/esm/next-ssr/index.js +34 -0
  186. package/node_modules/@instantdb/react/dist/esm/version.d.ts +2 -0
  187. package/node_modules/@instantdb/react/dist/esm/version.js +2 -0
  188. package/node_modules/@instantdb/react/package.json +24 -0
  189. package/node_modules/@instantdb/react-common/LICENSE +202 -0
  190. package/node_modules/@instantdb/react-common/dist/esm/InstantReactAbstractDatabase.d.ts +282 -0
  191. package/node_modules/@instantdb/react-common/dist/esm/InstantReactAbstractDatabase.js +386 -0
  192. package/node_modules/@instantdb/react-common/dist/esm/InstantReactRoom.d.ts +182 -0
  193. package/node_modules/@instantdb/react-common/dist/esm/InstantReactRoom.js +280 -0
  194. package/node_modules/@instantdb/react-common/dist/esm/index.d.ts +4 -0
  195. package/node_modules/@instantdb/react-common/dist/esm/index.js +3 -0
  196. package/node_modules/@instantdb/react-common/dist/esm/useInfiniteQuerySubscription.d.ts +27 -0
  197. package/node_modules/@instantdb/react-common/dist/esm/useInfiniteQuerySubscription.js +53 -0
  198. package/node_modules/@instantdb/react-common/dist/esm/useQuery.d.ts +6 -0
  199. package/node_modules/@instantdb/react-common/dist/esm/useQuery.js +75 -0
  200. package/node_modules/@instantdb/react-common/dist/esm/useTimeout.d.ts +4 -0
  201. package/node_modules/@instantdb/react-common/dist/esm/useTimeout.js +17 -0
  202. package/node_modules/@instantdb/react-common/dist/esm/version.d.ts +2 -0
  203. package/node_modules/@instantdb/react-common/dist/esm/version.js +2 -0
  204. package/node_modules/@instantdb/react-common/package.json +22 -0
  205. package/node_modules/@instantdb/version/LICENSE +202 -0
  206. package/node_modules/@instantdb/version/dist/esm/index.d.ts +2 -0
  207. package/node_modules/@instantdb/version/dist/esm/index.js +2 -0
  208. package/node_modules/@instantdb/version/dist/esm/version.d.ts +2 -0
  209. package/node_modules/@instantdb/version/dist/esm/version.js +5 -0
  210. package/node_modules/@instantdb/version/package.json +16 -0
  211. package/node_modules/@instantdb/webhooks/LICENSE +202 -0
  212. package/node_modules/@instantdb/webhooks/dist/esm/index.d.ts +587 -0
  213. package/node_modules/@instantdb/webhooks/dist/esm/index.js +748 -0
  214. package/node_modules/@instantdb/webhooks/package.json +18 -0
  215. package/node_modules/cookie/LICENSE +24 -0
  216. package/node_modules/cookie/README.md +295 -0
  217. package/node_modules/cookie/dist/index.d.ts +143 -0
  218. package/node_modules/cookie/dist/index.js +355 -0
  219. package/node_modules/cookie/dist/index.js.map +1 -0
  220. package/node_modules/cookie/package.json +57 -0
  221. package/node_modules/eventsource/LICENSE +22 -0
  222. package/node_modules/eventsource/README.md +252 -0
  223. package/node_modules/eventsource/dist/EventSource.d.ts +128 -0
  224. package/node_modules/eventsource/dist/EventSource.d.ts.map +1 -0
  225. package/node_modules/eventsource/dist/EventSource.js +556 -0
  226. package/node_modules/eventsource/dist/EventSource.js.map +1 -0
  227. package/node_modules/eventsource/dist/errors.d.ts +53 -0
  228. package/node_modules/eventsource/dist/errors.d.ts.map +1 -0
  229. package/node_modules/eventsource/dist/errors.js +120 -0
  230. package/node_modules/eventsource/dist/errors.js.map +1 -0
  231. package/node_modules/eventsource/dist/index.d.ts +4 -0
  232. package/node_modules/eventsource/dist/index.d.ts.map +1 -0
  233. package/node_modules/eventsource/dist/index.js +3 -0
  234. package/node_modules/eventsource/dist/index.js.map +1 -0
  235. package/node_modules/eventsource/dist/types.d.ts +156 -0
  236. package/node_modules/eventsource/dist/types.d.ts.map +1 -0
  237. package/node_modules/eventsource/dist/types.js +2 -0
  238. package/node_modules/eventsource/dist/types.js.map +1 -0
  239. package/node_modules/eventsource/node_modules/eventsource-parser/LICENSE +21 -0
  240. package/node_modules/eventsource/node_modules/eventsource-parser/README.md +177 -0
  241. package/node_modules/eventsource/node_modules/eventsource-parser/dist/errors.d.ts +35 -0
  242. package/node_modules/eventsource/node_modules/eventsource-parser/dist/errors.d.ts.map +1 -0
  243. package/node_modules/eventsource/node_modules/eventsource-parser/dist/errors.js +16 -0
  244. package/node_modules/eventsource/node_modules/eventsource-parser/dist/errors.js.map +1 -0
  245. package/node_modules/eventsource/node_modules/eventsource-parser/dist/index.d.ts +4 -0
  246. package/node_modules/eventsource/node_modules/eventsource-parser/dist/index.d.ts.map +1 -0
  247. package/node_modules/eventsource/node_modules/eventsource-parser/dist/index.js +3 -0
  248. package/node_modules/eventsource/node_modules/eventsource-parser/dist/index.js.map +1 -0
  249. package/node_modules/eventsource/node_modules/eventsource-parser/dist/parse.d.ts +12 -0
  250. package/node_modules/eventsource/node_modules/eventsource-parser/dist/parse.d.ts.map +1 -0
  251. package/node_modules/eventsource/node_modules/eventsource-parser/dist/parse.js +509 -0
  252. package/node_modules/eventsource/node_modules/eventsource-parser/dist/parse.js.map +1 -0
  253. package/node_modules/eventsource/node_modules/eventsource-parser/dist/stream.d.ts +76 -0
  254. package/node_modules/eventsource/node_modules/eventsource-parser/dist/stream.d.ts.map +1 -0
  255. package/node_modules/eventsource/node_modules/eventsource-parser/dist/stream.js +59 -0
  256. package/node_modules/eventsource/node_modules/eventsource-parser/dist/stream.js.map +1 -0
  257. package/node_modules/eventsource/node_modules/eventsource-parser/dist/types.d.ts +130 -0
  258. package/node_modules/eventsource/node_modules/eventsource-parser/dist/types.d.ts.map +1 -0
  259. package/node_modules/eventsource/node_modules/eventsource-parser/dist/types.js +1 -0
  260. package/node_modules/eventsource/node_modules/eventsource-parser/dist/types.js.map +1 -0
  261. package/node_modules/eventsource/node_modules/eventsource-parser/package.json +96 -0
  262. package/node_modules/eventsource/node_modules/eventsource-parser/src/errors.ts +44 -0
  263. package/node_modules/eventsource/node_modules/eventsource-parser/src/index.ts +3 -0
  264. package/node_modules/eventsource/node_modules/eventsource-parser/src/parse.ts +576 -0
  265. package/node_modules/eventsource/node_modules/eventsource-parser/src/stream.ts +118 -0
  266. package/node_modules/eventsource/node_modules/eventsource-parser/src/types.ts +138 -0
  267. package/node_modules/eventsource/package.json +103 -0
  268. package/node_modules/eventsource/src/EventSource.ts +844 -0
  269. package/node_modules/eventsource/src/errors.ts +141 -0
  270. package/node_modules/eventsource/src/index.ts +3 -0
  271. package/node_modules/eventsource/src/types.ts +166 -0
  272. package/node_modules/eventsource-parser/LICENSE +21 -0
  273. package/node_modules/eventsource-parser/README.md +157 -0
  274. package/node_modules/eventsource-parser/dist/index.cjs +177 -0
  275. package/node_modules/eventsource-parser/dist/index.cjs.map +1 -0
  276. package/node_modules/eventsource-parser/dist/index.d.cts +169 -0
  277. package/node_modules/eventsource-parser/dist/index.d.ts +169 -0
  278. package/node_modules/eventsource-parser/dist/index.js +177 -0
  279. package/node_modules/eventsource-parser/dist/index.js.map +1 -0
  280. package/node_modules/eventsource-parser/dist/stream.cjs +29 -0
  281. package/node_modules/eventsource-parser/dist/stream.cjs.map +1 -0
  282. package/node_modules/eventsource-parser/dist/stream.d.cts +134 -0
  283. package/node_modules/eventsource-parser/dist/stream.d.ts +134 -0
  284. package/node_modules/eventsource-parser/dist/stream.js +30 -0
  285. package/node_modules/eventsource-parser/dist/stream.js.map +1 -0
  286. package/node_modules/eventsource-parser/package.json +92 -0
  287. package/node_modules/eventsource-parser/src/errors.ts +44 -0
  288. package/node_modules/eventsource-parser/src/index.ts +8 -0
  289. package/node_modules/eventsource-parser/src/parse.ts +439 -0
  290. package/node_modules/eventsource-parser/src/stream.ts +107 -0
  291. package/node_modules/eventsource-parser/src/types.ts +122 -0
  292. package/node_modules/eventsource-parser/stream.js +2 -0
  293. package/node_modules/mutative/LICENSE +21 -0
  294. package/node_modules/mutative/README.md +870 -0
  295. package/node_modules/mutative/dist/apply.d.ts +31 -0
  296. package/node_modules/mutative/dist/array.d.ts +45 -0
  297. package/node_modules/mutative/dist/constant.d.ts +8 -0
  298. package/node_modules/mutative/dist/create.d.ts +46 -0
  299. package/node_modules/mutative/dist/current.d.ts +23 -0
  300. package/node_modules/mutative/dist/draft.d.ts +3 -0
  301. package/node_modules/mutative/dist/draftify.d.ts +2 -0
  302. package/node_modules/mutative/dist/error.d.ts +54 -0
  303. package/node_modules/mutative/dist/index.d.mts +1 -0
  304. package/node_modules/mutative/dist/index.d.ts +12 -0
  305. package/node_modules/mutative/dist/index.js +8 -0
  306. package/node_modules/mutative/dist/index.mjs +3 -0
  307. package/node_modules/mutative/dist/interface.d.ts +200 -0
  308. package/node_modules/mutative/dist/internal.d.ts +4 -0
  309. package/node_modules/mutative/dist/makeCreator.d.ts +54 -0
  310. package/node_modules/mutative/dist/map.d.ts +15 -0
  311. package/node_modules/mutative/dist/mutative.cjs.development.js +2126 -0
  312. package/node_modules/mutative/dist/mutative.cjs.development.js.map +1 -0
  313. package/node_modules/mutative/dist/mutative.cjs.production.min.js +2 -0
  314. package/node_modules/mutative/dist/mutative.cjs.production.min.js.map +1 -0
  315. package/node_modules/mutative/dist/mutative.esm.js +2123 -0
  316. package/node_modules/mutative/dist/mutative.esm.js.map +1 -0
  317. package/node_modules/mutative/dist/mutative.esm.mjs +2123 -0
  318. package/node_modules/mutative/dist/mutative.esm.mjs.map +1 -0
  319. package/node_modules/mutative/dist/mutative.esm.production.min.mjs +2 -0
  320. package/node_modules/mutative/dist/mutative.esm.production.min.mjs.map +1 -0
  321. package/node_modules/mutative/dist/mutative.umd.development.js +2132 -0
  322. package/node_modules/mutative/dist/mutative.umd.development.js.map +1 -0
  323. package/node_modules/mutative/dist/mutative.umd.production.min.js +2 -0
  324. package/node_modules/mutative/dist/mutative.umd.production.min.js.map +1 -0
  325. package/node_modules/mutative/dist/original.d.ts +19 -0
  326. package/node_modules/mutative/dist/patch.d.ts +2 -0
  327. package/node_modules/mutative/dist/rawReturn.d.ts +19 -0
  328. package/node_modules/mutative/dist/set.d.ts +14 -0
  329. package/node_modules/mutative/dist/unsafe.d.ts +34 -0
  330. package/node_modules/mutative/dist/utils/cast.d.ts +13 -0
  331. package/node_modules/mutative/dist/utils/copy.d.ts +5 -0
  332. package/node_modules/mutative/dist/utils/deepFreeze.d.ts +1 -0
  333. package/node_modules/mutative/dist/utils/draft.d.ts +27 -0
  334. package/node_modules/mutative/dist/utils/finalize.d.ts +13 -0
  335. package/node_modules/mutative/dist/utils/forEach.d.ts +1 -0
  336. package/node_modules/mutative/dist/utils/index.d.ts +7 -0
  337. package/node_modules/mutative/dist/utils/mark.d.ts +2 -0
  338. package/node_modules/mutative/dist/utils/marker.d.ts +5 -0
  339. package/node_modules/mutative/dist/utils/proto.d.ts +10 -0
  340. package/node_modules/mutative/package.json +142 -0
  341. package/node_modules/mutative/src/apply.ts +239 -0
  342. package/node_modules/mutative/src/array.ts +679 -0
  343. package/node_modules/mutative/src/constant.ts +17 -0
  344. package/node_modules/mutative/src/create.ts +27 -0
  345. package/node_modules/mutative/src/current.ts +206 -0
  346. package/node_modules/mutative/src/draft.ts +489 -0
  347. package/node_modules/mutative/src/draftify.ts +57 -0
  348. package/node_modules/mutative/src/error.ts +129 -0
  349. package/node_modules/mutative/src/index.ts +21 -0
  350. package/node_modules/mutative/src/interface.ts +321 -0
  351. package/node_modules/mutative/src/internal.ts +5 -0
  352. package/node_modules/mutative/src/makeCreator.ts +382 -0
  353. package/node_modules/mutative/src/map.ts +160 -0
  354. package/node_modules/mutative/src/original.ts +28 -0
  355. package/node_modules/mutative/src/patch.ts +386 -0
  356. package/node_modules/mutative/src/rawReturn.ts +41 -0
  357. package/node_modules/mutative/src/set.ts +201 -0
  358. package/node_modules/mutative/src/unsafe.ts +66 -0
  359. package/node_modules/mutative/src/utils/cast.ts +22 -0
  360. package/node_modules/mutative/src/utils/copy.ts +224 -0
  361. package/node_modules/mutative/src/utils/deepFreeze.ts +103 -0
  362. package/node_modules/mutative/src/utils/draft.ts +189 -0
  363. package/node_modules/mutative/src/utils/finalize.ts +232 -0
  364. package/node_modules/mutative/src/utils/forEach.ts +24 -0
  365. package/node_modules/mutative/src/utils/index.ts +7 -0
  366. package/node_modules/mutative/src/utils/mark.ts +11 -0
  367. package/node_modules/mutative/src/utils/marker.ts +34 -0
  368. package/node_modules/mutative/src/utils/proto.ts +38 -0
  369. package/node_modules/uuid/LICENSE.md +9 -0
  370. package/node_modules/uuid/README.md +491 -0
  371. package/node_modules/uuid/dist/index.d.ts +15 -0
  372. package/node_modules/uuid/dist/index.js +14 -0
  373. package/node_modules/uuid/dist/max.d.ts +2 -0
  374. package/node_modules/uuid/dist/max.js +1 -0
  375. package/node_modules/uuid/dist/md5.d.ts +2 -0
  376. package/node_modules/uuid/dist/md5.js +135 -0
  377. package/node_modules/uuid/dist/nil.d.ts +2 -0
  378. package/node_modules/uuid/dist/nil.js +1 -0
  379. package/node_modules/uuid/dist/parse.d.ts +3 -0
  380. package/node_modules/uuid/dist/parse.js +9 -0
  381. package/node_modules/uuid/dist/regex.d.ts +2 -0
  382. package/node_modules/uuid/dist/regex.js +1 -0
  383. package/node_modules/uuid/dist/rng.d.ts +1 -0
  384. package/node_modules/uuid/dist/rng.js +4 -0
  385. package/node_modules/uuid/dist/sha1.d.ts +2 -0
  386. package/node_modules/uuid/dist/sha1.js +70 -0
  387. package/node_modules/uuid/dist/stringify.d.ts +3 -0
  388. package/node_modules/uuid/dist/stringify.js +35 -0
  389. package/node_modules/uuid/dist/types.d.ts +22 -0
  390. package/node_modules/uuid/dist/types.js +1 -0
  391. package/node_modules/uuid/dist/uuid-bin.d.ts +1 -0
  392. package/node_modules/uuid/dist/uuid-bin.js +70 -0
  393. package/node_modules/uuid/dist/v1.d.ts +11 -0
  394. package/node_modules/uuid/dist/v1.js +87 -0
  395. package/node_modules/uuid/dist/v1ToV6.d.ts +3 -0
  396. package/node_modules/uuid/dist/v1ToV6.js +10 -0
  397. package/node_modules/uuid/dist/v3.d.ts +9 -0
  398. package/node_modules/uuid/dist/v3.js +9 -0
  399. package/node_modules/uuid/dist/v35.d.ts +7 -0
  400. package/node_modules/uuid/dist/v35.js +39 -0
  401. package/node_modules/uuid/dist/v4.d.ts +4 -0
  402. package/node_modules/uuid/dist/v4.js +29 -0
  403. package/node_modules/uuid/dist/v5.d.ts +9 -0
  404. package/node_modules/uuid/dist/v5.js +9 -0
  405. package/node_modules/uuid/dist/v6.d.ts +4 -0
  406. package/node_modules/uuid/dist/v6.js +20 -0
  407. package/node_modules/uuid/dist/v6ToV1.d.ts +2 -0
  408. package/node_modules/uuid/dist/v6ToV1.js +10 -0
  409. package/node_modules/uuid/dist/v7.d.ts +9 -0
  410. package/node_modules/uuid/dist/v7.js +68 -0
  411. package/node_modules/uuid/dist/validate.d.ts +2 -0
  412. package/node_modules/uuid/dist/validate.js +5 -0
  413. package/node_modules/uuid/dist/version.d.ts +2 -0
  414. package/node_modules/uuid/dist/version.js +8 -0
  415. package/node_modules/uuid/dist-node/bin/uuid +2 -0
  416. package/node_modules/uuid/dist-node/index.js +14 -0
  417. package/node_modules/uuid/dist-node/max.js +1 -0
  418. package/node_modules/uuid/dist-node/md5.js +11 -0
  419. package/node_modules/uuid/dist-node/nil.js +1 -0
  420. package/node_modules/uuid/dist-node/parse.js +9 -0
  421. package/node_modules/uuid/dist-node/regex.js +1 -0
  422. package/node_modules/uuid/dist-node/rng.js +4 -0
  423. package/node_modules/uuid/dist-node/sha1.js +11 -0
  424. package/node_modules/uuid/dist-node/stringify.js +35 -0
  425. package/node_modules/uuid/dist-node/types.js +1 -0
  426. package/node_modules/uuid/dist-node/uuid-bin.js +70 -0
  427. package/node_modules/uuid/dist-node/v1.js +87 -0
  428. package/node_modules/uuid/dist-node/v1ToV6.js +10 -0
  429. package/node_modules/uuid/dist-node/v3.js +9 -0
  430. package/node_modules/uuid/dist-node/v35.js +39 -0
  431. package/node_modules/uuid/dist-node/v4.js +29 -0
  432. package/node_modules/uuid/dist-node/v5.js +9 -0
  433. package/node_modules/uuid/dist-node/v6.js +20 -0
  434. package/node_modules/uuid/dist-node/v6ToV1.js +10 -0
  435. package/node_modules/uuid/dist-node/v7.js +68 -0
  436. package/node_modules/uuid/dist-node/validate.js +5 -0
  437. package/node_modules/uuid/dist-node/version.js +8 -0
  438. package/node_modules/uuid/package.json +115 -0
  439. package/package.json +80 -4
  440. package/release.json +78 -0
@@ -0,0 +1,748 @@
1
+ import { InstantAPIError, InstantError, version as coreVersion, } from '@instantdb/core';
2
+ const knownKeys = {
3
+ 'https://api.instantdb.com': {
4
+ keys: [
5
+ {
6
+ kty: 'OKP',
7
+ crv: 'Ed25519',
8
+ alg: 'EdDSA',
9
+ use: 'sig',
10
+ kid: '1034696293',
11
+ x: 'N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o',
12
+ },
13
+ ],
14
+ },
15
+ 'http://localhost:8888': {
16
+ keys: [
17
+ {
18
+ kty: 'OKP',
19
+ crv: 'Ed25519',
20
+ alg: 'EdDSA',
21
+ use: 'sig',
22
+ kid: '503090235',
23
+ x: 'qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow',
24
+ },
25
+ ],
26
+ },
27
+ };
28
+ function inferWebCryptoAlg(jwk) {
29
+ if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519') {
30
+ return { name: 'Ed25519' };
31
+ }
32
+ if (jwk.kty === 'EC') {
33
+ return { name: 'ECDSA', namedCurve: jwk.crv }; // e.g., P-256, P-384
34
+ }
35
+ if (jwk.kty === 'RSA') {
36
+ // RSA keys often specify the exact hash in the 'alg' field (e.g., RS256)
37
+ const hashMap = {
38
+ RS256: 'SHA-256',
39
+ RS384: 'SHA-384',
40
+ RS512: 'SHA-512',
41
+ };
42
+ return {
43
+ name: 'RSASSA-PKCS1-v1_5',
44
+ hash: hashMap[jwk.alg] || 'SHA-256',
45
+ };
46
+ }
47
+ throw new Error(`Unsupported JWK configuration: kty=${jwk.kty}, crv=${jwk.crv}`);
48
+ }
49
+ async function importKey(jwk) {
50
+ const alg = inferWebCryptoAlg(jwk);
51
+ const key = await crypto.subtle.importKey('jwk', jwk, alg, false, ['verify']);
52
+ return { alg, key };
53
+ }
54
+ function verify(alg, key, signature, message) {
55
+ return crypto.subtle.verify(alg, key, signature, message);
56
+ }
57
+ function hexToUint8Array(hexString) {
58
+ const bytes = new Uint8Array(Math.ceil(hexString.length / 2));
59
+ for (let i = 0; i < bytes.length; i++) {
60
+ bytes[i] = parseInt(hexString.substring(i * 2, i * 2 + 2), 16);
61
+ }
62
+ return bytes;
63
+ }
64
+ function parseSignatureHeader(h) {
65
+ let t, kid, v1;
66
+ for (const part of h.split(',')) {
67
+ const [k, v] = part.split('=');
68
+ switch (k) {
69
+ case 't': {
70
+ t = v;
71
+ break;
72
+ }
73
+ case 'kid': {
74
+ kid = v;
75
+ break;
76
+ }
77
+ case 'v1': {
78
+ v1 = v;
79
+ break;
80
+ }
81
+ }
82
+ }
83
+ const missingKeys = [];
84
+ if (!t) {
85
+ missingKeys.push('t');
86
+ }
87
+ if (!kid) {
88
+ missingKeys.push('kid');
89
+ }
90
+ if (!v1) {
91
+ missingKeys.push('v1');
92
+ }
93
+ if (missingKeys.length || !t || !kid || !v1) {
94
+ throw new InstantError('Invalid Instant-Signature header.', {
95
+ header: h,
96
+ missingKeys,
97
+ });
98
+ }
99
+ return { t, kid, v1 };
100
+ }
101
+ function validateT(receivedAt, t, tolerance) {
102
+ const age = Math.floor(receivedAt.getTime() / 1000) - parseInt(t, 10);
103
+ if (age > tolerance) {
104
+ throw new InstantError('Webhook signature is too old', {
105
+ tolerance,
106
+ receivedAt,
107
+ t,
108
+ });
109
+ }
110
+ }
111
+ // We make this a global cache so that it will survive across
112
+ // restarts. It will only store valid signing keys from instant, and we don't
113
+ // create many of them, so the memory usage will be only 1 or 2 keys.
114
+ const keyCache = {};
115
+ const defaultTolerance = 300; // 5 minutes
116
+ async function jsonReject(rejectFn, res) {
117
+ const body = await res.text();
118
+ try {
119
+ const json = JSON.parse(body);
120
+ return rejectFn(new InstantAPIError({ status: res.status, body: json }));
121
+ }
122
+ catch (_e) {
123
+ return rejectFn(new InstantAPIError({
124
+ status: res.status,
125
+ body: { type: undefined, message: body },
126
+ }));
127
+ }
128
+ }
129
+ const defaultJsonFetch = async (input, init) => {
130
+ const headers = {
131
+ ...(init?.headers || {}),
132
+ 'Instant-Core-Version': coreVersion,
133
+ };
134
+ const res = await fetch(input, { ...init, headers });
135
+ if (res.status === 200) {
136
+ return res.json();
137
+ }
138
+ return jsonReject((x) => Promise.reject(x), res);
139
+ };
140
+ function parseDate(s) {
141
+ return s ? new Date(s) : null;
142
+ }
143
+ function toWebhookInfo(raw) {
144
+ return {
145
+ id: raw.id,
146
+ sink: raw.sink,
147
+ namespaces: raw.namespaces ?? [],
148
+ actions: raw.actions,
149
+ status: raw.status,
150
+ disabledReason: raw.disabled_reason ?? null,
151
+ createdAt: new Date(raw.created_at),
152
+ updatedAt: new Date(raw.updated_at),
153
+ };
154
+ }
155
+ function toWebhookAttempt(raw) {
156
+ return {
157
+ attemptAt: parseDate(raw['attempt-at']),
158
+ durationMs: raw['duration-ms'] ?? null,
159
+ success: raw['success?'] ?? null,
160
+ statusCode: raw['status-code'] ?? null,
161
+ responseText: raw['response-text'] ?? null,
162
+ errorType: raw['error-type'] ?? null,
163
+ errorMessage: raw['error-message'] ?? null,
164
+ };
165
+ }
166
+ function toWebhookEventInfo(raw) {
167
+ return {
168
+ isn: raw.isn,
169
+ status: raw.status,
170
+ attempts: raw.attempts ? raw.attempts.map(toWebhookAttempt) : null,
171
+ nextAttemptAfter: parseDate(raw.next_attempt_after),
172
+ createdAt: new Date(raw.created_at),
173
+ updatedAt: new Date(raw.updated_at),
174
+ };
175
+ }
176
+ export class WebhooksManager {
177
+ #appId;
178
+ #apiURI;
179
+ #token;
180
+ #withAuth;
181
+ #jsonFetch;
182
+ constructor(opts) {
183
+ this.#appId = opts.appId;
184
+ this.#apiURI = opts.apiURI;
185
+ this.#token = opts.token;
186
+ this.#withAuth = opts.withAuth;
187
+ this.#jsonFetch = opts.jsonFetch;
188
+ }
189
+ #authedFetch(path, opts) {
190
+ if (!this.#appId) {
191
+ throw new InstantError('appId is required to manage webhooks. Pass it to the Webhooks constructor.');
192
+ }
193
+ const run = (token) => {
194
+ const init = {
195
+ method: opts?.method,
196
+ headers: {
197
+ authorization: `Bearer ${token}`,
198
+ 'content-type': 'application/json',
199
+ },
200
+ };
201
+ if (opts?.body !== undefined) {
202
+ init.body = JSON.stringify(opts.body);
203
+ }
204
+ return this.#jsonFetch(`${this.#apiURI}${path}`, init);
205
+ };
206
+ if (this.#withAuth) {
207
+ return this.#withAuth(run);
208
+ }
209
+ if (!this.#token) {
210
+ throw new InstantError('A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.');
211
+ }
212
+ return run(this.#token);
213
+ }
214
+ /**
215
+ * Returns every webhook configured on the app, newest first. Includes both
216
+ * active and disabled webhooks.
217
+ */
218
+ async list() {
219
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`);
220
+ return (res.webhooks || []).map(toWebhookInfo);
221
+ }
222
+ /**
223
+ * Creates a new webhook. The webhook is created in the `active` state and
224
+ * starts receiving matching events immediately.
225
+ *
226
+ * The server rejects the request if `url` is not an HTTPS URL pointing at a
227
+ * public host, if `namespaces` doesn't reference any entity in the app's
228
+ * schema, if `actions` is empty, or if the app has hit its webhook limit.
229
+ *
230
+ * An app may have at most **100 active webhooks** at a time; {@link delete}
231
+ * a webhook to free up a slot before creating another.
232
+ *
233
+ * @example
234
+ * const webhook = await db.webhooks.manager.create({
235
+ * url: 'https://example.com/instant',
236
+ * namespaces: ['posts', 'comments'],
237
+ * actions: ['create', 'update'],
238
+ * });
239
+ */
240
+ async create(params) {
241
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks`, {
242
+ method: 'POST',
243
+ body: params,
244
+ });
245
+ return toWebhookInfo(res.webhook);
246
+ }
247
+ /**
248
+ * Updates a webhook's `url`, `namespaces`, and/or `actions`. Pass only the
249
+ * fields you want to change; omitted fields keep their current value.
250
+ *
251
+ * Does not affect the webhook's status — use {@link enable} or
252
+ * {@link disable} for that.
253
+ */
254
+ async update(webhookId, params) {
255
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}`, { method: 'POST', body: params });
256
+ return toWebhookInfo(res.webhook);
257
+ }
258
+ /**
259
+ * Deletes a webhook. No further events will be queued for it. Returns the
260
+ * webhook as it looked just before deletion.
261
+ */
262
+ async delete(webhookId) {
263
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}`, { method: 'DELETE' });
264
+ return toWebhookInfo(res.webhook);
265
+ }
266
+ /**
267
+ * Re-enables a disabled webhook. Clears `disabledReason` and resumes
268
+ * delivery for new events. Has no effect if the webhook is already active.
269
+ *
270
+ * Events that occurred while the webhook was disabled are not retroactively
271
+ * delivered.
272
+ */
273
+ async enable(webhookId) {
274
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}/enable`, { method: 'POST', body: {} });
275
+ return toWebhookInfo(res.webhook);
276
+ }
277
+ /**
278
+ * Disables a webhook. No new events will be queued until it is re-enabled
279
+ * via {@link enable}. In-flight events already being processed will still
280
+ * complete.
281
+ *
282
+ * @param opts.reason Optional human-readable note stored on the webhook
283
+ * and surfaced in the dashboard.
284
+ */
285
+ async disable(webhookId, opts) {
286
+ const body = opts?.reason ? { reason: opts.reason } : {};
287
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}/disable`, { method: 'POST', body });
288
+ return toWebhookInfo(res.webhook);
289
+ }
290
+ /**
291
+ * Returns a page of events for a webhook, newest first.
292
+ *
293
+ * Events are retained for ~60 days. To paginate, pass the previous page's
294
+ * `pageInfo.endCursor` as `opts.after`; stop when `pageInfo.hasNextPage`
295
+ * is `false`.
296
+ */
297
+ async listEvents(webhookId, opts) {
298
+ const qs = opts?.after ? `?after=${encodeURIComponent(opts.after)}` : '';
299
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}/events${qs}`);
300
+ return {
301
+ events: (res.events || []).map(toWebhookEventInfo),
302
+ pageInfo: {
303
+ startCursor: res.pageInfo?.startCursor ?? null,
304
+ endCursor: res.pageInfo?.endCursor ?? null,
305
+ hasNextPage: !!res.pageInfo?.hasNextPage,
306
+ },
307
+ };
308
+ }
309
+ /**
310
+ * Fetches a single webhook event by its `isn`.
311
+ */
312
+ async getEvent(webhookId, isn) {
313
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`);
314
+ return toWebhookEventInfo(res.event);
315
+ }
316
+ /** Returns the full payload for an event. */
317
+ async getPayload(webhookId, isn) {
318
+ return this.#authedFetch(`/webhooks/payload/${this.#appId}/${webhookId}/${isn}`);
319
+ }
320
+ /**
321
+ * Re-queues an event for delivery, regardless of its current status. Use
322
+ * this to retry a `failed` event or force a redelivery of a `success` one.
323
+ *
324
+ * The server rate-limits resends; if the event was queued or resent very
325
+ * recently the call will fail with a validation error asking you to try
326
+ * again in about a minute.
327
+ */
328
+ async resendEvent(webhookId, isn) {
329
+ const res = await this.#authedFetch(`/dash/apps/${this.#appId}/webhooks/${webhookId}/events/${isn}`, { method: 'POST', body: {} });
330
+ return toWebhookEventInfo(res.event);
331
+ }
332
+ }
333
+ /**
334
+ * Verify incoming webhook requests from Instant, dispatch their records to
335
+ * typed handlers, and manage webhook subscriptions (via {@link manager}).
336
+ *
337
+ * Usually accessed as `db.webhooks` on the admin or platform SDK rather than
338
+ * constructed directly.
339
+ */
340
+ export class Webhooks {
341
+ /** App this instance is bound to. */
342
+ appId;
343
+ /** Schema used to type webhook payloads and handler records. */
344
+ schema;
345
+ #token;
346
+ /** Base URL for the Instant API. */
347
+ apiURI;
348
+ #jsonFetch;
349
+ /** Manage webhook subscriptions and inspect delivery events. */
350
+ manager;
351
+ /**
352
+ * Schema-bound helpers for building typed handler maps.
353
+ *
354
+ * - `typedHandlers(namespace, action, handler)` builds a single typed entry.
355
+ * Pass `'$default'` for `namespace` to register a catch-all handler.
356
+ * - `combineHandlers(...entries)` merges entries into a
357
+ * {@link WebhookHandlers} object suitable for {@link processPayload} and
358
+ * {@link processRequest}.
359
+ *
360
+ * If you already have a {@link Webhooks} instance, prefer the instance
361
+ * form (`db.webhooks.helpers()`) — it infers `Schema` automatically.
362
+ *
363
+ * @example
364
+ * const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();
365
+ * const handlers = combineHandlers(
366
+ * typedHandlers('posts', 'create', (record) => { ... }),
367
+ * typedHandlers('comments', '$default', (record) => { ... }),
368
+ * typedHandlers('$default', (record) => { ... }),
369
+ * );
370
+ */
371
+ static helpers() {
372
+ function typedHandlers(...args) {
373
+ if (args.length === 2) {
374
+ return { $default: args[1] };
375
+ }
376
+ const [namespace, action, handler] = args;
377
+ return { [namespace]: { [action]: handler } };
378
+ }
379
+ function combineHandlers(...entries) {
380
+ const result = {};
381
+ for (const entry of entries) {
382
+ for (const key of Object.keys(entry)) {
383
+ if (key === '$default') {
384
+ result.$default = entry.$default;
385
+ }
386
+ else {
387
+ result[key] = { ...result[key], ...entry[key] };
388
+ }
389
+ }
390
+ }
391
+ return result;
392
+ }
393
+ return {
394
+ typedHandlers: typedHandlers,
395
+ combineHandlers: combineHandlers,
396
+ };
397
+ }
398
+ /**
399
+ * Instance form of {@link Webhooks.helpers} that infers `Schema` from this
400
+ * instance — no `<typeof schema>` type argument required.
401
+ *
402
+ * @example
403
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
404
+ */
405
+ helpers() {
406
+ return Webhooks.helpers();
407
+ }
408
+ constructor(config, jsonFetch) {
409
+ this.appId = config.appId;
410
+ this.schema = config.schema;
411
+ this.#token = config.adminToken || config.token;
412
+ this.apiURI = config.apiURI || 'https://api.instantdb.com';
413
+ this.#jsonFetch = jsonFetch || defaultJsonFetch;
414
+ this.manager = new WebhooksManager({
415
+ appId: this.appId,
416
+ apiURI: this.apiURI,
417
+ token: this.#token,
418
+ withAuth: config.withAuth,
419
+ jsonFetch: this.#jsonFetch,
420
+ });
421
+ }
422
+ /** Fetches Instant's JWK set for verifying webhook signatures. */
423
+ async fetchJwks() {
424
+ const resp = await this.#jsonFetch(`${this.apiURI}/.well-known/webhooks/jwks.json`);
425
+ return resp;
426
+ }
427
+ /**
428
+ * Resolves a `kid` to an imported {@link CryptoKey}, hitting a
429
+ * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if
430
+ * the key isn't already known.
431
+ */
432
+ async keyOfKid(kid) {
433
+ const cacheKey = `${this.apiURI}:${kid}`;
434
+ const cached = keyCache[cacheKey];
435
+ if (cached) {
436
+ return cached;
437
+ }
438
+ const jwk = knownKeys[this.apiURI]?.keys.find((k) => k.kid === kid) ||
439
+ (await this.fetchJwks())?.keys?.find((k) => k.kid === kid);
440
+ if (!jwk) {
441
+ throw new InstantError('Could not find matching signing key', { kid });
442
+ }
443
+ const res = await importKey(jwk);
444
+ keyCache[cacheKey] = res;
445
+ return res;
446
+ }
447
+ /**
448
+ * Verifies an `Instant-Signature` header against a body and returns the
449
+ * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT
450
+ * `token` for fetching the records).
451
+ *
452
+ * Throws if the signature doesn't validate, the signature is older than
453
+ * `opts.tolerance` (default 300 seconds), or the body doesn't decode to
454
+ * the expected shape.
455
+ *
456
+ * @param body Either the raw body string, or a function returning it.
457
+ * Use a function to defer reading the body until after the
458
+ * header has been parsed.
459
+ */
460
+ async validate(signatureHeader, body, opts) {
461
+ const receivedAt = opts?.receivedAt || new Date();
462
+ const { t, kid, v1 } = parseSignatureHeader(signatureHeader);
463
+ const tolerance = opts?.tolerance ?? defaultTolerance;
464
+ validateT(receivedAt, t, tolerance);
465
+ const { alg, key } = await this.keyOfKid(kid);
466
+ const bodyText = typeof body === 'function' ? await body() : body;
467
+ const message = new TextEncoder().encode(`${t}.${bodyText}`);
468
+ const verified = await verify(alg, key, hexToUint8Array(v1), message);
469
+ if (!verified) {
470
+ throw new InstantError('Instant Signature did not validate', {
471
+ header: signatureHeader,
472
+ });
473
+ }
474
+ const res = JSON.parse(bodyText);
475
+ if (typeof res !== 'object' ||
476
+ typeof res.payloadUrl !== 'string' ||
477
+ typeof res.token !== 'string') {
478
+ throw new InstantError('Invalid webhook body, expected an object with payloadUrl and token fields', { body: res });
479
+ }
480
+ return res;
481
+ }
482
+ /**
483
+ * Pulls the `Instant-Signature` header and body from a `Request` and
484
+ * delegates to {@link validate}. Throws if the header is missing.
485
+ */
486
+ async validateRequest(req, opts) {
487
+ const signatureHeader = req.headers.get('instant-signature');
488
+ if (!signatureHeader) {
489
+ throw new InstantError('Request is missing Instant-Signature header');
490
+ }
491
+ return this.validate(signatureHeader, () => req.text(), opts);
492
+ }
493
+ /**
494
+ * Fetches the records and `idempotencyKey` for a validated
495
+ * {@link WebhookBody}, authenticating with the JWT `token` it carries.
496
+ */
497
+ fetchPayloads({ payloadUrl, token, }) {
498
+ return this.#jsonFetch(payloadUrl, {
499
+ headers: { Authorization: `Bearer ${token}`, accept: 'application/json' },
500
+ });
501
+ }
502
+ /**
503
+ * Dispatches each record in `payload` to its matching handler in
504
+ * `handlers`. Resolution order per record: exact `namespace` + `action` →
505
+ * `namespace`'s `$default` → top-level `$default`. Records with no matching
506
+ * handler are skipped.
507
+ *
508
+ * Handlers run concurrently. If any handler rejects, the call rejects so
509
+ * the caller (e.g. {@link processRequest}) can return a non-2xx response
510
+ * and let Instant retry the event.
511
+ */
512
+ async processPayload(handlers, payload) {
513
+ const results = [];
514
+ for (const record of payload.data) {
515
+ const { namespace, action } = record;
516
+ const handler = handlers?.[namespace]?.[action] ||
517
+ handlers?.[namespace]?.$default ||
518
+ handlers?.$default;
519
+ if (handler) {
520
+ // We need the as any here because typescript
521
+ // has trouble correlating the handler to the
522
+ // record namespace and action
523
+ results.push(handler(record));
524
+ }
525
+ }
526
+ await Promise.all(results);
527
+ }
528
+ /**
529
+ * The one-liner for handling webhooks. Hand it your handlers and the
530
+ * incoming `Request` — it verifies the signature, fetches the records, and
531
+ * dispatches each one to your code.
532
+ *
533
+ * Async handlers are executed in parallel, the return promise will resolve once
534
+ * all handlers complete and will reject if any of the handlers fails.
535
+ *
536
+ * @example
537
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
538
+ *
539
+ * const handlers = combineHandlers(
540
+ * typedHandlers('posts', 'create', async (record) => {
541
+ * await sendNewPostEmail(record.after);
542
+ * }),
543
+ * typedHandlers('$default', (record) => {
544
+ * console.log('webhook event', record);
545
+ * }),
546
+ * );
547
+ *
548
+ * export async function POST(req: Request) {
549
+ * await db.webhooks.processRequest(handlers, req);
550
+ * return new Response('ok');
551
+ * }
552
+ */
553
+ async processRequest(handlers, req, opts) {
554
+ const body = await this.validateRequest(req, opts);
555
+ const payload = await this.fetchPayloads(body);
556
+ await this.processPayload(handlers, payload);
557
+ }
558
+ /**
559
+ * Adapter for frameworks that hand you a Node-style `http.IncomingMessage`
560
+ * (Next.js Pages Router, Express, Koa, etc.) instead of a Web `Request`.
561
+ * Wraps the request in a Web `Request` and delegates to
562
+ * {@link processRequest}. You still send the HTTP response yourself.
563
+ *
564
+ * The raw body is required for signature verification. The adapter picks
565
+ * it up from one of:
566
+ *
567
+ * - `req.body` if it's a `Buffer` or `Uint8Array` (set by middleware like
568
+ * `express.raw({ type: 'application/json' })`)
569
+ * - `req.body` if it's a string (set by middleware like `express.text()`)
570
+ * - otherwise the unconsumed request stream
571
+ *
572
+ * Don't use a JSON body parser on this route — `express.json()` and
573
+ * `bodyParser: true` in Next.js both parse the body into an object,
574
+ * destroying the raw bytes the signature was computed over.
575
+ *
576
+ * @example
577
+ * // Next.js Pages Router (`pages/api/webhooks.ts`)
578
+ * import type { NextApiRequest, NextApiResponse } from 'next';
579
+ *
580
+ * export const config = { api: { bodyParser: false } };
581
+ *
582
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
583
+ *
584
+ * const handlers = combineHandlers(
585
+ * typedHandlers('posts', 'create', async (record) => {
586
+ * await sendNewPostEmail(record.after);
587
+ * }),
588
+ * typedHandlers('$default', (record) => {
589
+ * console.log('unhandled record', record);
590
+ * }),
591
+ * );
592
+ *
593
+ * export default async function handler(
594
+ * req: NextApiRequest,
595
+ * res: NextApiResponse,
596
+ * ) {
597
+ * try {
598
+ * await db.webhooks.processNodeRequest(handlers, req);
599
+ * res.status(200).end();
600
+ * } catch (e) {
601
+ * res.status(400).json({ error: String(e) });
602
+ * }
603
+ * }
604
+ *
605
+ * @example
606
+ * // Express — skip the JSON body parser on the webhook route and use
607
+ * // `express.raw()` so `req.body` arrives as a Buffer.
608
+ * import express from 'express';
609
+ *
610
+ * const app = express();
611
+ *
612
+ * app.use((req, res, next) => {
613
+ * if (req.originalUrl === '/webhooks/instant') return next();
614
+ * express.json()(req, res, next);
615
+ * });
616
+ *
617
+ * app.post(
618
+ * '/webhooks/instant',
619
+ * express.raw({ type: 'application/json' }),
620
+ * async (req, res) => {
621
+ * try {
622
+ * await db.webhooks.processNodeRequest(handlers, req);
623
+ * res.status(200).end();
624
+ * } catch (e) {
625
+ * res.status(400).json({ error: String(e) });
626
+ * }
627
+ * },
628
+ * );
629
+ *
630
+ * @example
631
+ * // Koa — `ctx.req` is the raw IncomingMessage. If `koa-bodyparser` (or
632
+ * // similar) runs on this route it consumes the stream, so either skip it
633
+ * // here or pull the raw body yourself and shim it onto the request:
634
+ * import Koa from 'koa';
635
+ * import Router from '@koa/router';
636
+ * import rawBody from 'raw-body';
637
+ *
638
+ * const router = new Router();
639
+ *
640
+ * router.post('/webhooks/instant', async (ctx) => {
641
+ * try {
642
+ * await db.webhooks.processNodeRequest(handlers, ctx.req, {
643
+ * body: rawBody(ctx.req), // adapter awaits the Promise
644
+ * });
645
+ * ctx.status = 200;
646
+ * } catch (e) {
647
+ * ctx.status = 400;
648
+ * ctx.body = { error: String(e) };
649
+ * }
650
+ * });
651
+ *
652
+ * @example
653
+ * // NestJS (Express adapter). With `rawBody: true` on the factory, Nest
654
+ * // populates `req.rawBody` itself — just pass `req`.
655
+ * import { Controller, Post, Req, HttpCode } from '@nestjs/common';
656
+ * import type { Request } from 'express';
657
+ *
658
+ * @Controller('webhooks')
659
+ * export class WebhooksController {
660
+ * @Post('instant')
661
+ * @HttpCode(200)
662
+ * async handle(@Req() req: Request) {
663
+ * await db.webhooks.processNodeRequest(handlers, req);
664
+ * }
665
+ * }
666
+ *
667
+ * // (Pair with `NestFactory.create(AppModule, { rawBody: true })` in main.ts.)
668
+ */
669
+ async processNodeRequest(handlers, req, opts) {
670
+ let rawBody;
671
+ let bodyWasReserialized = false;
672
+ // Priority: an explicit `opts.body`, then `req.rawBody` (set by
673
+ // middleware like Firebase Functions or body-parser's `verify` hook),
674
+ // then `req.body`, then the unconsumed request stream.
675
+ let bodyValue = opts?.body ?? req.rawBody ?? req.body;
676
+ // Allow callers to pass a Promise (e.g. the result of `raw-body(ctx.req)`
677
+ // in Koa) without having to await first.
678
+ if (bodyValue != null &&
679
+ typeof bodyValue.then === 'function') {
680
+ bodyValue = await bodyValue;
681
+ }
682
+ if (typeof bodyValue === 'string') {
683
+ rawBody = bodyValue;
684
+ }
685
+ else if (bodyValue instanceof Uint8Array) {
686
+ rawBody = new TextDecoder('utf-8').decode(bodyValue);
687
+ }
688
+ else if (bodyValue != null && typeof bodyValue === 'object') {
689
+ // A JSON parser middleware (e.g. `express.json()`) has consumed the
690
+ // stream and handed us a parsed object. Re-serialize and try anyway —
691
+ // for Instant's webhook body shape this typically round-trips to the
692
+ // bytes the server signed. If it doesn't, we surface a targeted error
693
+ // below.
694
+ try {
695
+ rawBody = JSON.stringify(bodyValue);
696
+ bodyWasReserialized = true;
697
+ }
698
+ catch {
699
+ throw new InstantError('Webhook request body has already been parsed and could not be re-serialized. Configure this route to receive the raw request body instead of parsed JSON.');
700
+ }
701
+ }
702
+ else if (req[Symbol.asyncIterator]) {
703
+ const encoder = new TextEncoder();
704
+ const chunks = [];
705
+ for await (const chunk of req) {
706
+ chunks.push(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);
707
+ }
708
+ let total = 0;
709
+ for (const c of chunks)
710
+ total += c.byteLength;
711
+ const buf = new Uint8Array(total);
712
+ let offset = 0;
713
+ for (const c of chunks) {
714
+ buf.set(c, offset);
715
+ offset += c.byteLength;
716
+ }
717
+ rawBody = new TextDecoder('utf-8').decode(buf);
718
+ }
719
+ else {
720
+ throw new InstantError('Could not read the webhook request body. Pass a Node IncomingMessage with an unconsumed stream, or set `req.body` to the raw bytes (Buffer/Uint8Array) or string.');
721
+ }
722
+ const host = typeof req.headers.host === 'string' ? req.headers.host : 'localhost';
723
+ const url = new URL(req.url ?? '/', `https://${host}`);
724
+ const headers = new Headers();
725
+ for (const [k, v] of Object.entries(req.headers)) {
726
+ if (typeof v === 'string')
727
+ headers.set(k, v);
728
+ else if (Array.isArray(v))
729
+ headers.set(k, v.join(', '));
730
+ }
731
+ const webReq = new Request(url, {
732
+ method: req.method ?? 'POST',
733
+ headers,
734
+ body: rawBody,
735
+ });
736
+ try {
737
+ await this.processRequest(handlers, webReq, opts);
738
+ }
739
+ catch (e) {
740
+ if (bodyWasReserialized &&
741
+ e instanceof InstantError &&
742
+ e.message === 'Instant Signature did not validate') {
743
+ throw new InstantError('Webhook signature did not validate. The request body was re-serialized from a parsed JSON object, which can produce different bytes than the server signed. Configure this route to receive the raw request body instead of parsed JSON.', { hint: e.hint });
744
+ }
745
+ throw e;
746
+ }
747
+ }
748
+ }