@haakco/custd-sdk 2.4.0 → 3.71.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +586 -40
  3. package/dist/admin-accounting-evidence.d.ts +48 -0
  4. package/dist/admin-accounting-evidence.js +24 -0
  5. package/dist/admin-app-releases.d.ts +116 -0
  6. package/dist/admin-app-releases.js +8 -0
  7. package/dist/admin-apps.d.ts +120 -0
  8. package/dist/admin-apps.js +47 -0
  9. package/dist/admin-auth-project-domain.d.ts +125 -0
  10. package/dist/admin-auth-project-domain.js +37 -0
  11. package/dist/admin-auth-projects.d.ts +989 -0
  12. package/dist/admin-auth-projects.js +527 -0
  13. package/dist/admin-campaign-email.d.ts +120 -0
  14. package/dist/admin-campaign-email.js +64 -0
  15. package/dist/admin-client-setup.d.ts +22 -0
  16. package/dist/admin-client-setup.js +11 -1
  17. package/dist/admin-data-scopes.d.ts +93 -0
  18. package/dist/admin-data-scopes.js +154 -0
  19. package/dist/admin-email-relay.d.ts +66 -0
  20. package/dist/admin-email-relay.js +25 -0
  21. package/dist/admin-environment-policy.d.ts +32 -0
  22. package/dist/admin-environment-policy.js +26 -0
  23. package/dist/admin-error-issues.d.ts +91 -0
  24. package/dist/admin-error-issues.js +52 -0
  25. package/dist/admin-event-types.d.ts +57 -0
  26. package/dist/admin-event-types.js +28 -0
  27. package/dist/admin-impersonation.d.ts +48 -0
  28. package/dist/admin-impersonation.js +27 -0
  29. package/dist/admin-ingest-claims.d.ts +35 -0
  30. package/dist/admin-ingest-claims.js +26 -0
  31. package/dist/admin-managed-audit.d.ts +13 -0
  32. package/dist/admin-managed-audit.js +13 -0
  33. package/dist/admin-measurement-projects.d.ts +166 -0
  34. package/dist/admin-measurement-projects.js +120 -0
  35. package/dist/admin-notification-destinations.d.ts +31 -0
  36. package/dist/admin-notification-destinations.js +19 -0
  37. package/dist/admin-notification-webhooks.d.ts +64 -0
  38. package/dist/admin-notification-webhooks.js +42 -0
  39. package/dist/admin-oauth-client-admissions.d.ts +65 -0
  40. package/dist/admin-oauth-client-admissions.js +46 -0
  41. package/dist/admin-offboarding.d.ts +20 -6
  42. package/dist/admin-offboarding.js +27 -6
  43. package/dist/admin-predictions.d.ts +127 -8
  44. package/dist/admin-predictions.js +22 -12
  45. package/dist/admin-privacy-erasures.d.ts +24 -12
  46. package/dist/admin-privacy-erasures.js +3 -2
  47. package/dist/admin-retention.d.ts +72 -24
  48. package/dist/admin-retention.js +38 -13
  49. package/dist/admin-rls.d.ts +94 -0
  50. package/dist/admin-rls.js +33 -0
  51. package/dist/admin-sdk-usage.d.ts +41 -0
  52. package/dist/admin-sdk-usage.js +23 -0
  53. package/dist/admin-site-ai.d.ts +72 -0
  54. package/dist/admin-site-ai.js +1 -0
  55. package/dist/admin-site-analytics.d.ts +52 -0
  56. package/dist/admin-site-analytics.js +14 -0
  57. package/dist/admin-site-audit-pages.d.ts +76 -0
  58. package/dist/admin-site-audit-pages.js +27 -0
  59. package/dist/admin-site-campaign-links.d.ts +40 -0
  60. package/dist/admin-site-campaign-links.js +9 -0
  61. package/dist/admin-site-domains.d.ts +733 -0
  62. package/dist/admin-site-domains.js +768 -0
  63. package/dist/admin-site-export.d.ts +76 -0
  64. package/dist/admin-site-export.js +15 -0
  65. package/dist/admin-site-insights-tasks.d.ts +44 -0
  66. package/dist/admin-site-insights-tasks.js +28 -0
  67. package/dist/admin-site-insights.d.ts +527 -0
  68. package/dist/admin-site-insights.js +61 -0
  69. package/dist/admin-site-links.d.ts +87 -0
  70. package/dist/admin-site-links.js +16 -0
  71. package/dist/admin-site-monitors.d.ts +110 -0
  72. package/dist/admin-site-monitors.js +25 -0
  73. package/dist/admin-site-next-actions.d.ts +93 -0
  74. package/dist/admin-site-next-actions.js +36 -0
  75. package/dist/admin-site-page-queries.d.ts +63 -0
  76. package/dist/admin-site-page-queries.js +20 -0
  77. package/dist/admin-site-rankings.d.ts +98 -0
  78. package/dist/admin-site-rankings.js +46 -0
  79. package/dist/admin-site-regional-trends.d.ts +30 -0
  80. package/dist/admin-site-regional-trends.js +1 -0
  81. package/dist/admin-site-saved-reports.d.ts +45 -0
  82. package/dist/admin-site-saved-reports.js +13 -0
  83. package/dist/admin-site-search-pool.d.ts +77 -0
  84. package/dist/admin-site-search-pool.js +41 -0
  85. package/dist/admin-site-search-value.d.ts +97 -0
  86. package/dist/admin-site-search-value.js +29 -0
  87. package/dist/admin-site-status-page.d.ts +57 -0
  88. package/dist/admin-site-status-page.js +10 -0
  89. package/dist/admin-site-traffic.d.ts +145 -0
  90. package/dist/admin-site-traffic.js +32 -0
  91. package/dist/admin-site-web-data.d.ts +258 -0
  92. package/dist/admin-site-web-data.js +60 -0
  93. package/dist/admin-subject-exports.d.ts +58 -27
  94. package/dist/admin-subject-exports.js +32 -16
  95. package/dist/admin-support-access.d.ts +32 -0
  96. package/dist/admin-support-access.js +21 -0
  97. package/dist/admin-system.d.ts +283 -0
  98. package/dist/admin-system.js +65 -0
  99. package/dist/admin-tenant-storage.d.ts +22 -14
  100. package/dist/admin-tenant-storage.js +13 -14
  101. package/dist/admin-timeplans.d.ts +276 -2
  102. package/dist/admin-timeplans.js +54 -0
  103. package/dist/admin-uncertainty-models.d.ts +42 -0
  104. package/dist/admin-uncertainty-models.js +53 -0
  105. package/dist/admin-usage.d.ts +124 -0
  106. package/dist/admin-usage.js +169 -0
  107. package/dist/admin-users.d.ts +124 -0
  108. package/dist/admin-users.js +82 -0
  109. package/dist/admin-workflow-timings.d.ts +367 -0
  110. package/dist/admin-workflow-timings.js +117 -0
  111. package/dist/analytics-events.d.ts +82 -0
  112. package/dist/analytics-events.js +157 -0
  113. package/dist/analytics-reads.d.ts +81 -0
  114. package/dist/analytics-reads.js +5 -0
  115. package/dist/app-account.d.ts +84 -0
  116. package/dist/app-account.js +177 -0
  117. package/dist/app-alerts.d.ts +120 -0
  118. package/dist/app-alerts.js +44 -0
  119. package/dist/app-items.d.ts +786 -0
  120. package/dist/app-items.js +524 -0
  121. package/dist/app-live.d.ts +84 -0
  122. package/dist/app-live.js +228 -0
  123. package/dist/app-meetings.d.ts +95 -0
  124. package/dist/app-meetings.js +26 -0
  125. package/dist/app-models.d.ts +271 -0
  126. package/dist/app-models.js +83 -0
  127. package/dist/app-push.d.ts +64 -0
  128. package/dist/app-push.js +178 -0
  129. package/dist/backend-lifecycle.d.ts +2 -2
  130. package/dist/browser-manifest.json +5 -5
  131. package/dist/browser-script-BWnwDjAC.js +711 -0
  132. package/dist/browser-sign-in.d.ts +153 -0
  133. package/dist/browser-sign-in.js +410 -0
  134. package/dist/browser-tracker.d.ts +95 -0
  135. package/dist/browser-tracker.js +362 -40
  136. package/dist/browser-web-vitals.d.ts +22 -0
  137. package/dist/browser-web-vitals.js +116 -0
  138. package/dist/browser.d.ts +9 -0
  139. package/dist/browser.js +9 -0
  140. package/dist/download-stream.d.ts +16 -0
  141. package/dist/download-stream.js +55 -0
  142. package/dist/error-capture.d.ts +62 -0
  143. package/dist/error-capture.js +168 -0
  144. package/dist/hosted-app.d.ts +115 -0
  145. package/dist/hosted-app.js +275 -0
  146. package/dist/index.d.ts +1168 -154
  147. package/dist/index.js +682 -162
  148. package/dist/ingest-operations.d.ts +483 -0
  149. package/dist/ingest-operations.js +154 -0
  150. package/dist/measurement.d.ts +164 -0
  151. package/dist/measurement.js +104 -0
  152. package/dist/parsers.d.ts +149 -0
  153. package/dist/parsers.js +115 -0
  154. package/dist/public-reads.d.ts +79 -0
  155. package/dist/public-reads.js +57 -0
  156. package/dist/reporting-catalogue.d.ts +264 -0
  157. package/dist/reporting-catalogue.js +5 -0
  158. package/dist/response-lists.d.ts +16 -0
  159. package/dist/response-lists.generated.d.ts +7 -0
  160. package/dist/response-lists.generated.js +1927 -0
  161. package/dist/response-lists.js +70 -0
  162. package/dist/response-validation.d.ts +30 -0
  163. package/dist/response-validation.js +94 -0
  164. package/dist/schema-registry.d.ts +45 -0
  165. package/dist/schema-registry.js +9 -0
  166. package/dist/secure-url.d.ts +4 -0
  167. package/dist/secure-url.js +23 -0
  168. package/dist/site-ai-owner.d.ts +34 -0
  169. package/dist/site-ai-owner.js +99 -0
  170. package/dist/site-monitor-reports.d.ts +15 -0
  171. package/dist/site-monitor-reports.js +87 -0
  172. package/dist/testing/fake-custd.d.ts +150 -0
  173. package/dist/testing/fake-custd.js +842 -0
  174. package/dist/testing/fake-results.d.ts +30 -0
  175. package/dist/testing/fake-results.js +293 -0
  176. package/dist/testing.d.ts +2 -0
  177. package/dist/testing.js +3 -0
  178. package/dist/version.d.ts +2 -2
  179. package/dist/version.js +1 -1
  180. package/package.json +25 -14
  181. package/dist/browser-script-BvgjdZSO.js +0 -429
  182. package/dist/fixtures.d.ts +0 -10
  183. package/dist/fixtures.js +0 -57
