@inflatable-cookie/longhorn 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +38 -0
  3. package/package.json +205 -0
  4. package/src/agent-control/index.ts +20 -0
  5. package/src/agent-control/inject.ts +4 -0
  6. package/src/agent-control/shim.ts +722 -0
  7. package/src/bridge/direct.ts +22 -0
  8. package/src/bridge/generated/fields.ts +32 -0
  9. package/src/bridge/generated/protocol.ts +218 -0
  10. package/src/bridge/generated/variant-fields.ts +10 -0
  11. package/src/bridge/index.ts +15 -0
  12. package/src/bridge/job.ts +51 -0
  13. package/src/bridge/loopback.ts +84 -0
  14. package/src/bridge/operation.ts +166 -0
  15. package/src/bridge/router.ts +71 -0
  16. package/src/bridge/runtime/connection.ts +318 -0
  17. package/src/bridge/runtime/policy.ts +89 -0
  18. package/src/bridge/runtime/retry.ts +60 -0
  19. package/src/bridge/runtime.ts +3 -0
  20. package/src/bridge/session.ts +67 -0
  21. package/src/bridge/stream/connection.ts +146 -0
  22. package/src/bridge/stream/source.ts +61 -0
  23. package/src/bridge/stream/tracker.ts +109 -0
  24. package/src/bridge/stream.ts +6 -0
  25. package/src/bridge/supervision.ts +204 -0
  26. package/src/bridge/validation/base.ts +164 -0
  27. package/src/bridge/validation/jobs.ts +105 -0
  28. package/src/bridge/validation/negotiation.ts +242 -0
  29. package/src/bridge/validation/operations.ts +213 -0
  30. package/src/bridge/validation/streams.ts +47 -0
  31. package/src/bridge/validation.ts +5 -0
  32. package/src/commands/client.ts +124 -0
  33. package/src/commands/controller.ts +411 -0
  34. package/src/commands/generated/fields.ts +43 -0
  35. package/src/commands/generated/protocol.ts +876 -0
  36. package/src/commands/generated/variant-fields.ts +88 -0
  37. package/src/commands/index.ts +13 -0
  38. package/src/commands/keyboard.ts +361 -0
  39. package/src/commands/ports.ts +82 -0
  40. package/src/commands/projectors.ts +306 -0
  41. package/src/commands/validation.ts +444 -0
  42. package/src/config/client.ts +215 -0
  43. package/src/config/generated/base.ts +714 -0
  44. package/src/config/generated/fields.ts +54 -0
  45. package/src/config/generated/label-template.ts +14 -0
  46. package/src/config/generated/labels.ts +30 -0
  47. package/src/config/generated/protocol.ts +3 -0
  48. package/src/config/generated/restore.ts +658 -0
  49. package/src/config/generated/variant-fields.ts +129 -0
  50. package/src/config/index.ts +12 -0
  51. package/src/config/names.ts +19 -0
  52. package/src/config/validation/commands.ts +155 -0
  53. package/src/config/validation/outcomes.ts +243 -0
  54. package/src/config/validation/primitives.ts +174 -0
  55. package/src/config/validation/projection.ts +351 -0
  56. package/src/config/validation.ts +7 -0
  57. package/src/core/connection.ts +252 -0
  58. package/src/core/index.ts +2 -0
  59. package/src/core/transport.ts +24 -0
  60. package/src/history/client.ts +65 -0
  61. package/src/history/controller.ts +385 -0
  62. package/src/history/direct.ts +21 -0
  63. package/src/history/generated/fields.ts +18 -0
  64. package/src/history/generated/protocol.ts +389 -0
  65. package/src/history/generated/variant-fields.ts +27 -0
  66. package/src/history/index.ts +13 -0
  67. package/src/history/ports.ts +31 -0
  68. package/src/history/serialized.ts +38 -0
  69. package/src/history/validation.ts +334 -0
  70. package/src/history-tree/client.ts +16 -0
  71. package/src/history-tree/controller.ts +199 -0
  72. package/src/history-tree/direct.ts +3 -0
  73. package/src/history-tree/generated/fields.ts +26 -0
  74. package/src/history-tree/generated/protocol.ts +711 -0
  75. package/src/history-tree/generated/variant-fields.ts +39 -0
  76. package/src/history-tree/index.ts +13 -0
  77. package/src/history-tree/ports.ts +43 -0
  78. package/src/history-tree/serialized.ts +15 -0
  79. package/src/history-tree/validation.ts +269 -0
  80. package/src/layout/generated/protocol.ts +289 -0
  81. package/src/layout/index.ts +4 -0
  82. package/src/layout/ratio.ts +22 -0
  83. package/src/layout/validation.ts +110 -0
  84. package/src/layout/visibility.ts +30 -0
  85. package/src/licence/client.ts +32 -0
  86. package/src/licence/controller.ts +301 -0
  87. package/src/licence/direct.ts +3 -0
  88. package/src/licence/generated/fields.ts +17 -0
  89. package/src/licence/generated/key-conformance.json +42 -0
  90. package/src/licence/generated/protocol.ts +249 -0
  91. package/src/licence/generated/variant-fields.ts +34 -0
  92. package/src/licence/index.ts +14 -0
  93. package/src/licence/key.ts +125 -0
  94. package/src/licence/ports.ts +39 -0
  95. package/src/licence/serialized.ts +13 -0
  96. package/src/licence/validation.ts +226 -0
  97. package/src/native-content/client.ts +474 -0
  98. package/src/native-content/direct.ts +16 -0
  99. package/src/native-content/generated/fields.ts +32 -0
  100. package/src/native-content/generated/protocol.ts +498 -0
  101. package/src/native-content/generated/variant-fields.ts +77 -0
  102. package/src/native-content/index.ts +12 -0
  103. package/src/native-content/ports.ts +46 -0
  104. package/src/native-content/serialized.ts +50 -0
  105. package/src/native-content/validation/base.ts +194 -0
  106. package/src/native-content/validation/messages.ts +192 -0
  107. package/src/native-content/validation/state.ts +404 -0
  108. package/src/native-content/validation.ts +7 -0
  109. package/src/notifications/client.ts +106 -0
  110. package/src/notifications/controller.ts +240 -0
  111. package/src/notifications/direct.ts +12 -0
  112. package/src/notifications/generated/fields.ts +19 -0
  113. package/src/notifications/generated/labels.ts +20 -0
  114. package/src/notifications/generated/protocol.ts +522 -0
  115. package/src/notifications/generated/variant-fields.ts +37 -0
  116. package/src/notifications/index.ts +16 -0
  117. package/src/notifications/ports.ts +22 -0
  118. package/src/notifications/serialized.ts +27 -0
  119. package/src/notifications/toast.ts +41 -0
  120. package/src/notifications/tone.ts +27 -0
  121. package/src/notifications/validation.ts +246 -0
  122. package/src/operation/bridge.ts +168 -0
  123. package/src/operation/client.ts +167 -0
  124. package/src/operation/controller.ts +321 -0
  125. package/src/operation/direct.ts +15 -0
  126. package/src/operation/generated/fields.ts +20 -0
  127. package/src/operation/generated/labels.ts +15 -0
  128. package/src/operation/generated/protocol.ts +762 -0
  129. package/src/operation/generated/variant-fields.ts +60 -0
  130. package/src/operation/index.ts +14 -0
  131. package/src/operation/ports.ts +29 -0
  132. package/src/operation/serialized.ts +39 -0
  133. package/src/operation/validation.ts +479 -0
  134. package/src/settings/client.ts +142 -0
  135. package/src/settings/connection.ts +246 -0
  136. package/src/settings/generated/fields.ts +34 -0
  137. package/src/settings/generated/protocol.ts +668 -0
  138. package/src/settings/generated/variant-fields.ts +26 -0
  139. package/src/settings/index.ts +12 -0
  140. package/src/settings/names.ts +8 -0
  141. package/src/settings/registry.ts +141 -0
  142. package/src/settings/validation/authority.ts +66 -0
  143. package/src/settings/validation/command.ts +165 -0
  144. package/src/settings/validation/error.ts +33 -0
  145. package/src/settings/validation/primitives.ts +203 -0
  146. package/src/settings/validation/projection.ts +50 -0
  147. package/src/settings/validation/registry.ts +170 -0
  148. package/src/settings/validation.ts +4 -0
  149. package/src/surface-transfer/client.ts +54 -0
  150. package/src/surface-transfer/generated/fields.ts +12 -0
  151. package/src/surface-transfer/generated/protocol.ts +61 -0
  152. package/src/surface-transfer/generated/variant-fields.ts +30 -0
  153. package/src/surface-transfer/index.ts +9 -0
  154. package/src/surface-transfer/validation.ts +209 -0
  155. package/src/surfaces/client.ts +140 -0
  156. package/src/surfaces/generated/fields.ts +19 -0
  157. package/src/surfaces/generated/protocol.ts +217 -0
  158. package/src/surfaces/generated/variant-fields.ts +42 -0
  159. package/src/surfaces/index.ts +9 -0
  160. package/src/surfaces/validation.ts +199 -0
  161. package/src/transfer/client.ts +133 -0
  162. package/src/transfer/connection.ts +87 -0
  163. package/src/transfer/generated/fields.ts +23 -0
  164. package/src/transfer/generated/protocol.ts +171 -0
  165. package/src/transfer/generated/variant-fields.ts +45 -0
  166. package/src/transfer/index.ts +11 -0
  167. package/src/transfer/payload.ts +71 -0
  168. package/src/transfer/validation.ts +282 -0
  169. package/src/update/client.ts +29 -0
  170. package/src/update/controller.ts +255 -0
  171. package/src/update/direct.ts +3 -0
  172. package/src/update/generated/fields.ts +14 -0
  173. package/src/update/generated/protocol.ts +238 -0
  174. package/src/update/generated/variant-fields.ts +44 -0
  175. package/src/update/index.ts +14 -0
  176. package/src/update/ports.ts +36 -0
  177. package/src/update/serialized.ts +12 -0
  178. package/src/update/validation.ts +191 -0
