@open-artifact/runtime 0.0.0-stage → 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.
@@ -0,0 +1,505 @@
1
+ /**
2
+ * Capability contracts of the Open Artifact page runtime.
3
+ *
4
+ * A type's page (an editor such as Design or Design System) never talks to its
5
+ * host directly. It asks `window.openartifact.use(name)` for a capability
6
+ * namespace and calls the methods below. The host decides which capabilities a
7
+ * given viewer gets: `use()` resolves to `null` when a capability is not
8
+ * available for this view (read-only viewer, no host, unknown name).
9
+ *
10
+ * Every method is asynchronous and may reject with an {@link ArtifactError}.
11
+ */
12
+ /** Version of the capability contract described in this file. */
13
+ export declare const CONTRACT_VERSION = "1.2.0";
14
+ /** Machine-readable error codes a capability call may reject with. */
15
+ export type ArtifactErrorCode =
16
+ /** A write lost a race: at least one `ifMatch` hash no longer matches. */
17
+ 'conflict'
18
+ /** The viewer may not write (viewer or commenter role). */
19
+ | 'not_writer'
20
+ /** The capability exists but the viewer declined or was never granted it. */
21
+ | 'not_granted'
22
+ /** The request was malformed (bad path, too large, wrong shape). */
23
+ | 'invalid'
24
+ /** The file or resource does not exist. */
25
+ | 'not_found'
26
+ /** The host could not be reached or answered with an unexpected status. */
27
+ | 'unavailable';
28
+ /** One path that failed an optimistic-concurrency check. */
29
+ export interface ConflictPath {
30
+ /** Artifact-relative path, e.g. `project/Main.dc.html`. */
31
+ path: string;
32
+ /** The hash the writer expected (`null`: expected the file to be absent). */
33
+ expected: string | null;
34
+ /** The hash currently stored (`null`: the file is absent). */
35
+ actual: string | null;
36
+ }
37
+ /** The error object every capability rejects with. */
38
+ export declare class ArtifactError extends Error {
39
+ readonly code: ArtifactErrorCode;
40
+ /** Present for `conflict`: every path whose `ifMatch` failed. */
41
+ readonly paths?: ConflictPath[];
42
+ constructor(code: ArtifactErrorCode, message: string, paths?: ConflictPath[]);
43
+ }
44
+ /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
45
+ export declare function isArtifactError(value: unknown, code?: ArtifactErrorCode): value is ArtifactError;
46
+ /** A JSON value. */
47
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
48
+ [key: string]: JsonValue;
49
+ };
50
+ /** A JSON object. */
51
+ export type JsonRecord = {
52
+ [key: string]: JsonValue;
53
+ };
54
+ /** Metadata of one stored file. */
55
+ export interface FileEntry {
56
+ /** Lower-case hex SHA-256 of the file's bytes. */
57
+ sha256: string;
58
+ /** Size in bytes. */
59
+ size: number;
60
+ }
61
+ /** A listing of every file of the artifact, keyed by artifact-relative path. */
62
+ export type FileListing = Record<string, FileEntry>;
63
+ /** One file in a publish batch. */
64
+ export interface PublishFile {
65
+ /** Text content (UTF-8), or base64 when `encoding` is `base64`. */
66
+ content: string;
67
+ encoding?: 'utf8' | 'base64';
68
+ /**
69
+ * Optimistic-concurrency guard: the hash the writer last saw.
70
+ * `null` means "the file must not exist yet". Omit to write unconditionally.
71
+ */
72
+ ifMatch?: string | null;
73
+ }
74
+ /** A publish batch: `null` deletes the path. */
75
+ export type PublishBatch = Record<string, PublishFile | null>;
76
+ /** The result of a successful publish. */
77
+ export interface PublishResult {
78
+ /** New hash of every written path; `null` for deleted paths. */
79
+ hashes: Record<string, string | null>;
80
+ }
81
+ /** A change pushed by the host: written by someone else (agent, another tab). */
82
+ export interface FilesChangedEvent {
83
+ /** Path → new hash, or `null` when the file was deleted. */
84
+ changes: Record<string, string | null>;
85
+ /** Who made the change, when the host knows (`agent`, `owner`, `guest:<name>`). */
86
+ author?: string;
87
+ }
88
+ /** The `artifact` capability. */
89
+ export interface ArtifactCapability {
90
+ /** Stable artifact id. */
91
+ readonly id: string;
92
+ /** Current title as recorded by the host. */
93
+ title(): Promise<string>;
94
+ /** Lists every file with its hash. */
95
+ list(): Promise<FileListing>;
96
+ /** Reads a text file; rejects with `not_found` when absent. */
97
+ readText(path: string): Promise<string>;
98
+ /** Reads a file as bytes. */
99
+ readBytes(path: string): Promise<Uint8Array>;
100
+ /**
101
+ * Writes a batch atomically. Rejects with `conflict` (listing every stale
102
+ * path, nothing written) or `not_writer`.
103
+ */
104
+ publish(batch: PublishBatch): Promise<PublishResult>;
105
+ /**
106
+ * Subscribes to changes made by anyone else. The host suppresses echoes of
107
+ * this page's own publishes. Returns an unsubscribe function.
108
+ */
109
+ onChange(listener: (event: FilesChangedEvent) => void): () => void;
110
+ }
111
+ /** A stored upload. Pages reference it only by `url` (`/_blob/<id>`). */
112
+ export interface AssetRecord {
113
+ /** First 32 hex digits of the SHA-256 of the bytes. */
114
+ id: string;
115
+ /** Root-relative URL, always `/_blob/<id>`. */
116
+ url: string;
117
+ sizeBytes: number;
118
+ contentType: string;
119
+ }
120
+ /** The `assets` capability. */
121
+ export interface AssetsCapability {
122
+ /** Uploads bytes; identical bytes always produce the same record. */
123
+ upload(data: Blob, options?: {
124
+ name?: string;
125
+ }): Promise<AssetRecord>;
126
+ }
127
+ /** Roles, from most to least privileged. */
128
+ export type Role = 'owner' | 'editor' | 'commenter' | 'viewer';
129
+ /** The current viewer. */
130
+ export interface Viewer {
131
+ id: string;
132
+ name: string;
133
+ role: Role;
134
+ }
135
+ /** The `user` capability. */
136
+ export interface UserCapability {
137
+ me(): Promise<Viewer>;
138
+ }
139
+ /** True when the role may change files and upload assets. */
140
+ export declare function canEdit(role: Role): boolean;
141
+ /** A request a page sends to the agent ("Send to agent", "Ask agent to fix"). */
142
+ export interface AgentRequest {
143
+ /** What the person asked for, in their words (already fenced if untrusted). */
144
+ text: string;
145
+ /** Short label for cards and logs, e.g. `Ask agent to fix`. */
146
+ title?: string;
147
+ /** Structured context: selection ids, labels, error text. Data, never instructions. */
148
+ context?: Record<string, unknown>;
149
+ }
150
+ /** How the request should arrive. */
151
+ export type AgentDelivery =
152
+ /** Start an agent turn now (falls back to queueing when the agent is away). */
153
+ 'send'
154
+ /** Only prefill the person's composer; never start a turn. */
155
+ | 'stage';
156
+ /** The outcome of {@link AgentCapability.send}. */
157
+ export interface AgentSendResult {
158
+ status: 'delivered' | 'queued' | 'staged' | 'failed';
159
+ /** Human-readable reason when `failed`. */
160
+ reason?: string;
161
+ }
162
+ /** Whether an agent is reachable and working. */
163
+ export interface AgentStatus {
164
+ /** An agent can receive requests (it waits, or a harness can wake it). */
165
+ available: boolean;
166
+ /** The agent is currently changing this artifact. */
167
+ busy: boolean;
168
+ /** Display name, e.g. `Agent`. */
169
+ name: string;
170
+ }
171
+ /** The `agent` capability. */
172
+ export interface AgentCapability {
173
+ send(request: AgentRequest, options?: {
174
+ deliver?: AgentDelivery;
175
+ }): Promise<AgentSendResult>;
176
+ status(): Promise<AgentStatus>;
177
+ onStatus(listener: (status: AgentStatus) => void): () => void;
178
+ }
179
+ /** One viewer (or the agent) present on the artifact. */
180
+ export interface Peer {
181
+ id: string;
182
+ name: string;
183
+ kind: 'person' | 'agent';
184
+ /** Whatever the peer last published with {@link RoomCapability.presence}. */
185
+ state: Record<string, unknown>;
186
+ }
187
+ /**
188
+ * An ephemeral message between the pages of one artifact (live strokes,
189
+ * drag previews, reactions). Never stored; a page that is not connected
190
+ * when it is sent never sees it.
191
+ */
192
+ export interface RoomMessage {
193
+ /** Peer id of the sender (see {@link RoomCapability.self}). */
194
+ from: string;
195
+ /** Free-form channel name chosen by the type, e.g. `gesture`. */
196
+ topic: string;
197
+ /** JSON payload, at most {@link ROOM_MESSAGE_MAX_BYTES} once serialized. */
198
+ data: JsonValue;
199
+ }
200
+ /** Largest serialized {@link RoomMessage.data} a host relays. */
201
+ export declare const ROOM_MESSAGE_MAX_BYTES = 16384;
202
+ /** The `room` capability. */
203
+ export interface RoomCapability {
204
+ /** This page's own peer id (its entry in {@link peers}). */
205
+ self(): Promise<string>;
206
+ /**
207
+ * Publishes (merges) this viewer's presence state; a `null` value removes
208
+ * a key. The `viewContext` key is what the agent receives before the
209
+ * viewer's next message.
210
+ */
211
+ presence(patch: Record<string, unknown>): Promise<void>;
212
+ peers(): Promise<Peer[]>;
213
+ onPeers(listener: (peers: Peer[]) => void): () => void;
214
+ /** Relays an ephemeral message to every other page of the artifact. */
215
+ emit(topic: string, data: JsonValue): Promise<void>;
216
+ /** Subscribes to ephemeral messages from other pages. */
217
+ onMessage(listener: (message: RoomMessage) => void): () => void;
218
+ }
219
+ /** The `downloads` capability. */
220
+ export interface DownloadsCapability {
221
+ /** Saves a file. Hosts cap a single file at 16 MB. */
222
+ save(file: {
223
+ name: string;
224
+ data: Blob;
225
+ }): Promise<{
226
+ savedTo?: string;
227
+ }>;
228
+ }
229
+ /**
230
+ * A document path: an even number of segments alternating collection and
231
+ * document id (`elements/n-12`, `data/users/u1/idea`). Segments match
232
+ * `[A-Za-z0-9_.~:@+-]+` and are never `.` or `..`.
233
+ */
234
+ export type DbPath = string;
235
+ /** One stored document. */
236
+ export interface DbDocument {
237
+ path: DbPath;
238
+ data: JsonRecord;
239
+ }
240
+ /**
241
+ * A write's precondition: write only while the document is still the one the
242
+ * writer read. `ifMatch` is that document's sha256 (lowercase hex of its data
243
+ * as compact JSON, `JSON.stringify`, UTF-8: what the agent's tools call
244
+ * `sha256`), or `null` for "only while it does not exist". When one fails
245
+ * the whole batch is refused with `conflict`, its `paths` naming each
246
+ * document (`expected`, `actual`), and nothing is written. Omit it to write
247
+ * unconditionally.
248
+ */
249
+ export interface DbWriteGuard {
250
+ ifMatch?: string | null;
251
+ }
252
+ /** One write of a {@link DbCapability.write} batch. */
253
+ export type DbWrite =
254
+ /** Replaces the document (creating it when absent). */
255
+ ({
256
+ op: 'set';
257
+ path: DbPath;
258
+ data: JsonRecord;
259
+ } & DbWriteGuard)
260
+ /**
261
+ * Applies a JSON merge patch (RFC 7396): objects merge, arrays and
262
+ * scalars replace, `null` removes a key. An absent document starts empty.
263
+ */
264
+ | ({
265
+ op: 'update';
266
+ path: DbPath;
267
+ patch: JsonRecord;
268
+ } & DbWriteGuard)
269
+ /** Removes the document (a no-op when it is absent). */
270
+ | ({
271
+ op: 'delete';
272
+ path: DbPath;
273
+ } & DbWriteGuard);
274
+ /** Documents changed by someone else (agent, another page). */
275
+ export interface DbChangeEvent {
276
+ /** Path → the document's new data, or `null` when it was deleted. */
277
+ changes: Record<DbPath, JsonRecord | null>;
278
+ /** Who made the change, when the host knows (`agent`, `owner`, a peer id). */
279
+ author?: string;
280
+ }
281
+ /** Limits every host enforces on the document store. */
282
+ export declare const DB_LIMITS: {
283
+ /** Writes in one batch. */
284
+ readonly maxWrites: 500;
285
+ /** Bytes of one document's JSON. */
286
+ readonly maxDocumentBytes: 262144;
287
+ /** Nesting depth of one document. */
288
+ readonly maxDepth: 32;
289
+ };
290
+ /** The `db` capability, granted to types whose manifest declares `store: "db"`. */
291
+ export interface DbCapability {
292
+ /** Reads one document; `null` when absent. */
293
+ get(path: DbPath): Promise<JsonRecord | null>;
294
+ /** Every document of one collection (`elements`, `data/users/u1/ideas`), sorted by path. */
295
+ list(collection: string): Promise<DbDocument[]>;
296
+ /**
297
+ * Applies a batch in order, all or nothing. Rejects with `invalid` (bad
298
+ * path, too large), `conflict` (an `ifMatch` no longer holds) or `not_writer`. The host never echoes the batch back
299
+ * through {@link onChange}.
300
+ */
301
+ write(writes: DbWrite[]): Promise<void>;
302
+ /** Subscribes to changes made by anyone else. Returns an unsubscribe function. */
303
+ onChange(listener: (event: DbChangeEvent) => void): () => void;
304
+ }
305
+ /** Who wrote a comment message. */
306
+ export interface CommentAuthor {
307
+ kind: 'person' | 'agent';
308
+ name: string;
309
+ }
310
+ /** One message of a thread. */
311
+ export interface CommentMessage {
312
+ id: string;
313
+ author: CommentAuthor;
314
+ text: string;
315
+ /** ISO 8601 time. */
316
+ at: string;
317
+ }
318
+ /** Where a thread stands with the agent. */
319
+ export interface CommentAgentState {
320
+ /** `pending`: sent, not yet read; `delivered`: the agent has it; `replied`: it answered. */
321
+ status: 'pending' | 'delivered' | 'replied';
322
+ }
323
+ /** A comment thread. */
324
+ export interface CommentThread {
325
+ id: string;
326
+ /**
327
+ * The type's own anchor, serialized (a board stores a JSON object naming
328
+ * an element and an offset). Opaque to the host.
329
+ */
330
+ anchor: string;
331
+ /** Short human label of what the thread is about (`Note "Q3 goals"`). */
332
+ label: string;
333
+ /** Longer description of the anchored content, for the agent. */
334
+ detail?: string;
335
+ /** Extra structured location (coordinates, element ids), for the agent. */
336
+ location: JsonRecord;
337
+ status: 'open' | 'resolved';
338
+ agent?: CommentAgentState;
339
+ messages: CommentMessage[];
340
+ }
341
+ /** What {@link CommentsCapability.create} takes. */
342
+ export interface CommentCreate {
343
+ anchor: string;
344
+ label: string;
345
+ detail?: string;
346
+ location?: JsonRecord;
347
+ /** The first message. */
348
+ text: string;
349
+ }
350
+ /** The `comments` capability, granted to types whose manifest declares `comments: true`. */
351
+ export interface CommentsCapability {
352
+ /** Every thread, open and resolved. */
353
+ list(): Promise<CommentThread[]>;
354
+ create(input: CommentCreate): Promise<CommentThread>;
355
+ reply(threadId: string, text: string): Promise<CommentThread>;
356
+ setResolved(threadId: string, resolved: boolean): Promise<CommentThread>;
357
+ /** Re-anchors a thread (its content moved or was replaced). */
358
+ move(threadId: string, anchor: string, location?: JsonRecord): Promise<CommentThread>;
359
+ /** Deletes one message, or the whole thread when `messageId` is omitted. */
360
+ remove(threadId: string, messageId?: string): Promise<void>;
361
+ /** Hands the thread to the agent (status `pending` until it reads it). */
362
+ sendToAgent(threadId: string): Promise<CommentThread>;
363
+ /** Subscribes to the full thread list whenever anyone changes it. */
364
+ onChange(listener: (threads: CommentThread[]) => void): () => void;
365
+ }
366
+ /** Who made a version: a person on the page, the agent (any change on disk), or the system (the first version). */
367
+ export interface HistoryAuthor {
368
+ kind: 'person' | 'agent' | 'system';
369
+ id: string;
370
+ name: string;
371
+ }
372
+ /** One path a version changed. Paths are `project/…` files or `db/<collection>/<doc>` documents. */
373
+ export interface HistoryFileChange {
374
+ path: string;
375
+ op: 'added' | 'edited' | 'deleted';
376
+ }
377
+ /**
378
+ * One version: an author's burst of changes (it ends after a 30 s pause or
379
+ * 5 min), or a restore.
380
+ */
381
+ export interface HistoryVersion {
382
+ /** Numbers the versions from 1, never reused. */
383
+ n: number;
384
+ /** First and last change in it (ISO 8601). */
385
+ first: string;
386
+ at: string;
387
+ author: HistoryAuthor;
388
+ /** What it changed, sorted by path. */
389
+ files: HistoryFileChange[];
390
+ /** A restore: the version it brought back. */
391
+ restoredFrom?: number;
392
+ /** The newest version: what the files hold now. */
393
+ current?: true;
394
+ /** Changes made moments before by someone else that this version undid, at least in part. */
395
+ overwrote?: {
396
+ path: string;
397
+ n: number;
398
+ author: HistoryAuthor;
399
+ }[];
400
+ }
401
+ /**
402
+ * A notice to the viewer: someone else's version `n` undid part of their
403
+ * change to `path` (version `lost.n`). Bring it back with
404
+ * `restore(lost.n, [path])`; it goes away by itself then.
405
+ */
406
+ export interface HistoryNotice {
407
+ id: string;
408
+ at: string;
409
+ path: string;
410
+ n: number;
411
+ author: HistoryAuthor;
412
+ lost: {
413
+ n: number;
414
+ author: HistoryAuthor;
415
+ deleted?: true;
416
+ };
417
+ }
418
+ /** What {@link HistoryCapability.list} answers. */
419
+ export interface HistoryListing {
420
+ /** Newest first. */
421
+ versions: HistoryVersion[];
422
+ /** The viewer's notices, newest first. */
423
+ notices: HistoryNotice[];
424
+ /** The viewer may restore (owner or editor). */
425
+ canRestore: boolean;
426
+ }
427
+ /**
428
+ * One path before and after a version, for a diff. `null`: the file did
429
+ * not exist on that side. Contents are left out (`null`) when `binary` or
430
+ * `tooLarge`.
431
+ */
432
+ export interface HistoryFileDiff {
433
+ path: string;
434
+ n: number;
435
+ op: HistoryFileChange['op'];
436
+ before: string | null;
437
+ after: string | null;
438
+ binary?: true;
439
+ tooLarge?: true;
440
+ }
441
+ /** What {@link HistoryCapability.restore} answers. */
442
+ export interface HistoryRestoreResult {
443
+ /** The version the restore made (`null`: everything already matched). */
444
+ version: number | null;
445
+ /** The paths it wrote or deleted. */
446
+ changed: string[];
447
+ }
448
+ /** The history changed: `n` is the newest version (it may be one that grew). */
449
+ export interface HistoryChangeEvent {
450
+ n: number | null;
451
+ }
452
+ /**
453
+ * The `history` capability: the artifact's versions, read-only previews of
454
+ * them, and restores. A restore writes through the host's normal write path
455
+ * (every open page hears of it) and is a version of its own.
456
+ */
457
+ export interface HistoryCapability {
458
+ /** Every kept version (newest first) and the viewer's notices. */
459
+ list(): Promise<HistoryListing>;
460
+ /** Every path as it was right after version `n`, with its hash and size. */
461
+ files(n: number): Promise<FileListing>;
462
+ /** A text file (or a document's JSON) as it was right after version `n`; rejects `not_found`. */
463
+ read(n: number, path: string): Promise<string>;
464
+ /** The same as bytes. */
465
+ readBytes(n: number, path: string): Promise<Uint8Array>;
466
+ /** One path right before and right after version `n` (a path version `n` changed). */
467
+ diff(n: number, path: string): Promise<HistoryFileDiff>;
468
+ /**
469
+ * Brings version `n` back: every path (default) or only `paths`. Rejects
470
+ * `not_writer` for readers, `not_found` for a version no longer kept.
471
+ */
472
+ restore(n: number, paths?: string[]): Promise<HistoryRestoreResult>;
473
+ /** Dismisses one of the viewer's notices. */
474
+ dismissNotice(id: string): Promise<void>;
475
+ /** Subscribes to new versions. Returns an unsubscribe function. */
476
+ onChange(listener: (event: HistoryChangeEvent) => void): () => void;
477
+ }
478
+ /** Every capability by name. */
479
+ export interface CapabilityMap {
480
+ artifact: ArtifactCapability;
481
+ assets: AssetsCapability;
482
+ user: UserCapability;
483
+ agent: AgentCapability;
484
+ room: RoomCapability;
485
+ downloads: DownloadsCapability;
486
+ db: DbCapability;
487
+ comments: CommentsCapability;
488
+ history: HistoryCapability;
489
+ }
490
+ export type CapabilityName = keyof CapabilityMap;
491
+ /** The object installed at `window.openartifact`. */
492
+ export interface OpenArtifactRuntime {
493
+ /** Contract version, see {@link CONTRACT_VERSION}. */
494
+ readonly version: string;
495
+ /**
496
+ * Resolves the namespace of a capability, or `null` when this view may not
497
+ * use it. Results are memoized and frozen.
498
+ */
499
+ use<K extends CapabilityName>(name: K): Promise<CapabilityMap[K] | null>;
500
+ }
501
+ declare global {
502
+ interface Window {
503
+ openartifact?: OpenArtifactRuntime;
504
+ }
505
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Capability contracts of the Open Artifact page runtime.
3
+ *
4
+ * A type's page (an editor such as Design or Design System) never talks to its
5
+ * host directly. It asks `window.openartifact.use(name)` for a capability
6
+ * namespace and calls the methods below. The host decides which capabilities a
7
+ * given viewer gets: `use()` resolves to `null` when a capability is not
8
+ * available for this view (read-only viewer, no host, unknown name).
9
+ *
10
+ * Every method is asynchronous and may reject with an {@link ArtifactError}.
11
+ */
12
+ /** Version of the capability contract described in this file. */
13
+ export const CONTRACT_VERSION = '1.2.0';
14
+ /** The error object every capability rejects with. */
15
+ export class ArtifactError extends Error {
16
+ code;
17
+ /** Present for `conflict`: every path whose `ifMatch` failed. */
18
+ paths;
19
+ constructor(code, message, paths) {
20
+ super(message);
21
+ this.name = 'ArtifactError';
22
+ this.code = code;
23
+ if (paths)
24
+ this.paths = paths;
25
+ }
26
+ }
27
+ /** Type guard for {@link ArtifactError} that also works across realms (iframes). */
28
+ export function isArtifactError(value, code) {
29
+ if (!value || typeof value !== 'object')
30
+ return false;
31
+ const candidate = value;
32
+ if (candidate.name !== 'ArtifactError' || typeof candidate.code !== 'string')
33
+ return false;
34
+ return code === undefined || candidate.code === code;
35
+ }
36
+ /** True when the role may change files and upload assets. */
37
+ export function canEdit(role) {
38
+ return role === 'owner' || role === 'editor';
39
+ }
40
+ /** Largest serialized {@link RoomMessage.data} a host relays. */
41
+ export const ROOM_MESSAGE_MAX_BYTES = 16_384;
42
+ /** Limits every host enforces on the document store. */
43
+ export const DB_LIMITS = {
44
+ /** Writes in one batch. */
45
+ maxWrites: 500,
46
+ /** Bytes of one document's JSON. */
47
+ maxDocumentBytes: 262_144,
48
+ /** Nesting depth of one document. */
49
+ maxDepth: 32,
50
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Installs `window.openartifact` on top of a capability provider.
3
+ *
4
+ * The provider is whatever actually implements the capabilities: the local
5
+ * type server ({@link createLocalProvider}), a test double, or a bridge to a
6
+ * remote host. This module adds the guarantees every page relies on:
7
+ * memoized and frozen namespaces, and a timeout so a missing host resolves to
8
+ * `null` instead of hanging forever.
9
+ */
10
+ import { type CapabilityMap, type CapabilityName, type OpenArtifactRuntime } from './capabilities.ts';
11
+ /** Something that can produce capability namespaces. */
12
+ export interface CapabilityProvider {
13
+ /** Returns the namespace, or `null` when this view may not use it. */
14
+ get<K extends CapabilityName>(name: K): Promise<CapabilityMap[K] | null> | CapabilityMap[K] | null;
15
+ }
16
+ /** Options of {@link createRuntime}. */
17
+ export interface RuntimeOptions {
18
+ /** Milliseconds before an unanswered `use()` resolves to `null`. Default 10 000. */
19
+ timeoutMs?: number;
20
+ }
21
+ /** Builds a runtime object without installing it globally. */
22
+ export declare function createRuntime(provider: CapabilityProvider, options?: RuntimeOptions): OpenArtifactRuntime;
23
+ /**
24
+ * Installs the runtime at `window.openartifact` (once) and returns it.
25
+ * A runtime already installed by the host wins: pages call this defensively.
26
+ */
27
+ export declare function installRuntime(provider: CapabilityProvider, options?: RuntimeOptions): OpenArtifactRuntime;
28
+ /** Shortcut for `window.openartifact?.use(name)` that never throws. */
29
+ export declare function useCapability<K extends CapabilityName>(name: K): Promise<CapabilityMap[K] | null>;
package/src/client.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Installs `window.openartifact` on top of a capability provider.
3
+ *
4
+ * The provider is whatever actually implements the capabilities: the local
5
+ * type server ({@link createLocalProvider}), a test double, or a bridge to a
6
+ * remote host. This module adds the guarantees every page relies on:
7
+ * memoized and frozen namespaces, and a timeout so a missing host resolves to
8
+ * `null` instead of hanging forever.
9
+ */
10
+ import { CONTRACT_VERSION, } from "./capabilities.js";
11
+ /** Builds a runtime object without installing it globally. */
12
+ export function createRuntime(provider, options = {}) {
13
+ const timeoutMs = options.timeoutMs ?? 10_000;
14
+ const cache = new Map();
15
+ const use = (name) => {
16
+ const cached = cache.get(name);
17
+ if (cached)
18
+ return cached;
19
+ const pending = new Promise((resolve) => {
20
+ const timer = setTimeout(() => resolve(null), timeoutMs);
21
+ Promise.resolve()
22
+ .then(() => provider.get(name))
23
+ .then((namespace) => {
24
+ clearTimeout(timer);
25
+ resolve(namespace ? Object.freeze(namespace) : null);
26
+ }, () => {
27
+ clearTimeout(timer);
28
+ resolve(null);
29
+ });
30
+ });
31
+ cache.set(name, pending);
32
+ return pending;
33
+ };
34
+ return Object.freeze({ version: CONTRACT_VERSION, use });
35
+ }
36
+ /**
37
+ * Installs the runtime at `window.openartifact` (once) and returns it.
38
+ * A runtime already installed by the host wins: pages call this defensively.
39
+ */
40
+ export function installRuntime(provider, options) {
41
+ const existing = globalThis.window?.openartifact;
42
+ if (existing)
43
+ return existing;
44
+ const runtime = createRuntime(provider, options);
45
+ Object.defineProperty(window, 'openartifact', {
46
+ value: runtime,
47
+ configurable: false,
48
+ enumerable: true,
49
+ writable: false,
50
+ });
51
+ return runtime;
52
+ }
53
+ /** Shortcut for `window.openartifact?.use(name)` that never throws. */
54
+ export async function useCapability(name) {
55
+ const runtime = globalThis.window?.openartifact;
56
+ if (!runtime)
57
+ return null;
58
+ try {
59
+ return await runtime.use(name);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }