@hot-updater/server 1.0.0-rc.17 → 1.0.0-rc.18

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 (304) hide show
  1. package/dist/adapters/drizzle.cjs +5 -5
  2. package/dist/adapters/drizzle.mjs +4 -4
  3. package/dist/adapters/kysely.cjs +3 -3
  4. package/dist/adapters/kysely.mjs +2 -2
  5. package/dist/adapters/mongodb.cjs +3 -3
  6. package/dist/adapters/mongodb.mjs +2 -2
  7. package/dist/adapters/mongodbAdapter.cjs +19 -1
  8. package/dist/adapters/mongodbAdapter.mjs +19 -1
  9. package/dist/adapters/prisma.cjs +5 -5
  10. package/dist/adapters/prisma.mjs +4 -4
  11. package/dist/assembly/assemblePlugins.cjs +47 -28
  12. package/dist/assembly/assemblePlugins.d.cts +3 -7
  13. package/dist/assembly/assemblePlugins.d.mts +3 -7
  14. package/dist/assembly/assemblePlugins.mjs +46 -27
  15. package/dist/assembly/clientPlugins.cjs +86 -0
  16. package/dist/assembly/clientPlugins.d.cts +16 -0
  17. package/dist/assembly/clientPlugins.d.mts +16 -0
  18. package/dist/assembly/clientPlugins.mjs +86 -0
  19. package/dist/assembly/configError.cjs +7 -0
  20. package/dist/assembly/configError.d.cts +7 -0
  21. package/dist/assembly/configError.d.mts +7 -0
  22. package/dist/assembly/configError.mjs +7 -0
  23. package/dist/assembly/databasePlugins.cjs +5 -1
  24. package/dist/assembly/databasePlugins.d.cts +5 -5
  25. package/dist/assembly/databasePlugins.d.mts +5 -5
  26. package/dist/assembly/databasePlugins.mjs +5 -1
  27. package/dist/assembly/pluginCli.cjs +125 -0
  28. package/dist/assembly/pluginCli.d.cts +59 -0
  29. package/dist/assembly/pluginCli.d.mts +59 -0
  30. package/dist/assembly/pluginCli.mjs +121 -0
  31. package/dist/createHotUpdaterCore.cjs +14 -16
  32. package/dist/createHotUpdaterCore.d.cts +10 -3
  33. package/dist/createHotUpdaterCore.d.mts +10 -3
  34. package/dist/createHotUpdaterCore.mjs +11 -13
  35. package/dist/database/aggregateBatching.cjs +626 -0
  36. package/dist/database/aggregateBatching.d.cts +10 -0
  37. package/dist/database/aggregateBatching.d.mts +10 -0
  38. package/dist/database/aggregateBatching.mjs +625 -0
  39. package/dist/{insights/errors.cjs → database/busy.cjs} +2 -15
  40. package/dist/database/busy.d.cts +12 -0
  41. package/dist/database/busy.d.mts +12 -0
  42. package/dist/{insights/errors.mjs → database/busy.mjs} +3 -14
  43. package/dist/database/database.cjs +22 -3
  44. package/dist/database/database.d.cts +15 -2
  45. package/dist/database/database.d.mts +15 -2
  46. package/dist/database/database.mjs +22 -3
  47. package/dist/database/definitions.d.cts +10 -0
  48. package/dist/database/definitions.d.mts +10 -0
  49. package/dist/database/engine.d.cts +2 -1
  50. package/dist/database/engine.d.mts +2 -1
  51. package/dist/database/engineAggregates.cjs +7 -4
  52. package/dist/database/engineAggregates.mjs +8 -5
  53. package/dist/database/engineReads.cjs +5 -3
  54. package/dist/database/engineReads.mjs +6 -4
  55. package/dist/database/engineTransaction.cjs +2 -6
  56. package/dist/database/engineTransaction.mjs +2 -6
  57. package/dist/database/fence.cjs +2 -1
  58. package/dist/database/fence.mjs +2 -1
  59. package/dist/database/index.cjs +17 -8
  60. package/dist/database/index.d.cts +5 -4
  61. package/dist/database/index.d.mts +5 -4
  62. package/dist/database/index.mjs +6 -5
  63. package/dist/database/kv/kvAdapter.cjs +15 -3
  64. package/dist/database/kv/kvAdapter.d.cts +8 -0
  65. package/dist/database/kv/kvAdapter.d.mts +8 -0
  66. package/dist/database/kv/kvAdapter.mjs +16 -4
  67. package/dist/database/resolveSchema.cjs +4 -1
  68. package/dist/database/resolveSchema.d.cts +1 -1
  69. package/dist/database/resolveSchema.d.mts +1 -1
  70. package/dist/database/resolveSchema.mjs +4 -1
  71. package/dist/database/retention.cjs +92 -0
  72. package/dist/database/retention.mjs +90 -0
  73. package/dist/database/schema.cjs +5 -2
  74. package/dist/database/schema.d.cts +30 -1
  75. package/dist/database/schema.d.mts +30 -1
  76. package/dist/database/schema.mjs +5 -2
  77. package/dist/database/sql/sqlAdapter.cjs +8 -0
  78. package/dist/database/sql/sqlAdapter.mjs +9 -1
  79. package/dist/database/sql/sqlSchema.cjs +56 -0
  80. package/dist/database/sql/sqlSchema.mjs +55 -1
  81. package/dist/db/coreDatabase.cjs +85 -0
  82. package/dist/db/coreDatabase.d.cts +57 -0
  83. package/dist/db/coreDatabase.d.mts +57 -0
  84. package/dist/db/coreDatabase.mjs +78 -0
  85. package/dist/db/index.cjs +11 -1
  86. package/dist/db/index.d.cts +7 -2
  87. package/dist/db/index.d.mts +7 -2
  88. package/dist/db/index.mjs +6 -2
  89. package/dist/db/types.d.cts +3 -3
  90. package/dist/db/types.d.mts +3 -3
  91. package/dist/handler.cjs +2 -14
  92. package/dist/handler.mjs +1 -13
  93. package/dist/handlerReleaseCatalogRoutes.cjs +21 -2
  94. package/dist/handlerReleaseCatalogRoutes.mjs +21 -2
  95. package/dist/index.cjs +2 -6
  96. package/dist/index.d.cts +4 -7
  97. package/dist/index.d.mts +4 -7
  98. package/dist/index.mjs +2 -4
  99. package/dist/package.cjs +1 -1
  100. package/dist/package.mjs +1 -1
  101. package/dist/{apiKeys.cjs → plugins/api-keys/apiKeys.cjs} +1 -1
  102. package/dist/{apiKeys.d.cts → plugins/api-keys/apiKeys.d.cts} +2 -2
  103. package/dist/{apiKeys.d.mts → plugins/api-keys/apiKeys.d.mts} +2 -2
  104. package/dist/{apiKeys.mjs → plugins/api-keys/apiKeys.mjs} +1 -1
  105. package/dist/plugins/api-keys/cli.cjs +115 -0
  106. package/dist/plugins/api-keys/cli.mjs +114 -0
  107. package/dist/plugins/api-keys/index.cjs +9 -6
  108. package/dist/plugins/api-keys/index.d.cts +4 -5
  109. package/dist/plugins/api-keys/index.d.mts +4 -5
  110. package/dist/plugins/api-keys/index.mjs +9 -7
  111. package/dist/plugins/api-keys/model.d.cts +20 -2
  112. package/dist/plugins/api-keys/model.d.mts +20 -2
  113. package/dist/plugins/definePlugin.cjs +1 -1
  114. package/dist/plugins/definePlugin.d.cts +130 -3
  115. package/dist/plugins/definePlugin.d.mts +130 -3
  116. package/dist/plugins/definePlugin.mjs +1 -1
  117. package/dist/plugins/index.cjs +25 -4
  118. package/dist/plugins/index.d.cts +7 -4
  119. package/dist/plugins/index.d.mts +7 -4
  120. package/dist/plugins/index.mjs +6 -4
  121. package/dist/plugins/insights/contract.cjs +193 -0
  122. package/dist/plugins/insights/contract.mjs +189 -0
  123. package/dist/{insights → plugins/insights}/domain.d.cts +60 -15
  124. package/dist/{insights → plugins/insights}/domain.d.mts +60 -15
  125. package/dist/plugins/insights/errors.cjs +15 -0
  126. package/dist/plugins/insights/errors.mjs +14 -0
  127. package/dist/{insights → plugins/insights}/eventInput.cjs +155 -22
  128. package/dist/{insights → plugins/insights}/eventInput.mjs +155 -22
  129. package/dist/plugins/insights/eventRow.cjs +49 -0
  130. package/dist/plugins/insights/eventRow.d.cts +64 -0
  131. package/dist/plugins/insights/eventRow.d.mts +64 -0
  132. package/dist/plugins/insights/eventRow.mjs +47 -0
  133. package/dist/plugins/insights/index.cjs +106 -26
  134. package/dist/plugins/insights/index.d.cts +130 -27
  135. package/dist/plugins/insights/index.d.mts +130 -27
  136. package/dist/plugins/insights/index.mjs +106 -29
  137. package/dist/plugins/insights/model.cjs +2 -2
  138. package/dist/plugins/insights/model.d.cts +1 -1
  139. package/dist/plugins/insights/model.d.mts +1 -1
  140. package/dist/plugins/insights/model.mjs +1 -1
  141. package/dist/plugins/insights/modelTypes.d.cts +176 -0
  142. package/dist/plugins/insights/modelTypes.d.mts +176 -0
  143. package/dist/plugins/insights/overview.cjs +109 -0
  144. package/dist/plugins/insights/overview.d.cts +15 -0
  145. package/dist/plugins/insights/overview.d.mts +15 -0
  146. package/dist/plugins/insights/overview.mjs +107 -0
  147. package/dist/{insights → plugins/insights}/provider.cjs +33 -14
  148. package/dist/{insights → plugins/insights}/provider.d.cts +2 -2
  149. package/dist/{insights → plugins/insights}/provider.d.mts +2 -2
  150. package/dist/{insights → plugins/insights}/provider.mjs +30 -11
  151. package/dist/{insights → plugins/insights}/queryInput.cjs +2 -2
  152. package/dist/{insights → plugins/insights}/queryInput.mjs +2 -2
  153. package/dist/plugins/insights/reads.cjs +298 -88
  154. package/dist/plugins/insights/reads.d.cts +61 -0
  155. package/dist/plugins/insights/reads.d.mts +61 -0
  156. package/dist/plugins/insights/reads.mjs +298 -90
  157. package/dist/plugins/insights/recordEvent.cjs +223 -39
  158. package/dist/plugins/insights/recordEvent.d.cts +9 -4
  159. package/dist/plugins/insights/recordEvent.d.mts +9 -4
  160. package/dist/plugins/insights/recordEvent.mjs +221 -37
  161. package/dist/{insights → plugins/insights}/routes.cjs +3 -30
  162. package/dist/{insights → plugins/insights}/routes.mjs +4 -28
  163. package/dist/plugins/insights/schema.cjs +182 -40
  164. package/dist/plugins/insights/schema.d.cts +446 -6
  165. package/dist/plugins/insights/schema.d.mts +446 -6
  166. package/dist/plugins/insights/schema.mjs +180 -41
  167. package/dist/plugins/insights/testing/eventRow.d.mts +64 -0
  168. package/dist/plugins/insights/testing/expectInsightsIndex.mjs +18 -0
  169. package/dist/plugins/insights/testing/fixtures.d.mts +8 -0
  170. package/dist/plugins/insights/testing/fixtures.mjs +25 -0
  171. package/dist/plugins/insights/testing/index.d.mts +24 -0
  172. package/dist/plugins/insights/testing/index.mjs +25 -0
  173. package/dist/plugins/insights/testing/insightsModelTests.mjs +714 -0
  174. package/dist/plugins/insights/testing/modelTypes.d.mts +176 -0
  175. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.d.mts +11 -0
  176. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.mjs +107 -0
  177. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.d.mts +11 -0
  178. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.mjs +31 -0
  179. package/dist/plugins/insights/testing/types.d.mts +26 -0
  180. package/dist/{insights → plugins/insights}/types.d.cts +3 -2
  181. package/dist/{insights → plugins/insights}/types.d.mts +3 -2
  182. package/package.json +14 -7
  183. package/src/adapters/drizzle.conformance.integration.spec.ts +2 -2
  184. package/src/adapters/drizzle.readBudgets.integration.spec.ts +6 -4
  185. package/src/adapters/drizzle.spec.ts +15 -7
  186. package/src/adapters/drizzle.ts +6 -6
  187. package/src/adapters/kysely.conformance.integration.spec.ts +2 -2
  188. package/src/adapters/kysely.readBudgets.integration.spec.ts +4 -2
  189. package/src/adapters/kysely.spec.ts +13 -9
  190. package/src/adapters/kysely.ts +2 -2
  191. package/src/adapters/mongodb.integration.spec.ts +98 -7
  192. package/src/adapters/mongodb.ts +2 -2
  193. package/src/adapters/mongodbAdapter.ts +14 -0
  194. package/src/adapters/prisma.conformance.integration.spec.ts +2 -2
  195. package/src/adapters/prisma.integration.spec.ts +16 -8
  196. package/src/adapters/prisma.readBudgets.integration.spec.ts +5 -2
  197. package/src/adapters/prisma.spec.ts +17 -9
  198. package/src/adapters/prisma.ts +6 -6
  199. package/src/adapters/prismaTestClients.ts +8 -1
  200. package/src/assembly/assemblePlugins.ts +73 -40
  201. package/src/assembly/assembly.spec.ts +63 -11
  202. package/src/assembly/assembly.types.spec.ts +50 -2
  203. package/src/assembly/clientPlugins.ts +113 -0
  204. package/src/assembly/configError.ts +4 -0
  205. package/src/assembly/databasePlugins.ts +11 -5
  206. package/src/assembly/pluginCli.spec.ts +254 -0
  207. package/src/assembly/pluginCli.ts +248 -0
  208. package/src/assembly/{builtInRoutes.spec.ts → pluginRoutes.spec.ts} +10 -37
  209. package/src/createHotUpdaterCore.ts +21 -17
  210. package/src/database/aggregateBatching.spec.ts +577 -0
  211. package/src/database/aggregateBatching.ts +803 -0
  212. package/src/{insights/errors.spec.ts → database/busy.spec.ts} +2 -5
  213. package/src/{insights/errors.ts → database/busy.ts} +1 -13
  214. package/src/database/database.ts +39 -8
  215. package/src/database/definitions.ts +4 -0
  216. package/src/database/engineAggregates.spec.ts +4 -7
  217. package/src/database/engineAggregates.ts +5 -9
  218. package/src/database/engineReads.ts +7 -5
  219. package/src/database/engineTransaction.ts +1 -7
  220. package/src/database/fence.spec.ts +5 -5
  221. package/src/database/fence.ts +4 -0
  222. package/src/database/index.ts +13 -7
  223. package/src/database/kv/kvAdapter.batching.integration.spec.ts +15 -0
  224. package/src/database/kv/kvAdapter.conformance.integration.spec.ts +2 -0
  225. package/src/database/kv/kvAdapter.spec.ts +128 -1
  226. package/src/database/kv/kvAdapter.ts +30 -1
  227. package/src/database/kv/kvTestStore.ts +28 -1
  228. package/src/database/resolveSchema.ts +4 -1
  229. package/src/database/retention.spec.ts +314 -0
  230. package/src/database/retention.ts +129 -0
  231. package/src/database/schema.ts +44 -0
  232. package/src/database/sql/sqlAdapter.integration.spec.ts +4 -7
  233. package/src/database/sql/sqlAdapter.readBudgets.integration.spec.ts +18 -4
  234. package/src/database/sql/sqlAdapter.spec.ts +91 -3
  235. package/src/database/sql/sqlAdapter.ts +20 -0
  236. package/src/database/sql/sqlSchema.ts +81 -0
  237. package/src/databaseTestSuite.spec.ts +9 -4
  238. package/src/db/coreDatabase.ts +153 -0
  239. package/src/db/engineSql.spec.ts +8 -7
  240. package/src/db/index.ts +19 -1
  241. package/src/db/pluginTables.spec.ts +57 -27
  242. package/src/db/types.ts +3 -3
  243. package/src/handler-standalone.integration.spec.ts +2 -3
  244. package/src/handler.ts +1 -32
  245. package/src/handlerReleaseCatalogRoutes.ts +26 -2
  246. package/src/index.ts +0 -10
  247. package/src/{apiKeys.integration.spec.ts → plugins/api-keys/apiKeys.integration.spec.ts} +4 -4
  248. package/src/{apiKeys.spec.ts → plugins/api-keys/apiKeys.spec.ts} +3 -3
  249. package/src/{apiKeys.ts → plugins/api-keys/apiKeys.ts} +1 -1
  250. package/src/plugins/api-keys/apiKeysPlugin.spec.ts +11 -15
  251. package/src/plugins/api-keys/cli.spec.ts +187 -0
  252. package/src/plugins/api-keys/cli.ts +140 -0
  253. package/src/plugins/api-keys/index.ts +48 -41
  254. package/src/plugins/api-keys/model.ts +21 -2
  255. package/src/plugins/definePlugin.ts +144 -2
  256. package/src/plugins/index.ts +20 -2
  257. package/src/plugins/insights/contract.spec.ts +285 -0
  258. package/src/plugins/insights/contract.ts +372 -0
  259. package/src/{insights → plugins/insights}/domain.ts +73 -15
  260. package/src/plugins/insights/errors.ts +11 -0
  261. package/src/{insights → plugins/insights}/eventInput.ts +189 -29
  262. package/src/plugins/insights/eventRow.ts +209 -0
  263. package/src/plugins/insights/index.ts +181 -45
  264. package/src/{insights → plugins/insights}/insights.integration.spec.ts +330 -34
  265. package/src/plugins/insights/insightsRollout.integration.spec.ts +1 -2
  266. package/src/plugins/insights/model.spec.ts +3 -5
  267. package/src/plugins/insights/model.ts +2 -3
  268. package/src/plugins/insights/modelTypes.ts +197 -0
  269. package/src/plugins/insights/overview.spec.ts +64 -0
  270. package/src/plugins/insights/overview.ts +214 -0
  271. package/src/{insights → plugins/insights}/provider.spec.ts +21 -10
  272. package/src/{insights → plugins/insights}/provider.ts +58 -21
  273. package/src/{insights → plugins/insights}/queryInput.ts +2 -2
  274. package/src/plugins/insights/reads.spec.ts +340 -52
  275. package/src/plugins/insights/reads.ts +453 -123
  276. package/src/plugins/insights/recordEvent.spec.ts +474 -20
  277. package/src/plugins/insights/recordEvent.ts +301 -63
  278. package/src/plugins/insights/retention.spec.ts +115 -0
  279. package/src/{insights → plugins/insights}/routes.ts +1 -31
  280. package/src/plugins/insights/schema.ts +356 -176
  281. package/src/plugins/insights/testing/expectInsightsIndex.spec.ts +42 -0
  282. package/src/plugins/insights/testing/expectInsightsIndex.ts +20 -0
  283. package/src/plugins/insights/testing/fixtures.ts +30 -0
  284. package/src/plugins/insights/testing/index.ts +45 -0
  285. package/src/plugins/insights/testing/insightsModelTests.ts +860 -0
  286. package/src/plugins/insights/testing/setupInsightsHttpTestSuite.ts +152 -0
  287. package/src/plugins/insights/testing/setupInsightsModelTestSuite.ts +36 -0
  288. package/src/plugins/insights/testing/types.ts +30 -0
  289. package/src/{insights → plugins/insights}/types.ts +1 -1
  290. package/src/readBudgets.testFixtures.ts +2 -2
  291. package/src/releaseCatalogRoutes.integration.spec.ts +7 -0
  292. package/src/retention.spec.ts +73 -0
  293. package/src/runtime.spec.ts +11 -12
  294. package/src/runtime.testFixtures.ts +7 -2
  295. package/src/testUtilsMutation.integration.spec.ts +2 -1
  296. package/src/testUtilsPackage.integration.spec.ts +7 -3
  297. package/dist/db/builtInDatabase.cjs +0 -104
  298. package/dist/db/builtInDatabase.d.cts +0 -38
  299. package/dist/db/builtInDatabase.d.mts +0 -38
  300. package/dist/db/builtInDatabase.mjs +0 -97
  301. package/dist/plugins/builtIn.cjs +0 -7
  302. package/dist/plugins/builtIn.mjs +0 -6
  303. package/src/db/builtInDatabase.ts +0 -149
  304. package/src/plugins/builtIn.ts +0 -5
