@bun-native/core 0.33.0 → 0.33.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.
package/src/batches.ts ADDED
@@ -0,0 +1,195 @@
1
+ import type { Limits } from '@bun-native/protocol'
2
+ import { NativeCommandError } from '@bun-native/runtime'
3
+ import { BATCH_ENVELOPE_BYTES, type Transaction } from './tree.ts'
4
+ import { NativeStateError, type NativeBatch } from './types.ts'
5
+
6
+ /** One caller's batch callback, queued behind the transaction in flight. */
7
+ export interface BatchEntry {
8
+ readonly update: (batch: NativeBatch) => unknown
9
+ resolve(value: unknown): void
10
+ reject(error: unknown): void
11
+ }
12
+
13
+ /** The window a group of batches commits to. */
14
+ export interface BatchWindow {
15
+ /** A transaction over the committed graph; throws once the window is closed. */
16
+ transaction(): Transaction
17
+ /**
18
+ * Send `transactions`, each continuing the one before it, as one native
19
+ * batch, and commit them in order after its acknowledgement.
20
+ */
21
+ apply(transactions: readonly Transaction[]): Promise<void>
22
+ }
23
+
24
+ /**
25
+ * A callback's outcome. Only one with operations takes part in a native
26
+ * batch; the others settle in their place in the order.
27
+ */
28
+ type Member = { entry: BatchEntry; transaction?: Transaction } & (
29
+ | { failed: false; value: unknown }
30
+ | { failed: true; error: unknown }
31
+ )
32
+
33
+ function settle(member: Member): void {
34
+ if (member.failed) member.entry.reject(member.error)
35
+ else member.entry.resolve(member.value)
36
+ }
37
+
38
+ function isThenable(value: unknown): boolean {
39
+ return (
40
+ value !== null &&
41
+ (typeof value === 'object' || typeof value === 'function') &&
42
+ typeof (value as { then?: unknown }).then === 'function'
43
+ )
44
+ }
45
+
46
+ /** Run one callback in its own transaction; a failure is that caller's alone. */
47
+ function build(window: BatchWindow, entry: BatchEntry, base: Transaction | undefined): Member {
48
+ let transaction: Transaction | undefined
49
+ try {
50
+ transaction = base ? base.next() : window.transaction()
51
+ const value = entry.update(transaction)
52
+ if (isThenable(value)) {
53
+ // Reject the async contract while consuming a later rejection from
54
+ // the already-started callback. Its escaped transaction is revoked.
55
+ void Promise.resolve(value).catch(() => {})
56
+ throw new NativeStateError('invalid_state', 'Batch callbacks must be synchronous')
57
+ }
58
+ transaction.validate()
59
+ return transaction.operations.length
60
+ ? { entry, transaction, failed: false, value }
61
+ : { entry, failed: false, value }
62
+ } catch (error) {
63
+ return { entry, failed: true, error }
64
+ } finally {
65
+ transaction?.finish()
66
+ }
67
+ }
68
+
69
+ const dependent = () =>
70
+ new NativeStateError(
71
+ 'stale_revision',
72
+ 'Batch was built on a coalesced batch that the native host rejected'
73
+ )
74
+
75
+ /**
76
+ * Send one native batch for `frame` and record its callers' outcomes in
77
+ * order. When the host rejects a merged batch, its transactions are retried
78
+ * one at a time so only the first rejected one and those built on it fail.
79
+ * Returns whether every transaction committed.
80
+ */
81
+ async function flush(
82
+ window: BatchWindow,
83
+ frame: readonly Member[],
84
+ outcomes: Member[]
85
+ ): Promise<boolean> {
86
+ const sent = frame.flatMap((member) => (member.transaction ? [member.transaction] : []))
87
+ let failure: { error: unknown } | undefined
88
+ try {
89
+ await window.apply(sent)
90
+ } catch (error) {
91
+ failure = { error }
92
+ }
93
+ if (!failure || sent.length === 1 || !(failure.error instanceof NativeCommandError)) {
94
+ // A callback without operations neither depends on nor changes the batch.
95
+ for (const member of frame)
96
+ outcomes.push(
97
+ failure && member.transaction
98
+ ? { entry: member.entry, failed: true, error: failure.error }
99
+ : member
100
+ )
101
+ return !failure
102
+ }
103
+ let rejected = false
104
+ for (const member of frame) {
105
+ if (!member.transaction) outcomes.push(member)
106
+ else if (rejected) outcomes.push({ entry: member.entry, failed: true, error: dependent() })
107
+ else
108
+ try {
109
+ await window.apply([member.transaction])
110
+ outcomes.push(member)
111
+ } catch (error) {
112
+ rejected = true
113
+ outcomes.push({ entry: member.entry, failed: true, error })
114
+ }
115
+ }
116
+ return !rejected
117
+ }
118
+
119
+ /**
120
+ * Run batch callbacks queued behind the transaction in flight, in order, and
121
+ * send them as few native batches as the negotiated limits allow. Each
122
+ * callback runs in its own transaction over the candidate before it, exactly
123
+ * as if the earlier ones had been acknowledged, so a throwing or invalid
124
+ * callback rejects only its own promise. A transaction joins the open batch
125
+ * only while the batch stays within the operation limit, a conservative
126
+ * frame size bound and the focus and scroll requests already in it;
127
+ * otherwise the open batch is sent first.
128
+ *
129
+ * Callers settle in order, each after the acknowledgement of the batch that
130
+ * carried its operations. The returned function settles the last ones; the
131
+ * queue calls it once it has released the next queued operation.
132
+ */
133
+ export async function runBatches(
134
+ window: BatchWindow,
135
+ entries: readonly BatchEntry[],
136
+ limits: Readonly<Limits>
137
+ ): Promise<() => void> {
138
+ const outcomes: Member[] = []
139
+ const release = () => {
140
+ for (const member of outcomes.splice(0)) settle(member)
141
+ }
142
+ if (entries.length === 1) {
143
+ // Nothing to merge: one transaction is one batch, whatever its size.
144
+ const member = build(window, entries[0]!, undefined)
145
+ if (member.transaction) await flush(window, [member], outcomes)
146
+ else outcomes.push(member)
147
+ return release
148
+ }
149
+ const budget = limits.max_frame_bytes - BATCH_ENVELOPE_BYTES
150
+ let frame: Member[] = []
151
+ let tip: Transaction | undefined
152
+ let operations = 0
153
+ let bytes = 0
154
+ const send = async () => {
155
+ release()
156
+ const committed = await flush(window, frame, outcomes)
157
+ frame = []
158
+ tip = undefined
159
+ operations = 0
160
+ bytes = 0
161
+ return committed
162
+ }
163
+ for (const entry of entries) {
164
+ const member = build(window, entry, tip)
165
+ const transaction = member.transaction
166
+ if (!transaction) {
167
+ ;(frame.length ? frame : outcomes).push(member)
168
+ continue
169
+ }
170
+ const count = transaction.operations.length
171
+ const size = transaction.bytesBound()
172
+ if (
173
+ tip &&
174
+ (operations + count > limits.max_operations ||
175
+ bytes + size > budget ||
176
+ !transaction.keepsPrior())
177
+ ) {
178
+ if (!(await send())) {
179
+ // It read the candidate of a batch that did not commit.
180
+ outcomes.push({ entry, failed: true, error: dependent() })
181
+ continue
182
+ }
183
+ transaction.detach()
184
+ }
185
+ frame.push(member)
186
+ tip = transaction
187
+ operations += count
188
+ bytes += size
189
+ // A transaction that may not fit one frame alone is sent before any other
190
+ // callback builds on it, so its failure is its own.
191
+ if (bytes > budget) await send()
192
+ }
193
+ if (frame.length) await send()
194
+ return release
195
+ }
@@ -1,4 +1,9 @@
1
- import { parseContextMenuItems, ProtocolError, type AppMenuEntry } from '@bun-native/protocol'
1
+ import {
2
+ MAX_POINTER_COORDINATE,
3
+ parseContextMenuItems,
4
+ ProtocolError,
5
+ type AppMenuEntry,
6
+ } from '@bun-native/protocol'
2
7
  import { menuEntriesRequest, type MenuEntryOptions } from './app-menu.ts'