@@ -0,0 +1,70 @@
1
+ // Custd's Go services send a nil list as JSON null. Every SDK result shows it as an empty list, so
2
+ // each transport passes the decoded body through one normaliser built from the generated table of
3
+ // list fields per operation. Only those fields change: a nullable field that is not a list stays null.
4
+ import { API_RESPONSE_LISTS, APP_RESPONSE_LISTS, SITE_CONFIG_RESPONSE_LISTS } from "./response-lists.generated.js";
5
+ /**
6
+ * Returns the decode step for one table: it takes the request method, the request path from /api/v1
7
+ * (a query is ignored) and the decoded body. The table's routes compile on the first response.
8
+ */
9
+ export function responseListNormaliser(table) {
10
+ let routes;
11
+ return function emptyNullListsOf(method, requestPath, body) {
12
+ routes ?? (routes = compileRoutes(table));
13
+ const [path = ""] = requestPath.split("?", 1);
14
+ const route = routes.find((candidate) => (candidate.method === method || candidate.method === "ANY") && candidate.pattern.test(path));
15
+ if (body === null && route?.fields.some((field) => field.length === 1 && field[0] === "[]"))
16
+ return [];
17
+ for (const field of route?.fields ?? [])
18
+ emptyNullLists(body, field, 0);
19
+ return body;
20
+ };
21
+ }
22
+ /** CustdClient's decode step. Each is pure, so a bundle that never uses one drops its table. */
23
+ export const emptyApiNullLists = /* @__PURE__ */ responseListNormaliser(API_RESPONSE_LISTS);
24
+ /** AppItemsClient's decode step. */
25
+ export const emptyAppNullLists = /* @__PURE__ */ responseListNormaliser(APP_RESPONSE_LISTS);
26
+ /** fetchBrowserSiteConfig's decode step. */
27
+ export const emptySiteConfigNullLists = /* @__PURE__ */ responseListNormaliser(SITE_CONFIG_RESPONSE_LISTS);
28
+ // A literal segment outranks a parameter, so /site-domains/keyword-lists is not read as a domain UUID.
29
+ function compileRoutes(table) {
30
+ return Object.entries(table)
31
+ .map(([operation, fields]) => {
32
+ const [method = "", template = ""] = operation.split(" ");
33
+ const segments = template
34
+ .split("/")
35
+ .map((segment) => (/^\{[^}]+\}$/.test(segment) ? "[^/]+" : escapeLiteral(segment)));
36
+ return {
37
+ method,
38
+ pattern: new RegExp(`^${segments.join("/")}$`),
39
+ parameters: segments.filter((segment) => segment === "[^/]+").length,
40
+ fields: fields.map((field) => field.split(".").flatMap(listSegments)),
41
+ };
42
+ })
43
+ .sort((left, right) => left.parameters - right.parameters);
44
+ }
45
+ function listSegments(segment) {
46
+ const name = segment.replace(/(\[\])+$/, "");
47
+ const items = (segment.length - name.length) / 2;
48
+ return [...(name ? [name] : []), ...Array(items).fill("[]")];
49
+ }
50
+ function escapeLiteral(segment) {
51
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
52
+ }
53
+ function emptyNullLists(node, field, index) {
54
+ const segment = field[index];
55
+ if (segment === "[]") {
56
+ if (Array.isArray(node))
57
+ for (const item of node)
58
+ emptyNullLists(item, field, index + 1);
59
+ return;
60
+ }
61
+ if (segment === undefined || typeof node !== "object" || node === null || Array.isArray(node))
62
+ return;
63
+ const record = node;
64
+ if (index === field.length - 1) {
65
+ if (record[segment] === null)
66
+ record[segment] = [];
67
+ return;
68
+ }
69
+ emptyNullLists(record[segment], field, index + 1);
70
+ }
@@ -0,0 +1,30 @@
1
+ /** A decoded JSON object, keyed by string. */
2
+ export type JsonRecord = Record<string, unknown>;
3
+ export declare function requireRecord(value: unknown, context: string): JsonRecord;
4
+ export declare function requireString(record: JsonRecord, key: string, context: string): string;
5
+ export declare function requireInteger(record: JsonRecord, key: string, context: string): number;
6
+ export declare function requireBoolean(record: JsonRecord, key: string, context: string): boolean;
7
+ /**
8
+ * Return the named list of JSON objects. A missing or non-list container, or a
9
+ * scalar element, fails. A JSON null list decodes as empty, and is replaced by
10
+ * `[]` in the record so the returned DTO always carries a list.
11
+ */
12
+ export declare function requireObjectList(record: JsonRecord, key: string, context: string): JsonRecord[];
13
+ /**
14
+ * Validate an optional field only when it is present. An absent field (or an
15
+ * explicitly `undefined` one) is valid; a present value must satisfy the
16
+ * declared type, so a present `null` fails rather than being treated as absent.
17
+ * Every producer of these DTOs omits an empty optional rather than sending null.
18
+ */
19
+ export declare function optionalString(record: JsonRecord, key: string, context: string): void;
20
+ /**
21
+ * Validate an optional integer field only when it is present. A present `null`
22
+ * fails because the declared type is omitted-or-integer, not nullable.
23
+ */
24
+ export declare function optionalInteger(record: JsonRecord, key: string, context: string): void;
25
+ /**
26
+ * Validate an optional JSON-object field only when it is present. An absent
27
+ * field is valid; a present value must be a JSON object, so a present `null` or
28
+ * array fails against the declared `Record` type.
29
+ */
30
+ export declare function optionalRecord(record: JsonRecord, key: string, context: string): void;
@@ -0,0 +1,94 @@
1
+ // Narrow runtime guards shared by the typed response boundaries.
2
+ //
3
+ // The TypeScript response types are erased at runtime, so a JSON success body
4
+ // that omits an owner-required field or carries the wrong shape would otherwise
5
+ // flow through a generic cast. These guards reject that body at the boundary.
6
+ // They are internal to the SDK and not re-exported from the package index.
7
+ export function requireRecord(value, context) {
8
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
9
+ throw new TypeError(`custd: ${context} must be a JSON object`);
10
+ }
11
+ return value;
12
+ }
13
+ function requireField(record, key, context) {
14
+ const value = record[key];
15
+ if (value === undefined || value === null) {
16
+ throw new TypeError(`custd: ${context} field ${key} is required`);
17
+ }
18
+ return value;
19
+ }
20
+ export function requireString(record, key, context) {
21
+ const value = requireField(record, key, context);
22
+ if (typeof value !== "string") {
23
+ throw new TypeError(`custd: ${context} field ${key} must be a string`);
24
+ }
25
+ return value;
26
+ }
27
+ export function requireInteger(record, key, context) {
28
+ const value = requireField(record, key, context);
29
+ if (typeof value !== "number" || !Number.isInteger(value)) {
30
+ throw new TypeError(`custd: ${context} field ${key} must be an integer`);
31
+ }
32
+ return value;
33
+ }
34
+ export function requireBoolean(record, key, context) {
35
+ const value = requireField(record, key, context);
36
+ if (typeof value !== "boolean") {
37
+ throw new TypeError(`custd: ${context} field ${key} must be a boolean`);
38
+ }
39
+ return value;
40
+ }
41
+ /**
42
+ * Return the named list of JSON objects. A missing or non-list container, or a
43
+ * scalar element, fails. A JSON null list decodes as empty, and is replaced by
44
+ * `[]` in the record so the returned DTO always carries a list.
45
+ */
46
+ export function requireObjectList(record, key, context) {
47
+ if (record[key] === null)
48
+ record[key] = [];
49
+ const value = requireField(record, key, context);
50
+ if (!Array.isArray(value)) {
51
+ throw new TypeError(`custd: ${context} field ${key} must be a list`);
52
+ }
53
+ return value.map((item, index) => requireRecord(item, `${context} ${key}[${index}]`));
54
+ }
55
+ /**
56
+ * Validate an optional field only when it is present. An absent field (or an
57
+ * explicitly `undefined` one) is valid; a present value must satisfy the
58
+ * declared type, so a present `null` fails rather than being treated as absent.
59
+ * Every producer of these DTOs omits an empty optional rather than sending null.
60
+ */
61
+ export function optionalString(record, key, context) {
62
+ const value = record[key];
63
+ if (value === undefined) {
64
+ return;
65
+ }
66
+ if (typeof value !== "string") {
67
+ throw new TypeError(`custd: ${context} field ${key} must be a string`);
68
+ }
69
+ }
70
+ /**
71
+ * Validate an optional integer field only when it is present. A present `null`
72
+ * fails because the declared type is omitted-or-integer, not nullable.
73
+ */
74
+ export function optionalInteger(record, key, context) {
75
+ const value = record[key];
76
+ if (value === undefined) {
77
+ return;
78
+ }
79
+ if (typeof value !== "number" || !Number.isInteger(value)) {
80
+ throw new TypeError(`custd: ${context} field ${key} must be an integer`);
81
+ }
82
+ }
83
+ /**
84
+ * Validate an optional JSON-object field only when it is present. An absent
85
+ * field is valid; a present value must be a JSON object, so a present `null` or
86
+ * array fails against the declared `Record` type.
87
+ */
88
+ export function optionalRecord(record, key, context) {
89
+ const value = record[key];
90
+ if (value === undefined) {
91
+ return;
92
+ }
93
+ requireRecord(value, `${context} field ${key}`);
94
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The tenant's event schema collection in the schema registry (/api/v1/schemas). The credential names
3
+ * the tenant, so no call takes a slug.
4
+ */
5
+ /** One event type the tenant can send. */
6
+ export type RegisteredEventType = {
7
+ slug: string;
8
+ name: string;
9
+ enabled: boolean;
10
+ };
11
+ export type RegisteredEventTypeList = {
12
+ eventTypes: RegisteredEventType[];
13
+ };
14
+ /** One stored version of an event type's schema. `jsonSchema` is the schema document as text. */
15
+ export type EventSchemaVersion = {
16
+ version: string;
17
+ jsonSchema: string;
18
+ isActive: boolean;
19
+ enabled: boolean;
20
+ };
21
+ export type EventSchemaVersionList = {
22
+ versions: EventSchemaVersion[];
23
+ };
24
+ /** One version's JSON Schema document exactly as stored. */
25
+ export type EventSchemaDocument = {
26
+ schema: unknown;
27
+ };
28
+ /**
29
+ * Registers a schema version, creating the event type when it is new. `jsonSchema` is the schema
30
+ * document as text.
31
+ */
32
+ export type EventSchemaRegisterRequest = {
33
+ slug: string;
34
+ name: string;
35
+ version: string;
36
+ jsonSchema: string;
37
+ enabled: boolean;
38
+ isActive: boolean;
39
+ };
40
+ /** Confirms a state change. */
41
+ export type EventSchemaStateResult = {
42
+ updated: boolean;
43
+ };
44
+ export declare const schemaRegistryPath = "/schemas";
45
+ export declare function eventSchemaPath(eventType: string, version?: string): string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The tenant's event schema collection in the schema registry (/api/v1/schemas). The credential names
3
+ * the tenant, so no call takes a slug.
4
+ */
5
+ export const schemaRegistryPath = "/schemas";
6
+ export function eventSchemaPath(eventType, version) {
7
+ const base = `${schemaRegistryPath}/${encodeURIComponent(eventType)}`;
8
+ return version === undefined ? base : `${base}/${encodeURIComponent(version)}`;
9
+ }
@@ -0,0 +1,4 @@
1
+ /** Whether a parsed URL hostname is a local development host. IPv6 hostnames keep their brackets. */
2
+ export declare function isLocalHostname(hostname: string): boolean;
3
+ /** The parsed URL when it follows the rule, otherwise undefined. */
4
+ export declare function secureOrLocalUrl(raw: string): URL | undefined;
@@ -0,0 +1,23 @@
1
+ // The URL rule for calls that carry a credential outside CustdClient: HTTPS, or plain HTTP only to a
2
+ // local development host, and never with embedded credentials, a query or a fragment.
3
+ const localHosts = ["localhost", "127.0.0.1", "[::1]", "host.docker.internal"];
4
+ /** Whether a parsed URL hostname is a local development host. IPv6 hostnames keep their brackets. */
5
+ export function isLocalHostname(hostname) {
6
+ return localHosts.includes(hostname);
7
+ }
8
+ /** The parsed URL when it follows the rule, otherwise undefined. */
9
+ export function secureOrLocalUrl(raw) {
10
+ let url;
11
+ try {
12
+ url = new URL(raw);
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ const local = isLocalHostname(url.hostname);
18
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local))
19
+ return undefined;
20
+ if (url.username || url.password || url.search || url.hash)
21
+ return undefined;
22
+ return url;
23
+ }
@@ -0,0 +1,34 @@
1
+ import type { SiteAIConsentRequest, SiteAIOwnerHandoff, SiteAISettings, SiteAISettingsRequest } from "./admin-site-ai.js";
2
+ import type { RequestOptions } from "./index.js";
3
+ /** The session's tenant, the binding its writes must echo and the tenant's current AI settings. */
4
+ export type SiteAIOwnerSettings = {
5
+ tenantSlug: string;
6
+ sessionBinding: string;
7
+ settings: SiteAISettings;
8
+ };
9
+ /** How the session sends requests and turns a refused response into the client's request error. */
10
+ export type SiteAIOwnerTransport = {
11
+ fetch: typeof fetch;
12
+ failure: (response: Response) => Promise<Error>;
13
+ };
14
+ /**
15
+ * A signed-in AI settings session for one tenant, valid for ten minutes after redeeming. Open one with
16
+ * CustdClient.redeemSiteAIOwnerHandoff.
17
+ */
18
+ export declare class SiteAIOwnerSession {
19
+ private readonly transport;
20
+ private readonly origin;
21
+ private readonly handle;
22
+ private binding;
23
+ constructor(transport: SiteAIOwnerTransport, origin: string, handle: string);
24
+ /** Reads the session tenant's AI settings and refreshes the write binding. */
25
+ getSettings(options?: RequestOptions): Promise<SiteAIOwnerSettings>;
26
+ /** Replaces the session tenant's AI mode and cap. */
27
+ setSettings(body: SiteAISettingsRequest, options?: RequestOptions): Promise<SiteAISettings>;
28
+ /** Records or revokes the session tenant's AI terms consent. */
29
+ setConsent(body: SiteAIConsentRequest, options?: RequestOptions): Promise<SiteAISettings>;
30
+ private write;
31
+ private send;
32
+ }
33
+ /** Opens an owner session from a handoff. hubOrigin is the broker's registered hub origin. */
34
+ export declare function redeemSiteAIOwnerHandoff(transport: SiteAIOwnerTransport, handoff: SiteAIOwnerHandoff, hubOrigin: string, options?: RequestOptions): Promise<SiteAIOwnerSession>;
@@ -0,0 +1,99 @@
1
+ // The AI settings session a data-space owner opens by redeeming a handoff the broker created with
2
+ // admin.siteDomains.createAIOwnerHandoff. Redeeming runs on the broker's hub server: it sends the
3
+ // hub origin and reads the session cookie, which a browser page cannot do. The session then carries
4
+ // its own cookie and write binding and never sends a Custd client credential or an acting company.
5
+ import { secureOrLocalUrl } from "./secure-url.js";
6
+ import { SDK_IDENTITY } from "./version.js";
7
+ const siteAIOwnerPath = "/api/v1/site-ai-owner";
8
+ const siteAIOwnerCookie = "__Host-custd-site-ai-owner";
9
+ const siteAIOwnerBindingHeader = "X-Custd-Site-AI-Session";
10
+ /**
11
+ * A signed-in AI settings session for one tenant, valid for ten minutes after redeeming. Open one with
12
+ * CustdClient.redeemSiteAIOwnerHandoff.
13
+ */
14
+ export class SiteAIOwnerSession {
15
+ constructor(transport, origin, handle) {
16
+ this.transport = transport;
17
+ this.origin = origin;
18
+ this.handle = handle;
19
+ this.binding = "";
20
+ }
21
+ /** Reads the session tenant's AI settings and refreshes the write binding. */
22
+ async getSettings(options) {
23
+ const settings = await this.send("GET", "/settings", undefined, options);
24
+ this.binding = settings.sessionBinding;
25
+ return settings;
26
+ }
27
+ /** Replaces the session tenant's AI mode and cap. */
28
+ setSettings(body, options) {
29
+ return this.write("/settings", body, options);
30
+ }
31
+ /** Records or revokes the session tenant's AI terms consent. */
32
+ setConsent(body, options) {
33
+ return this.write("/consent", body, options);
34
+ }
35
+ // A write needs the binding, so the first write after redeeming reads the settings once.
36
+ async write(path, body, options) {
37
+ if (this.binding === "")
38
+ await this.getSettings(options);
39
+ return this.send("PUT", path, body, options);
40
+ }
41
+ async send(method, path, body, options) {
42
+ const headers = {
43
+ Cookie: `${siteAIOwnerCookie}=${this.handle}`,
44
+ "X-Custd-Sdk": SDK_IDENTITY,
45
+ };
46
+ if (body !== undefined) {
47
+ headers["Content-Type"] = "application/json";
48
+ headers.Origin = this.origin;
49
+ headers[siteAIOwnerBindingHeader] = this.binding;
50
+ }
51
+ const response = await this.transport.fetch(`${this.origin}${siteAIOwnerPath}${path}`, {
52
+ method,
53
+ headers,
54
+ body: body === undefined ? undefined : JSON.stringify(body),
55
+ signal: options?.signal,
56
+ });
57
+ if (!response.ok)
58
+ throw await this.transport.failure(response);
59
+ return (await response.json());
60
+ }
61
+ }
62
+ /** Opens an owner session from a handoff. hubOrigin is the broker's registered hub origin. */
63
+ export async function redeemSiteAIOwnerHandoff(transport, handoff, hubOrigin, options) {
64
+ const origin = redeemOrigin(handoff.redeemUrl);
65
+ if (handoff.code === "" || hubOrigin === "") {
66
+ throw new Error("custd: AI owner handoff requires a code and the hub origin");
67
+ }
68
+ const response = await transport.fetch(handoff.redeemUrl, {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Origin: hubOrigin, "X-Custd-Sdk": SDK_IDENTITY },
71
+ body: new URLSearchParams({ code: handoff.code }).toString(),
72
+ redirect: "manual",
73
+ signal: options?.signal,
74
+ });
75
+ if (!response.ok && response.status !== 303)
76
+ throw await transport.failure(response);
77
+ if (response.status !== 303)
78
+ throw new Error(`custd: AI owner redeem returned HTTP ${response.status}, want 303`);
79
+ const handle = sessionHandle(response.headers);
80
+ if (handle === "")
81
+ throw new Error("custd: AI owner redeem returned no session cookie");
82
+ return new SiteAIOwnerSession(transport, origin, handle);
83
+ }
84
+ function redeemOrigin(redeemUrl) {
85
+ const url = secureOrLocalUrl(redeemUrl);
86
+ if (url?.pathname !== `${siteAIOwnerPath}/redeem`) {
87
+ throw new Error("custd: AI owner handoff requires the Custd redeem URL");
88
+ }
89
+ return url.origin;
90
+ }
91
+ function sessionHandle(headers) {
92
+ for (const cookie of headers.getSetCookie()) {
93
+ const [pair = ""] = cookie.split(";", 1);
94
+ const separator = pair.indexOf("=");
95
+ if (separator > 0 && pair.slice(0, separator).trim() === siteAIOwnerCookie)
96
+ return pair.slice(separator + 1).trim();
97
+ }
98
+ return "";
99
+ }
@@ -0,0 +1,15 @@
1
+ import type { PrivateUptimeReport, PrivateUptimeWork, SiteHeartbeatReceipt, SiteHeartbeatReport } from "./admin-site-monitors.js";
2
+ import type { RequestOptions } from "./index.js";
3
+ /** The API origin plus the monitor's reportPath and token from its one-time credential. */
4
+ export type SiteMonitorDestination = {
5
+ baseUrl: string;
6
+ reportPath: string;
7
+ writeToken: string;
8
+ fetch?: typeof fetch;
9
+ };
10
+ /** Sends a job result and returns the first accepted receipt for that occurrence. */
11
+ export declare function submitSiteHeartbeat(destination: SiteMonitorDestination, report: SiteHeartbeatReport, options?: RequestOptions): Promise<SiteHeartbeatReceipt>;
12
+ /** Sends one private uptime observation. */
13
+ export declare function submitPrivateUptime(destination: SiteMonitorDestination, report: PrivateUptimeReport, options?: RequestOptions): Promise<void>;
14
+ /** Reads the check queued for the private probe; requestedAt is absent when nothing is pending. */
15
+ export declare function getPrivateUptimeWork(destination: SiteMonitorDestination, options?: RequestOptions): Promise<PrivateUptimeWork>;
@@ -0,0 +1,87 @@
1
+ // Reports a domain's own monitors send with only the write credential that create or rotate returned:
2
+ // a scheduled job's heartbeat, and the private uptime probe's observations and pending work. They never
3
+ // carry a Custd client credential.
4
+ import { secureOrLocalUrl } from "./secure-url.js";
5
+ import { SDK_IDENTITY } from "./version.js";
6
+ const heartbeatReportPrefix = "/api/v1/site-heartbeat-reports/";
7
+ const privateUptimeReportPrefix = "/api/v1/site-private-uptime-reports/";
8
+ const maxReceiptBytes = 1024;
9
+ /** Sends a job result and returns the first accepted receipt for that occurrence. */
10
+ export async function submitSiteHeartbeat(destination, report, options) {
11
+ const scheduledFor = Date.parse(report.scheduledFor);
12
+ if (Number.isNaN(scheduledFor) || (report.outcome !== "succeeded" && report.outcome !== "failed")) {
13
+ throw new Error("custd: heartbeat requires a scheduled time and succeeded or failed outcome");
14
+ }
15
+ const response = await sendMonitorRequest(destination, heartbeatReportPrefix, "POST", report, options);
16
+ if (response.status !== 200)
17
+ throw new Error(`custd: heartbeat report returned HTTP ${response.status}`);
18
+ const receipt = await readBoundedJson(response, "heartbeat receipt");
19
+ if (!receipt.receivedAt ||
20
+ Date.parse(receipt.report?.scheduledFor ?? "") !== scheduledFor ||
21
+ receipt.report.outcome !== report.outcome) {
22
+ throw new Error("custd: heartbeat receipt does not match the submitted occurrence");
23
+ }
24
+ return receipt;
25
+ }
26
+ /** Sends one private uptime observation. */
27
+ export async function submitPrivateUptime(destination, report, options) {
28
+ const response = await sendMonitorRequest(destination, privateUptimeReportPrefix, "POST", report, options);
29
+ if (response.status !== 204)
30
+ throw new Error(`custd: uptime report returned HTTP ${response.status}`);
31
+ }
32
+ /** Reads the check queued for the private probe; requestedAt is absent when nothing is pending. */
33
+ export async function getPrivateUptimeWork(destination, options) {
34
+ const response = await sendMonitorRequest(destination, privateUptimeReportPrefix, "GET", undefined, options);
35
+ if (response.status !== 200)
36
+ throw new Error(`custd: uptime work returned HTTP ${response.status}`);
37
+ return readBoundedJson(response, "uptime work");
38
+ }
39
+ async function sendMonitorRequest(destination, prefix, method, body, options) {
40
+ const endpoint = monitorEndpoint(destination, prefix);
41
+ const fetchImpl = destination.fetch ?? fetch;
42
+ return fetchImpl(endpoint, {
43
+ method,
44
+ headers: {
45
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
46
+ Authorization: `Bearer ${destination.writeToken}`,
47
+ "X-Custd-Sdk": SDK_IDENTITY,
48
+ },
49
+ body: body === undefined ? undefined : JSON.stringify(body),
50
+ redirect: "manual",
51
+ signal: options?.signal,
52
+ });
53
+ }
54
+ function monitorEndpoint(destination, prefix) {
55
+ const base = secureOrLocalUrl(destination.baseUrl);
56
+ if (base === undefined || base.pathname !== "/")
57
+ throw new Error("custd: site monitor requires an HTTPS API origin");
58
+ const [tenant, monitor, ...rest] = destination.reportPath.startsWith(prefix)
59
+ ? destination.reportPath.slice(prefix.length).split("/")
60
+ : [];
61
+ if (rest.length > 0 ||
62
+ !validMonitorSegment(tenant) ||
63
+ !validMonitorSegment(monitor) ||
64
+ destination.writeToken.length !== 64) {
65
+ throw new Error("custd: site monitor requires a report path and write credential");
66
+ }
67
+ return `${base.origin}${destination.reportPath}`;
68
+ }
69
+ function validMonitorSegment(segment) {
70
+ if (!segment)
71
+ return false;
72
+ let decoded;
73
+ try {
74
+ decoded = decodeURIComponent(segment);
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ return decoded !== "" && decoded !== "." && decoded !== ".." && !/[/\\?#]/.test(decoded);
80
+ }
81
+ async function readBoundedJson(response, label) {
82
+ const text = await response.text();
83
+ if (new TextEncoder().encode(text).byteLength > maxReceiptBytes) {
84
+ throw new Error(`custd: ${label} exceeds ${maxReceiptBytes} bytes`);
85
+ }
86
+ return JSON.parse(text);
87
+ }
@@ -0,0 +1,150 @@
1
+ import { AppItemsClient } from "../app-items.js";
2
+ import type { BrowserSignIn, SignInSession, SignInStorage } from "../browser-sign-in.js";
3
+ import type { CaptureExceptionRequest } from "../error-capture.js";
4
+ import { type HostedAppCapability, type HostedAppDiscovery, type HostedAppOptions } from "../hosted-app.js";
5
+ export declare const FAKE_CUSTD_ORIGIN = "https://app.custd.test";
6
+ export declare const FAKE_CUSTD_SITE_KEY = "site_pk_fake";
7
+ export declare const FAKE_CUSTD_API_PATH = "/__custd";
8
+ export declare const FAKE_CUSTD_AUTH_PATH = "/__auth";
9
+ /** A request as a browser route interceptor sees it. Header names may use any case. */
10
+ export type FakeCustdRequest = {
11
+ method: string;
12
+ url: string;
13
+ headers: Record<string, string>;
14
+ body: string | null;
15
+ };
16
+ export type FakeCustdResponse = {
17
+ status: number;
18
+ headers: Record<string, string>;
19
+ body?: string;
20
+ };
21
+ /** One answered request, with lowercase header names and the parsed JSON body when there is one. */
22
+ export type FakeCustdRecordedRequest = FakeCustdRequest & {
23
+ path: string;
24
+ json?: unknown;
25
+ };
26
+ /** One event the hosted app's tracker was handed. */
27
+ export type FakeTrackedEvent = {
28
+ eventTypeSlug: string;
29
+ payload?: Record<string, unknown>;
30
+ };
31
+ /** One error the hosted app's error capture was handed; the error itself is reduced to its type, as Custd would. */
32
+ export type FakeCapturedError = {
33
+ exceptionType: string;
34
+ mode?: CaptureExceptionRequest["mode"];
35
+ correlationId?: string;
36
+ };
37
+ export type FakeCustdOptions = {
38
+ /** The app's origin; the API is served under `/__custd` on it. Defaults to `https://app.custd.test`. */
39
+ origin?: string;
40
+ siteKey?: string;
41
+ /** The sign-in public client's id. */
42
+ clientId?: string;
43
+ /** Defaults to every capability: tracking and error capture are recorded, never sent. */
44
+ capabilities?: HostedAppCapability[];
45
+ /** The clock every timestamp and estimate age uses. Defaults to `Date.now`. */
46
+ now?: () => number;
47
+ /** False makes alert email subscriptions refuse with `app_alert_no_verified_email`. */
48
+ signedInUsersHaveVerifiedEmail?: boolean;
49
+ };
50
+ /** Sign-in storage held in memory, for tests that have no `sessionStorage`. */
51
+ export declare function memorySignInStorage(): SignInStorage;
52
+ /** Signs `user` in through the real PKCE flow of `signIn`, against the fake's authorize and token endpoints. */
53
+ export declare function signInWithFake(fake: FakeCustd, signIn: BrowserSignIn, user?: string): Promise<SignInSession>;
54
+ export declare class FakeCustd {
55
+ readonly origin: string;
56
+ readonly apiBaseUrl: string;
57
+ readonly siteKey: string;
58
+ /** Every request the fake answered, oldest first. */
59
+ readonly requests: FakeCustdRecordedRequest[];
60
+ /** Every event the hosted app tracked, oldest first. Page views appear as `page-view`. */
61
+ readonly trackedEvents: FakeTrackedEvent[];
62
+ /** Every error the hosted app captured, oldest first. */
63
+ readonly capturedErrors: FakeCapturedError[];
64
+ private readonly clientId;
65
+ private readonly capabilities;
66
+ private readonly now;
67
+ private readonly verifiedEmail;
68
+ private readonly items;
69
+ private readonly links;
70
+ private readonly codes;
71
+ private readonly routes;
72
+ private sequence;
73
+ private userCount;
74
+ constructor(options?: FakeCustdOptions);
75
+ discovery(): HostedAppDiscovery;
76
+ /** Options for `startHostedApp` (or `CustdHostedAppProvider`) that reach this fake. */
77
+ hostedAppOptions(): HostedAppOptions;
78
+ private recordingTracker;
79
+ private recordingErrorCapture;
80
+ /** A client that reaches this fake; `userToken` is the signed-in user, as the fake names them. */
81
+ appItemsClient(options?: {
82
+ userToken?: string;
83
+ }): AppItemsClient;
84
+ /** Approves a sign-in as `user` (a new user when absent) and returns the redirect back to the app. */
85
+ authorize(authorizationUrl: string, user?: string): string;
86
+ /** The fake as a `fetch`, for the SDK's clients. */
87
+ readonly fetch: typeof fetch;
88
+ /** Answers one request, as a browser route interceptor hands it over. */
89
+ handle(raw: FakeCustdRequest): FakeCustdResponse;
90
+ private dispatch;
91
+ private auth;
92
+ private itemRoutes;
93
+ private resultRoutes;
94
+ private alertRoutes;
95
+ private routeWithId;
96
+ private remove;
97
+ private conditional;
98
+ private caller;
99
+ private linkCaller;
100
+ private owned;
101
+ private touch;
102
+ private change;
103
+ private nextSequence;
104
+ private uuid;
105
+ /** 43 base64url characters, the shape of a real link token. */
106
+ private token;
107
+ private nowIso;
108
+ private create;
109
+ private newItem;
110
+ private issueLinks;
111
+ private newModel;
112
+ private newProject;
113
+ private issue;
114
+ private rotate;
115
+ private revoke;
116
+ private linkOf;
117
+ private itemRead;
118
+ private read;
119
+ private ownership;
120
+ private linksOf;
121
+ private mine;
122
+ private claim;
123
+ private projectOf;
124
+ private meetingOf;
125
+ private settings;
126
+ private complete;
127
+ private setStatus;
128
+ private measure;
129
+ private estimate;
130
+ private addEntry;
131
+ private advance;
132
+ private runForecast;
133
+ private latestForecast;
134
+ private forecastRun;
135
+ private story;
136
+ private saveVersion;
137
+ private modelVersion;
138
+ private copyModel;
139
+ private runModel;
140
+ private calculate;
141
+ private latestModelRun;
142
+ private alertSettings;
143
+ private addRule;
144
+ private addWebhook;
145
+ private addSlack;
146
+ private subscribe;
147
+ private conditionMet;
148
+ private evaluateAlerts;
149
+ private deliver;
150
+ }