@haakco/custd-sdk 0.0.0-stage → 2.4.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.
- package/README.md +412 -2
- package/dist/admin-client-setup.d.ts +100 -0
- package/dist/admin-client-setup.js +398 -0
- package/dist/admin-data-labels.d.ts +124 -0
- package/dist/admin-data-labels.js +51 -0
- package/dist/admin-offboarding.d.ts +109 -0
- package/dist/admin-offboarding.js +108 -0
- package/dist/admin-predictions.d.ts +147 -0
- package/dist/admin-predictions.js +83 -0
- package/dist/admin-privacy-erasures.d.ts +62 -0
- package/dist/admin-privacy-erasures.js +72 -0
- package/dist/admin-retention.d.ts +51 -0
- package/dist/admin-retention.js +35 -0
- package/dist/admin-subject-exports.d.ts +48 -0
- package/dist/admin-subject-exports.js +28 -0
- package/dist/admin-tenant-storage.d.ts +27 -0
- package/dist/admin-tenant-storage.js +25 -0
- package/dist/admin-timeplans.d.ts +238 -0
- package/dist/admin-timeplans.js +146 -0
- package/dist/analytics-events.d.ts +85 -0
- package/dist/analytics-events.js +40 -0
- package/dist/backend-lifecycle.d.ts +85 -0
- package/dist/backend-lifecycle.js +212 -0
- package/dist/browser-manifest.json +7 -0
- package/dist/browser-script-BvgjdZSO.js +429 -0
- package/dist/browser-script.d.ts +1 -0
- package/dist/browser-script.js +5 -0
- package/dist/browser-tracker.d.ts +47 -0
- package/dist/browser-tracker.js +453 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +1 -0
- package/dist/fixtures.d.ts +10 -0
- package/dist/fixtures.js +57 -0
- package/dist/index.d.ts +1310 -0
- package/dist/index.js +1706 -0
- package/dist/mobile-adapter.d.ts +25 -0
- package/dist/mobile-adapter.js +57 -0
- package/dist/mobile-context.d.ts +32 -0
- package/dist/mobile-context.js +156 -0
- package/dist/mobile-queue.d.ts +22 -0
- package/dist/mobile-queue.js +73 -0
- package/dist/oauth.d.ts +1 -0
- package/dist/oauth.js +8 -0
- package/dist/reporting-state.d.ts +46 -0
- package/dist/reporting-state.js +76 -0
- package/dist/runtime-readiness.d.ts +30 -0
- package/dist/runtime-readiness.js +150 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.js +10 -0
- package/package.json +46 -4
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AsyncQueueStorage } from "./mobile-queue.js";
|
|
2
|
+
export type MobileKeyValueStorage = {
|
|
3
|
+
getItem: (key: string) => Promise<string | null>;
|
|
4
|
+
setItem: (key: string, value: string) => Promise<void>;
|
|
5
|
+
removeItem: (key: string) => Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
export type MobileAppState = {
|
|
8
|
+
addEventListener: (event: "change", listener: (state: string) => void) => MobileSubscription;
|
|
9
|
+
};
|
|
10
|
+
export type MobileNetworkState = {
|
|
11
|
+
isConnected: boolean | null;
|
|
12
|
+
isInternetReachable?: boolean | null;
|
|
13
|
+
};
|
|
14
|
+
export type MobileNetwork = {
|
|
15
|
+
addEventListener: (listener: (state: MobileNetworkState) => void) => MobileSubscription;
|
|
16
|
+
};
|
|
17
|
+
export type MobileSubscription = {
|
|
18
|
+
remove: () => void;
|
|
19
|
+
} | (() => void);
|
|
20
|
+
export type MobileFlushTriggerOptions = {
|
|
21
|
+
appState: MobileAppState;
|
|
22
|
+
network: MobileNetwork;
|
|
23
|
+
};
|
|
24
|
+
export declare function createMobileAsyncQueueStorage(storage: MobileKeyValueStorage, key: string): AsyncQueueStorage;
|
|
25
|
+
export declare function createMobileFlushTriggers(options: MobileFlushTriggerOptions): (flush: () => Promise<void>) => () => void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export function createMobileAsyncQueueStorage(storage, key) {
|
|
2
|
+
if (!key) {
|
|
3
|
+
throw new Error("custd: mobile queue storage key is required");
|
|
4
|
+
}
|
|
5
|
+
return {
|
|
6
|
+
async load() {
|
|
7
|
+
const raw = await storage.getItem(key);
|
|
8
|
+
if (!raw) {
|
|
9
|
+
return [];
|
|
10
|
+
}
|
|
11
|
+
try {
|
|
12
|
+
const events = JSON.parse(raw);
|
|
13
|
+
return Array.isArray(events) ? events : [];
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return [];
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
save(events) {
|
|
20
|
+
return storage.setItem(key, JSON.stringify(events));
|
|
21
|
+
},
|
|
22
|
+
clear() {
|
|
23
|
+
return storage.removeItem(key);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function createMobileFlushTriggers(options) {
|
|
28
|
+
return (flush) => {
|
|
29
|
+
const flushSafely = () => {
|
|
30
|
+
void flush().catch(() => undefined);
|
|
31
|
+
};
|
|
32
|
+
const appSubscription = options.appState.addEventListener("change", (state) => {
|
|
33
|
+
if (state === "active") {
|
|
34
|
+
flushSafely();
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
const networkSubscription = options.network.addEventListener((state) => {
|
|
38
|
+
if (isReachable(state)) {
|
|
39
|
+
flushSafely();
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return () => {
|
|
43
|
+
removeMobileSubscription(appSubscription);
|
|
44
|
+
removeMobileSubscription(networkSubscription);
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function isReachable(state) {
|
|
49
|
+
return state.isConnected === true && state.isInternetReachable !== false;
|
|
50
|
+
}
|
|
51
|
+
function removeMobileSubscription(subscription) {
|
|
52
|
+
if (typeof subscription === "function") {
|
|
53
|
+
subscription();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
subscription.remove();
|
|
57
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { EventEnvelope } from "./index.js";
|
|
2
|
+
declare const mobilePlatforms: readonly ["android", "ios"];
|
|
3
|
+
declare const mobileNetworkStates: readonly ["offline", "online", "unknown"];
|
|
4
|
+
export type MobilePlatform = (typeof mobilePlatforms)[number];
|
|
5
|
+
export type MobileNetworkState = (typeof mobileNetworkStates)[number];
|
|
6
|
+
export type MobileSubject = {
|
|
7
|
+
kind: "anonymous";
|
|
8
|
+
anonymousId: string;
|
|
9
|
+
} | {
|
|
10
|
+
kind: "authenticated";
|
|
11
|
+
userUuid: string;
|
|
12
|
+
};
|
|
13
|
+
export type MobileEventContext = {
|
|
14
|
+
appVersion: string;
|
|
15
|
+
platform: MobilePlatform;
|
|
16
|
+
locale: string;
|
|
17
|
+
timezone: string;
|
|
18
|
+
networkState: MobileNetworkState;
|
|
19
|
+
};
|
|
20
|
+
export type MobileEventInput = {
|
|
21
|
+
eventUuid?: string;
|
|
22
|
+
eventTypeSlug: string;
|
|
23
|
+
schemaVersion: string;
|
|
24
|
+
timestamp: string;
|
|
25
|
+
sessionId?: string;
|
|
26
|
+
companySlug?: string;
|
|
27
|
+
subject: MobileSubject;
|
|
28
|
+
context: MobileEventContext;
|
|
29
|
+
payload: Record<string, unknown>;
|
|
30
|
+
};
|
|
31
|
+
export declare function createMobileEvent(input: MobileEventInput): EventEnvelope;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
const mobilePlatforms = ["android", "ios"];
|
|
2
|
+
const mobileNetworkStates = ["offline", "online", "unknown"];
|
|
3
|
+
const sensitiveMobilePayloadKeys = new Set([
|
|
4
|
+
"secret",
|
|
5
|
+
"clientsecret",
|
|
6
|
+
"producersecret",
|
|
7
|
+
"reportingsecret",
|
|
8
|
+
"token",
|
|
9
|
+
"authtoken",
|
|
10
|
+
"idtoken",
|
|
11
|
+
"oauthtoken",
|
|
12
|
+
"refreshtoken",
|
|
13
|
+
"reportingtoken",
|
|
14
|
+
"accesstoken",
|
|
15
|
+
"bearertoken",
|
|
16
|
+
"apikey",
|
|
17
|
+
"authorization",
|
|
18
|
+
"password",
|
|
19
|
+
"credential",
|
|
20
|
+
"privatekey",
|
|
21
|
+
]);
|
|
22
|
+
// createMobileEvent deliberately accepts only event metadata safe for an app
|
|
23
|
+
// binary. Producer credentials and reporting-read credentials belong on the
|
|
24
|
+
// authenticated application relay, never in a mobile event envelope.
|
|
25
|
+
export function createMobileEvent(input) {
|
|
26
|
+
assertExactKeys(input, [
|
|
27
|
+
"eventUuid",
|
|
28
|
+
"eventTypeSlug",
|
|
29
|
+
"schemaVersion",
|
|
30
|
+
"timestamp",
|
|
31
|
+
"sessionId",
|
|
32
|
+
"companySlug",
|
|
33
|
+
"subject",
|
|
34
|
+
"context",
|
|
35
|
+
"payload",
|
|
36
|
+
], "mobile event");
|
|
37
|
+
assertRequiredEventFields(input);
|
|
38
|
+
assertMobileSubject(input.subject);
|
|
39
|
+
assertMobileContext(input.context);
|
|
40
|
+
assertNoSensitiveFields(input.payload);
|
|
41
|
+
return {
|
|
42
|
+
eventUuid: input.eventUuid,
|
|
43
|
+
eventTypeSlug: input.eventTypeSlug,
|
|
44
|
+
schemaVersion: input.schemaVersion,
|
|
45
|
+
timestamp: input.timestamp,
|
|
46
|
+
sessionId: input.sessionId,
|
|
47
|
+
anonymousId: input.subject.kind === "anonymous" ? input.subject.anonymousId : undefined,
|
|
48
|
+
userUuid: input.subject.kind === "authenticated" ? input.subject.userUuid : null,
|
|
49
|
+
companySlug: input.companySlug,
|
|
50
|
+
context: {
|
|
51
|
+
device: { type: "mobile", os: input.context.platform },
|
|
52
|
+
appVersion: input.context.appVersion,
|
|
53
|
+
locale: input.context.locale,
|
|
54
|
+
timezone: input.context.timezone,
|
|
55
|
+
networkState: input.context.networkState,
|
|
56
|
+
},
|
|
57
|
+
payload: input.payload,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function assertRequiredEventFields(input) {
|
|
61
|
+
for (const [field, value] of Object.entries({
|
|
62
|
+
eventTypeSlug: input.eventTypeSlug,
|
|
63
|
+
schemaVersion: input.schemaVersion,
|
|
64
|
+
timestamp: input.timestamp,
|
|
65
|
+
})) {
|
|
66
|
+
if (!isNonBlankString(value)) {
|
|
67
|
+
throw new Error(`custd: mobile ${field} is required`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (Number.isNaN(Date.parse(input.timestamp))) {
|
|
71
|
+
throw new Error("custd: mobile timestamp must be an ISO timestamp");
|
|
72
|
+
}
|
|
73
|
+
if (!input.payload || typeof input.payload !== "object" || Array.isArray(input.payload)) {
|
|
74
|
+
throw new Error("custd: mobile payload must be an object");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function assertMobileSubject(subject) {
|
|
78
|
+
if (!subject || typeof subject !== "object") {
|
|
79
|
+
throw new Error("custd: mobile subject is required");
|
|
80
|
+
}
|
|
81
|
+
if (subject.kind === "anonymous") {
|
|
82
|
+
assertExactKeys(subject, ["kind", "anonymousId"], "anonymous mobile subject");
|
|
83
|
+
if (!isNonBlankString(subject.anonymousId)) {
|
|
84
|
+
throw new Error("custd: mobile anonymousId is required");
|
|
85
|
+
}
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (subject.kind === "authenticated") {
|
|
89
|
+
assertExactKeys(subject, ["kind", "userUuid"], "authenticated mobile subject");
|
|
90
|
+
if (!isNonBlankString(subject.userUuid)) {
|
|
91
|
+
throw new Error("custd: mobile userUuid is required");
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
throw new Error("custd: mobile subject kind must be anonymous or authenticated");
|
|
96
|
+
}
|
|
97
|
+
function assertMobileContext(context) {
|
|
98
|
+
assertExactKeys(context, ["appVersion", "platform", "locale", "timezone", "networkState"], "mobile context");
|
|
99
|
+
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(context.appVersion)) {
|
|
100
|
+
throw new Error("custd: mobile appVersion must be a semantic version");
|
|
101
|
+
}
|
|
102
|
+
if (!mobilePlatforms.includes(context.platform)) {
|
|
103
|
+
throw new Error("custd: mobile platform must be ios or android");
|
|
104
|
+
}
|
|
105
|
+
if (!isLocale(context.locale)) {
|
|
106
|
+
throw new Error("custd: mobile locale must be a valid BCP 47 locale");
|
|
107
|
+
}
|
|
108
|
+
if (!isTimezone(context.timezone)) {
|
|
109
|
+
throw new Error("custd: mobile timezone must be a valid IANA timezone");
|
|
110
|
+
}
|
|
111
|
+
if (!mobileNetworkStates.includes(context.networkState)) {
|
|
112
|
+
throw new Error("custd: mobile networkState must be offline, online, or unknown");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function assertExactKeys(value, allowed, label) {
|
|
116
|
+
for (const key of Object.keys(value)) {
|
|
117
|
+
if (!allowed.includes(key)) {
|
|
118
|
+
throw new Error(`custd: unknown ${label} field: ${key}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function assertNoSensitiveFields(value) {
|
|
123
|
+
if (!value || typeof value !== "object") {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
for (const [key, child] of Object.entries(value)) {
|
|
127
|
+
if (isSensitiveKey(key)) {
|
|
128
|
+
throw new Error(`custd: mobile event contains sensitive field: ${key}`);
|
|
129
|
+
}
|
|
130
|
+
assertNoSensitiveFields(child);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function isSensitiveKey(key) {
|
|
134
|
+
const normalized = key.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
|
|
135
|
+
return sensitiveMobilePayloadKeys.has(normalized);
|
|
136
|
+
}
|
|
137
|
+
function isLocale(value) {
|
|
138
|
+
try {
|
|
139
|
+
return Intl.getCanonicalLocales(value).length === 1;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function isTimezone(value) {
|
|
146
|
+
try {
|
|
147
|
+
Intl.DateTimeFormat("en", { timeZone: value });
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function isNonBlankString(value) {
|
|
155
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
156
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { EventEnvelope } from "./index.js";
|
|
2
|
+
export type AsyncQueueStorage = {
|
|
3
|
+
load: () => Promise<EventEnvelope[]>;
|
|
4
|
+
save: (events: EventEnvelope[]) => Promise<void>;
|
|
5
|
+
clear: () => Promise<void>;
|
|
6
|
+
};
|
|
7
|
+
export declare class AsyncEventQueue {
|
|
8
|
+
private readonly storage;
|
|
9
|
+
private readonly maxQueueSize;
|
|
10
|
+
private events;
|
|
11
|
+
private loaded;
|
|
12
|
+
private pending;
|
|
13
|
+
constructor(storage: AsyncQueueStorage, maxQueueSize: number);
|
|
14
|
+
load(): Promise<void>;
|
|
15
|
+
enqueue(event: EventEnvelope): Promise<void>;
|
|
16
|
+
peek(limit: number): Promise<EventEnvelope[]>;
|
|
17
|
+
acknowledge(eventUUIDs: readonly string[]): Promise<void>;
|
|
18
|
+
clear(): Promise<void>;
|
|
19
|
+
private run;
|
|
20
|
+
private requireLoaded;
|
|
21
|
+
private trimToCapacity;
|
|
22
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// AsyncEventQueue serializes storage mutations so an offline client retains
|
|
2
|
+
// event IDs and ordering across restart, retry, and partial batch outcomes.
|
|
3
|
+
export class AsyncEventQueue {
|
|
4
|
+
constructor(storage, maxQueueSize) {
|
|
5
|
+
this.storage = storage;
|
|
6
|
+
this.maxQueueSize = maxQueueSize;
|
|
7
|
+
this.events = [];
|
|
8
|
+
this.loaded = false;
|
|
9
|
+
this.pending = Promise.resolve();
|
|
10
|
+
if (!Number.isSafeInteger(maxQueueSize) || maxQueueSize <= 0) {
|
|
11
|
+
throw new Error("custd: async queue maxQueueSize must be a positive integer");
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
load() {
|
|
15
|
+
return this.run(async () => {
|
|
16
|
+
const stored = await this.storage.load();
|
|
17
|
+
this.events = Array.isArray(stored) ? [...stored] : [];
|
|
18
|
+
this.trimToCapacity();
|
|
19
|
+
this.loaded = true;
|
|
20
|
+
await this.storage.save(this.events);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
enqueue(event) {
|
|
24
|
+
return this.run(async () => {
|
|
25
|
+
this.requireLoaded();
|
|
26
|
+
this.events.push(event);
|
|
27
|
+
this.trimToCapacity();
|
|
28
|
+
await this.storage.save(this.events);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
peek(limit) {
|
|
32
|
+
return this.run(async () => {
|
|
33
|
+
this.requireLoaded();
|
|
34
|
+
return this.events.slice(0, normalizeLimit(limit, this.events.length));
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
acknowledge(eventUUIDs) {
|
|
38
|
+
return this.run(async () => {
|
|
39
|
+
this.requireLoaded();
|
|
40
|
+
const accepted = new Set(eventUUIDs);
|
|
41
|
+
this.events = this.events.filter((event) => !accepted.has(event.eventUuid ?? ""));
|
|
42
|
+
await this.storage.save(this.events);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
clear() {
|
|
46
|
+
return this.run(async () => {
|
|
47
|
+
this.requireLoaded();
|
|
48
|
+
this.events = [];
|
|
49
|
+
await this.storage.clear();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
run(operation) {
|
|
53
|
+
const result = this.pending.then(operation, operation);
|
|
54
|
+
this.pending = result.then(() => undefined, () => undefined);
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
requireLoaded() {
|
|
58
|
+
if (!this.loaded) {
|
|
59
|
+
throw new Error("custd: async queue must load before use");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
trimToCapacity() {
|
|
63
|
+
if (this.events.length > this.maxQueueSize) {
|
|
64
|
+
this.events = this.events.slice(-this.maxQueueSize);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function normalizeLimit(limit, available) {
|
|
69
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) {
|
|
70
|
+
throw new Error("custd: async queue limit must be a positive integer");
|
|
71
|
+
}
|
|
72
|
+
return Math.min(limit, available);
|
|
73
|
+
}
|
package/dist/oauth.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function basicAuthorization(clientId: string, clientSecret: string): string;
|
package/dist/oauth.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { RenderedWidgetData, ReportingNextActionHint, ReportingQueryRequest } from "./index.js";
|
|
2
|
+
/**
|
|
3
|
+
* The server can return data with more than one quality signal at once. Keep
|
|
4
|
+
* the combined state explicit so callers do not infer it from colour or from
|
|
5
|
+
* a missing chart.
|
|
6
|
+
*/
|
|
7
|
+
export type ReportingDataState = "empty" | "ready" | "stale" | "partial" | "stale_partial" | "unavailable";
|
|
8
|
+
export type ReportingQueryState<T> = {
|
|
9
|
+
status: "loading";
|
|
10
|
+
data?: T;
|
|
11
|
+
} | {
|
|
12
|
+
status: "error";
|
|
13
|
+
error: unknown;
|
|
14
|
+
data?: T;
|
|
15
|
+
} | {
|
|
16
|
+
status: "success";
|
|
17
|
+
data: T;
|
|
18
|
+
};
|
|
19
|
+
export type ReportingViewState<T> = {
|
|
20
|
+
phase: "loading";
|
|
21
|
+
data?: T;
|
|
22
|
+
dataState?: ReportingDataState;
|
|
23
|
+
retryable: boolean;
|
|
24
|
+
nextAction: ReportingNextActionHint;
|
|
25
|
+
} | {
|
|
26
|
+
phase: "error";
|
|
27
|
+
error: unknown;
|
|
28
|
+
data?: T;
|
|
29
|
+
dataState?: ReportingDataState;
|
|
30
|
+
retryable: boolean;
|
|
31
|
+
nextAction: ReportingNextActionHint;
|
|
32
|
+
} | {
|
|
33
|
+
phase: "success";
|
|
34
|
+
data: T;
|
|
35
|
+
dataState: ReportingDataState;
|
|
36
|
+
retryable: boolean;
|
|
37
|
+
nextAction: ReportingNextActionHint;
|
|
38
|
+
};
|
|
39
|
+
export declare function classifyReportingData(data: RenderedWidgetData): ReportingDataState;
|
|
40
|
+
export declare function getReportingViewState<T extends RenderedWidgetData>(query: ReportingQueryState<T>): ReportingViewState<T>;
|
|
41
|
+
/**
|
|
42
|
+
* Build a deterministic cache key from a server-owned reporting request. The
|
|
43
|
+
* key contains no client-owned cache policy or response data, and filter order
|
|
44
|
+
* does not cause duplicate entries.
|
|
45
|
+
*/
|
|
46
|
+
export declare function reportingQueryKey(request: ReportingQueryRequest): readonly [string, string, string];
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const NO_ACTION = { action: "none" };
|
|
2
|
+
export function classifyReportingData(data) {
|
|
3
|
+
const trust = data.trust;
|
|
4
|
+
if (trust?.status === "unavailable" || trust?.dataFreshness === "unavailable")
|
|
5
|
+
return "unavailable";
|
|
6
|
+
if (data.buckets.length === 0 && data.value.sampleCount === 0)
|
|
7
|
+
return "empty";
|
|
8
|
+
const stale = trust?.dataFreshness === "stale";
|
|
9
|
+
const partial = data.value.complete === false ||
|
|
10
|
+
trust?.status === "partial" ||
|
|
11
|
+
trust?.coverage === "partial" ||
|
|
12
|
+
trust?.rollupState === "partial";
|
|
13
|
+
if (stale && partial)
|
|
14
|
+
return "stale_partial";
|
|
15
|
+
if (partial)
|
|
16
|
+
return "partial";
|
|
17
|
+
if (stale)
|
|
18
|
+
return "stale";
|
|
19
|
+
return "ready";
|
|
20
|
+
}
|
|
21
|
+
export function getReportingViewState(query) {
|
|
22
|
+
const data = query.data;
|
|
23
|
+
const action = data?.trust?.nextAction ?? NO_ACTION;
|
|
24
|
+
const retryable = data?.trust?.retryability === "bounded" || action.action === "retry" || action.action === "poll";
|
|
25
|
+
if (query.status === "loading") {
|
|
26
|
+
return {
|
|
27
|
+
phase: "loading",
|
|
28
|
+
data,
|
|
29
|
+
dataState: data ? classifyReportingData(data) : undefined,
|
|
30
|
+
retryable,
|
|
31
|
+
nextAction: action,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
if (query.status === "error") {
|
|
35
|
+
return {
|
|
36
|
+
phase: "error",
|
|
37
|
+
error: query.error,
|
|
38
|
+
data,
|
|
39
|
+
dataState: data ? classifyReportingData(data) : undefined,
|
|
40
|
+
retryable,
|
|
41
|
+
nextAction: action,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const successData = query.data;
|
|
45
|
+
return {
|
|
46
|
+
phase: "success",
|
|
47
|
+
data: successData,
|
|
48
|
+
dataState: classifyReportingData(successData),
|
|
49
|
+
retryable,
|
|
50
|
+
nextAction: action,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Build a deterministic cache key from a server-owned reporting request. The
|
|
55
|
+
* key contains no client-owned cache policy or response data, and filter order
|
|
56
|
+
* does not cause duplicate entries.
|
|
57
|
+
*/
|
|
58
|
+
export function reportingQueryKey(request) {
|
|
59
|
+
const normalized = { ...request, filters: request.filters?.slice().sort(compareFilters) };
|
|
60
|
+
return ["custd", "reporting", stableJson(normalized)];
|
|
61
|
+
}
|
|
62
|
+
function compareFilters(left, right) {
|
|
63
|
+
return `${left.dimension}\u0000${left.operator}\u0000${left.value ?? ""}`.localeCompare(`${right.dimension}\u0000${right.operator}\u0000${right.value ?? ""}`);
|
|
64
|
+
}
|
|
65
|
+
function stableJson(value) {
|
|
66
|
+
if (Array.isArray(value))
|
|
67
|
+
return `[${value.map(stableJson).join(",")}]`;
|
|
68
|
+
if (value && typeof value === "object") {
|
|
69
|
+
return `{${Object.entries(value)
|
|
70
|
+
.filter(([, child]) => child !== undefined)
|
|
71
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
72
|
+
.map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)
|
|
73
|
+
.join(",")}}`;
|
|
74
|
+
}
|
|
75
|
+
return JSON.stringify(value);
|
|
76
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type RuntimeReadinessOAuthConfig = {
|
|
2
|
+
name: string;
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
tokenUrl: string;
|
|
6
|
+
audience?: string;
|
|
7
|
+
scopes?: string[];
|
|
8
|
+
};
|
|
9
|
+
export type RuntimeReadinessCredentialResult = {
|
|
10
|
+
name: string;
|
|
11
|
+
tenantSlug: string;
|
|
12
|
+
tokenIssued: true;
|
|
13
|
+
};
|
|
14
|
+
export type RuntimeReadinessResult = {
|
|
15
|
+
ready: true;
|
|
16
|
+
tenantSlug: string;
|
|
17
|
+
eventTypeSlug: string;
|
|
18
|
+
schemaVersion: string;
|
|
19
|
+
credentials: RuntimeReadinessCredentialResult[];
|
|
20
|
+
};
|
|
21
|
+
export type RuntimeReadinessOptions = {
|
|
22
|
+
baseUrl: string;
|
|
23
|
+
schemaUrl?: string;
|
|
24
|
+
tenantSlug: string;
|
|
25
|
+
eventTypeSlug: string;
|
|
26
|
+
schemaVersion: string;
|
|
27
|
+
oauth: RuntimeReadinessOAuthConfig[];
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
};
|
|
30
|
+
export declare function checkRuntimeReadiness(options: RuntimeReadinessOptions): Promise<RuntimeReadinessResult>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { basicAuthorization } from "./oauth.js";
|
|
2
|
+
function nonEmpty(value) {
|
|
3
|
+
return typeof value === "string" && value.trim() !== "";
|
|
4
|
+
}
|
|
5
|
+
function validateText(name, value) {
|
|
6
|
+
if (!nonEmpty(value))
|
|
7
|
+
throw new Error(`Custd readiness requires ${name}`);
|
|
8
|
+
}
|
|
9
|
+
function normalizeEndpoint(name, value) {
|
|
10
|
+
let parsed;
|
|
11
|
+
try {
|
|
12
|
+
parsed = new URL(value);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
throw new Error(`Custd readiness ${name} is not a valid URL`);
|
|
16
|
+
}
|
|
17
|
+
if (parsed.username || parsed.password || parsed.search || parsed.hash) {
|
|
18
|
+
throw new Error(`Custd readiness ${name} must not contain credentials or URL query data`);
|
|
19
|
+
}
|
|
20
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
21
|
+
throw new Error(`Custd readiness ${name} must use HTTP or HTTPS`);
|
|
22
|
+
}
|
|
23
|
+
return value.replace(/\/+$/u, "");
|
|
24
|
+
}
|
|
25
|
+
function validateOptions(options) {
|
|
26
|
+
validateText("base URL", options.baseUrl);
|
|
27
|
+
validateText("tenant slug", options.tenantSlug);
|
|
28
|
+
validateText("event type", options.eventTypeSlug);
|
|
29
|
+
validateText("schema version", options.schemaVersion);
|
|
30
|
+
if (!Array.isArray(options.oauth) || options.oauth.length === 0) {
|
|
31
|
+
throw new Error("Custd readiness requires at least one OAuth credential");
|
|
32
|
+
}
|
|
33
|
+
const names = new Set();
|
|
34
|
+
for (const credential of options.oauth) {
|
|
35
|
+
validateText("OAuth credential name", credential?.name);
|
|
36
|
+
if (names.has(credential.name)) {
|
|
37
|
+
throw new Error(`Custd readiness has duplicate OAuth credential name "${credential.name}"`);
|
|
38
|
+
}
|
|
39
|
+
names.add(credential.name);
|
|
40
|
+
validateText(`OAuth credential "${credential.name}" client ID`, credential.clientId);
|
|
41
|
+
validateText(`OAuth credential "${credential.name}" client secret`, credential.clientSecret);
|
|
42
|
+
validateText(`OAuth credential "${credential.name}" token URL`, credential.tokenUrl);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async function request(fetchImpl, input, init, label) {
|
|
46
|
+
try {
|
|
47
|
+
return await fetchImpl(input, init);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new Error(`Custd readiness ${label} request failed`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function requireOk(fetchImpl, input, init, label) {
|
|
54
|
+
const response = await request(fetchImpl, input, init, label);
|
|
55
|
+
if (!response.ok) {
|
|
56
|
+
throw new Error(`Custd readiness ${label} failed (HTTP ${response.status})`);
|
|
57
|
+
}
|
|
58
|
+
return response;
|
|
59
|
+
}
|
|
60
|
+
async function readJson(response, label) {
|
|
61
|
+
try {
|
|
62
|
+
return await response.json();
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new Error(`Custd readiness ${label} returned invalid JSON`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function issueToken(fetchImpl, credential) {
|
|
69
|
+
const body = new URLSearchParams({
|
|
70
|
+
grant_type: "client_credentials",
|
|
71
|
+
...(credential.audience ? { audience: credential.audience } : {}),
|
|
72
|
+
...(credential.scopes?.length ? { scope: credential.scopes.join(" ") } : {}),
|
|
73
|
+
});
|
|
74
|
+
const response = await requireOk(fetchImpl, normalizeEndpoint("token URL", credential.tokenUrl), {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: {
|
|
77
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
78
|
+
Authorization: basicAuthorization(credential.clientId, credential.clientSecret),
|
|
79
|
+
},
|
|
80
|
+
body,
|
|
81
|
+
}, `credential "${credential.name}" token issuance`);
|
|
82
|
+
const token = await readJson(response, `credential "${credential.name}" token issuance`);
|
|
83
|
+
if (!token || typeof token !== "object" || !nonEmpty(token.access_token)) {
|
|
84
|
+
throw new Error(`Custd readiness credential "${credential.name}" token issuance returned no access token`);
|
|
85
|
+
}
|
|
86
|
+
return token.access_token;
|
|
87
|
+
}
|
|
88
|
+
function accountTenant(account) {
|
|
89
|
+
if (!account || typeof account !== "object")
|
|
90
|
+
return undefined;
|
|
91
|
+
const record = account;
|
|
92
|
+
if (nonEmpty(record.companySlug))
|
|
93
|
+
return record.companySlug;
|
|
94
|
+
return nonEmpty(record.tenant?.slug) ? record.tenant.slug : undefined;
|
|
95
|
+
}
|
|
96
|
+
async function verifyTenantBinding(fetchImpl, baseUrl, credential, token, tenantSlug) {
|
|
97
|
+
const response = await requireOk(fetchImpl, `${baseUrl}/api/v1/account/me`, { headers: { Authorization: `Bearer ${token}` } }, `credential "${credential.name}" tenant binding`);
|
|
98
|
+
const account = await readJson(response, `credential "${credential.name}" tenant binding`);
|
|
99
|
+
if (accountTenant(account) !== tenantSlug) {
|
|
100
|
+
throw new Error(`Custd readiness credential "${credential.name}" tenant binding failed`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function schemaVersions(body) {
|
|
104
|
+
if (Array.isArray(body))
|
|
105
|
+
return body;
|
|
106
|
+
if (body && typeof body === "object") {
|
|
107
|
+
const record = body;
|
|
108
|
+
if (Array.isArray(record.versions))
|
|
109
|
+
return record.versions;
|
|
110
|
+
if (Array.isArray(record.schemas))
|
|
111
|
+
return record.schemas;
|
|
112
|
+
}
|
|
113
|
+
return [];
|
|
114
|
+
}
|
|
115
|
+
async function verifyActiveSchema(fetchImpl, schemaUrl, token, eventTypeSlug, schemaVersion) {
|
|
116
|
+
const path = `/api/v1/schemas/${encodeURIComponent(eventTypeSlug)}/versions`;
|
|
117
|
+
const response = await requireOk(fetchImpl, schemaUrl + path, { headers: { Authorization: `Bearer ${token}` } }, "active schema");
|
|
118
|
+
const versions = schemaVersions(await readJson(response, "active schema"));
|
|
119
|
+
const selected = versions.find((version) => version && typeof version === "object" && version.version === schemaVersion);
|
|
120
|
+
if (!selected || (selected.isActive !== true && selected.enabled !== true)) {
|
|
121
|
+
throw new Error(`Custd readiness active schema "${eventTypeSlug}@${schemaVersion}" is not active`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export async function checkRuntimeReadiness(options) {
|
|
125
|
+
validateOptions(options);
|
|
126
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
127
|
+
if (typeof fetchImpl !== "function")
|
|
128
|
+
throw new Error("Custd readiness requires fetch");
|
|
129
|
+
const baseUrl = normalizeEndpoint("base URL", options.baseUrl);
|
|
130
|
+
const schemaUrl = normalizeEndpoint("schema URL", options.schemaUrl ?? options.baseUrl);
|
|
131
|
+
await requireOk(fetchImpl, `${baseUrl}/health`, undefined, "endpoint");
|
|
132
|
+
const issued = [];
|
|
133
|
+
for (const credential of options.oauth) {
|
|
134
|
+
const token = await issueToken(fetchImpl, credential);
|
|
135
|
+
await verifyTenantBinding(fetchImpl, baseUrl, credential, token, options.tenantSlug);
|
|
136
|
+
issued.push({ credential, token });
|
|
137
|
+
}
|
|
138
|
+
await verifyActiveSchema(fetchImpl, schemaUrl, issued[0].token, options.eventTypeSlug, options.schemaVersion);
|
|
139
|
+
return {
|
|
140
|
+
ready: true,
|
|
141
|
+
tenantSlug: options.tenantSlug,
|
|
142
|
+
eventTypeSlug: options.eventTypeSlug,
|
|
143
|
+
schemaVersion: options.schemaVersion,
|
|
144
|
+
credentials: issued.map(({ credential }) => ({
|
|
145
|
+
name: credential.name,
|
|
146
|
+
tenantSlug: options.tenantSlug,
|
|
147
|
+
tokenIssued: true,
|
|
148
|
+
})),
|
|
149
|
+
};
|
|
150
|
+
}
|