@inflatable-cookie/longhorn 0.6.0 → 0.7.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 (133) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -7
  3. package/src/agent-control/generated/protocol.ts +228 -0
  4. package/src/agent-control/index.ts +1 -5
  5. package/src/agent-control/selection.ts +10 -8
  6. package/src/agent-control/shim.ts +149 -77
  7. package/src/bridge/generated/fields.ts +1 -1
  8. package/src/bridge/generated/protocol.ts +55 -4
  9. package/src/bridge/generated/variant-fields.ts +1 -1
  10. package/src/bridge/job.ts +49 -2
  11. package/src/bridge/runtime/connection.ts +11 -14
  12. package/src/bridge/stream/connection.ts +14 -23
  13. package/src/bridge/stream/tracker.ts +5 -0
  14. package/src/bridge/supervision.ts +102 -80
  15. package/src/bridge/validation/base.ts +7 -27
  16. package/src/bridge/validation/negotiation.ts +1 -6
  17. package/src/bridge/validation/operations.ts +2 -14
  18. package/src/commands/client.ts +16 -2
  19. package/src/commands/controller.ts +96 -58
  20. package/src/commands/generated/fields.ts +4 -4
  21. package/src/commands/generated/protocol.ts +24 -1
  22. package/src/commands/generated/variant-fields.ts +1 -1
  23. package/src/commands/keyboard.ts +4 -13
  24. package/src/commands/physical-code.ts +11 -0
  25. package/src/commands/ports.ts +2 -1
  26. package/src/commands/projectors.ts +52 -29
  27. package/src/commands/validation.ts +408 -188
  28. package/src/config/client.ts +3 -3
  29. package/src/config/generated/base.ts +22 -6
  30. package/src/config/generated/fields.ts +2 -1
  31. package/src/config/generated/label-template.ts +1 -1
  32. package/src/config/generated/labels.ts +1 -1
  33. package/src/config/generated/protocol.ts +1 -1
  34. package/src/config/generated/restore.ts +35 -12
  35. package/src/config/generated/variant-fields.ts +1 -1
  36. package/src/config/validation/commands.ts +11 -13
  37. package/src/config/validation/outcomes.ts +147 -46
  38. package/src/config/validation/primitives.ts +11 -39
  39. package/src/config/validation/projection.ts +44 -44
  40. package/src/core/connection.ts +124 -29
  41. package/src/core/controller-lifecycle.ts +144 -0
  42. package/src/core/generated/identifiers.ts +4 -0
  43. package/src/core/identifiers.ts +40 -0
  44. package/src/core/index.ts +10 -1
  45. package/src/core/json-value.ts +58 -0
  46. package/src/core/listeners.ts +35 -0
  47. package/src/core/record.ts +76 -0
  48. package/src/core/transport.ts +10 -1
  49. package/src/core/wire-copy.ts +1 -0
  50. package/src/history/client.ts +11 -7
  51. package/src/history/controller.ts +72 -74
  52. package/src/history/generated/fields.ts +2 -1
  53. package/src/history/generated/protocol.ts +8 -5
  54. package/src/history/generated/variant-fields.ts +1 -1
  55. package/src/history/ports.ts +7 -2
  56. package/src/history/validation.ts +15 -37
  57. package/src/history-tree/client.ts +15 -13
  58. package/src/history-tree/controller.ts +131 -90
  59. package/src/history-tree/generated/fields.ts +3 -1
  60. package/src/history-tree/generated/protocol.ts +43 -7
  61. package/src/history-tree/generated/variant-fields.ts +7 -1
  62. package/src/history-tree/ports.ts +9 -4
  63. package/src/history-tree/validation.ts +44 -35
  64. package/src/layout/generated/protocol.ts +2 -1
  65. package/src/layout/generated/variant-fields.ts +47 -0
  66. package/src/layout/index.ts +1 -1
  67. package/src/layout/ratio.ts +9 -2
  68. package/src/layout/validation.ts +88 -13
  69. package/src/licence/client.ts +11 -7
  70. package/src/licence/controller.ts +64 -43
  71. package/src/licence/generated/fields.ts +2 -1
  72. package/src/licence/generated/protocol.ts +8 -4
  73. package/src/licence/generated/variant-fields.ts +1 -1
  74. package/src/licence/key.ts +2 -6
  75. package/src/licence/ports.ts +7 -2
  76. package/src/licence/validation.ts +27 -20
  77. package/src/native-content/client.ts +32 -1
  78. package/src/native-content/generated/fields.ts +4 -4
  79. package/src/native-content/generated/protocol.ts +16 -5
  80. package/src/native-content/generated/variant-fields.ts +1 -1
  81. package/src/native-content/ports.ts +2 -1
  82. package/src/native-content/validation/base.ts +16 -46
  83. package/src/native-content/validation/messages.ts +3 -0
  84. package/src/notifications/client.ts +17 -39
  85. package/src/notifications/controller.ts +266 -165
  86. package/src/notifications/generated/fields.ts +2 -1
  87. package/src/notifications/generated/labels.ts +1 -1
  88. package/src/notifications/generated/protocol.ts +5 -1
  89. package/src/notifications/generated/variant-fields.ts +1 -1
  90. package/src/notifications/ports.ts +2 -1
  91. package/src/notifications/tone.ts +1 -1
  92. package/src/notifications/validation.ts +41 -51
  93. package/src/operation/bridge.ts +79 -19
  94. package/src/operation/client.ts +17 -45
  95. package/src/operation/controller.ts +38 -59
  96. package/src/operation/generated/fields.ts +2 -1
  97. package/src/operation/generated/labels.ts +1 -1
  98. package/src/operation/generated/protocol.ts +5 -1
  99. package/src/operation/generated/variant-fields.ts +1 -1
  100. package/src/operation/ports.ts +2 -1
  101. package/src/operation/validation.ts +48 -50
  102. package/src/settings/connection.ts +10 -14
  103. package/src/settings/generated/fields.ts +2 -1
  104. package/src/settings/generated/protocol.ts +5 -1
  105. package/src/settings/generated/variant-fields.ts +1 -1
  106. package/src/settings/validation/authority.ts +2 -2
  107. package/src/settings/validation/command.ts +5 -4
  108. package/src/settings/validation/primitives.ts +32 -67
  109. package/src/settings/validation/registry.ts +13 -11
  110. package/src/surface-transfer/generated/fields.ts +1 -1
  111. package/src/surface-transfer/generated/protocol.ts +3 -3
  112. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  113. package/src/surface-transfer/validation.ts +76 -53
  114. package/src/surfaces/client.ts +26 -38
  115. package/src/surfaces/generated/fields.ts +1 -1
  116. package/src/surfaces/generated/protocol.ts +1 -1
  117. package/src/surfaces/generated/variant-fields.ts +1 -1
  118. package/src/surfaces/validation.ts +198 -61
  119. package/src/transfer/connection.ts +25 -39
  120. package/src/transfer/generated/fields.ts +2 -1
  121. package/src/transfer/generated/protocol.ts +9 -1
  122. package/src/transfer/generated/variant-fields.ts +1 -1
  123. package/src/transfer/index.ts +8 -1
  124. package/src/transfer/payload.ts +12 -9
  125. package/src/transfer/validation.ts +146 -60
  126. package/src/update/client.ts +43 -16
  127. package/src/update/controller.ts +187 -104
  128. package/src/update/generated/fields.ts +2 -1
  129. package/src/update/generated/protocol.ts +19 -7
  130. package/src/update/generated/variant-fields.ts +3 -2
  131. package/src/update/ports.ts +11 -7
  132. package/src/update/serialized.ts +8 -6
  133. package/src/update/validation.ts +18 -28
