@open-artifact/editor-kit 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.
Files changed (82) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +128 -2
  4. package/package.json +58 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +34 -0
  9. package/src/agent.d.ts +20 -0
  10. package/src/agent.js +40 -0
  11. package/src/announce.d.ts +18 -0
  12. package/src/announce.js +21 -0
  13. package/src/chrome.d.ts +180 -0
  14. package/src/chrome.js +108 -0
  15. package/src/collab/CommentList.d.ts +23 -0
  16. package/src/collab/CommentList.js +117 -0
  17. package/src/collab/CommentViews.d.ts +116 -0
  18. package/src/collab/CommentViews.js +531 -0
  19. package/src/collab/HistoryViews.d.ts +38 -0
  20. package/src/collab/HistoryViews.js +103 -0
  21. package/src/collab/PresenceViews.d.ts +52 -0
  22. package/src/collab/PresenceViews.js +46 -0
  23. package/src/collab/cds/cds.d.ts +148 -0
  24. package/src/collab/cds/cds.js +230 -0
  25. package/src/collab/cds/comment-card.d.ts +93 -0
  26. package/src/collab/cds/comment-card.js +211 -0
  27. package/src/collab/cds/comment-composer.d.ts +28 -0
  28. package/src/collab/cds/comment-composer.js +101 -0
  29. package/src/collab/cds/comments-css.d.ts +2 -0
  30. package/src/collab/cds/comments-css.js +3 -0
  31. package/src/collab/cds/comments.css +497 -0
  32. package/src/collab/cds/edge-piles.d.ts +69 -0
  33. package/src/collab/cds/edge-piles.js +178 -0
  34. package/src/collab/cds/layer.d.ts +41 -0
  35. package/src/collab/cds/layer.js +143 -0
  36. package/src/collab/cds/markdown.d.ts +17 -0
  37. package/src/collab/cds/markdown.js +507 -0
  38. package/src/collab/cds/shield.d.ts +28 -0
  39. package/src/collab/cds/shield.js +114 -0
  40. package/src/collab/cds/time.d.ts +2 -0
  41. package/src/collab/cds/time.js +41 -0
  42. package/src/collab/collab.d.ts +100 -0
  43. package/src/collab/collab.js +119 -0
  44. package/src/collab/comments.d.ts +147 -0
  45. package/src/collab/comments.js +287 -0
  46. package/src/collab/history-wiring.d.ts +32 -0
  47. package/src/collab/history-wiring.js +53 -0
  48. package/src/collab/history.d.ts +53 -0
  49. package/src/collab/history.js +94 -0
  50. package/src/collab/peer-colors.d.ts +123 -0
  51. package/src/collab/peer-colors.js +273 -0
  52. package/src/collab/pins.d.ts +70 -0
  53. package/src/collab/pins.js +44 -0
  54. package/src/collab/presence.d.ts +92 -0
  55. package/src/collab/presence.js +158 -0
  56. package/src/design-systems.d.ts +46 -0
  57. package/src/design-systems.js +61 -0
  58. package/src/downloads.d.ts +24 -0
  59. package/src/downloads.js +36 -0
  60. package/src/find.d.ts +64 -0
  61. package/src/find.js +147 -0
  62. package/src/index.d.ts +25 -0
  63. package/src/index.js +25 -0
  64. package/src/keys.d.ts +13 -0
  65. package/src/keys.js +20 -0
  66. package/src/merge.d.ts +23 -0
  67. package/src/merge.js +116 -0
  68. package/src/page-link.d.ts +33 -0
  69. package/src/page-link.js +75 -0
  70. package/src/project-sync.d.ts +118 -0
  71. package/src/project-sync.js +174 -0
  72. package/src/react.d.ts +16 -0
  73. package/src/react.js +16 -0
  74. package/src/roles.d.ts +33 -0
  75. package/src/roles.js +26 -0
  76. package/src/session.d.ts +42 -0
  77. package/src/session.js +37 -0
  78. package/src/shell.d.ts +56 -0
  79. package/src/shell.js +96 -0
  80. package/src/stash.d.ts +26 -0
  81. package/src/stash.js +66 -0
  82. package/src/styles.css +17 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Loading, autosave and changes made elsewhere, the shared part. An editor