package/src/db/types.ts CHANGED
@@ -51,7 +51,7 @@ export interface Migrator {
51
51
 
52
52
  /**
53
53
  * The tables `db migrate` and `db generate` create and the settings rows they
54
- * write: the built-in ones, and each third-party plugin's the server runs.
54
+ * write: core's, and those of each plugin the server runs.
55
55
  */
56
56
  export interface ToolingTarget {
57
57
  readonly schema: ResolvedSchema;
@@ -69,8 +69,8 @@ export type SchemaGenerator = (
69
69
 
70
70
  /**
71
71
  * What `hot-updater db generate` and `db migrate` run for a provider's
72
- * database, beside the database itself. Without a target they cover the
73
- * built-in tables.
72
+ * database, beside the database itself. Without a target they cover core's
73
+ * tables.
74
74
  */
75
75
  export interface DatabaseTooling {
76
76
  readonly provider?: ORMProvider;
@@ -290,7 +290,7 @@ describe("Insights through a self-hosted server's admin API", () => {
290
290
  );
291
291
  });
292
292
 
293
- it("reads events with the repository's headers, and a server without insights() says it is off", async () => {
293
+ it("reads events with the repository's headers, and a server without insights() serves no Insights route", async () => {
294
294
  const on = standaloneRepository({
295
295
  baseUrl: `${baseUrl}/hot-updater/admin`,
296
296
  });
@@ -300,8 +300,7 @@ describe("Insights through a self-hosted server's admin API", () => {
300
300
 
301
301
  const off = standaloneRepository({ baseUrl: `${baseUrl}${offPath}/admin` });
302
302
  const offResponse = await off.fetchAdmin("/events?limit=1");
303
- expect(offResponse.status).toBe(204);
304
- expect(offResponse.headers.get("x-hot-updater-insights")).toBe("disabled");
303
+ expect(offResponse.status).toBe(404);
305
304
  });
306
305
 
307
306
  it("lists the plugins each server runs on its admin /version, as the console reads them", async () => {
package/src/handler.ts CHANGED
@@ -11,11 +11,6 @@ import type {
11
11
  RouteHandler,
12
12
  } from "./handlerTypes";
13
13
  import { createVersionRouteHandlers } from "./handlerVersionRoutes";
14
- import {
15
- createDroppedEventHandler,
16
- INSIGHTS_ROUTES,
17
- insightsDisabled,
18
- } from "./insights/routes";
19
14
  import { addRoute, createRouter, findRoute } from "./internalRouter";
20
15
 
21
16
  export type {
@@ -193,10 +188,7 @@ export interface HotUpdaterHandlersOptions {
193
188
  token: string,
194
189
  signature: string,
195
190
  ) => Promise<Response | null>;
196
- /**
197
- * The plugins' endpoints; an Insights route none serves answers that
198
- * Insights is off, and `POST /events` also warns on the first event it drops.
199
- */
191
+ /** The plugins' endpoints; a route no plugin serves answers 404. */
200
192
  readonly endpoints?: readonly MountedEndpoint[];
201
193
  /** The ids of the plugins the server runs, which the admin `/version` lists. */
202
194
  readonly plugins?: readonly string[];
@@ -213,10 +205,6 @@ export function createHotUpdaterHandlers({
213
205
  ...createVersionRouteHandlers(plugins),
214
206
  ...createReleaseCatalogRouteHandlers(),
215
207
  ...createAdminRouteHandlers(),
216
- ...Object.fromEntries(
217
- INSIGHTS_ROUTES.map(({ handler }) => [handler, insightsDisabled]),
218
- ),
219
- appendBundleEvent: createDroppedEventHandler(),
220
208
  ...(downloadStorageObject === undefined
221
209
  ? {}
222
210
  : {
@@ -250,23 +238,6 @@ export function createHotUpdaterHandlers({
250
238
  : "client",
251
239
  });
252
240
  };
253
- /** The Insights routes no plugin endpoint serves, which answer that Insights is off. */
254
- const mountInsights = (
255
- access: "client" | "admin",
256
- add: (method: string, path: string, handler: string) => void,
257
- ) => {
258
- for (const route of INSIGHTS_ROUTES) {
259
- const served = endpoints.some(
260
- (endpoint) =>
261
- endpoint.access === route.access &&
262
- endpoint.method === route.method &&
263
- endpoint.path === route.path,
264
- );
265
- if (route.access === access && !served) {
266
- add(route.method, route.path, route.handler);
267
- }
268
- }
269
- };
270
241
  const clientRouter = createRouter<string>();
271
242
  const addClientRoute = mount(clientRouter, false);
272
243
  addClientRoute("GET", "/version", "version");
@@ -292,7 +263,6 @@ export function createHotUpdaterHandlers({
292
263
  "/artifacts/v1/:targetBundleId/from/:currentBundleId",
293
264
  "artifactV1",
294
265
  );
295
- mountInsights("client", addClientRoute);
296
266
 
297
267
  const adminRouter = createRouter<string>();
298
268
  const addAdminRoute = mount(adminRouter, true);
@@ -302,7 +272,6 @@ export function createHotUpdaterHandlers({
302
272
  for (const route of ADMIN_ROUTES) {
303
273
  addAdminRoute(route.method, route.path, route.handler);
304
274
  }
305
- mountInsights("admin", addAdminRoute);
306
275
  for (const endpoint of endpoints) {
307
276
  const name = `plugin ${endpoint.plugin}: ${endpoint.method} ${endpoint.path}`;
308
277
  routeHandlers[name] = (params, request) =>
@@ -10,6 +10,10 @@ const ARTIFACT_CONTENT_TYPE =
10
10
  "application/vnd.hot-updater.artifact+json; version=1";
11
11
  const ORIGIN_CACHE_TTL_MS = 5_000;
12
12
  const ORIGIN_CACHE_MAX_ENTRIES = 128;
13
+ /** Marks the 404 of a scope that has no catalog. */
14
+ const NO_CATALOG_HEADER = "x-hot-updater-catalog";
15
+ /** A shared cache keeps a catalog, or a scope's lack of one, five seconds. */
16
+ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
13
17
 
14
18
  const privateNotFound = (): Response =>
15
19
  Response.json(
@@ -20,6 +24,26 @@ const privateNotFound = (): Response =>
20
24
  },
21
25
  );
22
26
 
27
+ /**
28
+ * A scope with no catalog yet, such as a store version before its first
29
+ * OTA release: cached like a catalog, so its update checks don't all reach
30
+ * the origin, and it holds nothing an API key protects. The header tells it
31
+ * apart from a 404 for a wrong URL: clients read it as "no update", and
32
+ * doctor as a live catalog route.
33
+ */
34
+ const missingCatalog = (): Response =>
35
+ Response.json(
36
+ { error: "Not found" },
37
+ {
38
+ status: 404,
39
+ headers: {
40
+ "cache-control": CATALOG_CACHE_CONTROL,
41
+ vary: "Accept-Encoding",
42
+ [NO_CATALOG_HEADER]: "none",
43
+ },
44
+ },
45
+ );
46
+
23
47
  const responseHash = async (body: string): Promise<string> => {
24
48
  const digest = await crypto.subtle.digest(
25
49
  "SHA-256",
@@ -34,11 +58,11 @@ const catalogResponse = async (
34
58
  catalog: ReleaseCatalog | null,
35
59
  request: Request,
36
60
  ): Promise<Response> => {
37
- if (catalog === null) return privateNotFound();
61
+ if (catalog === null) return missingCatalog();
38
62
  const body = JSON.stringify(catalog);
39
63
  const etag = `"sha256:${await responseHash(body)}"`;
40
64
  const headers = {
41
- "cache-control": "public, max-age=0, s-maxage=5",
65
+ "cache-control": CATALOG_CACHE_CONTROL,
42
66
  "content-type": CATALOG_CONTENT_TYPE,
43
67
  etag,
44
68
  vary: "Accept-Encoding",
package/src/index.ts CHANGED
@@ -1,20 +1,10 @@
1
1
  export type { HotUpdaterHandler, HotUpdaterHandlers } from "./handler";
2
- export { createInsightsProvider } from "./insights/provider";
3
- export type * from "./insights/domain";
4
- export type * from "./insights/types";
5
- export { API_KEY_HEADER_NAME } from "./apiKeys";
6
- export type {
7
- ApiKeyManagementAPI,
8
- ApiKeyMetadata,
9
- CreatedApiKey,
10
- } from "./apiKeys";
11
2
  export { createHotUpdater } from "./createHotUpdaterCore";
12
3
  export type {
13
4
  ClientAccessPolicy,
14
5
  ClientAccessRule,
15
6
  CreateHotUpdaterOptions,
16
7
  HotUpdaterAPI,
17
- RemovedClientAccess,
18
8
  RuntimeHotUpdaterAPI,
19
9
  } from "./createHotUpdaterCore";
20
10
  export { HotUpdaterConfigError } from "./assembly/assemblePlugins";
@@ -1,9 +1,9 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
 
3
- import { API_KEY_HEADER_NAME, createHotUpdater } from "./index";
4
- import { apiKeys } from "./plugins/api-keys";
5
- import { insights } from "./plugins/insights";
6
- import { createRuntimeDatabase } from "./runtime.testFixtures";
3
+ import { createHotUpdater } from "../../index";
4
+ import { createRuntimeDatabase } from "../../runtime.testFixtures";
5
+ import { insights } from "../insights";
6
+ import { API_KEY_HEADER_NAME, apiKeys } from "./index";
7
7
 
8
8
  const API_KEY = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE";
9
9
  const updateUrl =
@@ -1,6 +1,8 @@
1
1
  import { createMemoryAdapter } from "@hot-updater/plugin-core/internal";
2
2
  import { describe, expect, it } from "vitest";
3
3
 
4
+ import { createDatabaseEngine } from "../../database/database";
5
+ import { resolveSchema } from "../../database/resolveSchema";
4
6
  import {
5
7
  API_KEY_HEADER_NAME,
6
8
  authenticateApiKey,
@@ -11,9 +13,7 @@ import {
11
13
  provisionApiKey,
12
14
  registerApiKey,
13
15
  } from "./apiKeys";
14
- import { createDatabaseEngine } from "./database/database";
15
- import { resolveSchema } from "./database/resolveSchema";
16
- import { apiKeysSchema, createApiKeyModel } from "./plugins/api-keys";
16
+ import { apiKeysSchema, createApiKeyModel } from "./index";
17
17
 
18
18
  /** The api-keys plugin's table model on an empty in-memory database. */
19
19
  const createModel = () => {
@@ -1,4 +1,4 @@
1
- import type { ApiKeyModel, ApiKeyRow } from "@hot-updater/plugin-core";
1
+ import type { ApiKeyModel, ApiKeyRow } from "./model";
2
2
 
3
3
  export const API_KEY_HEADER_NAME = "x-api-key";
4
4
 
@@ -2,7 +2,7 @@ import {
2
2
  createMemoryAdapter,
3
3
  type DatabaseAdapter,
4
4
  } from "@hot-updater/plugin-core/internal";
5
- import { describe, expect, it, vi } from "vitest";
5
+ import { describe, expect, it } from "vitest";
6
6
 
7
7
  import { createHotUpdater } from "../../createHotUpdaterCore";
8
8
  import { definePlugin } from "../definePlugin";
@@ -70,21 +70,17 @@ describe("API keys plugin", () => {
70
70
  expect((await client(catalog, { "x-api-key": "not-a-key" })).status).toBe(
71
71
  401,
72
72
  );
73
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
74
- expect(
75
- (await client("/events", {}, { method: "POST", body: "{" })).status,
76
- ).toBe(401);
77
- expect(warn).not.toHaveBeenCalled();
78
- // Past the key, /events answers that Insights is off: no insights() here.
79
- const events = await client(
80
- "/events",
73
+ // No insights() here, so /events is no route, with or without a key.
74
+ const keyed: readonly Record<string, string>[] = [
75
+ {},
81
76
  { "x-api-key": API_KEY },
82
- { method: "POST", body: "{" },
83
- );
84
- expect(events.status).toBe(204);
85
- expect(events.headers.get("x-hot-updater-insights")).toBe("disabled");
86
- expect(warn).toHaveBeenCalledOnce();
87
- warn.mockRestore();
77
+ ];
78
+ for (const headers of keyed) {
79
+ expect(
80
+ (await client("/events", headers, { method: "POST", body: "{" }))
81
+ .status,
82
+ ).toBe(404);
83
+ }
88
84
  const allowed = await client("/cached", { "x-api-key": API_KEY });
89
85
  expect(allowed.status).toBe(200);
90
86
  expect(allowed.headers.get("vary")).toBe("x-api-key");
@@ -0,0 +1,187 @@
1
+ import { createMemoryAdapter } from "@hot-updater/plugin-core/internal";
2
+ import { describe, expect, it, vi } from "vitest";
3
+
4
+ import { createDatabasePluginApis } from "../../assembly/databasePlugins";
5
+ import type { PluginCommand, PluginCommandUi } from "../definePlugin";
6
+ import type { ApiKeyMetadata } from "./apiKeys";
7
+ import { type ApiKeysCliApi, apiKeysCli } from "./cli";
8
+ import { apiKeys } from "./index";
9
+
10
+ /** A UI that keeps what the command writes, unstyled. */
11
+ const createUi = () => {
12
+ const output = { messages: [] as string[], warnings: [] as string[] };
13
+ const printed: string[] = [];
14
+ const ui: PluginCommandUi = {
15
+ block: (heading, lines) => [heading, ...lines].join("\n"),
16
+ kv: (label, value) => `${label}: ${value}`,
17
+ table: (columns, rows) =>
18
+ rows
19
+ .map((row) => columns.map(({ key }) => row[key]).join(" | "))
20
+ .join("\n"),
21
+ id: (value) => value,
22
+ muted: (value) => value,
23
+ success: (value) => value,
24
+ danger: (value) => value,
25
+ warning: (value) => value,
26
+ message: (text) => output.messages.push(text),
27
+ info: (text) => output.messages.push(text),
28
+ warn: (text) => output.warnings.push(text),
29
+ print: (text) => printed.push(text),
30
+ confirm: vi.fn(async () => {}),
31
+ };
32
+ return { ui, output, printed };
33
+ };
34
+
35
+ const command = (name: string): PluginCommand<ApiKeysCliApi> => {
36
+ const group = apiKeysCli("x-api-key").commands?.[0];
37
+ const found = group?.commands?.find((candidate) => candidate.name === name);
38
+ if (found?.run === undefined) throw new Error(`No ${name} command.`);
39
+ return found;
40
+ };
41
+
42
+ /** The apiKeys() plugin's API over a memory adapter, as the CLI assembles it. */
43
+ const assemble = () =>
44
+ createDatabasePluginApis({ name: "memory", adapter: createMemoryAdapter() }, [
45
+ apiKeys(),
46
+ ]).apiKeys;
47
+
48
+ describe("apiKeys() CLI commands", () => {
49
+ it("adds `hot-updater api-key` with create, list, and revoke", () => {
50
+ const [group] = apiKeysCli("x-api-key").commands ?? [];
51
+ expect(group?.name).toBe("api-key");
52
+ expect(group?.commands?.map(({ name }) => name)).toEqual([
53
+ "create",
54
+ "list",
55
+ "revoke",
56
+ ]);
57
+ expect(apiKeys().cli?.commands?.map(({ name }) => name)).toEqual([
58
+ "api-key",
59
+ ]);
60
+ });
61
+
62
+ it("creates a key and prints its plaintext exactly once", async () => {
63
+ const api = assemble();
64
+ const { ui, output } = createUi();
65
+
66
+ await command("create").run!({
67
+ api,
68
+ args: {},
69
+ options: { name: "Production app" },
70
+ ui,
71
+ });
72
+
73
+ const [record] = await api.list();
74
+ expect(record?.name).toBe("Production app");
75
+ const printed = output.messages.join("\n");
76
+ const apiKey = /API key: (\S+)/u.exec(printed)?.[1];
77
+ expect(apiKey).toMatch(/^[A-Za-z0-9_-]{43}$/u);
78
+ expect(printed.split(apiKey!).length - 1).toBe(1);
79
+ expect(JSON.stringify(record)).not.toContain(apiKey);
80
+ expect(output.warnings).toEqual([
81
+ "Save this API key now. It will not be shown again.",
82
+ ]);
83
+ });
84
+
85
+ it("lists JSON metadata newest first, without hashes or plaintext", async () => {
86
+ const api = assemble();
87
+ const older = await api.create({ name: "Older" });
88
+ await new Promise((resolve) => setTimeout(resolve, 2));
89
+ const newer = await api.create({ name: "Newer" });
90
+ const { ui, printed } = createUi();
91
+
92
+ await command("list").run!({ api, args: {}, options: { json: true }, ui });
93
+
94
+ const json = printed.join("\n");
95
+ const records = JSON.parse(json) as ApiKeyMetadata[];
96
+ expect(records.map(({ id }) => id)).toEqual([
97
+ newer.record.id,
98
+ older.record.id,
99
+ ]);
100
+ expect(json).not.toContain("hash");
101
+ expect(json).not.toContain(older.apiKey);
102
+ });
103
+
104
+ it("lists a table, or says there are no keys", async () => {
105
+ const api = assemble();
106
+ const empty = createUi();
107
+ await command("list").run!({
108
+ api,
109
+ args: {},
110
+ options: {},
111
+ ui: empty.ui,
112
+ });
113
+ expect(empty.output.messages).toEqual(["(no API keys)"]);
114
+
115
+ const created = await api.create({ name: "Production app" });
116
+ await api.revoke({ id: created.record.id });
117
+ const listed = createUi();
118
+ await command("list").run!({
119
+ api,
120
+ args: {},
121
+ options: {},
122
+ ui: listed.ui,
123
+ });
124
+ expect(listed.output.messages[0]).toContain(
125
+ `${created.record.id} | Production app | ${created.apiKey.slice(0, 6)} | revoked`,
126
+ );
127
+ });
128
+
129
+ it("confirms before revoking unless --yes is set", async () => {
130
+ const api = assemble();
131
+ const created = await api.create({ name: "Production app" });
132
+ const { ui, output } = createUi();
133
+
134
+ await command("revoke").run!({
135
+ api,
136
+ args: { id: created.record.id },
137
+ options: {},
138
+ ui,
139
+ });
140
+
141
+ expect(ui.confirm).toHaveBeenCalledWith(
142
+ `Revoke API key ${created.record.id}?`,
143
+ );
144
+ await expect(api.list()).resolves.toMatchObject([
145
+ { id: created.record.id, revoked_at_ms: expect.any(Number) },
146
+ ]);
147
+ expect(output.messages[0]).toContain("API key revoked");
148
+
149
+ const skipped = createUi();
150
+ await command("revoke").run!({
151
+ api,
152
+ args: { id: created.record.id },
153
+ options: { yes: true },
154
+ ui: skipped.ui,
155
+ });
156
+ expect(skipped.ui.confirm).not.toHaveBeenCalled();
157
+ });
158
+
159
+ it("fails to revoke a key it does not have", async () => {
160
+ const { ui } = createUi();
161
+ await expect(
162
+ command("revoke").run!({
163
+ api: assemble(),
164
+ args: { id: "api-missing" },
165
+ options: { yes: true },
166
+ ui,
167
+ }),
168
+ ).rejects.toThrow('API key "api-missing" was not found.');
169
+ });
170
+
171
+ it("gives init the app's key: a saved one again, else a new one", async () => {
172
+ const credential = apiKeys({ headerName: "X-Hot-Updater-Key" }).cli
173
+ ?.clientCredential;
174
+ expect(credential).toMatchObject({
175
+ label: "API key",
176
+ header: "x-hot-updater-key",
177
+ env: "HOT_UPDATER_API_KEY",
178
+ });
179
+ const api = assemble();
180
+ const created = await credential!.provision(api, { name: "Init" });
181
+ expect(created).toMatch(/^[A-Za-z0-9_-]{43}$/u);
182
+ await expect(
183
+ credential!.provision(api, { existing: created, name: "Init again" }),
184
+ ).resolves.toBe(created);
185
+ await expect(api.list()).resolves.toHaveLength(1);
186
+ });
187
+ });
@@ -0,0 +1,140 @@
1
+ import type { PluginCli, PluginCommandUi } from "../definePlugin";
2
+ import type {
3
+ ApiKeyManagementAPI,
4
+ ApiKeyMetadata,
5
+ CreatedApiKey,
6
+ } from "./apiKeys";
7
+
8
+ /** The part of the apiKeys() API the CLI uses. */
9
+ export interface ApiKeysCliApi extends ApiKeyManagementAPI {
10
+ provision(input: {
11
+ readonly existingApiKey?: string;
12
+ readonly name: string;
13
+ }): Promise<CreatedApiKey>;
14
+ }
15
+
16
+ /** The environment variable init stores the app's API key in. */
17
+ export const API_KEY_ENV = "HOT_UPDATER_API_KEY";
18
+
19
+ /** A new API key: 32 random bytes, base64url, as the plugin creates them. */
20
+ const generateApiKey = (): string => {
21
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
22
+ return btoa(String.fromCharCode(...bytes))
23
+ .replaceAll("+", "-")
24
+ .replaceAll("/", "_")
25
+ .replace(/=+$/u, "");
26
+ };
27
+
28
+ const formatList = (
29
+ ui: PluginCommandUi,
30
+ records: readonly ApiKeyMetadata[],
31
+ ): string =>
32
+ records.length === 0
33
+ ? ui.muted("(no API keys)")
34
+ : ui.table(
35
+ [
36
+ { key: "id", label: "ID", format: ui.id },
37
+ { key: "name", label: "Name" },
38
+ { key: "prefix", label: "Prefix", format: ui.muted },
39
+ {
40
+ key: "status",
41
+ label: "Status",
42
+ format: (value) =>
43
+ value.trim() === "active" ? ui.success(value) : ui.danger(value),
44
+ },
45
+ { key: "created", label: "Created", format: ui.muted },
46
+ ],
47
+ records.map((record) => ({
48
+ created: new Date(record.created_at_ms).toISOString(),
49
+ id: record.id,
50
+ name: record.name,
51
+ prefix: record.prefix,
52
+ status: record.revoked_at_ms === null ? "active" : "revoked",
53
+ })),
54
+ );
55
+
56
+ /**
57
+ * `hot-updater api-key create|list|revoke`, and the API key that init
58
+ * provisions for an app, sent in `headerName`.
59
+ */
60
+ export const apiKeysCli = (headerName: string): PluginCli<ApiKeysCliApi> => ({
61
+ commands: [
62
+ {
63
+ name: "api-key",
64
+ description: "Manage API keys",
65
+ commands: [
66
+ {
67
+ name: "create",
68
+ description: "Create an API key",
69
+ options: [
70
+ {
71
+ flags: "--name <name>",
72
+ description: "name used to identify the API key",
73
+ required: true,
74
+ },
75
+ ],
76
+ async run({ api, options, ui }) {
77
+ const created = await api.create({ name: String(options.name) });
78
+ ui.message(
79
+ ui.block("API key created", [
80
+ ui.kv("Name", created.record.name),
81
+ ui.kv("ID", ui.id(created.record.id)),
82
+ ui.kv("API key", ui.warning(created.apiKey)),
83
+ ]),
84
+ );
85
+ ui.warn("Save this API key now. It will not be shown again.");
86
+ },
87
+ },
88
+ {
89
+ name: "list",
90
+ description: "List API keys",
91
+ options: [
92
+ { flags: "--json", description: "output API key metadata as JSON" },
93
+ ],
94
+ async run({ api, options, ui }) {
95
+ const records = [...(await api.list())].sort(
96
+ (left, right) => right.created_at_ms - left.created_at_ms,
97
+ );
98
+ if (options.json) ui.print(JSON.stringify(records, null, 2));
99
+ else ui.message(formatList(ui, records));
100
+ },
101
+ },
102
+ {
103
+ name: "revoke",
104
+ description: "Revoke an API key",
105
+ arguments: [{ name: "id", description: "API key id" }],
106
+ options: [
107
+ { flags: "-y, --yes", description: "skip confirmation prompt" },
108
+ ],
109
+ async run({ api, args, options, ui }) {
110
+ const id = String(args.id);
111
+ if (!options.yes) await ui.confirm(`Revoke API key ${id}?`);
112
+ const revoked = await api.revoke({ id });
113
+ if (revoked === null) {
114
+ throw new Error(`API key "${id}" was not found.`);
115
+ }
116
+ ui.message(
117
+ ui.block("API key revoked", [
118
+ ui.kv("Name", revoked.name),
119
+ ui.kv("ID", ui.id(revoked.id)),
120
+ ]),
121
+ );
122
+ },
123
+ },
124
+ ],
125
+ },
126
+ ],
127
+ clientCredential: {
128
+ label: "API key",
129
+ header: headerName,
130
+ env: API_KEY_ENV,
131
+ generate: generateApiKey,
132
+ provision: async (api, { existing, name }) =>
133
+ (
134
+ await api.provision({
135
+ ...(existing === undefined ? {} : { existingApiKey: existing }),
136
+ name,
137
+ })
138
+ ).apiKey,
139
+ },
140
+ });