@@ -0,0 +1,226 @@
1
+ import { LICENCE_FIELDS } from "./generated/fields.ts";
2
+ import {
3
+ LICENCE_CHANGED_KINDS,
4
+ LICENCE_CREDENTIAL_KINDS,
5
+ LICENCE_OUTCOME_STATUSES,
6
+ LICENCE_PROTOCOL_VERSION,
7
+ LICENCE_REJECTION_CODES,
8
+ LICENCE_TRUST_BASIS_KINDS,
9
+ LICENCE_USABILITY_STATES,
10
+ type LicenceActivateCommand,
11
+ type LicenceChangedEvent,
12
+ type LicenceDeactivateCommand,
13
+ type LicenceOutcomeProjection,
14
+ type LicenceRefreshCommand,
15
+ type LicenceReleaseSeatCommand,
16
+ type LicenceRenameSeatCommand,
17
+ type LicenceSnapshot,
18
+ } from "./generated/protocol.ts";
19
+ import {
20
+ LICENCE_VARIANT_FIELDS,
21
+ LICENCE_VARIANT_FIELDS_DISCRIMINANTS,
22
+ } from "./generated/variant-fields.ts";
23
+
24
+ export class LicenceValidationError extends Error {
25
+ constructor(
26
+ readonly path: string,
27
+ message: string,
28
+ ) {
29
+ super(`${path}: ${message}`);
30
+ this.name = "LicenceValidationError";
31
+ }
32
+ }
33
+
34
+ export function assertLicenceSnapshot(value: unknown): asserts value is LicenceSnapshot {
35
+ noCredential(value);
36
+ const root = object(value, "$");
37
+ exact(root, "$", LICENCE_FIELDS.LicenceSnapshot);
38
+ protocol(root.protocolVersion, "$.protocolVersion");
39
+ positive(root.authorityEpoch, "$.authorityEpoch");
40
+ // Absent means unlicensed, which is the absence of a licence rather than a
41
+ // licence that cannot be used. Card 193 kept those apart deliberately.
42
+ if (root.licence !== null) held(root.licence, "$.licence");
43
+ }
44
+
45
+ export function assertLicenceOutcome(value: unknown): asserts value is LicenceOutcomeProjection {
46
+ noCredential(value);
47
+ const root = object(value, "$");
48
+ oneOf(root.status, "$.status", LICENCE_OUTCOME_STATUSES);
49
+ exact(root, "$", variantFields("LicenceOutcomeProjection", root, "$"));
50
+ if (root.status === "rejected") oneOf(root.code, "$.code", LICENCE_REJECTION_CODES);
51
+ assertLicenceSnapshot(root.snapshot);
52
+ }
53
+
54
+ export function assertLicenceChangedEvent(value: unknown): asserts value is LicenceChangedEvent {
55
+ noCredential(value);
56
+ const root = object(value, "$");
57
+ exact(root, "$", LICENCE_FIELDS.LicenceChangedEvent);
58
+ protocol(root.protocolVersion, "$.protocolVersion");
59
+ positive(root.authorityEpoch, "$.authorityEpoch");
60
+ oneOf(root.kind, "$.kind", LICENCE_CHANGED_KINDS);
61
+ }
62
+
63
+ export function assertLicenceActivateCommand(
64
+ value: unknown,
65
+ ): asserts value is LicenceActivateCommand {
66
+ const root = commandBase(value, LICENCE_FIELDS.LicenceActivateCommand);
67
+ const credential = object(root.credential, "$.credential");
68
+ oneOf(credential.kind, "$.credential.kind", LICENCE_CREDENTIAL_KINDS);
69
+ exact(
70
+ credential,
71
+ "$.credential",
72
+ variantFields("LicenceCredentialProjection", credential, "$.credential"),
73
+ );
74
+ // The one place credential material crosses, and it crosses inward only.
75
+ // Checked for shape, never echoed: `noCredential` runs on everything coming
76
+ // back and would reject a projection that returned any of this.
77
+ if (credential.kind === "key") nonEmpty(credential.key, "$.credential.key");
78
+ if (credential.kind === "accountToken") nonEmpty(credential.token, "$.credential.token");
79
+ if (credential.kind === "licenceFile") {
80
+ nonEmpty(credential.contentsBase64, "$.credential.contentsBase64");
81
+ }
82
+ // The label a customer gives this machine, asked for at the only moment it
83
+ // can be without inventing a settings screen. Absent is fine.
84
+ if (root.label !== null) nonEmpty(root.label, "$.label");
85
+ }
86
+
87
+ export function assertLicenceDeactivateCommand(
88
+ value: unknown,
89
+ ): asserts value is LicenceDeactivateCommand {
90
+ commandBase(value, LICENCE_FIELDS.LicenceDeactivateCommand);
91
+ }
92
+
93
+ export function assertLicenceRefreshCommand(
94
+ value: unknown,
95
+ ): asserts value is LicenceRefreshCommand {
96
+ commandBase(value, LICENCE_FIELDS.LicenceRefreshCommand);
97
+ }
98
+
99
+ export function assertLicenceReleaseSeatCommand(
100
+ value: unknown,
101
+ ): asserts value is LicenceReleaseSeatCommand {
102
+ const root = commandBase(value, LICENCE_FIELDS.LicenceReleaseSeatCommand);
103
+ nonEmpty(root.machineId, "$.machineId");
104
+ }
105
+
106
+ export function assertLicenceRenameSeatCommand(
107
+ value: unknown,
108
+ ): asserts value is LicenceRenameSeatCommand {
109
+ const root = commandBase(value, LICENCE_FIELDS.LicenceRenameSeatCommand);
110
+ nonEmpty(root.machineId, "$.machineId");
111
+ // Null clears the label back to unnamed; an empty string is a mistake
112
+ // wearing null's clothes and is refused rather than stored.
113
+ if (root.label !== null) nonEmpty(root.label, "$.label");
114
+ }
115
+
116
+ function held(value: unknown, path: string): void {
117
+ const licence = object(value, path);
118
+ exact(licence, path, LICENCE_FIELDS.HeldLicenceProjection);
119
+ string(licence.product, `${path}.product`);
120
+ usability(licence.usability, `${path}.usability`);
121
+ trustBasis(licence.trustBasis, `${path}.trustBasis`);
122
+ // Both windows, kept apart. A perpetual licence past its update window still
123
+ // runs, and one field cannot say that.
124
+ optionalTimestamp(licence.useUntil, `${path}.useUntil`);
125
+ optionalTimestamp(licence.updateUntil, `${path}.updateUntil`);
126
+ array(licence.seats, `${path}.seats`).forEach((entry, index) => {
127
+ const at = `${path}.seats[${index}]`;
128
+ const seat = object(entry, at);
129
+ exact(seat, at, LICENCE_FIELDS.LicenceSeatProjection);
130
+ // A `MachineId` is random and at least sixteen bytes by construction. This
131
+ // checks it is present and never what it says, because anything derived
132
+ // from the host would be a different value wearing the same field.
133
+ nonEmpty(seat.machineId, `${at}.machineId`);
134
+ if (seat.label !== null) nonEmpty(seat.label, `${at}.label`);
135
+ boolean(seat.thisMachine, `${at}.thisMachine`);
136
+ });
137
+ array(licence.entitlements, `${path}.entitlements`).forEach((entry, index) => {
138
+ const at = `${path}.entitlements[${index}]`;
139
+ const entitlement = object(entry, at);
140
+ exact(entitlement, at, LICENCE_FIELDS.LicenceEntitlementProjection);
141
+ // Opaque by design: Longhorn enumerates no features, so this checks that
142
+ // an id is present and never what it says.
143
+ nonEmpty(entitlement.id, `${at}.id`);
144
+ if (entitlement.atMost !== null) positive(entitlement.atMost, `${at}.atMost`);
145
+ });
146
+ }
147
+
148
+ function usability(value: unknown, path: string): void {
149
+ const root = object(value, path);
150
+ oneOf(root.state, `${path}.state`, LICENCE_USABILITY_STATES);
151
+ exact(root, path, variantFields("LicenceUsabilityProjection", root, path));
152
+ // `clockRefused` carries no timestamp on purpose: a licence refused because
153
+ // the machine clock moved is not expired, and giving it a date would invite
154
+ // a surface to render it as one.
155
+ if (root.state === "inGrace") timestamp(root.until, `${path}.until`);
156
+ if (root.state === "useWindowExpired" || root.state === "leaseLapsed") {
157
+ timestamp(root.at, `${path}.at`);
158
+ }
159
+ }
160
+
161
+ function trustBasis(value: unknown, path: string): void {
162
+ const root = object(value, path);
163
+ oneOf(root.kind, `${path}.kind`, LICENCE_TRUST_BASIS_KINDS);
164
+ exact(root, path, variantFields("LicenceTrustBasisProjection", root, path));
165
+ if (root.kind === "remoteAssertion") timestamp(root.checked, `${path}.checked`);
166
+ }
167
+
168
+ function commandBase(value: unknown, expected: readonly string[]): Record<string, unknown> {
169
+ const root = object(value, "$");
170
+ exact(root, "$", expected);
171
+ protocol(root.protocolVersion, "$.protocolVersion");
172
+ positive(root.authorityEpoch, "$.authorityEpoch");
173
+ return root;
174
+ }
175
+
176
+ /**
177
+ * Refuses anything that looks like credential material.
178
+ *
179
+ * The rule the licence protocol is built on: credentials travel inward on an
180
+ * activate command and never come back. This runs on every inbound projection,
181
+ * so a future field that leaked a token or a signature fails the boundary
182
+ * rather than reaching a surface that might display it.
183
+ *
184
+ * Deliberately name-based and deliberately broad. A false positive here is a
185
+ * field that has to be renamed; a false negative is a secret on a screen.
186
+ */
187
+ function noCredential(value: unknown): void {
188
+ const forbidden = ["credential", "secret", "signature", "token", "privatekey", "keyid"];
189
+ const visit = (candidate: unknown, path: string): void => {
190
+ if (Array.isArray(candidate)) return candidate.forEach((item, index) => visit(item, `${path}[${index}]`));
191
+ if (candidate !== null && typeof candidate === "object")
192
+ for (const [key, child] of Object.entries(candidate)) {
193
+ const lowered = key.toLocaleLowerCase();
194
+ if (forbidden.some((needle) => lowered.includes(needle))) {
195
+ fail(`${path}.${key}`, "credential material must not appear in a projection");
196
+ }
197
+ visit(child, `${path}.${key}`);
198
+ }
199
+ };
200
+ visit(value, "$");
201
+ }
202
+
203
+ function variantFields(
204
+ type: string,
205
+ value: Record<string, unknown>,
206
+ path: string,
207
+ ): readonly string[] {
208
+ const discriminant = value[LICENCE_VARIANT_FIELDS_DISCRIMINANTS[type] ?? "kind"];
209
+ const fields = LICENCE_VARIANT_FIELDS[type]?.[discriminant as string];
210
+ if (fields === undefined) fail(path, `no generated fields for ${type}.${String(discriminant)}`);
211
+ return fields;
212
+ }
213
+
214
+ function object(value: unknown, path: string): Record<string, unknown> { if (value === null || typeof value !== "object" || Array.isArray(value)) fail(path, "expected object"); return value as Record<string, unknown>; }
215
+ function array(value: unknown, path: string): unknown[] { if (!Array.isArray(value)) fail(path, "expected array"); return value; }
216
+ function exact(value: Record<string, unknown>, path: string, expected: readonly string[]): void { const actual = Object.keys(value).sort(); const wanted = [...expected].sort(); if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) fail(path, `unexpected keys: ${actual.join(",")}`); }
217
+ function protocol(value: unknown, path: string): void { if (value !== LICENCE_PROTOCOL_VERSION) fail(path, `expected exact protocol ${LICENCE_PROTOCOL_VERSION}`); }
218
+ function positive(value: unknown, path: string): void { if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) fail(path, "expected positive safe integer"); }
219
+ function string(value: unknown, path: string): void { if (typeof value !== "string") fail(path, "expected string"); }
220
+ function nonEmpty(value: unknown, path: string): void { string(value, path); if ((value as string).length === 0) fail(path, "expected a non-empty string"); }
221
+ /** Unix seconds, and negative is a real point in time. */
222
+ function timestamp(value: unknown, path: string): void { if (typeof value !== "number" || !Number.isSafeInteger(value)) fail(path, "expected a unix-second timestamp"); }
223
+ function optionalTimestamp(value: unknown, path: string): void { if (value !== null) timestamp(value, path); }
224
+ function boolean(value: unknown, path: string): void { if (typeof value !== "boolean") fail(path, "expected boolean"); }
225
+ function oneOf(value: unknown, path: string, values: readonly string[]): void { if (typeof value !== "string" || !values.includes(value)) fail(path, "unsupported value"); }
226
+ function fail(path: string, message: string): never { throw new LicenceValidationError(path, message); }
@@ -0,0 +1,474 @@
1
+ import type {
2
+ ConnectionFailure,
3
+ ConnectionFailureReporter,
4
+ } from "@inflatable-cookie/longhorn/core";
5
+
6
+ import {
7
+ assertValidNativeContentChangedEvent,
8
+ assertValidNativeContentConnectRequest,
9
+ assertValidNativeContentConnectResult,
10
+ assertValidNativeContentDecisionRequest,
11
+ assertValidNativeContentDecisionResult,
12
+ assertValidNativeContentDesiredUpdateRequest,
13
+ assertValidNativeContentDesiredUpdateResult,
14
+ assertValidNativeContentSnapshotRequest,
15
+ assertValidNativeContentSnapshotResult,
16
+ } from "./validation.ts";
17
+ import {
18
+ NATIVE_CONTENT_PROTOCOL_VERSION,
19
+ type ContentSizeDecision,
20
+ type ContentSizeProposal,
21
+ type DesiredUpdate,
22
+ type NativeContentChangedEvent,
23
+ type NativeContentContentSizeDecisionResult,
24
+ type NativeContentDesiredUpdateResult,
25
+ type NativeContentIslandId,
26
+ type NativeContentSnapshot,
27
+ } from "./generated/protocol.ts";
28
+ import type { NativeContentPort, NativeContentUnlisten } from "./ports.ts";
29
+
30
+ const DEFAULT_MAXIMUM_PENDING_REQUESTS = 32;
31
+
32
+ export interface NativeContentClientOptions {
33
+ readonly maximumPendingRequests?: number;
34
+ }
35
+
36
+ export interface NativeContentConnection {
37
+ readonly ready: Promise<NativeContentSnapshot>;
38
+ current(): NativeContentSnapshot | undefined;
39
+ failures(): readonly ConnectionFailure[];
40
+ updateDesired(update: DesiredUpdate): Promise<NativeContentDesiredUpdateResult>;
41
+ decideContentSize(
42
+ proposal: ContentSizeProposal,
43
+ decision: ContentSizeDecision,
44
+ ): Promise<NativeContentContentSizeDecisionResult>;
45
+ dispose(): Promise<void>;
46
+ }
47
+
48
+ export class NativeContentClient {
49
+ readonly #port: NativeContentPort;
50
+ readonly #islandId: NativeContentIslandId;
51
+ readonly #maximumPendingRequests: number;
52
+
53
+ constructor(
54
+ port: NativeContentPort,
55
+ islandId: NativeContentIslandId,
56
+ options: NativeContentClientOptions = {},
57
+ ) {
58
+ const maximum =
59
+ options.maximumPendingRequests ?? DEFAULT_MAXIMUM_PENDING_REQUESTS;
60
+ if (!Number.isSafeInteger(maximum) || maximum < 1) {
61
+ throw new RangeError("maximumPendingRequests must be a positive integer");
62
+ }
63
+ this.#port = port;
64
+ this.#islandId = islandId;
65
+ this.#maximumPendingRequests = maximum;
66
+ }
67
+
68
+ connect(
69
+ listener?: (snapshot: NativeContentSnapshot) => void,
70
+ onFailure?: ConnectionFailureReporter,
71
+ ): NativeContentConnection {
72
+ return new CheckedNativeContentConnection(
73
+ this.#port,
74
+ this.#islandId,
75
+ this.#maximumPendingRequests,
76
+ listener,
77
+ onFailure,
78
+ );
79
+ }
80
+ }
81
+
82
+ class CheckedNativeContentConnection implements NativeContentConnection {
83
+ readonly ready: Promise<NativeContentSnapshot>;
84
+ readonly #port: NativeContentPort;
85
+ readonly #islandId: NativeContentIslandId;
86
+ readonly #maximumPendingRequests: number;
87
+ readonly #listener: ((snapshot: NativeContentSnapshot) => void) | undefined;
88
+ readonly #onFailure: ConnectionFailureReporter | undefined;
89
+ readonly #failures: ConnectionFailure[] = [];
90
+ readonly #pending = new Set<string>();
91
+ readonly #queuedEvents: NativeContentChangedEvent[] = [];
92
+ #snapshot: NativeContentSnapshot | undefined;
93
+ #unlisten: NativeContentUnlisten | undefined;
94
+ #cleanup: Promise<void> | undefined;
95
+ #pump: Promise<void> | undefined;
96
+ #refreshPending = false;
97
+ #disposed = false;
98
+
99
+ constructor(
100
+ port: NativeContentPort,
101
+ islandId: NativeContentIslandId,
102
+ maximumPendingRequests: number,
103
+ listener?: (snapshot: NativeContentSnapshot) => void,
104
+ onFailure?: ConnectionFailureReporter,
105
+ ) {
106
+ this.#port = port;
107
+ this.#islandId = islandId;
108
+ this.#maximumPendingRequests = maximumPendingRequests;
109
+ this.#listener = listener;
110
+ this.#onFailure = onFailure;
111
+ this.ready = this.#start();
112
+ }
113
+
114
+ current(): NativeContentSnapshot | undefined {
115
+ return this.#snapshot;
116
+ }
117
+
118
+ failures(): readonly ConnectionFailure[] {
119
+ return [...this.#failures];
120
+ }
121
+
122
+ async updateDesired(
123
+ update: DesiredUpdate,
124
+ ): Promise<NativeContentDesiredUpdateResult> {
125
+ const current = await this.#requireCurrent();
126
+ const requestId = this.#beginRequest();
127
+ const session = sessionCursor(current);
128
+ const request = {
129
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
130
+ request_id: requestId,
131
+ island_id: this.#islandId,
132
+ client_epoch: current.cursor.client_epoch,
133
+ expected_desired_revision: current.cursor.desired_revision,
134
+ update,
135
+ };
136
+ assertValidNativeContentDesiredUpdateRequest(request);
137
+ try {
138
+ const value = await this.#port.updateDesired(request);
139
+ assertValidNativeContentDesiredUpdateResult(value);
140
+ assertCorrelation(value.request_id, requestId);
141
+ if (value.status === "committed") this.#offer(value.snapshot, session);
142
+ return value;
143
+ } finally {
144
+ this.#pending.delete(requestId);
145
+ }
146
+ }
147
+
148
+ async decideContentSize(
149
+ proposal: ContentSizeProposal,
150
+ decision: ContentSizeDecision,
151
+ ): Promise<NativeContentContentSizeDecisionResult> {
152
+ const current = await this.#requireCurrent();
153
+ const requestId = this.#beginRequest();
154
+ const session = sessionCursor(current);
155
+ const request = {
156
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
157
+ request_id: requestId,
158
+ island_id: this.#islandId,
159
+ client_epoch: current.cursor.client_epoch,
160
+ proposal,
161
+ decision,
162
+ };
163
+ assertValidNativeContentDecisionRequest(request);
164
+ try {
165
+ const value = await this.#port.decideContentSize(request);
166
+ assertValidNativeContentDecisionResult(value);
167
+ assertCorrelation(value.request_id, requestId);
168
+ if (value.status === "decided") this.#offer(value.snapshot, session);
169
+ return value;
170
+ } finally {
171
+ this.#pending.delete(requestId);
172
+ }
173
+ }
174
+
175
+ async dispose(): Promise<void> {
176
+ this.#disposed = true;
177
+ this.#pending.clear();
178
+ await this.#closeListener();
179
+ try {
180
+ await this.ready;
181
+ } catch {
182
+ // Registration/start failures are already retained in failures().
183
+ }
184
+ await this.#closeListener();
185
+ }
186
+
187
+ async #start(): Promise<NativeContentSnapshot> {
188
+ try {
189
+ this.#unlisten =
190
+ this.#port.listen === undefined
191
+ ? () => {}
192
+ : await this.#port.listen((value) => this.#handleEvent(value));
193
+ } catch (error) {
194
+ this.#recordFailure("registration", error);
195
+ throw error;
196
+ }
197
+
198
+ if (this.#disposed) {
199
+ await this.#closeListener();
200
+ throw new NativeContentConnectionDisposedError();
201
+ }
202
+
203
+ try {
204
+ const requestId = this.#port.nextRequestId();
205
+ const request = {
206
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
207
+ request_id: requestId,
208
+ island_id: this.#islandId,
209
+ };
210
+ assertValidNativeContentConnectRequest(request);
211
+ const value = await this.#port.connect(request);
212
+ assertValidNativeContentConnectResult(value);
213
+ assertCorrelation(value.request_id, requestId);
214
+ if (value.status === "rejected") {
215
+ throw new NativeContentRequestRejectedError(value.rejection);
216
+ }
217
+ if (this.#disposed) {
218
+ await this.#closeListener();
219
+ throw new NativeContentConnectionDisposedError();
220
+ }
221
+ this.#install(value.snapshot);
222
+ for (const event of this.#queuedEvents.splice(0)) this.#acceptEvent(event);
223
+ await this.#synchronize();
224
+ const current = this.#snapshot;
225
+ if (current === undefined) throw new Error("native-content connect returned no snapshot");
226
+ return current;
227
+ } catch (error) {
228
+ this.#recordFailure("snapshot", error);
229
+ await this.#closeAfterFailure();
230
+ throw error;
231
+ }
232
+ }
233
+
234
+ #handleEvent(value: unknown): void {
235
+ if (this.#disposed || this.#failures.length > 0) return;
236
+ try {
237
+ assertValidNativeContentChangedEvent(value);
238
+ if (value.cursor.island_id !== this.#islandId) return;
239
+ if (this.#snapshot === undefined) {
240
+ this.#queuedEvents.push(value);
241
+ return;
242
+ }
243
+ this.#acceptEvent(value);
244
+ } catch (error) {
245
+ this.#recordFailure("event", error);
246
+ void this.#closeAfterFailure();
247
+ }
248
+ }
249
+
250
+ #acceptEvent(event: NativeContentChangedEvent): void {
251
+ const current = this.#snapshot;
252
+ if (current === undefined) return;
253
+ const currentCursor = current.cursor;
254
+ if (event.cursor.authority_epoch < currentCursor.authority_epoch) return;
255
+ if (
256
+ event.cursor.authority_epoch > currentCursor.authority_epoch ||
257
+ event.cursor.client_epoch > currentCursor.client_epoch
258
+ ) {
259
+ throw new NativeContentSessionReplacedError();
260
+ }
261
+ if (event.cursor.client_epoch < currentCursor.client_epoch) return;
262
+ if (
263
+ event.cursor.desired_revision <= currentCursor.desired_revision &&
264
+ event.cursor.observed_revision <= currentCursor.observed_revision
265
+ ) {
266
+ return;
267
+ }
268
+ this.#refreshPending = true;
269
+ void this.#synchronize().catch((error) => {
270
+ this.#recordFailure("snapshot", error);
271
+ void this.#closeAfterFailure();
272
+ });
273
+ }
274
+
275
+ #synchronize(): Promise<void> {
276
+ if (this.#disposed || this.#failures.length > 0 || !this.#refreshPending) {
277
+ return Promise.resolve();
278
+ }
279
+ this.#pump ??= this.#runPump().finally(() => {
280
+ this.#pump = undefined;
281
+ });
282
+ return this.#pump;
283
+ }
284
+
285
+ async #runPump(): Promise<void> {
286
+ while (this.#refreshPending && !this.#disposed && this.#failures.length === 0) {
287
+ this.#refreshPending = false;
288
+ const current = this.#snapshot;
289
+ if (current === undefined) return;
290
+ const requestId = this.#port.nextRequestId();
291
+ const request = {
292
+ protocol_version: NATIVE_CONTENT_PROTOCOL_VERSION,
293
+ request_id: requestId,
294
+ island_id: this.#islandId,
295
+ client_epoch: current.cursor.client_epoch,
296
+ };
297
+ assertValidNativeContentSnapshotRequest(request);
298
+ const value = await this.#port.snapshot(request);
299
+ assertValidNativeContentSnapshotResult(value);
300
+ assertCorrelation(value.request_id, requestId);
301
+ if (value.status === "rejected") {
302
+ throw new NativeContentRequestRejectedError(value.rejection);
303
+ }
304
+ this.#offer(value.snapshot, sessionCursor(current));
305
+ }
306
+ }
307
+
308
+ #offer(snapshot: NativeContentSnapshot, session: SessionCursor): void {
309
+ if (this.#disposed) return;
310
+ const current = this.#snapshot;
311
+ if (current === undefined) return;
312
+ if (
313
+ current.cursor.authority_epoch !== session.authorityEpoch ||
314
+ current.cursor.client_epoch !== session.clientEpoch ||
315
+ snapshot.cursor.authority_epoch !== session.authorityEpoch ||
316
+ snapshot.cursor.client_epoch !== session.clientEpoch
317
+ ) {
318
+ return;
319
+ }
320
+ if (!isNewerSnapshot(snapshot, current)) return;
321
+ this.#install(snapshot);
322
+ }
323
+
324
+ #install(snapshot: NativeContentSnapshot): void {
325
+ this.#snapshot = snapshot;
326
+ this.#listener?.(snapshot);
327
+ }
328
+
329
+ async #requireCurrent(): Promise<NativeContentSnapshot> {
330
+ await this.ready;
331
+ if (this.#disposed) throw new NativeContentConnectionDisposedError();
332
+ const current = this.#snapshot;
333
+ if (current === undefined) throw new NativeContentConnectionUnavailableError();
334
+ return current;
335
+ }
336
+
337
+ #beginRequest(): string {
338
+ if (this.#pending.size >= this.#maximumPendingRequests) {
339
+ throw new NativeContentPendingRequestLimitError(
340
+ this.#maximumPendingRequests,
341
+ );
342
+ }
343
+ const requestId = this.#port.nextRequestId();
344
+ if (this.#pending.has(requestId)) {
345
+ throw new NativeContentDuplicateRequestIdError(requestId);
346
+ }
347
+ this.#pending.add(requestId);
348
+ return requestId;
349
+ }
350
+
351
+ #recordFailure(phase: ConnectionFailure["phase"], error: unknown): void {
352
+ if (this.#failures.some((failure) => failure.phase === phase && failure.error === error)) return;
353
+ const failure = { phase, error };
354
+ this.#failures.push(failure);
355
+ this.#onFailure?.(failure);
356
+ }
357
+
358
+ async #closeAfterFailure(): Promise<void> {
359
+ try {
360
+ await this.#closeListener();
361
+ } catch (error) {
362
+ this.#recordFailure("unlisten", error);
363
+ }
364
+ }
365
+
366
+ #closeListener(): Promise<void> {
367
+ if (this.#cleanup !== undefined) return this.#cleanup;
368
+ const unlisten = this.#unlisten;
369
+ if (unlisten === undefined) return Promise.resolve();
370
+ this.#unlisten = undefined;
371
+ this.#cleanup = Promise.resolve().then(() => unlisten());
372
+ return this.#cleanup;
373
+ }
374
+ }
375
+
376
+ interface SessionCursor {
377
+ readonly authorityEpoch: number;
378
+ readonly clientEpoch: number;
379
+ }
380
+
381
+ function sessionCursor(snapshot: NativeContentSnapshot): SessionCursor {
382
+ return {
383
+ authorityEpoch: snapshot.cursor.authority_epoch,
384
+ clientEpoch: snapshot.cursor.client_epoch,
385
+ };
386
+ }
387
+
388
+ export function isNewerNativeContentSnapshot(
389
+ candidate: NativeContentSnapshot,
390
+ current: NativeContentSnapshot | undefined,
391
+ ): boolean {
392
+ if (current === undefined) return true;
393
+ if (candidate.cursor.authority_epoch !== current.cursor.authority_epoch) {
394
+ return candidate.cursor.authority_epoch > current.cursor.authority_epoch;
395
+ }
396
+ if (candidate.cursor.client_epoch !== current.cursor.client_epoch) return false;
397
+ if (
398
+ candidate.cursor.desired_revision < current.cursor.desired_revision ||
399
+ candidate.cursor.observed_revision < current.cursor.observed_revision
400
+ ) {
401
+ return false;
402
+ }
403
+ return (
404
+ candidate.cursor.desired_revision > current.cursor.desired_revision ||
405
+ candidate.cursor.observed_revision > current.cursor.observed_revision
406
+ );
407
+ }
408
+
409
+ function isNewerSnapshot(
410
+ candidate: NativeContentSnapshot,
411
+ current: NativeContentSnapshot,
412
+ ): boolean {
413
+ return isNewerNativeContentSnapshot(candidate, current);
414
+ }
415
+
416
+ function assertCorrelation(received: string, expected: string): void {
417
+ if (received !== expected) {
418
+ throw new NativeContentResponseCorrelationError(expected, received);
419
+ }
420
+ }
421
+
422
+ export class NativeContentResponseCorrelationError extends Error {
423
+ constructor(
424
+ readonly expectedRequestId: string,
425
+ readonly receivedRequestId: string,
426
+ ) {
427
+ super(
428
+ `native-content response correlation mismatch: expected ${expectedRequestId}; received ${receivedRequestId}`,
429
+ );
430
+ this.name = "NativeContentResponseCorrelationError";
431
+ }
432
+ }
433
+
434
+ export class NativeContentRequestRejectedError extends Error {
435
+ constructor(readonly rejection: import("./generated/protocol.ts").NativeContentProtocolRejection) {
436
+ super(rejection.message);
437
+ this.name = "NativeContentRequestRejectedError";
438
+ }
439
+ }
440
+
441
+ export class NativeContentConnectionDisposedError extends Error {
442
+ constructor() {
443
+ super("native-content connection was disposed");
444
+ this.name = "NativeContentConnectionDisposedError";
445
+ }
446
+ }
447
+
448
+ export class NativeContentConnectionUnavailableError extends Error {
449
+ constructor() {
450
+ super("native-content connection has no authoritative snapshot");
451
+ this.name = "NativeContentConnectionUnavailableError";
452
+ }
453
+ }
454
+
455
+ export class NativeContentSessionReplacedError extends Error {
456
+ constructor() {
457
+ super("native-content renderer session was replaced");
458
+ this.name = "NativeContentSessionReplacedError";
459
+ }
460
+ }
461
+
462
+ export class NativeContentPendingRequestLimitError extends Error {
463
+ constructor(readonly maximum: number) {
464
+ super(`native-content pending request limit reached: ${maximum}`);
465
+ this.name = "NativeContentPendingRequestLimitError";
466
+ }
467
+ }
468
+
469
+ export class NativeContentDuplicateRequestIdError extends Error {
470
+ constructor(readonly requestId: string) {
471
+ super(`native-content request id is already pending: ${requestId}`);
472
+ this.name = "NativeContentDuplicateRequestIdError";
473
+ }
474
+ }