@abloatai/humans 0.59.2 → 0.61.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 (96) hide show
  1. package/README.md +1 -1
  2. package/dist/Ablo.d.ts +2 -10
  3. package/dist/Ablo.js +0 -1
  4. package/dist/client.d.ts +1 -48
  5. package/dist/humans.d.ts +1 -1
  6. package/dist/local/BaseSyncedStore.d.ts +5 -5
  7. package/dist/local/BaseSyncedStore.js +7 -7
  8. package/dist/local/Database.d.ts +2 -2
  9. package/dist/local/LazyReferenceCollection.d.ts +1 -1
  10. package/dist/local/Model.js +46 -56
  11. package/dist/local/NetworkMonitor.js +2 -0
  12. package/dist/local/RuntimeContext.js +2 -0
  13. package/dist/local/SyncClient.d.ts +12 -36
  14. package/dist/local/SyncClient.js +50 -108
  15. package/dist/local/client/createModelOperations.d.ts +3 -27
  16. package/dist/local/client/createModelOperations.js +20 -21
  17. package/dist/local/client/options.d.ts +14 -39
  18. package/dist/local/client/reactiveEngine.d.ts +3 -9
  19. package/dist/local/client/reactiveEngine.js +6 -151
  20. package/dist/local/client/storeLifecycle.js +5 -1
  21. package/dist/local/fileUploads.d.ts +27 -0
  22. package/dist/local/fileUploads.js +55 -0
  23. package/dist/local/storeContract.d.ts +5 -5
  24. package/dist/local/stores/syncAction.d.ts +4 -4
  25. package/dist/local/sync/contextOnChange.js +1 -1
  26. package/dist/local/sync/createClaimStream.js +1 -1
  27. package/dist/local/sync/credentialLifecycle.d.ts +4 -5
  28. package/dist/local/sync/credentialLifecycle.js +4 -5
  29. package/dist/local/sync/deltaPipeline.js +12 -6
  30. package/dist/local/sync/schemas.d.ts +10 -10
  31. package/dist/local/sync/scopeGroups.d.ts +11 -0
  32. package/dist/local/sync/scopeGroups.js +75 -0
  33. package/dist/local/sync/wsFrameHandlers.d.ts +1 -1
  34. package/dist/local/transactions/localMutation.js +3 -3
  35. package/dist/local/transactions/mutations/MutationQueue.d.ts +4 -5
  36. package/dist/local/transactions/mutations/MutationQueue.js +25 -51
  37. package/dist/local/transactions/mutations/batchProcessing.js +23 -10
  38. package/dist/local/transactions/mutations/commitPayload.d.ts +9 -2
  39. package/dist/local/transactions/mutations/commitTransport.js +3 -1
  40. package/dist/local/transactions/mutations/executionSelection.d.ts +0 -1
  41. package/dist/local/transactions/mutations/executionSelection.js +9 -17
  42. package/dist/local/transactions/mutations/failureHandling.js +9 -0
  43. package/dist/local/transactions/mutations/localMutation.js +3 -3
  44. package/dist/local/transactions/mutations/queueCoalescing.js +8 -0
  45. package/dist/local/transactions/mutations/replayValidation.d.ts +15 -15
  46. package/dist/react/AbloProvider.d.ts +11 -86
  47. package/dist/react/AbloProvider.js +11 -163
  48. package/dist/react/ClientSideSuspense.d.ts +1 -1
  49. package/dist/react/DefaultFallback.d.ts +1 -1
  50. package/dist/react/createAbloReact.js +1 -1
  51. package/dist/react/useErrorListener.js +1 -1
  52. package/dist/react/useMutationFailureListener.js +1 -1
  53. package/dist/react.d.ts +1 -1
  54. package/dist/react.js +1 -1
  55. package/dist/surface.d.ts +3 -3
  56. package/dist/surface.js +1 -4
  57. package/package.json +3 -3
  58. package/src/Ablo.ts +5 -17
  59. package/src/client.ts +0 -51
  60. package/src/local/BaseSyncedStore.ts +14 -14
  61. package/src/local/Model.ts +45 -55
  62. package/src/local/NetworkMonitor.ts +2 -0
  63. package/src/local/RuntimeContext.ts +2 -0
  64. package/src/local/SyncClient.ts +73 -140
  65. package/src/local/client/createModelOperations.ts +30 -64
  66. package/src/local/client/options.ts +20 -43
  67. package/src/local/client/reactiveEngine.ts +7 -179
  68. package/src/local/client/storeLifecycle.ts +6 -1
  69. package/src/local/fileUploads.ts +97 -0
  70. package/src/local/storeContract.ts +5 -5
  71. package/src/local/sync/contextOnChange.ts +1 -1
  72. package/src/local/sync/createClaimStream.ts +1 -1
  73. package/src/local/sync/credentialLifecycle.ts +4 -5
  74. package/src/local/sync/deltaPipeline.ts +10 -6
  75. package/src/local/sync/scopeGroups.ts +91 -0
  76. package/src/local/sync/wsFrameHandlers.ts +0 -1
  77. package/src/local/transactions/localMutation.ts +3 -3
  78. package/src/local/transactions/mutations/MutationQueue.ts +24 -53
  79. package/src/local/transactions/mutations/batchProcessing.ts +25 -10
  80. package/src/local/transactions/mutations/commitPayload.ts +11 -1
  81. package/src/local/transactions/mutations/commitTransport.ts +2 -2
  82. package/src/local/transactions/mutations/executionSelection.ts +9 -15
  83. package/src/local/transactions/mutations/failureHandling.ts +10 -0
  84. package/src/local/transactions/mutations/localMutation.ts +3 -3
  85. package/src/local/transactions/mutations/queueCoalescing.ts +6 -0
  86. package/src/react/AbloProvider.tsx +17 -249
  87. package/src/react/useErrorListener.ts +1 -1
  88. package/src/react/useMutationFailureListener.ts +1 -1
  89. package/src/react.ts +1 -5
  90. package/src/surface.ts +1 -4
  91. package/dist/local/sync/participants.d.ts +0 -132
  92. package/dist/local/sync/participants.js +0 -342
  93. package/dist/local/transactions/mutations/pendingDrain.d.ts +0 -33
  94. package/dist/local/transactions/mutations/pendingDrain.js +0 -117
  95. package/src/local/sync/participants.ts +0 -564
  96. package/src/local/transactions/mutations/pendingDrain.ts +0 -169