@@ -1,3 +1,4 @@
1
+ import { ListenerDisposal } from "./listeners.ts";
1
2
  import type { Unlisten } from "./transport.ts";
2
3
 
3
4
  export type SnapshotEventAction =
@@ -14,6 +15,75 @@ export interface ConnectionFailure {
14
15
 
15
16
  export type ConnectionFailureReporter = (failure: ConnectionFailure) => void;
16
17
 
18
+ interface CheckedListenerOptions<Event> {
19
+ readonly listen: (listener: (payload: unknown) => void) => Unlisten | Promise<Unlisten>;
20
+ readonly validate: (payload: unknown) => asserts payload is Event;
21
+ readonly listener: (event: Event) => void;
22
+ readonly onFailure?: ConnectionFailureReporter | undefined;
23
+ }
24
+
25
+ export async function listenChecked<Event>(
26
+ options: CheckedListenerOptions<Event>,
27
+ ): Promise<Unlisten> {
28
+ const disposal = new ListenerDisposal();
29
+ const { listener, onFailure } = options;
30
+ const validate: CheckedListenerOptions<Event>["validate"] = options.validate;
31
+ let closed = false;
32
+ let registered = false;
33
+ const close = () => {
34
+ closed = true;
35
+ return disposal.close();
36
+ };
37
+ const closeAfterFailure = async () => {
38
+ try {
39
+ await close();
40
+ } catch (error) {
41
+ reportFailure(onFailure, { phase: "unlisten", error });
42
+ }
43
+ };
44
+
45
+ disposal.unlisten = await options.listen((payload) => {
46
+ if (closed) {
47
+ return;
48
+ }
49
+ try {
50
+ validate(payload);
51
+ } catch (error) {
52
+ closed = true;
53
+ reportFailure(onFailure, { phase: "event", error });
54
+ if (registered) {
55
+ void closeAfterFailure();
56
+ }
57
+ return;
58
+ }
59
+ try {
60
+ listener(payload);
61
+ } catch (error) {
62
+ // A callback during registration cannot unwind a listen that still owes us its disposer.
63
+ if (registered) {
64
+ throw error;
65
+ }
66
+ }
67
+ });
68
+ registered = true;
69
+ if (closed) {
70
+ await closeAfterFailure();
71
+ }
72
+ return close;
73
+ }
74
+
75
+ /** Reports to an optional consumer callback, which cannot throw back into the caller. */
76
+ export function reportFailure(
77
+ reporter: ConnectionFailureReporter | undefined,
78
+ failure: ConnectionFailure,
79
+ ): void {
80
+ try {
81
+ reporter?.(failure);
82
+ } catch {
83
+ // A failure reporter cannot interrupt teardown or replace the recorded error.
84
+ }
85
+ }
86
+
17
87
  export interface CheckedSnapshotConnectionOptions<Snapshot> {
18
88
  readonly listen: (listener: (payload: unknown) => void) => Promise<Unlisten>;
19
89
  readonly loadSnapshot: () => Promise<unknown>;
@@ -31,8 +101,7 @@ export class CheckedSnapshotConnection<Snapshot> {
31
101
  readonly #options: CheckedSnapshotConnectionOptions<Snapshot>;
32
102
  readonly #failures: Array<ConnectionFailure> = [];
33
103
  #current: Snapshot | undefined;
34
- #unlisten: Unlisten | undefined;
35
- #cleanup: Promise<void> | undefined;
104
+ readonly #listener = new ListenerDisposal();
36
105
  #pump: Promise<void> | undefined;
37
106
  #registered = false;
38
107
  #refreshPending = false;
@@ -51,6 +120,25 @@ export class CheckedSnapshotConnection<Snapshot> {
51
120
  return [...this.#failures];
52
121
  }
53
122
 
123
+ /**
124
+ * Asks for one more authoritative load: the caller learned that the snapshot
125
+ * it was just given does not cover everything already observed. Requests made
126
+ * while a load is in flight collapse into one further pass. It is a no-op
127
+ * after dispose or failure.
128
+ */
129
+ requestRefresh(): void {
130
+ if (this.#disposed || this.#failures.length > 0) {
131
+ return;
132
+ }
133
+ this.#refreshPending = true;
134
+ if (this.#registered) {
135
+ void this.#synchronize().catch((error: unknown) => {
136
+ this.#recordFailure("snapshot", error);
137
+ void this.#closeAfterFailure();
138
+ });
139
+ }
140
+ }
141
+
54
142
  /**
55
143
  * Accepts a snapshot the caller obtained from its own request (for example,
56
144
  * a mutation result), under the same `isNewer` rule the refresh pump uses.
@@ -67,7 +155,7 @@ export class CheckedSnapshotConnection<Snapshot> {
67
155
 
68
156
  let cleanupFailure: { error: unknown } | undefined;
69
157
  try {
70
- await this.#closeListener();
158
+ await this.#listener.close();
71
159
  } catch (error) {
72
160
  cleanupFailure = { error };
73
161
  this.#recordFailure("unlisten", error);
@@ -82,7 +170,7 @@ export class CheckedSnapshotConnection<Snapshot> {
82
170
 
83
171
  if (cleanupFailure === undefined) {
84
172
  try {
85
- await this.#closeListener();
173
+ await this.#listener.close();
86
174
  } catch (error) {
87
175
  cleanupFailure = { error };
88
176
  this.#recordFailure("unlisten", error);
@@ -106,7 +194,7 @@ export class CheckedSnapshotConnection<Snapshot> {
106
194
  throw error;
107
195
  }
108
196
 
109
- this.#unlisten = unlisten;
197
+ this.#listener.unlisten = unlisten;
110
198
  this.#registered = true;
111
199
 
112
200
  if (this.#disposed) {
@@ -155,13 +243,7 @@ export class CheckedSnapshotConnection<Snapshot> {
155
243
  case "ignore":
156
244
  return;
157
245
  case "refresh":
158
- this.#refreshPending = true;
159
- if (this.#registered) {
160
- void this.#synchronize().catch((error: unknown) => {
161
- this.#recordFailure("snapshot", error);
162
- void this.#closeAfterFailure();
163
- });
164
- }
246
+ this.requestRefresh();
165
247
  return;
166
248
  case "snapshot":
167
249
  candidate = this.#options.validateSnapshot(action.value);
@@ -231,31 +313,44 @@ export class CheckedSnapshotConnection<Snapshot> {
231
313
  }
232
314
  const failure = { phase, error };
233
315
  this.#failures.push(failure);
234
- try {
235
- this.#options.onFailure?.(failure);
236
- } catch {
237
- // A failure reporter cannot interrupt teardown or replace the recorded error.
238
- }
316
+ reportFailure(this.#options.onFailure, failure);
239
317
  }
240
318
 
241
319
  async #closeAfterFailure(): Promise<void> {
242
320
  try {
243
- await this.#closeListener();
321
+ await this.#listener.close();
244
322
  } catch (error) {
245
323
  this.#recordFailure("unlisten", error);
246
324
  }
247
325
  }
326
+ }
248
327
 
249
- #closeListener(): Promise<void> {
250
- if (this.#cleanup !== undefined) {
251
- return this.#cleanup;
252
- }
253
- const unlisten = this.#unlisten;
254
- if (unlisten === undefined) {
255
- return Promise.resolve();
256
- }
257
- this.#unlisten = undefined;
258
- this.#cleanup = Promise.resolve().then(() => unlisten());
259
- return this.#cleanup;
328
+ /**
329
+ * The lifetime a domain subscription exposes over one connection. `ready`
330
+ * settles when the first synchronization does, and `present` decides what it
331
+ * resolves to.
332
+ */
333
+ export class CheckedSubscription<Snapshot, Ready = void> {
334
+ readonly ready: Promise<Ready>;
335
+ readonly #connection: CheckedSnapshotConnection<Snapshot>;
336
+
337
+ constructor(
338
+ connection: CheckedSnapshotConnection<Snapshot>,
339
+ present: (snapshot: Snapshot | undefined) => Ready,
340
+ ) {
341
+ this.#connection = connection;
342
+ this.ready = connection.ready.then(present);
343
+ }
344
+
345
+ current(): Snapshot | undefined {
346
+ return this.#connection.current();
347
+ }
348
+
349
+ failures(): ReadonlyArray<ConnectionFailure> {
350
+ return this.#connection.failures();
351
+ }
352
+
353
+ dispose(): Promise<void> {
354
+ return this.#connection.dispose();
260
355
  }
261
356
  }
@@ -0,0 +1,144 @@
1
+ import type { ConnectionFailure, ConnectionFailureReporter } from "./connection.ts";
2
+ import { disposeAll } from "./listeners.ts";
3
+ import type { Unlisten } from "./transport.ts";
4
+
5
+ interface ControllerLifetime {
6
+ readonly isCurrent: () => boolean;
7
+ readonly own: (...unlisten: Array<Unlisten>) => Promise<void>;
8
+ readonly reportFailure: ConnectionFailureReporter;
9
+ readonly watch: (subscription: SnapshotSubscription, ready: () => void) => Promise<void>;
10
+ }
11
+
12
+ interface SnapshotSubscription {
13
+ readonly ready: Promise<unknown>;
14
+ failures(): ReadonlyArray<ConnectionFailure>;
15
+ dispose(): Promise<void>;
16
+ }
17
+
18
+ interface ControllerStart {
19
+ readonly loading: () => void;
20
+ readonly connect: (lifetime: ControllerLifetime) => Promise<void>;
21
+ readonly failed: (error: unknown) => void;
22
+ }
23
+
24
+ export class ControllerLifecycle {
25
+ #unlisten: Array<Unlisten> | undefined;
26
+ #revision = 0;
27
+ #eventFailure: { readonly kind: "failed"; readonly error: unknown } | undefined;
28
+
29
+ get revision(): number {
30
+ return this.#revision;
31
+ }
32
+
33
+ get active(): boolean {
34
+ return this.#unlisten !== undefined;
35
+ }
36
+
37
+ get eventFailure() {
38
+ return this.#eventFailure;
39
+ }
40
+
41
+ isCurrent(revision: number): boolean {
42
+ return this.active && this.#revision === revision;
43
+ }
44
+
45
+ /** Retains the lifetime's first event failure until the controller stops. */
46
+ recordEventFailure(error: unknown): void {
47
+ this.#eventFailure ??= { kind: "failed", error };
48
+ }
49
+
50
+ async start({ loading, connect, failed }: ControllerStart): Promise<void> {
51
+ if (this.active) {
52
+ return;
53
+ }
54
+ const listeners: Array<Unlisten> = [];
55
+ this.#unlisten = listeners;
56
+ const revision = ++this.#revision;
57
+ const isCurrent = () => this.isCurrent(revision);
58
+ const own = async (...unlisten: Array<Unlisten>) => {
59
+ if (isCurrent()) {
60
+ listeners.push(...unlisten);
61
+ } else {
62
+ await disposeAll(unlisten);
63
+ }
64
+ };
65
+ try {
66
+ loading();
67
+ if (isCurrent()) {
68
+ await connect({
69
+ isCurrent,
70
+ own,
71
+ reportFailure: ({ phase, error }) => {
72
+ if (isCurrent() && phase !== "unlisten") {
73
+ if (phase === "event") {
74
+ this.recordEventFailure(error);
75
+ }
76
+ failed(error);
77
+ }
78
+ },
79
+ watch: async (subscription, ready) => {
80
+ // The connection owns cleanup on registration and snapshot failures.
81
+ await own(() => subscription.dispose());
82
+ try {
83
+ await subscription.ready;
84
+ if (isCurrent() && subscription.failures().length === 0) {
85
+ ready();
86
+ }
87
+ } catch (error) {
88
+ if (isCurrent()) {
89
+ failed(error);
90
+ }
91
+ }
92
+ },
93
+ });
94
+ }
95
+ } catch (error) {
96
+ if (isCurrent()) {
97
+ const unlisten = listeners.splice(0);
98
+ try {
99
+ failed(error);
100
+ } finally {
101
+ await disposeAll(unlisten);
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ /** Replaces a lifetime unless another lifecycle action supersedes its teardown. */
108
+ async restart(
109
+ status: { readonly kind: string; readonly error?: unknown },
110
+ stop: () => Promise<void>,
111
+ start: () => Promise<void>,
112
+ ): Promise<void> {
113
+ const stopping = stop();
114
+ const revision = this.#revision;
115
+ try {
116
+ await stopping;
117
+ } catch (error) {
118
+ if (status.kind !== "failed" || !Object.is(error, status.error)) {
119
+ throw error;
120
+ }
121
+ }
122
+ if (this.#revision === revision) {
123
+ await start();
124
+ }
125
+ }
126
+
127
+ /** Resets the controller, then releases every owned listener before reporting a failure. */
128
+ async stop(reset: () => void): Promise<void> {
129
+ const listeners = this.#unlisten ?? [];
130
+ this.#unlisten = undefined;
131
+ this.#eventFailure = undefined;
132
+ this.#revision += 1;
133
+ let results: Array<PromiseSettledResult<void>>;
134
+ try {
135
+ reset();
136
+ } finally {
137
+ results = await disposeAll(listeners);
138
+ }
139
+ const failure = results.find((result) => result.status === "rejected");
140
+ if (failure !== undefined) {
141
+ throw failure.reason;
142
+ }
143
+ }
144
+ }
@@ -0,0 +1,4 @@
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
+ // Rust is the identifier authority.
3
+
4
+ export const OPAQUE_ID_RULE = {"characters":"abcdefghijklmnopqrstuvwxyz0123456789._:-","maximumBytes":128} as const;
@@ -0,0 +1,40 @@
1
+ import { OPAQUE_ID_RULE } from "./generated/identifiers.ts";
2
+
3
+ /** Whether Rust would admit `value` as an opaque Longhorn identifier. */
4
+ export function isOpaqueId(value: unknown): value is string {
5
+ // Every admitted character is one byte, so the length is also the byte count.
6
+ return (
7
+ typeof value === "string" &&
8
+ value.length > 0 &&
9
+ value.length <= OPAQUE_ID_RULE.maximumBytes &&
10
+ Array.from(value).every((character) => OPAQUE_ID_RULE.characters.includes(character))
11
+ );
12
+ }
13
+
14
+ /** The shape of a generated `DomainId` grammar. */
15
+ export interface DomainIdRule {
16
+ readonly maximumBytes: number;
17
+ readonly separator: string;
18
+ readonly segmentInitial: string;
19
+ readonly segmentAdditional: string;
20
+ }
21
+
22
+ /** Whether Rust would admit `value` as a `DomainId` under the generated rule. */
23
+ export function matchesDomainIdRule(value: unknown, rule: DomainIdRule): value is string {
24
+ const { maximumBytes, separator, segmentInitial, segmentAdditional } = rule;
25
+ return (
26
+ typeof value === "string" &&
27
+ new TextEncoder().encode(value).length <= maximumBytes &&
28
+ value.split(separator).every((segment) => {
29
+ const [first, ...rest] = segment;
30
+ return (
31
+ first !== undefined &&
32
+ segmentInitial.includes(first) &&
33
+ rest.every(
34
+ (character) =>
35
+ segmentInitial.includes(character) || segmentAdditional.includes(character),
36
+ )
37
+ );
38
+ })
39
+ );
40
+ }
package/src/core/index.ts CHANGED
@@ -1,2 +1,11 @@
1
- export * from "./connection.ts";
1
+ export { CheckedSnapshotConnection, CheckedSubscription } from "./connection.ts";
2
+ export type {
3
+ CheckedSnapshotConnectionOptions,
4
+ ConnectionFailure,
5
+ ConnectionFailurePhase,
6
+ ConnectionFailureReporter,
7
+ SnapshotEventAction,
8
+ } from "./connection.ts";
2
9
  export * from "./transport.ts";
10
+ export { isOpaqueId } from "./identifiers.ts";
11
+ export { OPAQUE_ID_RULE } from "./generated/identifiers.ts";
@@ -0,0 +1,58 @@
1
+ import { hasHole } from "./record.ts";
2
+
3
+ /**
4
+ * Whether JSON encoding carries `value` to Rust unchanged: nothing in it
5
+ * throws, is dropped, turns into `null`, is rewritten by a `toJSON`, holds text
6
+ * Rust cannot decode or nests more than `maximumDepth` arrays and records.
7
+ */
8
+ export function isJsonValue(value: unknown, maximumDepth: number): boolean {
9
+ return carries(value, new Set(), maximumDepth);
10
+ }
11
+
12
+ /** Rust strings are Unicode, so it cannot decode an unpaired surrogate. */
13
+ export function isUnicodeText(value: string): boolean {
14
+ return !/\p{Surrogate}/u.test(value);
15
+ }
16
+
17
+ function carries(value: unknown, ancestors: Set<object>, depth: number): boolean {
18
+ if (value === null || typeof value === "boolean") {
19
+ return true;
20
+ }
21
+ if (typeof value === "string") {
22
+ return isUnicodeText(value);
23
+ }
24
+ if (typeof value === "number") {
25
+ return Number.isFinite(value);
26
+ }
27
+ if (typeof value !== "object" || depth === 0 || ancestors.has(value)) {
28
+ return false;
29
+ }
30
+ if ("toJSON" in value && typeof value.toJSON === "function") {
31
+ return false;
32
+ }
33
+ const keys = Reflect.ownKeys(value).filter((key) =>
34
+ Object.prototype.propertyIsEnumerable.call(value, key),
35
+ );
36
+ let members: ReadonlyArray<unknown>;
37
+ if (Array.isArray(value)) {
38
+ // A hole encodes as `null` and a property beside the indices is dropped.
39
+ if (keys.length !== value.length || hasHole(value)) {
40
+ return false;
41
+ }
42
+ members = value;
43
+ } else {
44
+ // A plain object of any realm: its prototype, if any, is a root.
45
+ const prototype: unknown = Object.getPrototypeOf(value);
46
+ if (prototype !== null && Object.getPrototypeOf(prototype) !== null) {
47
+ return false;
48
+ }
49
+ if (keys.some((key) => typeof key !== "string" || !isUnicodeText(key))) {
50
+ return false;
51
+ }
52
+ members = Object.values(value);
53
+ }
54
+ ancestors.add(value);
55
+ const carried = members.every((member) => carries(member, ancestors, depth - 1));
56
+ ancestors.delete(value);
57
+ return carried;
58
+ }
@@ -0,0 +1,35 @@
1
+ import type { Unlisten } from "./transport.ts";
2
+
3
+ /**
4
+ * Runs `run` inside a promise so a synchronous throw becomes a rejection that
5
+ * the caller can settle alongside the others, instead of abandoning them.
6
+ */
7
+ export function attempt<Value>(run: () => Value | PromiseLike<Value>): Promise<Value> {
8
+ return new Promise<Value>((resolve) => {
9
+ resolve(run());
10
+ });
11
+ }
12
+
13
+ /**
14
+ * Disposes every registration. One unlisten that throws, sync or async, does
15
+ * not skip the rest. Results include any failures and follow registration order.
16
+ */
17
+ export function disposeAll(
18
+ unlisten: ReadonlyArray<() => void | Promise<void>>,
19
+ ): Promise<Array<PromiseSettledResult<void>>> {
20
+ return Promise.allSettled(unlisten.map((dispose) => attempt(dispose)));
21
+ }
22
+ /** Holds one unlisten and shares its result between competing cleanup paths. */
23
+ export class ListenerDisposal {
24
+ unlisten: Unlisten | undefined;
25
+ #cleanup: Promise<void> | undefined;
26
+
27
+ close(): Promise<void> {
28
+ const unlisten = this.unlisten;
29
+ if (unlisten !== undefined) {
30
+ this.unlisten = undefined;
31
+ this.#cleanup = Promise.resolve().then(() => unlisten());
32
+ }
33
+ return this.#cleanup ?? Promise.resolve();
34
+ }
35
+ }
@@ -2,3 +2,79 @@
2
2
  export function isRecord(value: unknown): value is Record<string, unknown> {
3
3
  return typeof value === "object" && value !== null && !Array.isArray(value);
4
4
  }
5
+
6
+ export function readWireRecord(
7
+ value: unknown,
8
+ invalidObject: () => never,
9
+ ): Record<string, unknown> {
10
+ return isRecord(value) ? value : invalidObject();
11
+ }
12
+
13
+ // A required wire field must be an own, enumerable property to appear in JSON.
14
+ export function checkWireFields(
15
+ value: Record<string, unknown>,
16
+ required: ReadonlyArray<string> | undefined,
17
+ invalidField: (code: "unknown_field" | "missing_field", key: string) => never,
18
+ optional: ReadonlyArray<string> = [],
19
+ ): void {
20
+ if (required === undefined) {
21
+ return;
22
+ }
23
+ const present = new Set(Object.keys(value));
24
+ const allowed = new Set([...required, ...optional]);
25
+ for (const key of present) {
26
+ if (!allowed.has(key)) {
27
+ invalidField("unknown_field", key);
28
+ }
29
+ }
30
+ for (const key of required) {
31
+ if (!present.has(key)) {
32
+ invalidField("missing_field", key);
33
+ }
34
+ }
35
+ }
36
+
37
+ export function wireVariantFields(
38
+ fields: Readonly<Record<string, Readonly<Record<string, ReadonlyArray<string>>>>>,
39
+ discriminants: Readonly<Record<string, string>>,
40
+ type: string,
41
+ value: Record<string, unknown>,
42
+ invalidVariant: (discriminant: unknown) => never,
43
+ ): ReadonlyArray<string> {
44
+ const tag = discriminants[type];
45
+ const discriminant = tag === undefined ? undefined : value[tag];
46
+ const variants = fields[type];
47
+ if (
48
+ typeof discriminant !== "string" ||
49
+ variants === undefined ||
50
+ !Object.hasOwn(variants, discriminant)
51
+ ) {
52
+ return invalidVariant(discriminant);
53
+ }
54
+ return variants[discriminant] ?? invalidVariant(discriminant);
55
+ }
56
+
57
+ // JSON writes a hole as `null` and `forEach` skips it. `in` is the test
58
+ // `forEach` skips by, also for a state proxy, and it reads no item.
59
+ export function hasHole(values: ReadonlyArray<unknown>): boolean {
60
+ for (let index = 0; index < values.length; index += 1) {
61
+ if (!(index in values)) {
62
+ return true;
63
+ }
64
+ }
65
+ return false;
66
+ }
67
+
68
+ export function unsignedInteger(value: unknown): value is number {
69
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
70
+ }
71
+
72
+ export function unsigned32(value: unknown): value is number {
73
+ const maximum = 0xff_ff_ff_ff;
74
+ return unsignedInteger(value) && value <= maximum;
75
+ }
76
+
77
+ export function signed32(value: unknown): value is number {
78
+ const limit = 0x80_00_00_00;
79
+ return typeof value === "number" && Number.isInteger(value) && value >= -limit && value < limit;
80
+ }
@@ -4,8 +4,17 @@ export interface InvokeTransport {
4
4
  invoke(command: string, arguments_: Record<string, unknown>): Promise<unknown>;
5
5
  }
6
6
 
7
+ export interface EventListenOptions {
8
+ /** Selects a host-targeted event or an event delivered inside this renderer. */
9
+ readonly scope: "current-webview" | "renderer-local";
10
+ }
11
+
7
12
  export interface EventTransport extends InvokeTransport {
8
- listen(event: string, listener: (payload: unknown) => void): Promise<Unlisten>;
13
+ listen(
14
+ event: string,
15
+ listener: (payload: unknown) => void,
16
+ options?: EventListenOptions,
17
+ ): Promise<Unlisten>;
9
18
  }
10
19
 
11
20
  export function isEventTransport(transport: InvokeTransport): transport is EventTransport {
@@ -1,5 +1,6 @@
1
1
  // Serialized ports simulate the JSON transport, including its handling of
2
2
  // undefined fields, so a structured clone would exercise a different wire.
3
+ // A client that must hold what it dispatched takes the same copy.
3
4
  export function wireCopy<Value>(value: Value): Value {
4
5
  // oxlint-disable-next-line unicorn/prefer-structured-clone,typescript/no-unsafe-type-assertion -- Typed port inputs retain their wire type after the JSON round trip; checked clients validate the raw output.
5
6
  return JSON.parse(JSON.stringify(value)) as Value;
@@ -1,3 +1,5 @@
1
+ import { listenChecked } from "../core/connection.ts";
2
+ import type { ConnectionFailureReporter } from "../core/connection.ts";
1
3
  import {
2
4
  assertValidHistoryChangedEvent,
3
5
  assertValidHistoryNavigationCommand,
@@ -47,13 +49,15 @@ export class HistoryClient implements CheckedHistoryPort {
47
49
  return value;
48
50
  }
49
51
 
50
- async listen(listener: (event: HistoryChangedEvent) => void): Promise<HistoryUnlisten> {
51
- if (this.#port.listen === undefined) {
52
- return () => {};
53
- }
54
- return this.#port.listen((value) => {
55
- assertValidHistoryChangedEvent(value);
56
- listener(value);
52
+ listen(
53
+ listener: (event: HistoryChangedEvent) => void,
54
+ onFailure?: ConnectionFailureReporter,
55
+ ): Promise<HistoryUnlisten> {
56
+ return listenChecked({
57
+ listen: (receive) => this.#port.listen?.(receive) ?? (() => {}),
58
+ validate: assertValidHistoryChangedEvent,
59
+ listener,
60
+ onFailure,
57
61
  });
58
62
  }
59
63
  }