3
8
 
4
9
  /** Where an OS context menu opens, in logical pixels of the window's content. */
@@ -7,8 +12,6 @@ export interface ContextMenuPosition {
7
12
  readonly y: number
8
13
  }
9
14
 
10
- const MAX_COORDINATE = 1_048_576
11
-
12
15
  /** Copies consumer items into the closed wire shape and validates it with the shared parser. */
13
16
  export function contextMenuRequest(
14
17
  items: readonly MenuEntryOptions[],
@@ -18,7 +21,12 @@ export function contextMenuRequest(
18
21
  throw new TypeError('Context menu position must be an object')
19
22
  const { x, y } = position
20
23
  for (const value of [x, y])
21
- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > MAX_COORDINATE)
24
+ if (
25
+ typeof value !== 'number' ||
26
+ !Number.isFinite(value) ||
27
+ value < 0 ||
28
+ value > MAX_POINTER_COORDINATE
29
+ )
22
30
  throw new TypeError('Context menu position must be finite, nonnegative logical pixels')
23
31
  try {
24
32
  return { items: parseContextMenuItems(menuEntriesRequest(items)), x, y }
package/src/drops.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { DropRejection } from '@bun-native/protocol'
2
+ import { Registration } from './registration.ts'
2
3
  import type { Listener, NativeNode } from './types.ts'
3
4
 
4
5
  /**
@@ -40,43 +41,26 @@ export interface NativeDropTarget {
40
41
  }
41
42
 
42
43
  /** Internal registry entry. Consumers only receive its frozen handle. */
43
- export class DropTargetRegistration {
44
+ export class DropTargetRegistration extends Registration<DropTargetEvent> {
44
45
  readonly handle: NativeDropTarget
45
- readonly controller = new AbortController()
46
- listener: Listener<DropTargetEvent> | undefined
47
46
  /** The host retains paths only for the target's latest accepted drop. */
48
47
  latestDrop: number | undefined
49
- private released = false
50
- private releasing: Promise<void> | undefined
51
48
 
52
49
  constructor(
53
- readonly id: number,
54
- readonly windowId: number,
50
+ id: number,
51
+ windowId: number,
55
52
  readonly nodeId: number,
56
53
  node: NativeNode,
57
54
  listener: Listener<DropTargetEvent>,
58
55
  release: (registration: DropTargetRegistration) => Promise<void>
59
56
  ) {
60
- this.listener = listener
57
+ super(id, windowId, listener)
61
58
  this.handle = publicHandle(this, node, release)
62
59
  }
63
60
 
64
- release(release: (registration: DropTargetRegistration) => Promise<void>): Promise<void> {
65
- this.releasing ??= this.released ? Promise.resolve() : release(this)
66
- return this.releasing
67
- }
68
-
69
- get live(): boolean {
70
- return !this.released
71
- }
72
-
73
- /** Synchronous local revocation; native removal happens separately. */
74
- revoke(): void {
75
- if (this.released) return
76
- this.released = true
77
- this.listener = undefined
61
+ override revoke(): void {
62
+ super.revoke()
78
63
  this.latestDrop = undefined
79
- this.controller.abort()
80
64
  }
81
65
  }
82
66
 
package/src/events.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { WindowEvent } from '@bun-native/runtime'
1
+ import type { WindowEvent } from '@bun-native/protocol'
2
2
  import {
3
3
  NativeStateError,
4
4
  type Listener,
@@ -211,14 +211,27 @@ export class EventBindings {
211
211
  return unsubscribe(subscription)
212
212
  }
213
213
 
214
- retain(ids: ReadonlyMap<number, unknown>): void {
215
- for (const [id, bindings] of this.nodes) {
216
- if (ids.has(id)) continue
214
+ /**
215
+ * Revoke the bindings and queued plans of committed nodes a batch removed.
216
+ * Only committed nodes hold bindings, and a commit records every committed
217
+ * node it removes, so this costs O(removed) instead of O(listeners).
218
+ */
219
+ forget(removed: ReadonlySet<number>): void {
220
+ if (!removed.size) return
221
+ let changed = false
222
+ for (const id of removed) {
223
+ const bindings = this.nodes.get(id)
224
+ if (!bindings) continue
217
225
  this.nodes.delete(id)
218
226
  for (const binding of bindings.values()) revoke(binding)
227
+ changed = true
219
228
  }
220
- for (const plan of this.plans) if (!ids.has(plan.targetId)) plan.cancellation.abort()
221
- this.changed()
229
+ for (const plan of this.plans)
230
+ if (removed.has(plan.targetId)) {
231
+ plan.cancellation.abort()
232
+ changed = true
233
+ }
234
+ if (changed) this.changed()
222
235
  }
223
236
 
224
237
  clear(): void {
package/src/files.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  type FileResult,
10
10
  type WriteMode,
11
11
  } from '@bun-native/protocol'
12
+ import { Registration } from './registration.ts'
12
13
 
13
14
  export interface FileGrantOptions {
14
15
  /** At most the root's launch access. Defaults to `read`. */
@@ -200,19 +201,18 @@ const fileCalls = {
200
201
  }
201
202
 
202
203
  /** Internal registry entry. Consumers only receive its frozen handle. */
203
- export class FileGrantRegistration {
204
+ export class FileGrantRegistration extends Registration {
204
205
  readonly handle: NativeFileGrant
205
- private revoked = false
206
- private closing: Promise<void> | undefined
207
206
 
208
207
  constructor(
209
- readonly id: number,
210
- readonly windowId: number,
208
+ id: number,
209
+ windowId: number,
211
210
  root: string,
212
211
  access: FileAccess,
213
212
  call: (registration: FileGrantRegistration, request: FileCall) => Promise<unknown>,
214
213
  close: (registration: FileGrantRegistration) => Promise<void>
215
214
  ) {
215
+ super(id, windowId)
216
216
  const run = <T>(request: () => FileCall) => {
217
217
  try {
218
218
  return call(this, request()) as Promise<T>
@@ -236,18 +236,7 @@ export class FileGrantRegistration {
236
236
  run<number>(() => fileCalls.write(target, bytes, value)),
237
237
  createDirectory: (target: string) => run<void>(() => fileCalls.createDirectory(target)),
238
238
  remove: (target: string) => run<void>(() => fileCalls.remove(target)),
239
- close: () => {
240
- this.closing ??= this.revoked ? Promise.resolve() : close(this)
241
- return this.closing
242
- },
239
+ close: () => this.release(close),
243
240
  })
244
241
  }
245
-
246
- get live(): boolean {
247
- return !this.revoked
248
- }
249
-
250
- revoke(): void {
251
- this.revoked = true
252
- }
253
242
  }
@@ -1,20 +1,20 @@
1
- import type {
2
- KeyModifiers,
3
- MessageDialogOptions as WireMessageDialogOptions,
1
+ import {
2
+ MAX_MESSAGE_DIALOG_BUTTONS,
3
+ MAX_MESSAGE_DIALOG_DETAIL_BYTES as MAX_DETAIL_BYTES,
4
+ MAX_MESSAGE_DIALOG_ID_BYTES as MAX_ID_BYTES,
5
+ MAX_MESSAGE_DIALOG_LABEL_BYTES as MAX_LABEL_BYTES,
6
+ MAX_MESSAGE_DIALOG_MESSAGE_BYTES as MAX_MESSAGE_BYTES,
7
+ MAX_MESSAGE_DIALOG_TITLE_BYTES as MAX_TITLE_BYTES,
8
+ ProtocolError,
9
+ type KeyModifiers,
10
+ type MessageDialogOptions as WireMessageDialogOptions,
4
11
  } from '@bun-native/protocol'
5
12
  import { NativeServiceError } from './services.ts'
6
13
  import { defaultTheme } from './theme.ts'
7
14
  import { NativeStateError, type NativeBatch, type NativeNode, type NativeWindow } from './types.ts'
8
15
 
9
- /** Buttons in one message dialog. */
10
- const MAX_MESSAGE_DIALOG_BUTTONS = 4
11
16
  /** Dialogs one window holds at a time: the shown one plus those queued behind it. */
12
17
  const MAX_MESSAGE_DIALOGS_PER_WINDOW = 8
13
- const MAX_TITLE_BYTES = 256
14
- const MAX_MESSAGE_BYTES = 2_048
15
- const MAX_DETAIL_BYTES = 4_096
16
- const MAX_LABEL_BYTES = 64
17
- const MAX_ID_BYTES = 64
18
18
 
19
19
  export interface MessageDialogButton {
20
20
  /** Returned in the result. 1-64 UTF-8 bytes without control characters, unique per dialog. */
@@ -262,6 +262,8 @@ export class MessageDialogs {
262
262
  ): void {
263
263
  const dialog = this.native.get(id)
264
264
  if (!dialog) return
265
+ if (result.kind === 'button' && !dialog.spec.buttons.some((button) => button.id === result.id))
266
+ throw new ProtocolError('Native message dialog chose a button it was not given')
265
267
  this.native.delete(id)
266
268
  dialog.nativeId = undefined
267
269
  if (dialog.state === 'closing' || dialog.state === 'settled') return
@@ -3,6 +3,7 @@ import {
3
3
  MAX_NOTIFICATION_TITLE_BYTES,
4
4
  type NotificationDismissal,
5
5
  } from '@bun-native/protocol'
6
+ import { Registration } from './registration.ts'
6
7
  import type { Listener } from './types.ts'
7
8
 
8
9
  export interface NotificationOptions {
@@ -72,52 +73,34 @@ export function notificationRequest(options: NotificationOptions): { title: stri
72
73
  return { title, body }
73
74
  }
74
75
 
75
- /** Internal registry entry. Consumers only receive its frozen handle. */
76
- export class NotificationRegistration {
76
+ /**
77
+ * Internal registry entry. Consumers only receive its frozen handle. `live`
78
+ * accepts activations; `deliverable` keeps a queued callback, including the
79
+ * final dismissal, runnable.
80
+ */
81
+ export class NotificationRegistration extends Registration<NotificationEvent> {
77
82
  readonly handle: NativeNotification
78
- readonly controller = new AbortController()
79
- listener: Listener<NotificationEvent> | undefined
80
83
  activatable = false
81
- private ended = false
82
- private withdrawing: Promise<void> | undefined
83
84
 
84
85
  constructor(
85
- readonly id: number,
86
- readonly windowId: number,
86
+ id: number,
87
+ windowId: number,
87
88
  title: string,
88
89
  body: string,
89
90
  listener: Listener<NotificationEvent>,
90
91
  withdraw: (registration: NotificationRegistration) => Promise<void>
91
92
  ) {
92
- this.listener = listener
93
+ super(id, windowId, listener)
93
94
  this.handle = publicHandle(this, title, body, withdraw)
94
95
  }
95
96
 
96
- withdraw(withdraw: (registration: NotificationRegistration) => Promise<void>): Promise<void> {
97
- this.withdrawing ??= this.ended ? Promise.resolve() : withdraw(this)
98
- return this.withdrawing
99
- }
100
-
101
- /** Accepts activations. */
102
- get live(): boolean {
103
- return !this.ended
104
- }
105
-
106
- /** A queued callback, including the final dismissal, may still run. */
107
97
  get deliverable(): boolean {
108
98
  return this.listener !== undefined
109
99
  }
110
100
 
111
101
  /** The server removed it: no activation follows, but the dismissal is delivered. */
112
102
  end(): void {
113
- this.ended = true
114
- }
115
-
116
- /** Synchronous local revocation; the server notification is closed separately. */
117
- revoke(): void {
118
- this.ended = true
119
- this.listener = undefined
120
- this.controller.abort()
103
+ this.released = true
121
104
  }
122
105
  }
123
106
 
@@ -136,6 +119,6 @@ function publicHandle(
136
119
  get active() {
137
120
  return registration.live
138
121
  },
139
- withdraw: () => registration.withdraw(withdraw),
122
+ withdraw: () => registration.release(withdraw),
140
123
  })
141
124
  }
package/src/order.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Flag, by index in `desired`, a longest existing sibling subsequence; every
3
+ * other desired child needs a move. Children are distinct within each list:
4
+ * renderer nodes or native node identities.
5
+ */
6
+ export function stableChildren<T>(current: readonly T[], desired: readonly T[]): Uint8Array {
7
+ const stable = new Uint8Array(desired.length)
8
+ // A common prefix and suffix extend some longest subsequence, so only the
9
+ // middle needs the search; keyed edits usually leave both ends in place.
10
+ let start = 0
11
+ const shorter = Math.min(current.length, desired.length)
12
+ while (start < shorter && current[start] === desired[start]) stable[start++] = 1
13
+ let currentEnd = current.length
14
+ let desiredEnd = desired.length
15
+ while (
16
+ currentEnd > start &&
17
+ desiredEnd > start &&
18
+ current[currentEnd - 1] === desired[desiredEnd - 1]
19
+ ) {
20
+ currentEnd -= 1
21
+ stable[--desiredEnd] = 1
22
+ }
23
+ if (start === currentEnd || start === desiredEnd) return stable
24
+ const positions = new Map<T, number>()
25
+ for (let index = start; index < currentEnd; index += 1) positions.set(current[index]!, index)
26
+ // tails[length - 1]: desired index ending the lowest-positioned run of that length.
27
+ const size = desiredEnd - start
28
+ const tails = new Int32Array(size)
29
+ const tailPositions = new Int32Array(size)
30
+ const preceding = new Int32Array(size)
31
+ let length = 0
32
+ for (let index = start; index < desiredEnd; index += 1) {
33
+ const position = positions.get(desired[index]!)
34
+ if (position === undefined) continue
35
+ let low = 0
36
+ let high = length
37
+ while (low < high) {
38
+ const middle = (low + high) >>> 1
39
+ if (tailPositions[middle]! < position) low = middle + 1
40
+ else high = middle
41
+ }
42
+ preceding[index - start] = low > 0 ? tails[low - 1]! : -1
43
+ tails[low] = index
44
+ tailPositions[low] = position
45
+ if (low === length) length += 1
46
+ }
47
+ for (let index = length ? tails[length - 1]! : -1; index >= 0; index = preceding[index - start]!)
48
+ stable[index] = 1
49
+ return stable
50
+ }
package/src/processes.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  type TerminalSize,
11
11
  } from '@bun-native/protocol'
12
12
  import type { NativeFileGrant } from './files.ts'
13
+ import { Registration } from './registration.ts'
13
14
  import type { Listener } from './types.ts'
14
15
 
15
16
  export interface ProcessOptions {
@@ -146,27 +147,23 @@ function processCall(name: string, value: unknown): ProcessCall {
146
147
  }
147
148
 
148
149
  /** Internal registry entry. Consumers only receive its frozen handle. */
149
- export class ProcessRegistration {
150
+ export class ProcessRegistration extends Registration<ProcessEvent> {
150
151
  readonly handle: NativeProcess
151
- readonly controller = new AbortController()
152
- listener: Listener<ProcessEvent> | undefined
153
152
  exit: NativeProcessExit | undefined
154
153
  /** The highest output chunk received from the host. */
155
154
  chunk = 0
156
- private revoked = false
157
155
  private exited = false
158
- private releasing: Promise<void> | undefined
159
156
 
160
157
  constructor(
161
- readonly id: number,
162
- readonly windowId: number,
158
+ id: number,
159
+ windowId: number,
163
160
  executable: string,
164
161
  terminal: boolean,
165
162
  listener: Listener<ProcessEvent>,
166
163
  call: (registration: ProcessRegistration, request: ProcessCall) => Promise<void>,
167
164
  release: (registration: ProcessRegistration) => Promise<void>
168
165
  ) {
169
- this.listener = listener
166
+ super(id, windowId, listener)
170
167
  const run = (name: string, value?: unknown) => {
171
168
  try {
172
169
  return call(this, processCall(name, value))
@@ -189,17 +186,10 @@ export class ProcessRegistration {
189
186
  closeInput: () => run('close'),
190
187
  resize: (size: TerminalSize) => run('resize', size),
191
188
  signal: (signal: ProcessSignal) => run('signal', signal),
192
- release: () => {
193
- this.releasing ??= this.revoked ? Promise.resolve() : release(this)
194
- return this.releasing
195
- },
189
+ release: () => this.release(release),
196
190
  })
197
191
  }
198
192
 
199
- get live(): boolean {
200
- return !this.revoked
201
- }
202
-
203
193
  /** True after the host reported the exit; no further output follows. */
204
194
  get ended(): boolean {
205
195
  return this.exited
@@ -208,11 +198,4 @@ export class ProcessRegistration {
208
198
  end(): void {
209
199
  this.exited = true
210
200
  }
211
-
212
- /** Synchronous local revocation; the native group is stopped separately. */
213
- revoke(): void {
214
- this.revoked = true
215
- this.listener = undefined
216
- this.controller.abort()
217
- }
218
201
  }
@@ -0,0 +1,39 @@
1
+ import type { Listener } from './types.ts'
2
+
3
+ /**
4
+ * Internal registry entry behind one window-owned service handle: its
5
+ * identity, owner window, listener, the signal that listener receives and one
6
+ * memoized native release. Consumers only receive the frozen handle.
7
+ */
8
+ export class Registration<Event = never> {
9
+ readonly controller = new AbortController()
10
+ listener: Listener<Event> | undefined
11
+ /** No further event is accepted and release is a no-op. */
12
+ protected released = false
13
+ private releasing: Promise<void> | undefined
14
+
15
+ constructor(
16
+ readonly id: number,
17
+ readonly windowId: number,
18
+ listener?: Listener<Event>
19
+ ) {
20
+ this.listener = listener
21
+ }
22
+
23
+ get live(): boolean {
24
+ return !this.released
25
+ }
26
+
27
+ /** Shared by the public handle; one native release per registration. */
28
+ release(release: (registration: this) => Promise<void>): Promise<void> {
29
+ this.releasing ??= this.released ? Promise.resolve() : release(this)
30
+ return this.releasing
31
+ }
32
+
33
+ /** Synchronous local revocation; the native resource is released separately. */
34
+ revoke(): void {
35
+ this.released = true
36
+ this.listener = undefined
37
+ this.controller.abort()
38
+ }
39
+ }