@@ -1,564 +0,0 @@
1
- import type { JoinOptions } from '@abloatai/transaction/client/resources/modelOperations';
2
- import type { SyncWebSocket } from './SyncWebSocket.js';
3
- import type { Schema, SchemaRecord } from '@abloatai/transaction/schema/schema';
4
- import { scopeKindOf, type ModelDef } from '@abloatai/transaction/schema/model';
5
- import { AbloValidationError } from '@abloatai/transaction/errors';
6
- import type {
7
- Claim,
8
- Activity,
9
- ClaimTarget,
10
- ClaimLeaseOptions,
11
- ClaimStream,
12
- Peer,
13
- PresenceStream,
14
- PresenceTarget,
15
- } from '@abloatai/transaction/types/streams';
16
- import {
17
- subTarget,
18
- streamTarget,
19
- wireTarget,
20
- } from '@abloatai/transaction/coordination';
21
- import type { AttachableClaimStream } from './createClaimStream.js';
22
-
23
- /**
24
- * The scope a participant can be joined to. The usual form is an entity target
25
- * (`{ type, id }`); raw sync-group strings are an advanced escape hatch for
26
- * addressing a transport scope directly.
27
- */
28
- export type ParticipantScope =
29
- | ClaimTarget
30
- | readonly ClaimTarget[]
31
- | string
32
- | readonly string[]
33
- | { readonly syncGroup: string }
34
- | { readonly syncGroups: readonly string[] }
35
- | Record<string, string | readonly string[] | undefined>;
36
-
37
- export type ParticipantStatus =
38
- | 'idle'
39
- | 'connecting'
40
- | 'connected'
41
- | 'error'
42
- | 'disconnected';
43
-
44
- export interface EngineParticipant {
45
- readonly presence: PresenceStream;
46
- readonly claims: ClaimStream;
47
- }
48
-
49
- /**
50
- * The options for a participant join. It extends the public per-model
51
- * {@link JoinOptions} rather than restating its members, so the lease dial is
52
- * declared once, in the core, and this surface adds only what a lower-level
53
- * join can additionally say.
54
- */
55
- export interface ParticipantJoinOptions extends JoinOptions {
56
- /**
57
- * The initial focus target, named in your schema's vocabulary and optionally
58
- * narrowed to a field. When `scope` is omitted, this target also becomes the
59
- * routing scope.
60
- */
61
- readonly target?: PresenceTarget;
62
- /** Alias for `target` when the participant is joined to a broader scope. */
63
- readonly focus?: PresenceTarget;
64
- /**
65
- * The routing scope: one entity, many entities, or a raw sync-group escape
66
- * hatch. Use it for "joined to the folder, focused on one file" shapes,
67
- * where the participant listens more broadly than its focus target.
68
- */
69
- readonly scope?: ParticipantScope;
70
- /** Present a narrower capability for this logical participant. */
71
- readonly capabilityToken?: string;
72
- /**
73
- * @deprecated Use `ttl`. Removed in 0.37.0.
74
- *
75
- * One lease, spelled two ways, and the seconds spelling was the one that
76
- * misled: it accepted a duration string, so `ablo.<model>.join(ids, { ttl:
77
- * '5m' })` reached this surface as `ttlSeconds: '5m'` — a field whose name
78
- * asserts a unit its value did not carry. `ttl` takes the same values and is
79
- * the spelling every other lease in the SDK already uses (`claim`'s `ttl`,
80
- * `ClaimLeaseOptions.ttl`). The wire is unchanged: it has always carried
81
- * seconds, and still does.
82
- */
83
- readonly ttlSeconds?: number | string | null;
84
- /**
85
- * The activity to announce as soon as the claim is acknowledged. Defaults to
86
- * `reading` when a `target` is present. Pass `false` to join without
87
- * announcing anything.
88
- */
89
- readonly activity?: 'reading' | 'viewing' | 'editing' | false;
90
- readonly detail?: string;
91
- }
92
-
93
- export interface ScopedPresence {
94
- readonly self: Peer;
95
- readonly focus: ClaimTarget | null;
96
- readonly others: readonly Peer[];
97
- update(activity: Activity): void;
98
- reading(detail?: string): void;
99
- reading(target: PresenceTarget, detail?: string): void;
100
- viewing(detail?: string): void;
101
- viewing(target: PresenceTarget, detail?: string): void;
102
- editing(detail?: string): void;
103
- editing(target: PresenceTarget, detail?: string): void;
104
- idle(): void;
105
- onChange(listener: () => void): () => void;
106
- }
107
-
108
- export interface ScopedClaimOptions {
109
- /** Override the participant's focus target for this one claim. */
110
- readonly target?: PresenceTarget;
111
- /** Peer-visible description of the work. Defaults to `'editing'`. */
112
- readonly description?: string;
113
- /** How long the claim lives; the server expires it automatically after this. */
114
- readonly ttl?: import('@abloatai/transaction/types/streams').Duration;
115
- }
116
-
117
- export interface ScopedClaims {
118
- readonly focus: ClaimTarget | null;
119
- readonly others: readonly Claim[];
120
- /**
121
- * Takes an exclusive claim on the participant's focus target, or on an
122
- * explicit target passed via `opts.target`. While the claim is held, other
123
- * participants that request an overlapping target are rejected.
124
- */
125
- claim(opts?: ScopedClaimOptions): Claim;
126
- onRejected(listener: Parameters<ClaimStream['onRejected']>[0]): () => void;
127
- onChange(listener: () => void): () => void;
128
- }
129
-
130
- export interface ParticipantFocusOptions {
131
- readonly activity?: 'reading' | 'viewing' | 'editing' | false;
132
- readonly detail?: string;
133
- }
134
-
135
- export interface JoinedParticipant {
136
- /** The exact entity this participant is currently reading or editing. */
137
- readonly target: ClaimTarget | null;
138
- readonly focusTarget: ClaimTarget | null;
139
- /** The transport scopes this participant is joined to, which govern what it sees and receives. */
140
- readonly syncGroups: readonly string[];
141
- readonly presence: ScopedPresence;
142
- readonly claims: ScopedClaims;
143
- readonly peers: readonly Peer[];
144
- readonly activeClaims: readonly Claim[];
145
- focus(target: PresenceTarget, options?: ParticipantFocusOptions): JoinedParticipant;
146
- leave(): void;
147
- [Symbol.asyncDispose](): Promise<void>;
148
- }
149
-
150
- export interface ParticipantManager {
151
- join(target: PresenceTarget, options?: Omit<ParticipantJoinOptions, 'target'>): Promise<JoinedParticipant>;
152
- join(options: ParticipantJoinOptions): Promise<JoinedParticipant>;
153
- }
154
-
155
- export interface ParticipantManagerConfig {
156
- readonly ready: () => Promise<void>;
157
- /** The connection, host-built and stable for the client's lifetime. */
158
- readonly transport: SyncWebSocket;
159
- readonly presence: PresenceStream;
160
- readonly claims: AttachableClaimStream;
161
- readonly schema?: Schema;
162
- }
163
-
164
- export function createParticipantManager(
165
- config: ParticipantManagerConfig,
166
- ): ParticipantManager {
167
- return {
168
- async join(
169
- input: PresenceTarget | ParticipantJoinOptions,
170
- overrides?: Omit<ParticipantJoinOptions, 'target'>,
171
- ): Promise<JoinedParticipant> {
172
- const options = normalizeJoinOptions(input, overrides);
173
- const target = options.focus ?? options.target
174
- ? targetToEntityRef((options.focus ?? options.target)!)
175
- : null;
176
- const syncGroups = unique(
177
- resolveParticipantSyncGroups(options.scope ?? target ?? undefined, config.schema),
178
- );
179
-
180
- await config.ready();
181
- // Not-connected joins surface through `sendClaim`'s diagnosed
182
- // rejection below; a scopeless join needs no wire send at all.
183
- const transport = config.transport;
184
-
185
- const claimId = createParticipantClaimId();
186
- if (syncGroups.length > 0) {
187
- await transport.sendClaim(claimId, syncGroups, {
188
- capabilityToken: options.capabilityToken,
189
- // `ttl` is the spelling; `ttlSeconds` is the deprecated one, read
190
- // second so a caller passing both gets the current name honored.
191
- // eslint-disable-next-line @typescript-eslint/no-deprecated -- reading the deprecated alias IS the back-compat this line provides
192
- ttlSeconds: parseParticipantTtlSeconds(options.ttl ?? options.ttlSeconds),
193
- });
194
- }
195
-
196
- const participant = createJoinedParticipant({
197
- target,
198
- syncGroups,
199
- claimId,
200
- transport,
201
- presence: config.presence,
202
- claims: config.claims,
203
- });
204
-
205
- if (target && options.activity !== false) {
206
- const activity = options.activity ?? 'reading';
207
- if (activity === 'editing') {
208
- participant.presence.editing(options.detail);
209
- } else if (activity === 'viewing') {
210
- participant.presence.viewing(options.detail);
211
- } else {
212
- participant.presence.reading(options.detail);
213
- }
214
- }
215
-
216
- return participant;
217
- },
218
- };
219
- }
220
-
221
- export function resolveParticipantSyncGroups(
222
- scope: ParticipantScope | undefined,
223
- schema?: Schema,
224
- ): string[] {
225
- if (!scope) return [];
226
- if (typeof scope === 'string') return [scope];
227
- if (Array.isArray(scope)) {
228
- return scope.flatMap((entry) =>
229
- typeof entry === 'string' ? [entry] : [syncGroupFromEntityRef(entry, schema)],
230
- );
231
- }
232
- const direct = scope as { syncGroup?: unknown; syncGroups?: unknown };
233
- if (isEntityScope(scope)) return [syncGroupFromEntityRef(scope, schema)];
234
- if (typeof direct.syncGroup === 'string') return [direct.syncGroup];
235
- if (Array.isArray(direct.syncGroups)) {
236
- return direct.syncGroups.filter((g): g is string => typeof g === 'string');
237
- }
238
- const out: string[] = [];
239
- for (const [key, value] of Object.entries(scope)) {
240
- if (value === undefined) continue;
241
- if (Array.isArray(value)) {
242
- for (const id of value) out.push(syncGroupFromSchemaKey(key, id, schema));
243
- } else {
244
- out.push(syncGroupFromSchemaKey(key, value, schema));
245
- }
246
- }
247
- return out;
248
- }
249
-
250
- /**
251
- * The group kind for a model, in the wire dialect every plane shares: a
252
- * declared scope root wins; otherwise the lowercased typename — the same
253
- * token the commit plane and claim targets use (`wireModel`). Never the
254
- * camelCase schema key: the server validates inbound subscription groups
255
- * against a lowercase-only grammar, so a key like `reportBlocks` would be
256
- * rejected as malformed on subscribe — and even a lowercase key would put
257
- * this client in a different group than a peer who resolved the same row
258
- * through an entity ref, so the two would never see each other's claims.
259
- */
260
- function groupKindForModel(def: ModelDef, key: string): string {
261
- return scopeKindOf(def, key) ?? (def.typename ?? key).toLowerCase();
262
- }
263
-
264
- export function syncGroupFromEntityRef(
265
- ref: ClaimTarget,
266
- schema?: Schema,
267
- ): string {
268
- const match = findModelForEntityRef(ref, schema);
269
- const kind = match
270
- ? groupKindForModel(match.def, match.key)
271
- : ref.type.toLowerCase();
272
- return `${kind}:${ref.id}`;
273
- }
274
-
275
- function syncGroupFromSchemaKey(
276
- schemaKey: string,
277
- id: string,
278
- schema?: Schema,
279
- ): string {
280
- const def = schema?.models?.[schemaKey];
281
- const kind = def ? groupKindForModel(def, schemaKey) : schemaKey.toLowerCase();
282
- return `${kind}:${id}`;
283
- }
284
-
285
- function findModelForEntityRef(
286
- ref: ClaimTarget,
287
- schema?: Schema,
288
- ): { key: string; def: ModelDef } | null {
289
- if (!schema?.models) return null;
290
- const wanted = ref.type.toLowerCase();
291
- for (const [key, def] of Object.entries(schema.models) as [string, ModelDef][]) {
292
- const typename = def.typename ?? key;
293
- if (typename.toLowerCase() === wanted || key.toLowerCase() === wanted) {
294
- return { key, def };
295
- }
296
- }
297
- return null;
298
- }
299
-
300
- export function parseParticipantTtlSeconds(
301
- value: number | string | null | undefined,
302
- ): number | undefined {
303
- if (typeof value === 'number' && Number.isFinite(value)) return value;
304
- if (!value) return undefined;
305
- if (typeof value !== 'string') return undefined;
306
- const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
307
- if (!match) return undefined;
308
- const amount = Number(match[1]);
309
- const unit = match[2] ?? 's';
310
- if (unit === 'ms') return Math.max(1, Math.ceil(amount / 1000));
311
- if (unit === 'm') return Math.ceil(amount * 60);
312
- if (unit === 'h') return Math.ceil(amount * 3600);
313
- return Math.ceil(amount);
314
- }
315
-
316
- export function createParticipantClaimId(): string {
317
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
318
- return `participant:${crypto.randomUUID()}`;
319
- }
320
- return `participant:${Date.now()}:${Math.random().toString(36).slice(2)}`;
321
- }
322
-
323
- function normalizeJoinOptions(
324
- input: PresenceTarget | ParticipantJoinOptions,
325
- overrides?: Omit<ParticipantJoinOptions, 'target'>,
326
- ): ParticipantJoinOptions {
327
- if (isTupleTarget(input) || isEntityScope(input)) {
328
- return { ...overrides, target: input };
329
- }
330
- return { ...input, ...overrides };
331
- }
332
-
333
- function isTupleTarget(value: unknown): value is readonly [type: string, id: string] {
334
- return (
335
- Array.isArray(value) &&
336
- typeof value[0] === 'string' &&
337
- typeof value[1] === 'string'
338
- );
339
- }
340
-
341
- function isEntityScope(scope: unknown): scope is ClaimTarget {
342
- return (
343
- typeof scope === 'object' &&
344
- scope !== null &&
345
- !Array.isArray(scope) &&
346
- typeof (scope as { type?: unknown }).type === 'string' &&
347
- typeof (scope as { id?: unknown }).id === 'string'
348
- );
349
- }
350
-
351
- function targetToEntityRef(target: PresenceTarget): ClaimTarget {
352
- if (isTupleTarget(target)) return { type: target[0], id: target[1] };
353
- return target;
354
- }
355
-
356
- function unique(values: string[]): string[] {
357
- return [...new Set(values)];
358
- }
359
-
360
- function createJoinedParticipant(args: {
361
- readonly target: ClaimTarget | null;
362
- readonly syncGroups: readonly string[];
363
- readonly claimId: string;
364
- readonly transport: SyncWebSocket;
365
- readonly presence: PresenceStream;
366
- readonly claims: AttachableClaimStream;
367
- }): JoinedParticipant {
368
- const ownHandles = new Set<Claim>();
369
- let currentTarget = args.target;
370
- let left = false;
371
-
372
- const requireTarget = (target?: PresenceTarget): ClaimTarget => {
373
- const resolved = target ? targetToEntityRef(target) : currentTarget;
374
- if (!resolved) {
375
- throw new AbloValidationError('Participant action requires a structured target', {
376
- code: 'invalid_request',
377
- });
378
- }
379
- return resolved;
380
- };
381
-
382
- const setFocus = (
383
- target: PresenceTarget,
384
- options?: ParticipantFocusOptions,
385
- ): JoinedParticipant => {
386
- currentTarget = targetToEntityRef(target);
387
- if (options?.activity === 'editing') {
388
- scopedPresence.editing(options.detail);
389
- } else if (options?.activity === 'viewing') {
390
- scopedPresence.viewing(options.detail);
391
- } else if (options?.activity === 'reading') {
392
- scopedPresence.reading(options.detail);
393
- }
394
- return joined;
395
- };
396
-
397
- const resolvePresenceAction = (
398
- targetOrDetail?: PresenceTarget | string,
399
- detail?: string,
400
- ): { target: ClaimTarget; detail?: string } => {
401
- if (typeof targetOrDetail === 'string' || targetOrDetail === undefined) {
402
- return { target: requireTarget(), detail: targetOrDetail ?? detail };
403
- }
404
- return { target: requireTarget(targetOrDetail), detail };
405
- };
406
-
407
- const scopedPresence: ScopedPresence = {
408
- get self() {
409
- return args.presence.self;
410
- },
411
- get focus() {
412
- return currentTarget;
413
- },
414
- get others() {
415
- return args.presence.others.filter((entry) =>
416
- presenceMatchesParticipant(entry, currentTarget, args.syncGroups),
417
- );
418
- },
419
- update(activity: Activity): void {
420
- args.presence.update(activity);
421
- },
422
- reading(targetOrDetail?: PresenceTarget | string, detail?: string): void {
423
- const action = resolvePresenceAction(targetOrDetail, detail);
424
- args.presence.update({
425
- ...activityFromTarget(action.target),
426
- action: 'reading',
427
- detail: action.detail,
428
- });
429
- },
430
- viewing(targetOrDetail?: PresenceTarget | string, detail?: string): void {
431
- const action = resolvePresenceAction(targetOrDetail, detail);
432
- args.presence.viewing(action.target, action.detail);
433
- },
434
- editing(targetOrDetail?: PresenceTarget | string, detail?: string): void {
435
- const action = resolvePresenceAction(targetOrDetail, detail);
436
- args.presence.editing(action.target, action.detail);
437
- },
438
- idle(): void {
439
- args.presence.idle();
440
- },
441
- onChange(listener: () => void): () => void {
442
- return args.presence.onChange(listener);
443
- },
444
- };
445
-
446
- const track = (handle: Claim): Claim => {
447
- ownHandles.add(handle);
448
- return {
449
- object: 'claim',
450
- id: handle.id,
451
- description: handle.description,
452
- target: handle.target,
453
- async release(): Promise<void> {
454
- ownHandles.delete(handle);
455
- await handle.release?.();
456
- },
457
- revoke(): void {
458
- ownHandles.delete(handle);
459
- handle.revoke?.();
460
- },
461
- [Symbol.asyncDispose]: async () => {
462
- ownHandles.delete(handle);
463
- await handle[Symbol.asyncDispose]?.();
464
- },
465
- };
466
- };
467
-
468
- const scopedClaims: ScopedClaims = {
469
- get focus() {
470
- return currentTarget;
471
- },
472
- get others() {
473
- return args.claims.others.filter((claim) =>
474
- currentTarget ? targetsOverlap(claim.target, currentTarget) : true,
475
- );
476
- },
477
- claim(opts?: ScopedClaimOptions): Claim {
478
- return track(
479
- args.claims.claim(requireTarget(opts?.target), {
480
- description: opts?.description,
481
- ttl: opts?.ttl,
482
- }),
483
- );
484
- },
485
- onRejected(listener) {
486
- return args.claims.onRejected(listener);
487
- },
488
- onChange(listener: () => void): () => void {
489
- return args.claims.onChange(listener);
490
- },
491
- };
492
-
493
- const leave = (): void => {
494
- if (left) return;
495
- left = true;
496
- for (const handle of Array.from(ownHandles)) {
497
- handle.revoke?.();
498
- ownHandles.delete(handle);
499
- }
500
- args.presence.idle();
501
- if (args.syncGroups.length > 0) {
502
- args.transport.sendRelease(args.claimId);
503
- }
504
- };
505
-
506
- const joined: JoinedParticipant = {
507
- get target() {
508
- return currentTarget;
509
- },
510
- get focusTarget() {
511
- return currentTarget;
512
- },
513
- syncGroups: [...args.syncGroups],
514
- presence: scopedPresence,
515
- claims: scopedClaims,
516
- get peers() {
517
- return scopedPresence.others;
518
- },
519
- get activeClaims() {
520
- return scopedClaims.others;
521
- },
522
- focus: setFocus,
523
- leave,
524
- [Symbol.asyncDispose]: async () => {
525
- leave();
526
- },
527
- };
528
- return joined;
529
- }
530
-
531
- function activityFromTarget(target: ClaimTarget): Omit<Activity, 'action'> {
532
- return {
533
- ...wireTarget(target),
534
- ...subTarget(target),
535
- };
536
- }
537
-
538
- function presenceMatchesParticipant(
539
- entry: Peer,
540
- target: ClaimTarget | null,
541
- syncGroups: readonly string[],
542
- ): boolean {
543
- if (syncGroups.some((g) => entry.syncGroups.includes(g))) return true;
544
- if (!target) return true;
545
- return targetsOverlap(
546
- {
547
- ...streamTarget(entry.activity),
548
- ...subTarget(entry.activity),
549
- },
550
- target,
551
- );
552
- }
553
-
554
- function targetsOverlap(a: ClaimTarget, b: ClaimTarget): boolean {
555
- if (a.type !== b.type || a.id !== b.id) return false;
556
- if (!hasSubtarget(a) || !hasSubtarget(b)) return true;
557
- // Field is the floor: same field overlaps, different fields do not. Sub-field
558
- // targeting returns when same-field concurrency (OT) is solved.
559
- return !a.field || !b.field || a.field === b.field;
560
- }
561
-
562
- function hasSubtarget(target: ClaimTarget): boolean {
563
- return Boolean(target.field);
564
- }