3
+ * keeps its project as an index file plus item files under `project/`; this
4
+ * module owns the mechanics around them:
5
+ *
6
+ * - Load: the listing, the named files and every item file ({@link readProject}).
7
+ * - Save: a debounced save after each local change, one at a time (a change
8
+ * during a save saves again after it), one publish batch with `ifMatch` on
9
+ * every file. A conflict reads the files that lost the race and lets the
10
+ * editor merge, then retries (a bounded number of times). Offline: backoff.
11
+ * - Remote changes: pushed by the host, read and handed to the editor. A file
12
+ * held by a text edit waits until the edit ends.
13
+ *
14
+ * What a batch holds, what a save marks saved and how a change is merged
15
+ * are the editor's ({@link ProjectSyncOptions}).
16
+ */
17
+ import { type ArtifactCapability, type PublishBatch } from '@open-artifact/runtime';
18
+ /** The save states the engine sets (an editor's badge may know more). */
19
+ export type ProjectSaveState = 'saved' | 'dirty' | 'saving' | 'offline' | 'readonly';
20
+ /** How the editor takes one changed file (see {@link ProjectSyncOptions.remote}). */
21
+ export interface RemoteFile {
22
+ /** The hash this tab holds; a change to the same hash is skipped (unless forced). `undefined`: never skipped. */
23
+ hash: string | null | undefined;
24
+ /** A text edit holds the file: the change waits until it ends (unless forced). */
25
+ held?: boolean;
26
+ /** Takes their version (`text` null: deleted or unreadable). */
27
+ apply(text: string | null, hash: string | null): void;
28
+ }
29
+ /** What {@link createProjectSync} drives. `Sent` is what one batch sent; `Run` is one pass of remote changes. */
30
+ export interface ProjectSyncOptions<Sent, Run> {
31
+ /** The artifact capability (read when used, so it may come from a session set up later). */
32
+ artifact(): Pick<ArtifactCapability, 'readText' | 'publish' | 'onChange'>;
33
+ /** Delay between the last change and the save, ms. */
34
+ saveDelay: number;
35
+ /** Conflict retries per save (default 4). */
36
+ maxRetries?: number;
37
+ readOnly(): boolean;
38
+ /** True when something has not reached the server. */
39
+ isDirty(): boolean;
40
+ save(): string;
41
+ setSave(save: ProjectSaveState): void;
42
+ /** Builds the next batch. */
43
+ collect(): {
44
+ batch: PublishBatch;
45
+ sent: Sent;
46
+ };
47
+ /** The batch went through; `hashes` as the host returned them (artifact paths). */
48
+ acknowledge(sent: Sent, hashes: Record<string, string | null>): void;
49
+ /** The batch was empty (nothing to publish). */
50
+ unsent?(sent: Sent): void;
51
+ /** Everything is saved (after the badge says so). */
52
+ saved?(): void;
53
+ /** The host refused the write (`not_writer`): go read-only and tell the person. */
54
+ lostWriteAccess(): void;
55
+ /** Remote changes, one pass at a time: `begin`, `file` per changed path (`undefined`: ignored), `end`. */
56
+ remote: {
57
+ begin(): Run;
58
+ file(path: string, hash: string | null, run: Run): RemoteFile | undefined;
59
+ end(run: Run): void;
60
+ };
61
+ /** Calls `changed` after each local change (the store's revision moved). */
62
+ watchChanges(changed: () => void): void;
63
+ /** Calls `ended` when a text edit ends. */
64
+ watchTextEdit(ended: () => void): void;
65
+ /** Before a flush on unload with unsaved work. */
66
+ beforeUnload?(): void;
67
+ /** Timers (tests inject fakes). */
68
+ timers?: {
69
+ set(run: () => void, ms: number): unknown;
70
+ clear(handle: unknown): void;
71
+ };
72
+ /** Where `beforeunload` is listened to (default `window`; none in node). */
73
+ window?: Pick<Window, 'addEventListener'> | null;
74
+ }
75
+ /** A running sync (see {@link createProjectSync}). */
76
+ export interface ProjectSync {
77
+ /** Listens to remote changes, local changes, text edits and unload. Call once, after loading. */
78
+ start(): void;
79
+ /** Schedules a save (default: the save delay). */
80
+ schedule(delay?: number): void;
81
+ /** Saves now (coalescing with a save already running). */
82
+ flush(): Promise<void>;
83
+ /** Retries a failed save now, resetting the backoff. */
84
+ retryNow(): void;
85
+ /** Applies changes made elsewhere (path → new hash, `null`: deleted). `force` re-reads even known hashes and ignores text edits. */
86
+ applyRemote(changes: Record<string, string | null>, options?: {
87
+ force?: boolean;
88
+ }): Promise<void>;
89
+ }
90
+ /** First offline retry delay, ms (doubles up to {@link OFFLINE_MAX_MS}). */
91
+ export declare const OFFLINE_FIRST_MS = 2000;
92
+ /** Longest offline retry delay, ms. */
93
+ export declare const OFFLINE_MAX_MS = 30000;
94
+ /** Creates the save and remote-change engine of one project. */
95
+ export declare function createProjectSync<Sent, Run>(options: ProjectSyncOptions<Sent, Run>): ProjectSync;
96
+ /** What {@link readProject} read. */
97
+ export interface ProjectFiles {
98
+ title: string;
99
+ /** Each named file, `null` when absent. */
100
+ files: Record<string, {
101
+ text: string;
102
+ hash: string;
103
+ } | null>;
104
+ /** Each item file by its key. */
105
+ items: Record<string, {
106
+ text: string;
107
+ hash: string;
108
+ }>;
109
+ }
110
+ /**
111
+ * Reads the title, the listing, the named `files` and every item file (a path
112
+ * `item` maps to a key; `undefined`: not an item), all at once. Rejects when
113
+ * any read fails.
114
+ */
115
+ export declare function readProject(artifact: Pick<ArtifactCapability, 'title' | 'list' | 'readText'>, spec: {
116
+ files: readonly string[];
117
+ item(path: string): string | null | undefined;
118
+ }): Promise<ProjectFiles>;
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Loading, autosave and changes made elsewhere, the shared part. An editor
3
+ * keeps its project as an index file plus item files under `project/`; this
4
+ * module owns the mechanics around them:
5
+ *
6
+ * - Load: the listing, the named files and every item file ({@link readProject}).
7
+ * - Save: a debounced save after each local change, one at a time (a change
8
+ * during a save saves again after it), one publish batch with `ifMatch` on
9
+ * every file. A conflict reads the files that lost the race and lets the
10
+ * editor merge, then retries (a bounded number of times). Offline: backoff.
11
+ * - Remote changes: pushed by the host, read and handed to the editor. A file
12
+ * held by a text edit waits until the edit ends.
13
+ *
14
+ * What a batch holds, what a save marks saved and how a change is merged
15
+ * are the editor's ({@link ProjectSyncOptions}).
16
+ */
17
+ import { isArtifactError } from '@open-artifact/runtime';
18
+ /** First offline retry delay, ms (doubles up to {@link OFFLINE_MAX_MS}). */
19
+ export const OFFLINE_FIRST_MS = 2_000;
20
+ /** Longest offline retry delay, ms. */
21
+ export const OFFLINE_MAX_MS = 30_000;
22
+ /** Creates the save and remote-change engine of one project. */
23
+ export function createProjectSync(options) {
24
+ const maxRetries = options.maxRetries ?? 4;
25
+ const timers = options.timers ?? { set: (run, ms) => setTimeout(run, ms), clear: (handle) => clearTimeout(handle) };
26
+ let timer = null;
27
+ let running = false;
28
+ let again = false;
29
+ let offlineDelay = OFFLINE_FIRST_MS;
30
+ /** Paths whose remote change waits for a text edit to end. */
31
+ const deferred = new Map();
32
+ function schedule(delay = options.saveDelay) {
33
+ if (options.readOnly())
34
+ return;
35
+ if (options.isDirty())
36
+ options.setSave(options.save() === 'offline' ? 'offline' : 'dirty');
37
+ if (timer !== null)
38
+ timers.clear(timer);
39
+ timer = timers.set(() => {
40
+ timer = null;
41
+ void flush();
42
+ }, delay);
43
+ }
44
+ async function flush() {
45
+ if (running) {
46
+ again = true;
47
+ return;
48
+ }
49
+ running = true;
50
+ try {
51
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
52
+ const { batch, sent } = options.collect();
53
+ if (Object.keys(batch).length === 0) {
54
+ options.unsent?.(sent);
55
+ break;
56
+ }
57
+ options.setSave('saving');
58
+ try {
59
+ const result = await options.artifact().publish(batch);
60
+ options.acknowledge(sent, result.hashes);
61
+ offlineDelay = OFFLINE_FIRST_MS;
62
+ break;
63
+ }
64
+ catch (error) {
65
+ if (isArtifactError(error, 'conflict') && attempt < maxRetries) {
66
+ await resolveConflicts(error.paths ?? []);
67
+ continue;
68
+ }
69
+ if (isArtifactError(error, 'not_writer')) {
70
+ options.lostWriteAccess();
71
+ return;
72
+ }
73
+ // Offline or host error: keep the edits and retry with backoff.
74
+ options.setSave('offline');
75
+ offlineDelay = Math.min(offlineDelay * 2, OFFLINE_MAX_MS);
76
+ schedule(offlineDelay);
77
+ return;
78
+ }
79
+ }
80
+ }
81
+ finally {
82
+ running = false;
83
+ }
84
+ const dirty = options.isDirty();
85
+ if (again || dirty) {
86
+ again = false;
87
+ schedule(dirty ? options.saveDelay : 0);
88
+ }
89
+ else {
90
+ options.setSave('saved');
91
+ options.saved?.();
92
+ }
93
+ }
94
+ /** Reads the files that lost a race and merges ours on top. */
95
+ async function resolveConflicts(paths) {
96
+ const changes = {};
97
+ for (const conflict of paths)
98
+ changes[conflict.path] = conflict.actual;
99
+ await applyRemote(changes, { force: true });
100
+ }
101
+ async function applyRemote(changes, { force = false } = {}) {
102
+ const artifact = options.artifact();
103
+ const run = options.remote.begin();
104
+ for (const [path, hash] of Object.entries(changes)) {
105
+ const file = options.remote.file(path, hash, run);
106
+ if (!file)
107
+ continue;
108
+ if (!force && hash === file.hash)
109
+ continue;
110
+ if (!force && file.held) {
111
+ deferred.set(path, hash);
112
+ continue;
113
+ }
114
+ const text = hash === null ? null : await artifact.readText(path).catch(() => null);
115
+ file.apply(text, hash);
116
+ }
117
+ options.remote.end(run);
118
+ }
119
+ function start() {
120
+ options.artifact().onChange((event) => void applyRemote(event.changes));
121
+ options.watchChanges(() => schedule());
122
+ // Merge deferred remote changes once a text edit ends.
123
+ options.watchTextEdit(() => {
124
+ if (!deferred.size)
125
+ return;
126
+ const changes = Object.fromEntries(deferred);
127
+ deferred.clear();
128
+ void applyRemote(changes);
129
+ });
130
+ const target = options.window === undefined ? globalThis.window : options.window;
131
+ target?.addEventListener('beforeunload', (event) => {
132
+ if (options.isDirty()) {
133
+ options.beforeUnload?.();
134
+ void flush();
135
+ event.preventDefault();
136
+ }
137
+ });
138
+ }
139
+ return {
140
+ start,
141
+ schedule,
142
+ flush,
143
+ retryNow() {
144
+ offlineDelay = OFFLINE_FIRST_MS;
145
+ schedule(0);
146
+ },
147
+ applyRemote,
148
+ };
149
+ }
150
+ /**
151
+ * Reads the title, the listing, the named `files` and every item file (a path
152
+ * `item` maps to a key; `undefined`: not an item), all at once. Rejects when
153
+ * any read fails.
154
+ */
155
+ export async function readProject(artifact, spec) {
156
+ const [title, listing] = await Promise.all([artifact.title(), artifact.list()]);
157
+ const items = {};
158
+ const reads = Object.entries(listing).flatMap(([path, entry]) => {
159
+ const key = spec.item(path);
160
+ if (key === undefined || key === null)
161
+ return [];
162
+ return [
163
+ (async () => {
164
+ items[key] = { text: await artifact.readText(path), hash: entry.sha256 };
165
+ })(),
166
+ ];
167
+ });
168
+ const named = spec.files.map(async (path) => {
169
+ const entry = listing[path];
170
+ return [path, entry ? { text: await artifact.readText(path), hash: entry.sha256 } : null];
171
+ });
172
+ const [read] = await Promise.all([Promise.all(named), ...reads]);
173
+ return { title, files: Object.fromEntries(read), items };
174
+ }
package/src/react.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@open-artifact/editor-kit/react`: the views editors share. Every one is
3
+ * driven by a controller from the pure entry (`@open-artifact/editor-kit`)
4
+ * plus props for what differs per editor. Include
5
+ * `@open-artifact/editor-kit/styles.css` so Tailwind sees their classes.
6
+ */
7
+ export * from './collab/CommentViews.tsx';
8
+ export * from './collab/CommentList.tsx';
9
+ export { CommentsLayer, InLayer } from './collab/cds/layer.tsx';
10
+ export * from './collab/HistoryViews.tsx';
11
+ export * from './collab/PresenceViews.tsx';
12
+ export * from './Announcer.tsx';
13
+ export * from './chrome.tsx';
14
+ export * from './FindBar.tsx';
15
+ /** Key labels for the chrome's shortcut chips (also in the pure entry). */
16
+ export { ALT, MOD, SHIFT } from './keys.ts';
package/src/react.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@open-artifact/editor-kit/react`: the views editors share. Every one is
3
+ * driven by a controller from the pure entry (`@open-artifact/editor-kit`)
4
+ * plus props for what differs per editor. Include
5
+ * `@open-artifact/editor-kit/styles.css` so Tailwind sees their classes.
6
+ */
7
+ export * from "./collab/CommentViews.js";
8
+ export * from "./collab/CommentList.js";
9
+ export { CommentsLayer, InLayer } from "./collab/cds/layer.js";
10
+ export * from "./collab/HistoryViews.js";
11
+ export * from "./collab/PresenceViews.js";
12
+ export * from "./Announcer.js";
13
+ export * from "./chrome.js";
14
+ export * from "./FindBar.js";
15
+ /** Key labels for the chrome's shortcut chips (also in the pure entry). */
16
+ export { ALT, MOD, SHIFT } from "./keys.js";
package/src/roles.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What each role may do in an artifact, the way the host's sharing rules
3
+ * allow it, so an editor only offers what the server will accept:
4
+ *
5
+ * - owner: everything, including sending requests to the agent and saving
6
+ * files to the computer that shares the artifact;
7
+ * - editor (a guest who may edit): changes the artifact, removes comments
8
+ * and restores versions, but cannot reach the owner's agent or downloads;
9
+ * - commenter: comments (add, reply, resolve, move) on a read-only artifact;
10
+ * - viewer: reads only.
11
+ *
12
+ * Pure.
13
+ */
14
+ import type { Role } from '@open-artifact/runtime';
15
+ /** What a viewer may do. */
16
+ export interface RoleAbilities {
17
+ /** Change the artifact (owner or editor). */
18
+ canEdit: boolean;
19
+ /** Add, reply to, resolve and move comments (anyone but a plain viewer). */
20
+ canComment: boolean;
21
+ /** Delete comment threads (owner or editor). */
22
+ canRemoveComments: boolean;
23
+ /** Restore a past version (owner or editor). */
24
+ canRestore: boolean;
25
+ /** Send requests to the agent: Ask, "Send to agent" on a comment (the owner alone). */
26
+ canAsk: boolean;
27
+ /** Save files through the host's downloads, on the sharing computer (the owner alone; guests get a browser download). */
28
+ canSaveToHost: boolean;
29
+ }
30
+ /** The abilities of a role. An unknown role reads only. */
31
+ export declare function roleAbilities(role: Role | string): RoleAbilities;
32
+ /** How the chrome names a read-only role (`null`: the viewer can edit). */
33
+ export declare function readOnlyLabel(role: Role | string): string | null;
package/src/roles.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What each role may do in an artifact, the way the host's sharing rules
3
+ * allow it, so an editor only offers what the server will accept:
4
+ *
5
+ * - owner: everything, including sending requests to the agent and saving
6
+ * files to the computer that shares the artifact;
7
+ * - editor (a guest who may edit): changes the artifact, removes comments
8
+ * and restores versions, but cannot reach the owner's agent or downloads;
9
+ * - commenter: comments (add, reply, resolve, move) on a read-only artifact;
10
+ * - viewer: reads only.
11
+ *
12
+ * Pure.
13
+ */
14
+ /** The abilities of a role. An unknown role reads only. */
15
+ export function roleAbilities(role) {
16
+ const owner = role === 'owner';
17
+ const edits = owner || role === 'editor';
18
+ const comments = edits || role === 'commenter';
19
+ return { canEdit: edits, canComment: comments, canRemoveComments: edits, canRestore: edits, canAsk: owner, canSaveToHost: owner };
20
+ }
21
+ /** How the chrome names a read-only role (`null`: the viewer can edit). */
22
+ export function readOnlyLabel(role) {
23
+ if (roleAbilities(role).canEdit)
24
+ return null;
25
+ return role === 'commenter' ? 'Comment only' : 'View only';
26
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * An editor's connection to its host: installs `window.openartifact` (unless
3
+ * a host already did), resolves the capabilities the editor names, reads the
4
+ * viewer and their role, and connects to the Open Artifact Shell framing the
5
+ * page. Each editor keeps its own `Session` shape (which capabilities it
6
+ * needs, which one it cannot work without) and builds it from
7
+ * {@link connectHost}. Pure (no DOM until called).
8
+ */
9
+ import { type CapabilityMap, type CapabilityName, type ShellConnection, type Viewer } from '@open-artifact/runtime';
10
+ import { type RoleAbilities } from './roles.ts';
11
+ /** The viewer a host that names no one gets: reads only. */
12
+ export declare const GUEST_VIEWER: Readonly<Viewer>;
13
+ /** The named capabilities; a missing one is `null`. */
14
+ export type HostCapabilities<N extends CapabilityName> = {
15
+ [K in N]: CapabilityMap[K] | null;
16
+ };
17
+ /** What {@link connectHost} resolves. */
18
+ export interface HostConnection<N extends CapabilityName> {
19
+ caps: HostCapabilities<N>;
20
+ viewer: Viewer;
21
+ /** What the viewer's role allows. */
22
+ abilities: RoleAbilities;
23
+ /** The Open Artifact Shell framing this page, if any. */
24
+ shell: ShellConnection | null;
25
+ }
26
+ /** Connects to the host and resolves `names` (plus `user`, for the viewer). */
27
+ export declare function connectHost<const N extends Exclude<CapabilityName, 'user'>>(names: readonly N[]): Promise<HostConnection<N>>;
28
+ /** Holds an editor's session once it started. */
29
+ export interface SessionSlot<S> {
30
+ /** The session; throws before it started. */
31
+ session(): S;
32
+ /** The session, or `null` before it started (code that may run early). */
33
+ maybeSession(): S | null;
34
+ /** Stores the started session and returns it. */
35
+ set(session: S): S;
36
+ }
37
+ /** A {@link SessionSlot}. */
38
+ export declare function sessionSlot<S>(): SessionSlot<S>;
39
+ /** The artifact path of a project path. */
40
+ export declare const artifactPath: (path: string) => string;
41
+ /** The project path of an artifact path, or `null` outside `project/`. */
42
+ export declare const projectPath: (path: string) => string | null;
package/src/session.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * An editor's connection to its host: installs `window.openartifact` (unless
3
+ * a host already did), resolves the capabilities the editor names, reads the
4
+ * viewer and their role, and connects to the Open Artifact Shell framing the
5
+ * page. Each editor keeps its own `Session` shape (which capabilities it
6
+ * needs, which one it cannot work without) and builds it from
7
+ * {@link connectHost}. Pure (no DOM until called).
8
+ */
9
+ import { connectShell, createPageProvider, installRuntime } from '@open-artifact/runtime';
10
+ import { roleAbilities } from "./roles.js";
11
+ /** The viewer a host that names no one gets: reads only. */
12
+ export const GUEST_VIEWER = Object.freeze({ id: 'viewer', name: 'Viewer', role: 'viewer' });
13
+ /** Connects to the host and resolves `names` (plus `user`, for the viewer). */
14
+ export async function connectHost(names) {
15
+ const runtime = installRuntime(createPageProvider());
16
+ const [user, ...granted] = await Promise.all([runtime.use('user'), ...names.map((name) => runtime.use(name))]);
17
+ const caps = Object.fromEntries(names.map((name, i) => [name, granted[i] ?? null]));
18
+ const viewer = (await user?.me()) ?? { ...GUEST_VIEWER };
19
+ return { caps, viewer, abilities: roleAbilities(viewer.role), shell: connectShell() };
20
+ }
21
+ /** A {@link SessionSlot}. */
22
+ export function sessionSlot() {
23
+ let current = null;
24
+ return {
25
+ session() {
26
+ if (current === null)
27
+ throw new Error('The session has not started.');
28
+ return current;
29
+ },
30
+ maybeSession: () => current,
31
+ set: (session) => (current = session),
32
+ };
33
+ }
34
+ /** The artifact path of a project path. */
35
+ export const artifactPath = (path) => `project/${path}`;
36
+ /** The project path of an artifact path, or `null` outside `project/`. */
37
+ export const projectPath = (path) => (path.startsWith('project/') ? path.slice('project/'.length) : null);
package/src/shell.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The bridge to an Open Artifact Shell framing the page.
3
+ *
4
+ * The Shell draws the shared top bar (save state, comments, export, Ask)
5
+ * from one report the page sends whole. An editor builds that report one of
6
+ * two ways:
7
+ *
8
+ * - from one function that reads every store: {@link chromeReporter} sends
9
+ * it only when it changed (Design, Slides, Design System);
10
+ * - from parts different services own (sync owns `saved`, collaboration
11
+ * owns `comments`, export owns `formats`): {@link createShellBridge}
12
+ * merges the parts, sends one report per microtask and fans the Shell's
13
+ * commands out to every handler (Whiteboard).
14
+ *
15
+ * Outside a Shell every call is a no-op. Pure (no DOM).
16
+ */
17
+ import { type StoreApi, type UseBoundStore } from 'zustand';
18
+ import type { ChromeCommand, ChromeDraw, ChromeExportItem, ChromeReport, ShellConnection } from '@open-artifact/runtime';
19
+ /** The agent part of a report, from the agent status every editor watches. */
20
+ export declare function agentChrome(status: {
21
+ available: boolean;
22
+ busy: boolean;
23
+ }): NonNullable<ChromeReport['agent']>;
24
+ /**
25
+ * A function that builds the report with `build` and sends it to `shell`
26
+ * when it differs from the last one sent.
27
+ */
28
+ export declare function chromeReporter(shell: ShellConnection, build: () => ChromeReport): () => void;
29
+ /** What the Shell draws for the page (empty outside a Shell). */
30
+ export interface ShellDrawsState {
31
+ draws: ReadonlySet<ChromeDraw>;
32
+ /** A Shell frames this page. */
33
+ framed: boolean;
34
+ }
35
+ /** A handler of Shell commands; may answer an `exports` request with items. */
36
+ export type ShellCommandHandler = (command: ChromeCommand) => ChromeExportItem[] | void;
37
+ /** A bridge made by {@link createShellBridge}. */
38
+ export interface ShellBridge {
39
+ /** What the Shell draws for this page; components hide their own copy of what it draws. */
40
+ useShellDraws: UseBoundStore<StoreApi<ShellDrawsState>>;
41
+ /**
42
+ * Sets parts of the report (keys set to `undefined` are removed) and sends
43
+ * the merged report on the next microtask.
44
+ */
45
+ setShellReport(part: Partial<ChromeReport>): void;
46
+ /** Adds a Shell command handler; returns a function that removes it. The first handler that returns export items answers an `exports` request. */
47
+ onShellCommand(handler: ShellCommandHandler): () => void;
48
+ /**
49
+ * Connects to the Shell, if one frames the page: tracks what it draws,
50
+ * dispatches its commands and tells it the page merges file changes live
51
+ * (so it never reloads the frame under the viewer). Returns a stop function.
52
+ */
53
+ startShell(): () => void;
54
+ }
55
+ /** A report-by-parts bridge; `shell` reads the connection (`null` outside a Shell or before the session started). */
56
+ export declare function createShellBridge(shell: () => ShellConnection | null | undefined): ShellBridge;
package/src/shell.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The bridge to an Open Artifact Shell framing the page.
3
+ *
4
+ * The Shell draws the shared top bar (save state, comments, export, Ask)
5
+ * from one report the page sends whole. An editor builds that report one of
6
+ * two ways:
7
+ *
8
+ * - from one function that reads every store: {@link chromeReporter} sends
9
+ * it only when it changed (Design, Slides, Design System);
10
+ * - from parts different services own (sync owns `saved`, collaboration
11
+ * owns `comments`, export owns `formats`): {@link createShellBridge}
12
+ * merges the parts, sends one report per microtask and fans the Shell's
13
+ * commands out to every handler (Whiteboard).
14
+ *
15
+ * Outside a Shell every call is a no-op. Pure (no DOM).
16
+ */
17
+ import { create } from 'zustand';
18
+ /** The agent part of a report, from the agent status every editor watches. */
19
+ export function agentChrome(status) {
20
+ return { available: status.available, listening: status.available, busy: status.busy };
21
+ }
22
+ /**
23
+ * A function that builds the report with `build` and sends it to `shell`
24
+ * when it differs from the last one sent.
25
+ */
26
+ export function chromeReporter(shell, build) {
27
+ let last = '';
28
+ return () => {
29
+ const next = build();
30
+ const text = JSON.stringify(next);
31
+ if (text === last)
32
+ return;
33
+ last = text;
34
+ shell.report(next);
35
+ };
36
+ }
37
+ /** A report-by-parts bridge; `shell` reads the connection (`null` outside a Shell or before the session started). */
38
+ export function createShellBridge(shell) {
39
+ const useShellDraws = create()(() => ({ draws: new Set(), framed: false }));
40
+ let report = {};
41
+ let scheduled = false;
42
+ const handlers = new Set();
43
+ function send() {
44
+ scheduled = false;
45
+ shell()?.report(report);
46
+ }
47
+ function setShellReport(part) {
48
+ const next = { ...report };
49
+ let changed = false;
50
+ for (const [key, value] of Object.entries(part)) {
51
+ if (JSON.stringify(next[key]) === JSON.stringify(value))
52
+ continue;
53
+ changed = true;
54
+ if (value === undefined)
55
+ delete next[key];
56
+ else
57
+ next[key] = value;
58
+ }
59
+ if (!changed)
60
+ return;
61
+ report = next;
62
+ if (!scheduled) {
63
+ scheduled = true;
64
+ queueMicrotask(send);
65
+ }
66
+ }
67
+ function onShellCommand(handler) {
68
+ handlers.add(handler);
69
+ return () => void handlers.delete(handler);
70
+ }
71
+ function startShell() {
72
+ const connection = shell();
73
+ if (!connection)
74
+ return () => { };
75
+ useShellDraws.setState({ draws: connection.draws, framed: true });
76
+ const stops = [
77
+ connection.onHello((draws) => useShellDraws.setState({ draws })),
78
+ connection.onCommand((command) => {
79
+ let answer;
80
+ for (const handler of [...handlers]) {
81
+ const result = handler(command);
82
+ if (answer === undefined && Array.isArray(result))
83
+ answer = result;
84
+ }
85
+ return answer ?? (command.cmd === 'exports' ? [] : undefined);
86
+ }),
87
+ connection.onFilesChanged(() => true),
88
+ ];
89
+ send();
90
+ return () => {
91
+ for (const stop of stops)
92
+ stop();
93
+ };
94
+ }
95
+ return { useShellDraws, setShellReport, onShellCommand, startShell };
96
+ }
package/src/stash.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Unsaved-work recovery, the shared part: while edits wait to be saved, an
3
+ * editor copies what differs from the saved files to `localStorage` (a
4
+ * "stash"); if the tab closes before the save lands, the next visit offers
5
+ * it back. What a stash holds and how it is restored is the editor's; this
6
+ * module keeps the storage guarded, the age limit and the debounce.
7
+ */
8
+ /** How long a stash is kept, ms (three days). */
9
+ export declare const STASH_KEEP_MS: number;
10
+ /** True while a stash written at `at` may still be offered (not too old, not from the future). */
11
+ export declare function stashFresh(at: number, now: number): boolean;
12
+ /** A stored JSON value under one key, every access guarded. */
13
+ export interface StoredJson<T> {
14
+ read(): T | null;
15
+ /** Writes `value`; `null` clears. */
16
+ write(value: T | null): void;
17
+ clear(): void;
18
+ }
19
+ /**
20
+ * A JSON value stored under `key` (e.g. `open-artifact-design:recovery:<path>`).
21
+ * `parse` validates what is read back (`null`: unusable). Storage that is
22
+ * missing, full or blocked reads as empty and ignores writes.
23
+ */
24
+ export declare function storedJson<T>(key: string, parse: (value: unknown) => T | null, storage?: () => Storage | undefined): StoredJson<T>;
25
+ /** JSON compared by value (key order and spacing aside), text otherwise. */
26
+ export declare function normalizeJson(text: string): string;