@hot-updater/plugin-insights 1.0.0-rc.20

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 (85) hide show
  1. package/LICENSE +33 -0
  2. package/README.md +24 -0
  3. package/client/package.json +7 -0
  4. package/dist/client/eventId.cjs +181 -0
  5. package/dist/client/eventId.mjs +179 -0
  6. package/dist/client/index.cjs +234 -0
  7. package/dist/client/index.d.cts +42 -0
  8. package/dist/client/index.d.mts +42 -0
  9. package/dist/client/index.mjs +233 -0
  10. package/dist/client/sender.cjs +103 -0
  11. package/dist/client/sender.mjs +103 -0
  12. package/dist/client/state.cjs +121 -0
  13. package/dist/client/state.mjs +119 -0
  14. package/dist/internal.cjs +9 -0
  15. package/dist/internal.d.cts +5 -0
  16. package/dist/internal.d.mts +5 -0
  17. package/dist/internal.mjs +5 -0
  18. package/dist/server/contract.cjs +193 -0
  19. package/dist/server/contract.mjs +189 -0
  20. package/dist/server/domain.d.cts +149 -0
  21. package/dist/server/domain.d.mts +149 -0
  22. package/dist/server/errors.cjs +15 -0
  23. package/dist/server/errors.d.cts +6 -0
  24. package/dist/server/errors.d.mts +6 -0
  25. package/dist/server/errors.mjs +14 -0
  26. package/dist/server/eventInput.cjs +284 -0
  27. package/dist/server/eventInput.d.cts +6 -0
  28. package/dist/server/eventInput.d.mts +6 -0
  29. package/dist/server/eventInput.mjs +282 -0
  30. package/dist/server/eventRow.cjs +49 -0
  31. package/dist/server/eventRow.d.cts +64 -0
  32. package/dist/server/eventRow.d.mts +64 -0
  33. package/dist/server/eventRow.mjs +47 -0
  34. package/dist/server/index.cjs +128 -0
  35. package/dist/server/index.d.cts +394 -0
  36. package/dist/server/index.d.mts +394 -0
  37. package/dist/server/index.mjs +121 -0
  38. package/dist/server/model.cjs +17 -0
  39. package/dist/server/model.d.cts +10 -0
  40. package/dist/server/model.d.mts +10 -0
  41. package/dist/server/model.mjs +17 -0
  42. package/dist/server/modelTypes.d.cts +176 -0
  43. package/dist/server/modelTypes.d.mts +176 -0
  44. package/dist/server/overview.cjs +109 -0
  45. package/dist/server/overview.d.cts +15 -0
  46. package/dist/server/overview.d.mts +15 -0
  47. package/dist/server/overview.mjs +107 -0
  48. package/dist/server/provider.cjs +375 -0
  49. package/dist/server/provider.d.cts +6 -0
  50. package/dist/server/provider.d.mts +6 -0
  51. package/dist/server/provider.mjs +374 -0
  52. package/dist/server/queryInput.cjs +93 -0
  53. package/dist/server/queryInput.mjs +91 -0
  54. package/dist/server/reads.cjs +681 -0
  55. package/dist/server/reads.d.cts +60 -0
  56. package/dist/server/reads.d.mts +60 -0
  57. package/dist/server/reads.mjs +674 -0
  58. package/dist/server/recordEvent.cjs +319 -0
  59. package/dist/server/recordEvent.d.cts +17 -0
  60. package/dist/server/recordEvent.d.mts +17 -0
  61. package/dist/server/recordEvent.mjs +316 -0
  62. package/dist/server/routes.cjs +96 -0
  63. package/dist/server/routes.d.cts +36 -0
  64. package/dist/server/routes.d.mts +36 -0
  65. package/dist/server/routes.mjs +95 -0
  66. package/dist/server/schema.cjs +489 -0
  67. package/dist/server/schema.d.cts +706 -0
  68. package/dist/server/schema.d.mts +706 -0
  69. package/dist/server/schema.mjs +483 -0
  70. package/dist/server/testing/eventRow.d.mts +64 -0
  71. package/dist/server/testing/expectInsightsIndex.mjs +18 -0
  72. package/dist/server/testing/fixtures.d.mts +8 -0
  73. package/dist/server/testing/fixtures.mjs +25 -0
  74. package/dist/server/testing/index.d.mts +24 -0
  75. package/dist/server/testing/index.mjs +25 -0
  76. package/dist/server/testing/insightsModelTests.mjs +714 -0
  77. package/dist/server/testing/modelTypes.d.mts +176 -0
  78. package/dist/server/testing/setupInsightsHttpTestSuite.d.mts +11 -0
  79. package/dist/server/testing/setupInsightsHttpTestSuite.mjs +107 -0
  80. package/dist/server/testing/setupInsightsModelTestSuite.d.mts +11 -0
  81. package/dist/server/testing/setupInsightsModelTestSuite.mjs +31 -0
  82. package/dist/server/testing/types.d.mts +26 -0
  83. package/dist/server/types.d.cts +33 -0
  84. package/dist/server/types.d.mts +33 -0
  85. package/package.json +68 -0
@@ -0,0 +1,374 @@
1
+ import { compareInsightsText, isInsightsMovementEvent } from "./contract.mjs";
2
+ import { InsightsBadRequestError } from "./errors.mjs";
3
+ import { createBundleEventRow } from "./eventInput.mjs";
4
+ import { isUUIDv7 } from "@hot-updater/plugin-core";
5
+ //#region src/server/provider.ts
6
+ const DEFAULT_PAGE_LIMIT = 50;
7
+ const MAX_PAGE_LIMIT = 100;
8
+ const MAX_EVENT_ID_LENGTH = 1024;
9
+ const MAX_IDENTITY_LENGTH = 255;
10
+ const MAX_CURSOR_LENGTH = 8192;
11
+ const HOUR_MS = 36e5;
12
+ const DAY_MS = 24 * HOUR_MS;
13
+ const WINDOW_MS = {
14
+ "24h": 864e5,
15
+ "7d": 6048e5,
16
+ "30d": 2592e6
17
+ };
18
+ /**
19
+ * The longest receipt range, `[sinceMs, beforeReceivedAtMs)`, of a global or
20
+ * bundle event list, and the range one covers without `sinceMs`: raw events
21
+ * are listed inside a time range, as analytics products list them. It is a
22
+ * duration, so a range that ends mid-day touches 91 UTC days. Installation
23
+ * history is one index range and reads back to `sinceMs`.
24
+ */
25
+ const EVENT_LIST_RANGE_MS = 2160 * HOUR_MS;
26
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
27
+ const requireString = (value, label, maximumLength) => {
28
+ if (typeof value !== "string" || value.length === 0 || value.length > maximumLength || new TextDecoder("utf-8", { ignoreBOM: true }).decode(new TextEncoder().encode(value)) !== value) throw new InsightsBadRequestError(`Invalid ${label}.`);
29
+ return value;
30
+ };
31
+ const requireTimestamp = (value, label) => {
32
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new InsightsBadRequestError(`Invalid ${label}.`);
33
+ return Number(value);
34
+ };
35
+ const readLimit = (value) => {
36
+ const limit = value ?? DEFAULT_PAGE_LIMIT;
37
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new InsightsBadRequestError("Invalid page limit.");
38
+ return limit;
39
+ };
40
+ const encodeBase64Url = (value) => {
41
+ const bytes = new TextEncoder().encode(value);
42
+ let binary = "";
43
+ for (const byte of bytes) binary += String.fromCharCode(byte);
44
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
45
+ };
46
+ const decodeBase64Url = (value) => {
47
+ if (value.length === 0 || value.length > MAX_CURSOR_LENGTH) throw new InsightsBadRequestError("Invalid Insights cursor.");
48
+ try {
49
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
50
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
51
+ const binary = atob(padded);
52
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
53
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
54
+ } catch {
55
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
56
+ }
57
+ };
58
+ const encodeCursor = (value) => encodeBase64Url(JSON.stringify(value));
59
+ const decodeCursor = (value) => {
60
+ try {
61
+ return JSON.parse(decodeBase64Url(value));
62
+ } catch (error) {
63
+ if (error instanceof InsightsBadRequestError) throw error;
64
+ throw new InsightsBadRequestError("Invalid Insights cursor.");
65
+ }
66
+ };
67
+ const readScope = (input) => {
68
+ if (input.platform !== "ios" && input.platform !== "android") throw new InsightsBadRequestError("Invalid Insights platform.");
69
+ return {
70
+ platform: input.platform,
71
+ channel: requireString(input.channel, "channel", MAX_EVENT_ID_LENGTH)
72
+ };
73
+ };
74
+ const bundleFilter = (input) => {
75
+ const scope = readScope(input);
76
+ const bundleId = requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
77
+ switch (input.outcome) {
78
+ case "downloaded": return {
79
+ ...scope,
80
+ type: "UPDATE_DOWNLOADED",
81
+ toBundleId: bundleId
82
+ };
83
+ case "applied": return {
84
+ ...scope,
85
+ type: "UPDATE_APPLIED",
86
+ toBundleId: bundleId
87
+ };
88
+ case "recovered": return {
89
+ ...scope,
90
+ type: "RECOVERED",
91
+ fromBundleId: bundleId
92
+ };
93
+ case "failed": return {
94
+ ...scope,
95
+ type: "UPDATE_FAILED",
96
+ toBundleId: bundleId
97
+ };
98
+ default: throw new InsightsBadRequestError("Invalid Insights outcome.");
99
+ }
100
+ };
101
+ const sameFilter = (left, right) => {
102
+ if (!isRecord(left) || left.kind !== right.kind) return false;
103
+ switch (right.kind) {
104
+ case "all": return true;
105
+ case "installationMovement": return left.installId === right.installId;
106
+ case "bundle": return left.platform === right.platform && left.channel === right.channel && left.type === right.type && (right.type === "RECOVERED" ? left.fromBundleId === right.fromBundleId : left.toBundleId === right.toBundleId);
107
+ }
108
+ };
109
+ const readEventCursor = (value, filter) => {
110
+ const cursor = decodeCursor(value);
111
+ if (!isRecord(cursor) || cursor.version !== 2 || cursor.kind !== "events" || !isRecord(cursor.filter) || !isRecord(cursor.after)) throw new InsightsBadRequestError("Invalid Insights cursor.");
112
+ if (!sameFilter(cursor.filter, filter)) throw new InsightsBadRequestError("Insights cursor does not match the requested events.");
113
+ if (typeof cursor.after.id !== "string" || !isUUIDv7(cursor.after.id)) throw new InsightsBadRequestError("Invalid Insights event cursor ID.");
114
+ return {
115
+ after: {
116
+ id: cursor.after.id,
117
+ receivedAtMs: requireTimestamp(cursor.after.receivedAtMs, "event cursor")
118
+ },
119
+ beforeReceivedAtMs: requireTimestamp(cursor.beforeReceivedAtMs, "event cutoff"),
120
+ kind: "events",
121
+ sinceMs: requireTimestamp(cursor.sinceMs, "event start"),
122
+ filter,
123
+ version: 2
124
+ };
125
+ };
126
+ const readUserInstallationCursor = (value, userId) => {
127
+ const cursor = decodeCursor(value);
128
+ if (!isRecord(cursor) || cursor.version !== 1 || cursor.kind !== "user-installations" || cursor.userId !== userId) throw new InsightsBadRequestError("Insights cursor does not match the requested user ID.");
129
+ return {
130
+ afterInstallId: requireString(cursor.afterInstallId, "installation cursor", MAX_IDENTITY_LENGTH),
131
+ kind: "user-installations",
132
+ userId,
133
+ version: 1
134
+ };
135
+ };
136
+ const compareEventNewest = (left, right) => right.received_at_ms - left.received_at_ms || compareInsightsText(right.id, left.id);
137
+ const isAfterEventCursor = (row, after) => row.received_at_ms < after.receivedAtMs || row.received_at_ms === after.receivedAtMs && compareInsightsText(row.id, after.id) < 0;
138
+ const assertEventRows = (rows, input) => {
139
+ if (rows.length > input.limit) throw new Error("Insights database returned too many event rows.");
140
+ for (let index = 0; index < rows.length; index += 1) {
141
+ const row = rows[index];
142
+ const previous = rows[index - 1];
143
+ if (!row || typeof row.id !== "string" || !isUUIDv7(row.id) || !Number.isSafeInteger(row.received_at_ms) || row.received_at_ms >= input.beforeReceivedAtMs || row.received_at_ms < input.sinceMs || previous !== void 0 && compareEventNewest(previous, row) >= 0 || input.after !== void 0 && !isAfterEventCursor(row, input.after) || input.filter.kind === "installationMovement" && (row.install_id !== input.filter.installId || !isInsightsMovementEvent(row)) || input.filter.kind === "bundle" && (row.platform !== input.filter.platform || row.channel !== input.filter.channel || row.type !== input.filter.type || (input.filter.type === "RECOVERED" ? row.from_bundle_id !== input.filter.fromBundleId : row.to_bundle_id !== input.filter.toBundleId))) throw new Error("Insights database returned invalid event rows.");
144
+ }
145
+ };
146
+ /** An `UPDATE_FAILED` row's failure, as the event lists show it. */
147
+ const toFailure = (failure) => ({
148
+ stage: failure.stage,
149
+ reason: failure.reason,
150
+ ...failure.resource === void 0 ? {} : { resource: failure.resource },
151
+ ...failure.http_status === void 0 ? {} : { httpStatus: failure.http_status },
152
+ ...failure.transport === void 0 ? {} : { transport: failure.transport },
153
+ ...failure.origin_code === void 0 ? {} : { originCode: failure.origin_code },
154
+ ...failure.previous_process_exit === void 0 ? {} : { previousProcessExit: failure.previous_process_exit }
155
+ });
156
+ /** What a row's metadata adds for its type: a failure, a delivery, an exit reason. */
157
+ const eventDetails = ({ type, metadata }) => ({
158
+ ...type === "UPDATE_FAILED" && metadata.failure !== void 0 ? { failure: toFailure(metadata.failure) } : {},
159
+ ...type === "UPDATE_DOWNLOADED" && metadata.delivery !== void 0 ? { delivery: metadata.delivery } : {},
160
+ ...type === "UPDATE_DOWNLOADED" && metadata.patch_fallback === true ? { patchFallback: true } : {},
161
+ ...type === "RECOVERED" && metadata.previous_process_exit !== void 0 ? { previousProcessExit: metadata.previous_process_exit } : {}
162
+ });
163
+ const toEventHistoryRow = (row) => ({
164
+ appVersion: row.app_version,
165
+ channel: row.channel,
166
+ cohort: row.metadata.cohort,
167
+ fromBundleId: row.from_bundle_id,
168
+ id: row.id,
169
+ installId: row.install_id,
170
+ platform: row.platform,
171
+ receivedAtMs: row.received_at_ms,
172
+ toBundleId: row.to_bundle_id,
173
+ type: row.type,
174
+ userId: row.user_id,
175
+ ...eventDetails(row)
176
+ });
177
+ const toInstallationRow = (row) => ({
178
+ appVersion: row.app_version,
179
+ channel: row.channel,
180
+ cohort: row.metadata.cohort,
181
+ installId: row.install_id,
182
+ lastKnownBundleId: row.type === "UPDATE_DOWNLOADED" ? row.from_bundle_id : row.to_bundle_id,
183
+ pendingBundleId: row.type === "UPDATE_DOWNLOADED" ? row.to_bundle_id : null,
184
+ pendingReleaseId: row.type === "UPDATE_DOWNLOADED" ? row.to_release_id : null,
185
+ latestStatus: row.type,
186
+ platform: row.platform,
187
+ receivedAtMs: row.received_at_ms,
188
+ userId: row.user_id
189
+ });
190
+ /**
191
+ * Where a list without `sinceMs` starts: 90 days before its cutoff for the
192
+ * global and bundle lists, at the first event for installation history.
193
+ */
194
+ const defaultEventStart = (filter, beforeReceivedAtMs) => filter.kind === "installationMovement" ? 0 : Math.max(0, beforeReceivedAtMs - EVENT_LIST_RANGE_MS);
195
+ /** Whether a cursor's row lies inside the list's range. */
196
+ const isInsideBounds = ({ after }, bounds) => after.receivedAtMs >= bounds.sinceMs && after.receivedAtMs < bounds.beforeReceivedAtMs;
197
+ /** A page's range: its cursor's, which the request may repeat but not change. */
198
+ const readEventBounds = (input, cursor, filter) => {
199
+ const beforeReceivedAtMs = cursor?.beforeReceivedAtMs ?? (input.beforeReceivedAtMs === void 0 ? Date.now() : requireTimestamp(input.beforeReceivedAtMs, "event cutoff"));
200
+ if (cursor !== void 0 && input.beforeReceivedAtMs !== void 0 && input.beforeReceivedAtMs !== beforeReceivedAtMs) throw new InsightsBadRequestError("Insights cursor does not match the requested event cutoff.");
201
+ const sinceMs = cursor?.sinceMs ?? (input.sinceMs === void 0 ? defaultEventStart(filter, beforeReceivedAtMs) : requireTimestamp(input.sinceMs, "event start"));
202
+ const bounds = {
203
+ beforeReceivedAtMs,
204
+ sinceMs
205
+ };
206
+ if (sinceMs > beforeReceivedAtMs || input.sinceMs !== void 0 && input.sinceMs !== sinceMs || cursor !== void 0 && !isInsideBounds(cursor, bounds)) throw new InsightsBadRequestError("Insights cursor or range does not match the requested event start.");
207
+ if (filter.kind !== "installationMovement" && beforeReceivedAtMs - sinceMs > 7776e6) throw new InsightsBadRequestError("Insights event lists cover at most 90 days: send a sinceMs no more than 90 days before beforeReceivedAtMs.");
208
+ return bounds;
209
+ };
210
+ const pageEventRows = async (model, input, filter, map) => {
211
+ const limit = readLimit(input.limit);
212
+ const cursor = input.cursor === void 0 ? void 0 : readEventCursor(input.cursor, filter);
213
+ const bounds = readEventBounds(input, cursor, filter);
214
+ const query = {
215
+ filter,
216
+ ...bounds,
217
+ ...cursor === void 0 ? {} : { after: cursor.after },
218
+ limit
219
+ };
220
+ const rows = await model.listEvents(query);
221
+ assertEventRows(rows, query);
222
+ const last = rows.at(-1);
223
+ return {
224
+ beforeReceivedAtMs: bounds.beforeReceivedAtMs,
225
+ data: rows.map(map),
226
+ nextCursor: rows.length === limit && last ? encodeCursor({
227
+ after: {
228
+ id: last.id,
229
+ receivedAtMs: last.received_at_ms
230
+ },
231
+ ...bounds,
232
+ kind: "events",
233
+ filter,
234
+ version: 2
235
+ }) : null
236
+ };
237
+ };
238
+ const assertInstallationRows = (rows, input) => {
239
+ if (rows.length > input.limit) throw new Error("Insights database returned too many installation rows.");
240
+ for (let index = 0; index < rows.length; index += 1) {
241
+ const row = rows[index];
242
+ const previous = rows[index - 1];
243
+ if (!row || row.user_id !== input.userId || input.afterInstallId !== void 0 && compareInsightsText(row.install_id, input.afterInstallId) <= 0 || previous !== void 0 && compareInsightsText(previous.install_id, row.install_id) >= 0) throw new Error("Insights database returned invalid installation rows.");
244
+ }
245
+ };
246
+ const createInsightsProvider = (model) => Object.freeze({
247
+ async appendBundleEvent(input) {
248
+ const event = createBundleEventRow(input);
249
+ await model.recordEvent({ event });
250
+ },
251
+ listEvents(input) {
252
+ const filter = input.bundle === void 0 ? { kind: "all" } : {
253
+ kind: "bundle",
254
+ ...bundleFilter(input.bundle)
255
+ };
256
+ return pageEventRows(model, input, filter, toEventHistoryRow);
257
+ },
258
+ async listInstallationEvents(input) {
259
+ if ("bundle" in input && input.bundle !== void 0) throw new InsightsBadRequestError("Installation movement queries cannot include a bundle filter.");
260
+ const installId = requireString(input.installId, "install ID", MAX_IDENTITY_LENGTH);
261
+ return pageEventRows(model, input, {
262
+ kind: "installationMovement",
263
+ installId
264
+ }, (row) => toEventHistoryRow(row));
265
+ },
266
+ async getInstallation({ installId }) {
267
+ const normalizedInstallId = requireString(installId, "install ID", MAX_IDENTITY_LENGTH);
268
+ const rows = await model.findLatestEvents({ installId: normalizedInstallId });
269
+ const row = rows[0] ?? null;
270
+ if (rows.length > 1 || row !== null && row.install_id !== normalizedInstallId) throw new Error("Insights database returned an invalid installation.");
271
+ return row === null ? null : toInstallationRow(row);
272
+ },
273
+ async pageInstallationsByCurrentUserId(input) {
274
+ const userId = requireString(input.userId, "user ID", MAX_IDENTITY_LENGTH);
275
+ const limit = readLimit(input.limit);
276
+ const cursor = input.cursor === void 0 ? void 0 : readUserInstallationCursor(input.cursor, userId);
277
+ const databaseInput = {
278
+ userId,
279
+ ...cursor === void 0 ? {} : { afterInstallId: cursor.afterInstallId },
280
+ limit
281
+ };
282
+ const rows = await model.findLatestEvents(databaseInput);
283
+ assertInstallationRows(rows, databaseInput);
284
+ const last = rows.at(-1);
285
+ return {
286
+ data: rows.map(toInstallationRow),
287
+ nextCursor: rows.length === limit && last ? encodeCursor({
288
+ afterInstallId: last.install_id,
289
+ kind: "user-installations",
290
+ userId,
291
+ version: 1
292
+ }) : null
293
+ };
294
+ },
295
+ async getReportingOverview(input) {
296
+ const scope = readScope(input);
297
+ const { window } = input;
298
+ if (!Object.hasOwn(WINDOW_MS, window)) throw new InsightsBadRequestError("Invalid reporting installation window.");
299
+ const now = Date.now();
300
+ const beforeReceivedAtMs = now - now % HOUR_MS + (now % HOUR_MS === 0 ? 0 : HOUR_MS);
301
+ const reach = Math.max(0, beforeReceivedAtMs - WINDOW_MS[window]);
302
+ const sinceMs = reach - reach % DAY_MS;
303
+ const measure = async (count) => {
304
+ const value = await count;
305
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Insights database returned an invalid count.");
306
+ return {
307
+ count: value,
308
+ measuredAtMs: Date.now()
309
+ };
310
+ };
311
+ const bundleId = input.bundleId === void 0 ? void 0 : requireString(input.bundleId, "bundle ID", MAX_EVENT_ID_LENGTH);
312
+ const reporting = measure(model.countLatestEvents({
313
+ ...scope,
314
+ sinceMs
315
+ }));
316
+ if (bundleId === void 0) return {
317
+ ...scope,
318
+ window,
319
+ sinceMs,
320
+ beforeReceivedAtMs,
321
+ reportingInstallations: await reporting
322
+ };
323
+ const countOutcome = (outcome) => measure(model.countEvents({
324
+ filter: bundleFilter({
325
+ ...scope,
326
+ bundleId,
327
+ outcome
328
+ }),
329
+ sinceMs,
330
+ beforeReceivedAtMs
331
+ }));
332
+ const [reportingInstallations, bundleInstallations, downloadedReports, appliedReports, recoveredReports, failedReports] = await Promise.all([
333
+ reporting,
334
+ measure(model.countLatestEvents({
335
+ ...scope,
336
+ sinceMs,
337
+ bundle: [{
338
+ field: "from_bundle_id",
339
+ value: bundleId,
340
+ types: ["UPDATE_DOWNLOADED"]
341
+ }, {
342
+ field: "to_bundle_id",
343
+ value: bundleId,
344
+ types: [
345
+ "UNCHANGED",
346
+ "UPDATE_APPLIED",
347
+ "RECOVERED"
348
+ ]
349
+ }]
350
+ })),
351
+ countOutcome("downloaded"),
352
+ countOutcome("applied"),
353
+ countOutcome("recovered"),
354
+ countOutcome("failed")
355
+ ]);
356
+ return {
357
+ ...scope,
358
+ window,
359
+ sinceMs,
360
+ beforeReceivedAtMs,
361
+ reportingInstallations,
362
+ bundle: {
363
+ bundleId,
364
+ reportingInstallations: bundleInstallations,
365
+ downloadedReports,
366
+ appliedReports,
367
+ recoveredReports,
368
+ failedReports
369
+ }
370
+ };
371
+ }
372
+ });
373
+ //#endregion
374
+ export { EVENT_LIST_RANGE_MS, createInsightsProvider };
@@ -0,0 +1,93 @@
1
+ const require_errors = require("./errors.cjs");
2
+ //#region src/server/queryInput.ts
3
+ const MAX_PAGE_LIMIT = 100;
4
+ const MAX_IDENTITY_LENGTH = 255;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const readSingle = (url, key) => {
7
+ const values = url.searchParams.getAll(key);
8
+ if (values.length > 1) throw new require_errors.InsightsBadRequestError(`Duplicate '${key}' query parameter.`);
9
+ return values[0];
10
+ };
11
+ const readPageLimit = (url) => {
12
+ const value = readSingle(url, "limit");
13
+ if (value === void 0) return void 0;
14
+ const limit = Number(value);
15
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new require_errors.InsightsBadRequestError("Invalid 'limit' query parameter.");
16
+ return limit;
17
+ };
18
+ const readCursor = (url) => {
19
+ const cursor = readSingle(url, "cursor");
20
+ if (cursor !== void 0 && (cursor.length === 0 || cursor.length > MAX_CURSOR_LENGTH)) throw new require_errors.InsightsBadRequestError("Invalid 'cursor' query parameter.");
21
+ return cursor;
22
+ };
23
+ const readId = (url, key, maximumLength = MAX_IDENTITY_LENGTH) => {
24
+ const value = readSingle(url, key);
25
+ if (value === void 0 || value.length === 0 || value.length > maximumLength) throw new require_errors.InsightsBadRequestError(`Invalid '${key}' query parameter.`);
26
+ return value;
27
+ };
28
+ const readTimestamp = (url, key) => {
29
+ const raw = readSingle(url, key);
30
+ if (raw === void 0) return void 0;
31
+ const value = Number(raw);
32
+ if (!raw.length || !Number.isSafeInteger(value) || value < 0) throw new require_errors.InsightsBadRequestError(`Invalid '${key}' query parameter.`);
33
+ return value;
34
+ };
35
+ const readScope = (url) => {
36
+ const platform = readSingle(url, "platform");
37
+ if (platform !== "ios" && platform !== "android") throw new require_errors.InsightsBadRequestError("Invalid 'platform' query parameter.");
38
+ return {
39
+ platform,
40
+ channel: readId(url, "channel", 1024)
41
+ };
42
+ };
43
+ const parseEventPageInput = (request) => {
44
+ const url = new URL(request.url);
45
+ const bundleFields = [
46
+ "bundleId",
47
+ "outcome",
48
+ "platform",
49
+ "channel"
50
+ ];
51
+ let bundle;
52
+ if (bundleFields.some((key) => url.searchParams.has(key))) {
53
+ const outcome = readSingle(url, "outcome");
54
+ if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new require_errors.InsightsBadRequestError("Invalid 'outcome' query parameter.");
55
+ bundle = {
56
+ ...readScope(url),
57
+ bundleId: readId(url, "bundleId", 1024),
58
+ outcome
59
+ };
60
+ }
61
+ return {
62
+ beforeReceivedAtMs: readTimestamp(url, "beforeReceivedAtMs"),
63
+ sinceMs: readTimestamp(url, "sinceMs"),
64
+ cursor: readCursor(url),
65
+ limit: readPageLimit(url),
66
+ ...bundle === void 0 ? {} : { bundle }
67
+ };
68
+ };
69
+ const parseUserInstallationPageInput = (request) => {
70
+ const url = new URL(request.url);
71
+ const cursor = readCursor(url);
72
+ const limit = readPageLimit(url);
73
+ return {
74
+ userId: readId(url, "userId"),
75
+ ...cursor === void 0 ? {} : { cursor },
76
+ ...limit === void 0 ? {} : { limit }
77
+ };
78
+ };
79
+ const parseReportingOverviewInput = (request) => {
80
+ const url = new URL(request.url);
81
+ const window = readSingle(url, "window") ?? "30d";
82
+ if (window !== "24h" && window !== "7d" && window !== "30d") throw new require_errors.InsightsBadRequestError("Invalid 'window' query parameter.");
83
+ const bundleId = readSingle(url, "bundleId");
84
+ return {
85
+ ...readScope(url),
86
+ window,
87
+ ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
88
+ };
89
+ };
90
+ //#endregion
91
+ exports.parseEventPageInput = parseEventPageInput;
92
+ exports.parseReportingOverviewInput = parseReportingOverviewInput;
93
+ exports.parseUserInstallationPageInput = parseUserInstallationPageInput;
@@ -0,0 +1,91 @@
1
+ import { InsightsBadRequestError } from "./errors.mjs";
2
+ //#region src/server/queryInput.ts
3
+ const MAX_PAGE_LIMIT = 100;
4
+ const MAX_IDENTITY_LENGTH = 255;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const readSingle = (url, key) => {
7
+ const values = url.searchParams.getAll(key);
8
+ if (values.length > 1) throw new InsightsBadRequestError(`Duplicate '${key}' query parameter.`);
9
+ return values[0];
10
+ };
11
+ const readPageLimit = (url) => {
12
+ const value = readSingle(url, "limit");
13
+ if (value === void 0) return void 0;
14
+ const limit = Number(value);
15
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_PAGE_LIMIT) throw new InsightsBadRequestError("Invalid 'limit' query parameter.");
16
+ return limit;
17
+ };
18
+ const readCursor = (url) => {
19
+ const cursor = readSingle(url, "cursor");
20
+ if (cursor !== void 0 && (cursor.length === 0 || cursor.length > MAX_CURSOR_LENGTH)) throw new InsightsBadRequestError("Invalid 'cursor' query parameter.");
21
+ return cursor;
22
+ };
23
+ const readId = (url, key, maximumLength = MAX_IDENTITY_LENGTH) => {
24
+ const value = readSingle(url, key);
25
+ if (value === void 0 || value.length === 0 || value.length > maximumLength) throw new InsightsBadRequestError(`Invalid '${key}' query parameter.`);
26
+ return value;
27
+ };
28
+ const readTimestamp = (url, key) => {
29
+ const raw = readSingle(url, key);
30
+ if (raw === void 0) return void 0;
31
+ const value = Number(raw);
32
+ if (!raw.length || !Number.isSafeInteger(value) || value < 0) throw new InsightsBadRequestError(`Invalid '${key}' query parameter.`);
33
+ return value;
34
+ };
35
+ const readScope = (url) => {
36
+ const platform = readSingle(url, "platform");
37
+ if (platform !== "ios" && platform !== "android") throw new InsightsBadRequestError("Invalid 'platform' query parameter.");
38
+ return {
39
+ platform,
40
+ channel: readId(url, "channel", 1024)
41
+ };
42
+ };
43
+ const parseEventPageInput = (request) => {
44
+ const url = new URL(request.url);
45
+ const bundleFields = [
46
+ "bundleId",
47
+ "outcome",
48
+ "platform",
49
+ "channel"
50
+ ];
51
+ let bundle;
52
+ if (bundleFields.some((key) => url.searchParams.has(key))) {
53
+ const outcome = readSingle(url, "outcome");
54
+ if (outcome !== "downloaded" && outcome !== "applied" && outcome !== "recovered" && outcome !== "failed") throw new InsightsBadRequestError("Invalid 'outcome' query parameter.");
55
+ bundle = {
56
+ ...readScope(url),
57
+ bundleId: readId(url, "bundleId", 1024),
58
+ outcome
59
+ };
60
+ }
61
+ return {
62
+ beforeReceivedAtMs: readTimestamp(url, "beforeReceivedAtMs"),
63
+ sinceMs: readTimestamp(url, "sinceMs"),
64
+ cursor: readCursor(url),
65
+ limit: readPageLimit(url),
66
+ ...bundle === void 0 ? {} : { bundle }
67
+ };
68
+ };
69
+ const parseUserInstallationPageInput = (request) => {
70
+ const url = new URL(request.url);
71
+ const cursor = readCursor(url);
72
+ const limit = readPageLimit(url);
73
+ return {
74
+ userId: readId(url, "userId"),
75
+ ...cursor === void 0 ? {} : { cursor },
76
+ ...limit === void 0 ? {} : { limit }
77
+ };
78
+ };
79
+ const parseReportingOverviewInput = (request) => {
80
+ const url = new URL(request.url);
81
+ const window = readSingle(url, "window") ?? "30d";
82
+ if (window !== "24h" && window !== "7d" && window !== "30d") throw new InsightsBadRequestError("Invalid 'window' query parameter.");
83
+ const bundleId = readSingle(url, "bundleId");
84
+ return {
85
+ ...readScope(url),
86
+ window,
87
+ ...bundleId === void 0 ? {} : { bundleId: readId(url, "bundleId", 1024) }
88
+ };
89
+ };
90
+ //#endregion
91
+ export { parseEventPageInput, parseReportingOverviewInput, parseUserInstallationPageInput };