@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
|
@@ -0,0 +1,1363 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// packages/server-sdk/src/frame/client/runtime.ts
|
|
4
|
+
(() => {
|
|
5
|
+
"use strict";
|
|
6
|
+
const w = window;
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return value !== null && typeof value === "object";
|
|
9
|
+
}
|
|
10
|
+
if (w.openArtifacts && w.openArtifacts.__openArtifactsFrame) return;
|
|
11
|
+
const boot = w.__OPEN_ARTIFACTS_FRAME || {};
|
|
12
|
+
const SHELL = boot.shellOrigin || "";
|
|
13
|
+
const parentWin = window.parent;
|
|
14
|
+
const framed = !!SHELL && !!parentWin && parentWin !== window;
|
|
15
|
+
const INIT_TIMEOUT_MS = 1e4;
|
|
16
|
+
const WANT_TIMEOUT_MS = 1e4;
|
|
17
|
+
const ACKED_MS = 9e5;
|
|
18
|
+
const BUDGET_MAX_MS = 6e5;
|
|
19
|
+
const REWIRED_MESSAGE = "may not have run: the artifact was updated before this call was answered";
|
|
20
|
+
const SAMPLE_SRC = "/_runtime/open-artifacts-sample.js";
|
|
21
|
+
const SAMPLE_LOAD_MS = 15e3;
|
|
22
|
+
const MCP_SRC = "/_runtime/open-artifacts-mcp.js";
|
|
23
|
+
const SAMPLE_MAX_EARLY = 6;
|
|
24
|
+
const grants = Array.isArray(boot.grants) ? boot.grants.slice() : [];
|
|
25
|
+
const stubs = Array.isArray(boot.stubs) ? boot.stubs.slice() : [];
|
|
26
|
+
const TIMEOUTS = {
|
|
27
|
+
downloads: [15e4, "unavailable", 0],
|
|
28
|
+
assets: [13e4, "upstream_error", ACKED_MS],
|
|
29
|
+
user: [2e4, null, 0],
|
|
30
|
+
artifact: [13e4, "upstream_error", 0],
|
|
31
|
+
comments: [13e4, "upstream_error", ACKED_MS],
|
|
32
|
+
permissions: [13e4, "upstream_error", ACKED_MS],
|
|
33
|
+
room: [13e4, "upstream_error", 0],
|
|
34
|
+
db: [13e4, "unavailable", 0],
|
|
35
|
+
// Only its permission methods go through call(): `request` waits for the person once the shell acks it.
|
|
36
|
+
sample: [13e4, "upstream_error", ACKED_MS],
|
|
37
|
+
// Only its permission state goes through call(); client/mcp.ts carries the rest.
|
|
38
|
+
mcp: [7e4, "upstream_error", 0]
|
|
39
|
+
};
|
|
40
|
+
const PREFIX = { mcp: "c", sample: "a", downloads: "d", assets: "e", permissions: "p", user: "u", artifact: "s", room: "r", comments: "k", db: "b" };
|
|
41
|
+
const ACTIVATED = { "permissions.request": true, "sample.request": true, "sample.manage": true, "room.sendToAgentSession": true };
|
|
42
|
+
let seq = 0;
|
|
43
|
+
const salt = new Uint32Array(1);
|
|
44
|
+
const pending = /* @__PURE__ */ new Map();
|
|
45
|
+
let init = null;
|
|
46
|
+
let initDone = false;
|
|
47
|
+
let initWaiters = [];
|
|
48
|
+
let brokerGen;
|
|
49
|
+
const configs = /* @__PURE__ */ Object.create(null);
|
|
50
|
+
function post(msg, activation = false) {
|
|
51
|
+
if (!framed) return;
|
|
52
|
+
try {
|
|
53
|
+
if (activation) parentWin.postMessage(msg, { targetOrigin: SHELL, includeUserActivation: true });
|
|
54
|
+
else parentWin.postMessage(msg, SHELL);
|
|
55
|
+
} catch {
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function frameError(code, message, extra, name) {
|
|
59
|
+
const err = Object.assign(new Error(typeof message === "string" && message ? message : String(code || "error")), {
|
|
60
|
+
name: name || "FrameError",
|
|
61
|
+
code: typeof code === "string" && code ? code : "upstream_error"
|
|
62
|
+
});
|
|
63
|
+
if (isRecord(extra)) for (const k of Object.keys(extra)) {
|
|
64
|
+
if (k !== "message" && k !== "name" && k !== "stack" && k !== "code") Reflect.set(err, k, extra[k]);
|
|
65
|
+
}
|
|
66
|
+
return err;
|
|
67
|
+
}
|
|
68
|
+
function whenInit() {
|
|
69
|
+
if (initDone) return Promise.resolve(init);
|
|
70
|
+
return new Promise((resolve) => initWaiters.push(resolve));
|
|
71
|
+
}
|
|
72
|
+
function finishInit(packet) {
|
|
73
|
+
if (initDone) return;
|
|
74
|
+
initDone = true;
|
|
75
|
+
if (packet) {
|
|
76
|
+
if (typeof packet.brokerGen === "number") brokerGen = packet.brokerGen;
|
|
77
|
+
const grants2 = /* @__PURE__ */ new Set();
|
|
78
|
+
if (isRecord(packet.capabilities)) {
|
|
79
|
+
for (const [name, grant] of Object.entries(packet.capabilities)) {
|
|
80
|
+
if (!grant) continue;
|
|
81
|
+
grants2.add(name);
|
|
82
|
+
configs[name] = isRecord(grant) && isRecord(grant.config) ? grant.config : {};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
init = {
|
|
86
|
+
client: typeof packet.client === "string" ? packet.client : void 0,
|
|
87
|
+
grants: grants2,
|
|
88
|
+
usable: Array.isArray(packet.usable) ? packet.usable.filter((name) => typeof name === "string") : [],
|
|
89
|
+
capBudgets: isRecord(packet.capBudgets) ? packet.capBudgets : {},
|
|
90
|
+
capWants: packet.capWants === true
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const list = initWaiters;
|
|
94
|
+
initWaiters = [];
|
|
95
|
+
for (const fn of list) fn(init);
|
|
96
|
+
}
|
|
97
|
+
function timeoutOf(cap, method) {
|
|
98
|
+
const t = TIMEOUTS[cap] || [13e4, "upstream_error", 0];
|
|
99
|
+
const methods = init?.capBudgets[cap];
|
|
100
|
+
const budget = isRecord(methods) ? methods[method] : void 0;
|
|
101
|
+
if (typeof budget === "number" && budget > 0) return [Math.min(budget, BUDGET_MAX_MS) + 2e3, t[1]];
|
|
102
|
+
return [t[0], t[1]];
|
|
103
|
+
}
|
|
104
|
+
function arm(id, p, ms, code) {
|
|
105
|
+
if (p.timer) clearTimeout(p.timer);
|
|
106
|
+
p.timer = setTimeout(() => {
|
|
107
|
+
if (!pending.delete(id)) return;
|
|
108
|
+
if (code === null) p.resolve(null);
|
|
109
|
+
else p.reject({ code, message: `${p.cap}.${p.method} did not answer in time.` });
|
|
110
|
+
}, ms);
|
|
111
|
+
}
|
|
112
|
+
function call(cap, method, arg, errorName, transfer) {
|
|
113
|
+
if (!framed) return Promise.reject(frameError("unavailable", "This page is not inside its frame shell.", null, errorName));
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
crypto.getRandomValues(salt);
|
|
116
|
+
const id = `${PREFIX[cap] || "x"}${salt[0].toString(36)}.${++seq}`;
|
|
117
|
+
const p = {
|
|
118
|
+
cap,
|
|
119
|
+
method,
|
|
120
|
+
resolve: (v) => {
|
|
121
|
+
if (p.timer) clearTimeout(p.timer);
|
|
122
|
+
resolve(v);
|
|
123
|
+
},
|
|
124
|
+
reject: (reason) => {
|
|
125
|
+
const e = isRecord(reason) ? reason : void 0;
|
|
126
|
+
if (p.timer) clearTimeout(p.timer);
|
|
127
|
+
if (boot.debug) post({ __open_artifacts_console: true, level: "warn", text: `${cap}.${method} → ${e && e.code || "error"}: ${e && e.message || ""}` });
|
|
128
|
+
reject(frameError(e && e.code, e && e.message, e, errorName));
|
|
129
|
+
},
|
|
130
|
+
timer: null
|
|
131
|
+
};
|
|
132
|
+
pending.set(id, p);
|
|
133
|
+
const [ms, code] = timeoutOf(cap, method);
|
|
134
|
+
arm(id, p, ms, code);
|
|
135
|
+
const msg = { __frame_cap: true, cap, id, method, args: [arg] };
|
|
136
|
+
if (brokerGen !== void 0) msg.brokerGen = brokerGen;
|
|
137
|
+
if (cap === "assets") msg.holds = true;
|
|
138
|
+
const activation = cap === "comments" || ACTIVATED[`${cap}.${method}`] === true;
|
|
139
|
+
try {
|
|
140
|
+
if (transfer && transfer.length) parentWin.postMessage(msg, { targetOrigin: SHELL, transfer });
|
|
141
|
+
else if (activation) parentWin.postMessage(msg, { targetOrigin: SHELL, includeUserActivation: true });
|
|
142
|
+
else parentWin.postMessage(msg, SHELL);
|
|
143
|
+
} catch (e) {
|
|
144
|
+
pending.delete(id);
|
|
145
|
+
p.reject({ code: "invalid_argument", message: String(e?.message || e) });
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
const dbSubs = /* @__PURE__ */ new Map();
|
|
150
|
+
const roomHandlers = /* @__PURE__ */ new Map();
|
|
151
|
+
const peerHandlers = /* @__PURE__ */ new Set();
|
|
152
|
+
const connHandlers = /* @__PURE__ */ new Set();
|
|
153
|
+
const wants = /* @__PURE__ */ new Map();
|
|
154
|
+
const sampleRoutes = /* @__PURE__ */ new Map();
|
|
155
|
+
let anchors = null;
|
|
156
|
+
let commentsMode = false;
|
|
157
|
+
window.addEventListener("message", (ev) => {
|
|
158
|
+
if (ev.source !== parentWin || ev.origin !== SHELL) return;
|
|
159
|
+
const d = ev.data;
|
|
160
|
+
if (!isRecord(d)) return;
|
|
161
|
+
if (isRecord(d.__frame_init)) return finishInit(d.__frame_init);
|
|
162
|
+
const sampleRoute = typeof d.id === "string" ? sampleRoutes.get(d.id) : void 0;
|
|
163
|
+
if (sampleRoute && (d.__frame_cap_r === true || d.__frame_cap_ack === true || d.__frame_cap_p === true)) return sampleRoute(d);
|
|
164
|
+
if (d.__frame_mcp_watch === true) return void mcpModule?.watchEvent(d);
|
|
165
|
+
if (d.__frame_cap_p === true) {
|
|
166
|
+
const p = typeof d.id === "string" ? pending.get(d.id) : void 0;
|
|
167
|
+
if (p && typeof d.id === "string") arm(d.id, p, ...timeoutOf(p.cap, p.method));
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (d.__frame_cap_r === true) {
|
|
171
|
+
if (typeof d.id !== "string") return;
|
|
172
|
+
const p = pending.get(d.id);
|
|
173
|
+
if (!p) return;
|
|
174
|
+
pending.delete(d.id);
|
|
175
|
+
if (d.error != null) p.reject(d.error);
|
|
176
|
+
else p.resolve(d.result);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (d.__frame_cap_ack === true) {
|
|
180
|
+
if (typeof d.id !== "string") return;
|
|
181
|
+
const p = pending.get(d.id);
|
|
182
|
+
const t = p && TIMEOUTS[p.cap];
|
|
183
|
+
if (p && t && t[2]) arm(d.id, p, t[2], t[1]);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (d.__frame_cap_rewired === true) return onRewired(d);
|
|
187
|
+
if (d.__frame_cap_grant === true) {
|
|
188
|
+
if (typeof d.cap !== "string") return;
|
|
189
|
+
const fn = wants.get(d.cap === "self" ? "artifact" : d.cap);
|
|
190
|
+
if (fn) fn(d);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (d.__frame_db_ev === true) {
|
|
194
|
+
if (typeof d.sub !== "string") return;
|
|
195
|
+
const sub = dbSubs.get(d.sub);
|
|
196
|
+
if (sub) sub.deliver(d);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (d.__frame_room_ev === true) return onRoomEvent(d);
|
|
200
|
+
if (d.__open_artifacts_comments === true) onCommentsEvent(d);
|
|
201
|
+
});
|
|
202
|
+
function onRewired(d) {
|
|
203
|
+
const changed = typeof d.brokerGen === "number" && brokerGen !== void 0 && d.brokerGen !== brokerGen;
|
|
204
|
+
if (typeof d.brokerGen === "number") brokerGen = d.brokerGen;
|
|
205
|
+
const caps = Array.isArray(d.caps) && d.caps.every((c) => typeof c === "string") ? d.caps : null;
|
|
206
|
+
const gone = (cap) => !!caps && caps.indexOf(cap) < 0 && !(cap === "artifact" && caps.indexOf("self") >= 0);
|
|
207
|
+
for (const [id, p] of [...pending]) {
|
|
208
|
+
if (gone(p.cap) && p.cap === "db") {
|
|
209
|
+
pending.delete(id);
|
|
210
|
+
p.reject({ code: "revoked", message: "The document store is no longer available to this artifact." });
|
|
211
|
+
} else if (changed && !(p.cap === "artifact" && p.method === "publish")) {
|
|
212
|
+
pending.delete(id);
|
|
213
|
+
if (p.cap === "user") p.resolve(null);
|
|
214
|
+
else p.reject({ code: p.cap === "db" || p.cap === "downloads" ? "unavailable" : "upstream_error", message: REWIRED_MESSAGE });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (gone("db")) for (const s of [...dbSubs.values()]) s.revoke();
|
|
218
|
+
else if (changed) for (const s of dbSubs.values()) s.resubscribe();
|
|
219
|
+
if (gone("room")) {
|
|
220
|
+
connected = false;
|
|
221
|
+
for (const fn of connHandlers) safely(fn, false);
|
|
222
|
+
}
|
|
223
|
+
if (changed || gone("sample")) sampleModule?.rewired(REWIRED_MESSAGE);
|
|
224
|
+
if (changed || gone("mcp")) mcpModule?.rewired(REWIRED_MESSAGE, gone("mcp"));
|
|
225
|
+
}
|
|
226
|
+
function connect() {
|
|
227
|
+
if (!framed) return finishInit(null);
|
|
228
|
+
let tries = 0;
|
|
229
|
+
const tick = () => {
|
|
230
|
+
if (initDone) return;
|
|
231
|
+
post({ __frame_connect: true, contract: boot.contract, key: boot.key });
|
|
232
|
+
if (++tries * 400 < INIT_TIMEOUT_MS) setTimeout(tick, 400);
|
|
233
|
+
else finishInit(null);
|
|
234
|
+
};
|
|
235
|
+
tick();
|
|
236
|
+
}
|
|
237
|
+
function safely(fn, ...args) {
|
|
238
|
+
try {
|
|
239
|
+
fn(...args);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
setTimeout(() => {
|
|
242
|
+
throw e;
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const SEG = /^[A-Za-z0-9_\-.~:@+]+$/;
|
|
247
|
+
const enc = new TextEncoder();
|
|
248
|
+
function segsOf(path, kind) {
|
|
249
|
+
if (typeof path !== "string") throw new TypeError("A db path is a string.");
|
|
250
|
+
const t = path;
|
|
251
|
+
if (!t) throw new TypeError("An empty db path.");
|
|
252
|
+
if (enc.encode(t).length > 1e3) throw new TypeError("A db path is at most 1000 bytes.");
|
|
253
|
+
const segs = t.split("/");
|
|
254
|
+
if (segs.length > 16) throw new TypeError("A db path has at most 16 segments.");
|
|
255
|
+
for (const s of segs) {
|
|
256
|
+
if (!SEG.test(s) || s === "." || s === ".." || enc.encode(s).length > 200) throw new TypeError(`Bad db path segment ${JSON.stringify(s)}.`);
|
|
257
|
+
}
|
|
258
|
+
if (kind === "doc" && segs.length % 2 !== 0) throw new TypeError(`${t} names a collection, not a document.`);
|
|
259
|
+
if (kind === "collection" && segs.length % 2 !== 1) throw new TypeError(`${t} names a document, not a collection.`);
|
|
260
|
+
return segs;
|
|
261
|
+
}
|
|
262
|
+
const clone = (value) => value === void 0 ? value : JSON.parse(JSON.stringify(value));
|
|
263
|
+
function fieldOf(data, field) {
|
|
264
|
+
let value = data;
|
|
265
|
+
for (const key of String(field).split(".")) {
|
|
266
|
+
if (!value || typeof value !== "object" || !Object.hasOwn(value, key)) return void 0;
|
|
267
|
+
value = value[key];
|
|
268
|
+
}
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
271
|
+
const META = Object.freeze({ fromCache: false, hasPendingWrites: false });
|
|
272
|
+
function freezeData(value) {
|
|
273
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
274
|
+
for (const child of Object.values(value)) freezeData(child);
|
|
275
|
+
Object.freeze(value);
|
|
276
|
+
}
|
|
277
|
+
return value;
|
|
278
|
+
}
|
|
279
|
+
function sameData(left, right) {
|
|
280
|
+
if (left === right) return true;
|
|
281
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
282
|
+
return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, i) => sameData(item, right[i]));
|
|
283
|
+
}
|
|
284
|
+
if (!isRecord(left) || !isRecord(right)) return false;
|
|
285
|
+
const keys = Object.keys(left);
|
|
286
|
+
return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && sameData(left[key], right[key]));
|
|
287
|
+
}
|
|
288
|
+
function docSnap(ref, data) {
|
|
289
|
+
const value = freezeData(data);
|
|
290
|
+
return Object.freeze({
|
|
291
|
+
id: ref.id,
|
|
292
|
+
ref,
|
|
293
|
+
exists: data !== void 0,
|
|
294
|
+
metadata: META,
|
|
295
|
+
data: () => value,
|
|
296
|
+
get: (field) => fieldOf(value, field)
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
const dbCall = (method, arg) => call("db", method, arg, "DbError");
|
|
300
|
+
function observer(next, error) {
|
|
301
|
+
const handler = typeof next === "function" ? next : next?.next?.bind(next);
|
|
302
|
+
if (typeof handler !== "function") throw new TypeError("onSnapshot needs a callback.");
|
|
303
|
+
const onError = typeof next === "object" ? next?.error?.bind(next) : error;
|
|
304
|
+
return { next: handler, error: onError ?? ((reason) => {
|
|
305
|
+
throw reason;
|
|
306
|
+
}) };
|
|
307
|
+
}
|
|
308
|
+
function subscribe(kind, path, spec, onData, onError) {
|
|
309
|
+
const id = `sub${++seq}`;
|
|
310
|
+
let active = true;
|
|
311
|
+
let generation = 0;
|
|
312
|
+
const stop = () => {
|
|
313
|
+
if (!active) return;
|
|
314
|
+
active = false;
|
|
315
|
+
if (dbSubs.delete(id)) dbCall("unsubscribe", { sub: id }).catch(() => {
|
|
316
|
+
});
|
|
317
|
+
};
|
|
318
|
+
const fail = (error) => {
|
|
319
|
+
if (!active) return;
|
|
320
|
+
stop();
|
|
321
|
+
safely(onError, error);
|
|
322
|
+
};
|
|
323
|
+
if (dbSubs.size >= 64) {
|
|
324
|
+
queueMicrotask(() => fail(frameError("resource_exhausted", "At most 64 db subscriptions.", null, "DbError")));
|
|
325
|
+
return stop;
|
|
326
|
+
}
|
|
327
|
+
const start = () => {
|
|
328
|
+
const current = ++generation;
|
|
329
|
+
dbCall("subscribe", { sub: id, kind, path, spec }).catch((error) => {
|
|
330
|
+
if (current === generation) fail(error);
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
dbSubs.set(id, {
|
|
334
|
+
deliver: (event) => {
|
|
335
|
+
if (event.error) {
|
|
336
|
+
const reason = isRecord(event.error) ? event.error : {};
|
|
337
|
+
fail(frameError(reason.code, reason.message, null, "DbError"));
|
|
338
|
+
} else onData(event);
|
|
339
|
+
},
|
|
340
|
+
resubscribe: start,
|
|
341
|
+
revoke: () => fail(frameError("revoked", "The document store is no longer available to this artifact.", null, "DbError"))
|
|
342
|
+
});
|
|
343
|
+
start();
|
|
344
|
+
return stop;
|
|
345
|
+
}
|
|
346
|
+
let holder = null;
|
|
347
|
+
const holderId = () => holder ||= `tab-${Math.random().toString(36).slice(2, 10)}`;
|
|
348
|
+
function docRef(path) {
|
|
349
|
+
const segs = segsOf(path, "doc");
|
|
350
|
+
const full = segs.join("/");
|
|
351
|
+
const ref = {
|
|
352
|
+
id: segs[segs.length - 1],
|
|
353
|
+
path: full,
|
|
354
|
+
get parent() {
|
|
355
|
+
return collectionRef(segs.slice(0, -1).join("/"));
|
|
356
|
+
},
|
|
357
|
+
collection: (sub) => collectionRef(`${full}/${sub}`),
|
|
358
|
+
get: () => dbCall("get", { path: full }).then((r) => docSnap(ref, r && r.exists ? r.data : void 0)),
|
|
359
|
+
set: (data) => dbCall("set", { path: full, data: clone(data) }).then(() => {
|
|
360
|
+
}),
|
|
361
|
+
update: (data) => dbCall("update", { path: full, data: clone(data) }).then(() => {
|
|
362
|
+
}),
|
|
363
|
+
delete: () => dbCall("delete", { path: full }).then(() => {
|
|
364
|
+
}),
|
|
365
|
+
acquire: (opts) => {
|
|
366
|
+
const o = opts || {};
|
|
367
|
+
return dbCall("acquire", { path: full, options: { holder: o.holder || holderId(), ttlMs: o.ttlMs === void 0 ? 3e4 : o.ttlMs, data: o.data } });
|
|
368
|
+
},
|
|
369
|
+
release: (h) => dbCall("release", { path: full, holder: h || holderId() }),
|
|
370
|
+
onSnapshot: (next, error) => {
|
|
371
|
+
const o = observer(next, error);
|
|
372
|
+
let previous;
|
|
373
|
+
return subscribe("doc", full, null, (d) => {
|
|
374
|
+
const data = d.exists && isDocumentData(d.data) ? d.data : void 0;
|
|
375
|
+
if (!previous || !sameData(previous.data(), data)) {
|
|
376
|
+
previous = docSnap(ref, data);
|
|
377
|
+
o.next(previous);
|
|
378
|
+
}
|
|
379
|
+
}, o.error);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
return ref;
|
|
383
|
+
}
|
|
384
|
+
function isDocumentData(value) {
|
|
385
|
+
return isRecord(value) && !Array.isArray(value);
|
|
386
|
+
}
|
|
387
|
+
function isDbRow(value) {
|
|
388
|
+
return isRecord(value) && typeof value.id === "string" && isDocumentData(value.data);
|
|
389
|
+
}
|
|
390
|
+
function querySnapshot(path, rows, previous) {
|
|
391
|
+
const old = new Map(previous?.map((doc) => [doc.id, doc]));
|
|
392
|
+
const next = Object.freeze(rows.map(({ id, data }) => {
|
|
393
|
+
const doc = old.get(id);
|
|
394
|
+
return doc && sameData(data, doc.data()) ? doc : docSnap(docRef(`${path}/${id}`), data);
|
|
395
|
+
}));
|
|
396
|
+
const retained = new Set(next.map((doc) => doc.id));
|
|
397
|
+
const order = previous?.map((doc) => doc.id) ?? [];
|
|
398
|
+
const changes = [];
|
|
399
|
+
for (let i = order.length - 1; i >= 0; i--) {
|
|
400
|
+
const id = order[i];
|
|
401
|
+
if (retained.has(id)) continue;
|
|
402
|
+
changes.push(Object.freeze({ type: "removed", doc: old.get(id), oldIndex: i, newIndex: -1 }));
|
|
403
|
+
order.splice(i, 1);
|
|
404
|
+
}
|
|
405
|
+
next.forEach((doc, newIndex) => {
|
|
406
|
+
const oldIndex = order[newIndex] === doc.id ? newIndex : order.indexOf(doc.id, newIndex);
|
|
407
|
+
if (oldIndex === newIndex && old.get(doc.id) === doc) return;
|
|
408
|
+
if (oldIndex >= 0) order.splice(oldIndex, 1);
|
|
409
|
+
order.splice(newIndex, 0, doc.id);
|
|
410
|
+
changes.push(Object.freeze({ type: oldIndex === -1 ? "added" : "modified", doc, oldIndex, newIndex }));
|
|
411
|
+
});
|
|
412
|
+
const frozenChanges = Object.freeze(changes);
|
|
413
|
+
return Object.freeze({
|
|
414
|
+
docs: next,
|
|
415
|
+
size: next.length,
|
|
416
|
+
empty: next.length === 0,
|
|
417
|
+
metadata: META,
|
|
418
|
+
forEach: (fn, thisArg) => next.forEach(fn, thisArg),
|
|
419
|
+
docChanges: () => frozenChanges
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
const OPS = ["==", "!=", "<", "<=", ">", ">=", "in", "not-in", "array-contains"];
|
|
423
|
+
function query(path, spec) {
|
|
424
|
+
return {
|
|
425
|
+
where: (field, op, value) => {
|
|
426
|
+
if (OPS.indexOf(op) < 0) throw new TypeError(`where(): unknown operator ${op}`);
|
|
427
|
+
return query(path, { ...spec, where: (spec.where || []).concat([{ field: String(field), op, value: clone(value) }]) });
|
|
428
|
+
},
|
|
429
|
+
orderBy: (field, dir) => {
|
|
430
|
+
if (spec.orderBy) throw new TypeError("One orderBy() per query.");
|
|
431
|
+
return query(path, { ...spec, orderBy: { field: String(field), dir: dir === "desc" ? "desc" : "asc" } });
|
|
432
|
+
},
|
|
433
|
+
limit: (n) => {
|
|
434
|
+
if (!Number.isInteger(n) || n < 1 || n > 1e3) throw new TypeError("limit() takes 1 to 1000.");
|
|
435
|
+
return query(path, { ...spec, limit: n });
|
|
436
|
+
},
|
|
437
|
+
get: () => dbCall("query", { path, spec }).then((r) => querySnapshot(path, r && r.docs || [], null)),
|
|
438
|
+
onSnapshot: (next, error) => {
|
|
439
|
+
const o = observer(next, error);
|
|
440
|
+
let prev = null;
|
|
441
|
+
return subscribe(
|
|
442
|
+
"query",
|
|
443
|
+
path,
|
|
444
|
+
spec,
|
|
445
|
+
(d) => {
|
|
446
|
+
const docs = d.docs || [];
|
|
447
|
+
if (!Array.isArray(docs) || !docs.every(isDbRow)) return;
|
|
448
|
+
const snap = querySnapshot(path, docs, prev);
|
|
449
|
+
const first = prev === null;
|
|
450
|
+
prev = snap.docs;
|
|
451
|
+
if (first || snap.docChanges().length) o.next(snap);
|
|
452
|
+
},
|
|
453
|
+
o.error
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
function collectionRef(path) {
|
|
459
|
+
const segs = segsOf(path, "collection");
|
|
460
|
+
const full = segs.join("/");
|
|
461
|
+
const collection = Object.assign(query(full, {}), { id: segs[segs.length - 1], path: full });
|
|
462
|
+
const withParent = Object.defineProperty(
|
|
463
|
+
collection,
|
|
464
|
+
"parent",
|
|
465
|
+
{ get: () => segs.length > 1 ? docRef(segs.slice(0, -1).join("/")) : null }
|
|
466
|
+
);
|
|
467
|
+
return Object.assign(withParent, {
|
|
468
|
+
doc(id) {
|
|
469
|
+
const key = id === void 0 ? Array.from(crypto.getRandomValues(new Uint8Array(20)), (byte) => (byte % 36).toString(36)).join("") : id;
|
|
470
|
+
if (typeof key !== "string" || !SEG.test(key)) throw new TypeError("A document id must be one path segment.");
|
|
471
|
+
return docRef(`${full}/${key}`);
|
|
472
|
+
},
|
|
473
|
+
add: (data) => dbCall("add", { path: full, data: clone(data) }).then((r) => docRef(r.path))
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
const network = {
|
|
477
|
+
async origins() {
|
|
478
|
+
await whenInit();
|
|
479
|
+
const origins = configs.network?.origins;
|
|
480
|
+
return Array.isArray(origins) && origins.every((value) => typeof value === "string") ? [...origins] : [];
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
const db = {
|
|
484
|
+
collection: (path) => collectionRef(path),
|
|
485
|
+
doc: (path) => docRef(path)
|
|
486
|
+
};
|
|
487
|
+
function bytesToB64(bytes) {
|
|
488
|
+
let out = "";
|
|
489
|
+
for (let i = 0; i < bytes.length; i += 32768) out += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + 32768)));
|
|
490
|
+
return btoa(out);
|
|
491
|
+
}
|
|
492
|
+
async function encodeContent(value) {
|
|
493
|
+
if (typeof value === "string") return { text: value };
|
|
494
|
+
if (value instanceof Blob) return { b64: bytesToB64(new Uint8Array(await value.arrayBuffer())), ...value.type ? { contentType: value.type } : {} };
|
|
495
|
+
if (value instanceof ArrayBuffer) return { b64: bytesToB64(new Uint8Array(value)) };
|
|
496
|
+
if (ArrayBuffer.isView(value)) return { b64: bytesToB64(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)) };
|
|
497
|
+
throw frameError("invalid_content", "A file is a string, Blob or bytes.");
|
|
498
|
+
}
|
|
499
|
+
const isBytes = (v) => v instanceof Blob || v instanceof ArrayBuffer || ArrayBuffer.isView(v);
|
|
500
|
+
async function publish(files, opts) {
|
|
501
|
+
if (typeof files === "string") return call("artifact", "publish", { html: files, ver: pageVer });
|
|
502
|
+
if (!files || typeof files !== "object") throw frameError("invalid_content", "publish() takes a map of files.");
|
|
503
|
+
const guards = opts && opts.ifMatch && typeof opts.ifMatch === "object" ? opts.ifMatch : null;
|
|
504
|
+
const paths = Object.keys(files);
|
|
505
|
+
if (paths.length < 1 || paths.length > 256) throw frameError("too_large", "publish() takes 1 to 256 paths.");
|
|
506
|
+
const out = {};
|
|
507
|
+
for (const p of paths) {
|
|
508
|
+
const v = files[p];
|
|
509
|
+
const guard = guards && Object.prototype.hasOwnProperty.call(guards, p) ? { ifMatch: guards[p] } : {};
|
|
510
|
+
if (v === null) out[p] = { delete: true, ...guard };
|
|
511
|
+
else if (v && typeof v === "object" && !isBytes(v)) {
|
|
512
|
+
const g = "ifMatch" in v ? { ifMatch: v.ifMatch } : guard;
|
|
513
|
+
if ("delete" in v && v.delete === true) out[p] = { delete: true, ...g };
|
|
514
|
+
else out[p] = { ...await encodeContent("content" in v ? v.content : void 0), ..."contentType" in v && v.contentType ? { contentType: v.contentType } : {}, ...g };
|
|
515
|
+
} else out[p] = { ...await encodeContent(v), ...guard };
|
|
516
|
+
}
|
|
517
|
+
const result = await call("artifact", "publish", { files: out });
|
|
518
|
+
if (result && typeof result.version === "string" && result.version) pageVer = result.version;
|
|
519
|
+
return result;
|
|
520
|
+
}
|
|
521
|
+
const self = {
|
|
522
|
+
get id() {
|
|
523
|
+
const id = configs.artifact?.id;
|
|
524
|
+
return typeof id === "string" && id ? id : boot.id;
|
|
525
|
+
},
|
|
526
|
+
publish,
|
|
527
|
+
sync: () => call("artifact", "sync", {}),
|
|
528
|
+
metadata: (refs) => call("artifact", "metadata", { refs: Array.isArray(refs) ? refs : [refs] }),
|
|
529
|
+
search: (q, o) => call("artifact", "search", { q: String(q || ""), ...o || {} }),
|
|
530
|
+
edit: () => Promise.reject(frameError("capability_disabled", "edit() is for live documents; publish the files instead."))
|
|
531
|
+
};
|
|
532
|
+
const assets = {
|
|
533
|
+
upload: (blob, opts) => {
|
|
534
|
+
if (!(blob instanceof Blob)) return Promise.reject(frameError("invalid_request", "upload() takes a Blob."));
|
|
535
|
+
return call("assets", "upload", { blob, type: opts && opts.type || blob.type || "" });
|
|
536
|
+
},
|
|
537
|
+
list: () => call("assets", "list", {}),
|
|
538
|
+
delete: (ref) => call("assets", "delete", { ref: typeof ref === "object" && ref ? ref.id || ref.url : ref })
|
|
539
|
+
};
|
|
540
|
+
const downloads = {
|
|
541
|
+
save: (opts) => {
|
|
542
|
+
const o = opts || {};
|
|
543
|
+
const filename = String(o.filename || "download").replace(/[\\/:*?"<>|\u0000-\u001f]+/g, "_").slice(0, 200) || "download";
|
|
544
|
+
const data = o.data;
|
|
545
|
+
const blob = data instanceof Blob ? data : new Blob([typeof data === "string" || data instanceof ArrayBuffer || ArrayBuffer.isView(data) ? data : JSON.stringify(data)]);
|
|
546
|
+
try {
|
|
547
|
+
const url = URL.createObjectURL(blob);
|
|
548
|
+
const a = document.createElement("a");
|
|
549
|
+
a.href = url;
|
|
550
|
+
a.download = filename;
|
|
551
|
+
a.rel = "noopener";
|
|
552
|
+
a.style.display = "none";
|
|
553
|
+
(document.body || document.documentElement).appendChild(a);
|
|
554
|
+
a.click();
|
|
555
|
+
a.remove();
|
|
556
|
+
setTimeout(() => URL.revokeObjectURL(url), 6e4);
|
|
557
|
+
if (typeof o.request === "string") post({ __open_artifacts_export_done: true, request: o.request });
|
|
558
|
+
return Promise.resolve({ status: "saved" });
|
|
559
|
+
} catch (e) {
|
|
560
|
+
return Promise.reject(frameError("unavailable", String(e?.message || e)));
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
const samplePermission = (method) => call("sample", method, {}).then(
|
|
565
|
+
(state) => state === "granted" || state === "denied" || state === "prompt" ? state : "prompt",
|
|
566
|
+
() => "unavailable"
|
|
567
|
+
);
|
|
568
|
+
function permissionState(name) {
|
|
569
|
+
if (name === "sample" && grants.indexOf("sample") >= 0) return samplePermission("state");
|
|
570
|
+
if (name.startsWith("mcp:") && grants.indexOf("mcp") >= 0) return mcpPermission(name.slice(4));
|
|
571
|
+
if (grants.indexOf(name === "self" ? "artifact" : name) >= 0) return Promise.resolve("granted");
|
|
572
|
+
const perms = navigator.permissions;
|
|
573
|
+
if (perms && typeof perms.query === "function") {
|
|
574
|
+
return perms.query({ name }).then(
|
|
575
|
+
(s) => s.state,
|
|
576
|
+
() => "unavailable"
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
return Promise.resolve("unavailable");
|
|
580
|
+
}
|
|
581
|
+
async function permissionMap(list, request = false) {
|
|
582
|
+
const out = {};
|
|
583
|
+
await Promise.all(list.map(async (n) => out[String(n)] = request && String(n) === "sample" && grants.indexOf("sample") >= 0 ? await samplePermission("request") : await permissionState(String(n))));
|
|
584
|
+
return out;
|
|
585
|
+
}
|
|
586
|
+
function stateOfPermissions(name) {
|
|
587
|
+
return name === void 0 ? permissionMap(grants) : permissionState(String(name));
|
|
588
|
+
}
|
|
589
|
+
const permissions = {
|
|
590
|
+
state: stateOfPermissions,
|
|
591
|
+
// `sample` only when named: a bare request() asks the person nothing.
|
|
592
|
+
request: (names) => names === void 0 ? permissionMap(grants) : permissionMap(Array.isArray(names) ? names : [names], true),
|
|
593
|
+
// The Shell's AI models panel, for a page that declares `sample`; nothing else to manage here.
|
|
594
|
+
manage: () => grants.indexOf("sample") >= 0 ? call("sample", "manage", {}).then(() => void 0, () => void 0) : Promise.resolve()
|
|
595
|
+
};
|
|
596
|
+
const FALLBACK_COLOR = "#c7c9d1";
|
|
597
|
+
const userConfig = async () => {
|
|
598
|
+
await whenInit();
|
|
599
|
+
return configs.user || {};
|
|
600
|
+
};
|
|
601
|
+
let profileCache = null;
|
|
602
|
+
const profile = () => profileCache ||= userConfig().then(
|
|
603
|
+
(c) => c.profile === true ? call("user", "profile", {}).catch(() => {
|
|
604
|
+
profileCache = null;
|
|
605
|
+
return {};
|
|
606
|
+
}) : {}
|
|
607
|
+
);
|
|
608
|
+
const colorOf = (c) => typeof c.color === "string" && /^#[0-9a-f]{6}$/.test(c.color) ? c.color : FALLBACK_COLOR;
|
|
609
|
+
const user = {
|
|
610
|
+
id: () => userConfig().then((c) => typeof c.id === "string" ? c.id : null),
|
|
611
|
+
isOwner: () => userConfig().then((c) => c.owner === true),
|
|
612
|
+
canEdit: () => userConfig().then((c) => c.canEdit === true),
|
|
613
|
+
// Here: with no `can` list, the owner can do anything; otherwise permissions are checked.
|
|
614
|
+
can: (permission) => userConfig().then((c) => Array.isArray(c.can) ? typeof permission === "string" && c.can.indexOf(permission) >= 0 : c.owner === true ? typeof permission === "string" && permission.length > 0 : null),
|
|
615
|
+
me: () => Promise.all([userConfig(), profile(), user.email()]).then(
|
|
616
|
+
([c, p, email]) => ({ id: typeof c.id === "string" ? c.id : null, name: p?.name ?? "", avatarUrl: p?.avatarUrl ?? null, color: colorOf(c), email, isOwner: c.owner === true, canEdit: c.canEdit === true }),
|
|
617
|
+
() => ({ id: null, name: "", avatarUrl: null, color: FALLBACK_COLOR, email: null, isOwner: false, canEdit: false })
|
|
618
|
+
),
|
|
619
|
+
name: () => profile().then((p) => p?.name ?? "", () => ""),
|
|
620
|
+
avatarUrl: () => profile().then((p) => p?.avatarUrl ?? null, () => null),
|
|
621
|
+
email: () => userConfig().then((c) => c.email === true ? call("user", "email", {}) : null).catch(() => null),
|
|
622
|
+
profiles: (ids) => call("user", "profiles", { ids: Array.isArray(ids) ? ids : [ids] }).catch(() => ({})),
|
|
623
|
+
access: (ids) => call("user", "access", { ids: Array.isArray(ids) ? ids : [ids] }).catch(() => ({})),
|
|
624
|
+
search: (q) => call("user", "search", { q: String(q || "") }).catch(() => [])
|
|
625
|
+
};
|
|
626
|
+
let peersNow = [];
|
|
627
|
+
let connected = false;
|
|
628
|
+
function isRoomPeer(value) {
|
|
629
|
+
return isRecord(value) && typeof value.peer === "string" && (value.by === null || typeof value.by === "string") && typeof value.name === "string" && value.kind === "user" && isRecord(value.presence);
|
|
630
|
+
}
|
|
631
|
+
function onRoomEvent(d) {
|
|
632
|
+
if (d.kind === "msg") {
|
|
633
|
+
if (typeof d.topic !== "string" || typeof d.from !== "string" || !(d.by === null || typeof d.by === "string")) return;
|
|
634
|
+
const listeners = roomHandlers.get(d.topic);
|
|
635
|
+
if (!listeners) return;
|
|
636
|
+
const mine = !!init && d.from === init.client;
|
|
637
|
+
const sender = { peer: d.from, by: d.by, isMe: mine, sameTab: mine, kind: "user", guest: false };
|
|
638
|
+
for (const listener of listeners) safely(listener, clone(d.data), { ...sender });
|
|
639
|
+
} else if (d.kind === "peers") {
|
|
640
|
+
const peers = Array.isArray(d.peers) ? d.peers : [];
|
|
641
|
+
peersNow = peers.filter(isRoomPeer).map((peer) => ({ ...peer, isMe: !!init && peer.peer === init.client }));
|
|
642
|
+
for (const fn of peerHandlers) safely(fn, peersNow.slice());
|
|
643
|
+
} else if (d.kind === "connection") {
|
|
644
|
+
connected = !!d.connected;
|
|
645
|
+
for (const fn of connHandlers) safely(fn, connected);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
function makeRoom(prefix) {
|
|
649
|
+
const t = (topic) => prefix + String(topic);
|
|
650
|
+
return {
|
|
651
|
+
emit: (topic, data) => call("room", "emit", { topic: t(topic), data: clone(data) }),
|
|
652
|
+
on: (topic, handler) => {
|
|
653
|
+
const key = t(topic);
|
|
654
|
+
if (!roomHandlers.has(key)) roomHandlers.set(key, /* @__PURE__ */ new Set());
|
|
655
|
+
roomHandlers.get(key).add(handler);
|
|
656
|
+
return () => roomHandlers.get(key)?.delete(handler);
|
|
657
|
+
},
|
|
658
|
+
presence: (patch) => call("room", "presence", { patch: clone(patch || {}) }),
|
|
659
|
+
peers: () => peersNow.slice(),
|
|
660
|
+
onPeers: (fn) => {
|
|
661
|
+
peerHandlers.add(fn);
|
|
662
|
+
return () => peerHandlers.delete(fn);
|
|
663
|
+
},
|
|
664
|
+
connected: () => connected,
|
|
665
|
+
onConnection: (fn) => {
|
|
666
|
+
connHandlers.add(fn);
|
|
667
|
+
return () => connHandlers.delete(fn);
|
|
668
|
+
},
|
|
669
|
+
sendToAgentSession: (data, opts) => {
|
|
670
|
+
const o = opts || {};
|
|
671
|
+
const report = typeof o.onStatus === "function" ? o.onStatus : () => {
|
|
672
|
+
};
|
|
673
|
+
report("sending");
|
|
674
|
+
return call("room", "sendToAgentSession", { data: clone(data), deliver: o.deliver === "stage" ? "stage" : "send" }).then(
|
|
675
|
+
(r) => {
|
|
676
|
+
report("sent");
|
|
677
|
+
return r;
|
|
678
|
+
},
|
|
679
|
+
(e) => {
|
|
680
|
+
report("failed");
|
|
681
|
+
throw e;
|
|
682
|
+
}
|
|
683
|
+
);
|
|
684
|
+
},
|
|
685
|
+
canSendToAgentSession: () => call("room", "canSendToAgentSession", {}),
|
|
686
|
+
join: (name) => makeRoom(`${prefix}${String(name)}/`)
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
const room = makeRoom("");
|
|
690
|
+
function cssPath(start) {
|
|
691
|
+
const parts = [];
|
|
692
|
+
let el = start;
|
|
693
|
+
while (el && el.nodeType === 1 && el !== document.documentElement && parts.length < 12) {
|
|
694
|
+
if (el.id && /^[A-Za-z][\w-]*$/.test(el.id)) {
|
|
695
|
+
parts.unshift(`#${el.id}`);
|
|
696
|
+
break;
|
|
697
|
+
}
|
|
698
|
+
let i = 1;
|
|
699
|
+
let sib = el.previousElementSibling;
|
|
700
|
+
for (; sib; sib = sib.previousElementSibling) if (sib.tagName === el.tagName) i++;
|
|
701
|
+
parts.unshift(`${el.tagName.toLowerCase()}:nth-of-type(${i})`);
|
|
702
|
+
el = el.parentElement;
|
|
703
|
+
}
|
|
704
|
+
return parts.join(" > ");
|
|
705
|
+
}
|
|
706
|
+
function anchorFor(el, ev) {
|
|
707
|
+
if (!el || !el.getBoundingClientRect) return { path: "", x: 0.5, y: 0.5 };
|
|
708
|
+
const r = el.getBoundingClientRect();
|
|
709
|
+
const x = ev && r.width ? (ev.clientX - r.left) / r.width : 0.5;
|
|
710
|
+
const y = ev && r.height ? (ev.clientY - r.top) / r.height : 0.5;
|
|
711
|
+
return { path: cssPath(el), x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
|
|
712
|
+
}
|
|
713
|
+
function labelFor(el) {
|
|
714
|
+
const text = String(el && (el.getAttribute("aria-label") || el.textContent) || "").replace(/\s+/g, " ").trim();
|
|
715
|
+
return text ? text.slice(0, 80) : el ? el.tagName.toLowerCase() : "the page";
|
|
716
|
+
}
|
|
717
|
+
function viewportPoint(at) {
|
|
718
|
+
if (!at) return null;
|
|
719
|
+
if (typeof Element !== "undefined" && at instanceof Element) {
|
|
720
|
+
const r = at.getBoundingClientRect();
|
|
721
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
|
722
|
+
}
|
|
723
|
+
return { x: (Number("x" in at ? at.x : 0) || 0) - window.scrollX, y: (Number("y" in at ? at.y : 0) || 0) - window.scrollY };
|
|
724
|
+
}
|
|
725
|
+
let placedDoc = null;
|
|
726
|
+
let shellThreads = [];
|
|
727
|
+
let fallbackDraft = null;
|
|
728
|
+
let placeFrame = 0;
|
|
729
|
+
let placeQueued = false;
|
|
730
|
+
let placeObserver = null;
|
|
731
|
+
function pinsShown() {
|
|
732
|
+
if (anchors) return !!placedDoc && (commentsMode || anchors.callbacks.pinsOutsideMode === true && shellThreads.length > 0);
|
|
733
|
+
return fallbackOn;
|
|
734
|
+
}
|
|
735
|
+
function fallbackPoint(anchor) {
|
|
736
|
+
if (!isRecord(anchor)) return null;
|
|
737
|
+
let el = null;
|
|
738
|
+
try {
|
|
739
|
+
el = anchor.path ? document.querySelector(String(anchor.path)) : document.documentElement;
|
|
740
|
+
} catch {
|
|
741
|
+
el = null;
|
|
742
|
+
}
|
|
743
|
+
if (!el) return null;
|
|
744
|
+
const r = el.getBoundingClientRect();
|
|
745
|
+
if (!r.width && !r.height) return null;
|
|
746
|
+
const fx = typeof anchor.x === "number" && Number.isFinite(anchor.x) ? anchor.x : 0.5;
|
|
747
|
+
const fy = typeof anchor.y === "number" && Number.isFinite(anchor.y) ? anchor.y : 0.5;
|
|
748
|
+
return { x: r.left + r.width * fx, y: r.top + r.height * fy };
|
|
749
|
+
}
|
|
750
|
+
function sendPlaced() {
|
|
751
|
+
placeQueued = false;
|
|
752
|
+
placeFrame = 0;
|
|
753
|
+
if (!pinsShown()) return;
|
|
754
|
+
const map = {};
|
|
755
|
+
if (anchors) {
|
|
756
|
+
for (const k of Object.keys(placedDoc || {})) map[k] = placedDoc[k] ? viewportPoint(placedDoc[k]) : null;
|
|
757
|
+
} else {
|
|
758
|
+
for (const t of shellThreads) map[t.id] = fallbackPoint(t.anchor);
|
|
759
|
+
if (fallbackDraft) map.composer = fallbackPoint(fallbackDraft);
|
|
760
|
+
}
|
|
761
|
+
post({ __open_artifacts_comments_placed: true, map });
|
|
762
|
+
}
|
|
763
|
+
function queuePlaced(frame = false) {
|
|
764
|
+
if (frame) {
|
|
765
|
+
if (!placeFrame) placeFrame = requestAnimationFrame(sendPlaced);
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
if (placeQueued) return;
|
|
769
|
+
placeQueued = true;
|
|
770
|
+
queueMicrotask(sendPlaced);
|
|
771
|
+
}
|
|
772
|
+
const onPlaceMove = () => {
|
|
773
|
+
if (pinsShown()) queuePlaced(true);
|
|
774
|
+
};
|
|
775
|
+
window.addEventListener("scroll", onPlaceMove, { capture: true, passive: true });
|
|
776
|
+
window.addEventListener("resize", onPlaceMove);
|
|
777
|
+
function watchLayout(on) {
|
|
778
|
+
if (on && !placeObserver && typeof MutationObserver === "function" && document.body) {
|
|
779
|
+
placeObserver = new MutationObserver(onPlaceMove);
|
|
780
|
+
placeObserver.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
781
|
+
} else if (!on && placeObserver) {
|
|
782
|
+
placeObserver.disconnect();
|
|
783
|
+
placeObserver = null;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
const sendListeners = /* @__PURE__ */ new Set();
|
|
787
|
+
function commentResponseText(value, maxBytes) {
|
|
788
|
+
if (typeof value !== "string" || value.length > maxBytes || !value.trim()) return void 0;
|
|
789
|
+
return enc.encode(value).length <= maxBytes ? value : void 0;
|
|
790
|
+
}
|
|
791
|
+
async function answerCommentSend(ticket, payload) {
|
|
792
|
+
let reply;
|
|
793
|
+
let handoffNote;
|
|
794
|
+
for (const listener of [...sendListeners]) {
|
|
795
|
+
if (!sendListeners.has(listener)) continue;
|
|
796
|
+
try {
|
|
797
|
+
const result = await listener(payload);
|
|
798
|
+
if (result?.handled === true) {
|
|
799
|
+
post({ __open_artifacts_comments_sent: true, ticket, handled: true, reply: commentResponseText(result.reply, 500) });
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
reply ??= commentResponseText(result?.reply, 500);
|
|
803
|
+
handoffNote ??= commentResponseText(result?.handoffNote, 2e3);
|
|
804
|
+
} catch {
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
post({ __open_artifacts_comments_sent: true, ticket, handled: false, reply, handoffNote });
|
|
808
|
+
}
|
|
809
|
+
let fallbackOn = false;
|
|
810
|
+
const COMMENT_CURSOR = 'url("data:image/svg+xml,%3Csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20width=%2728%27%20height=%2728%27%20viewBox=%270%200%2028%2028%27%3E%3Cpath%20d=%27M%202%2026%20L%202%2014%20A%2012%2012%200%201%201%2014%2026%20Z%27%20fill=%27%23000%27%20stroke=%27%23fff%27%20stroke-width=%272%27/%3E%3C/svg%3E") 2 26, crosshair';
|
|
811
|
+
let cursorStyle = null;
|
|
812
|
+
let hoverBox = null;
|
|
813
|
+
let hoverFrame = 0;
|
|
814
|
+
let hoverEvent = null;
|
|
815
|
+
function fallbackTarget(ev) {
|
|
816
|
+
const target = ev.target;
|
|
817
|
+
return target && target.nodeType === 1 ? target : target && target.parentElement || null;
|
|
818
|
+
}
|
|
819
|
+
function paintHover() {
|
|
820
|
+
hoverFrame = 0;
|
|
821
|
+
const ev = hoverEvent;
|
|
822
|
+
const el = ev ? fallbackTarget(ev) : null;
|
|
823
|
+
if (!el || el === document.documentElement || el === document.body || !el.getBoundingClientRect) {
|
|
824
|
+
if (hoverBox) hoverBox.style.display = "none";
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
if (!hoverBox) {
|
|
828
|
+
hoverBox = document.createElement("div");
|
|
829
|
+
hoverBox.setAttribute("aria-hidden", "true");
|
|
830
|
+
Object.assign(hoverBox.style, {
|
|
831
|
+
position: "fixed",
|
|
832
|
+
zIndex: "2147483647",
|
|
833
|
+
pointerEvents: "none",
|
|
834
|
+
boxSizing: "border-box",
|
|
835
|
+
border: "2px solid rgba(245, 158, 11, 0.8)",
|
|
836
|
+
borderRadius: "2px"
|
|
837
|
+
});
|
|
838
|
+
document.documentElement.append(hoverBox);
|
|
839
|
+
}
|
|
840
|
+
const r = el.getBoundingClientRect();
|
|
841
|
+
Object.assign(hoverBox.style, { display: "block", left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
|
842
|
+
}
|
|
843
|
+
function fallbackMove(ev) {
|
|
844
|
+
hoverEvent = ev;
|
|
845
|
+
if (!hoverFrame) hoverFrame = requestAnimationFrame(paintHover);
|
|
846
|
+
}
|
|
847
|
+
function fallbackLeave() {
|
|
848
|
+
hoverEvent = null;
|
|
849
|
+
if (hoverBox) hoverBox.style.display = "none";
|
|
850
|
+
}
|
|
851
|
+
function fallbackClick(ev) {
|
|
852
|
+
if (!commentsMode || anchors) return;
|
|
853
|
+
ev.preventDefault();
|
|
854
|
+
ev.stopPropagation();
|
|
855
|
+
const el = fallbackTarget(ev);
|
|
856
|
+
fallbackLeave();
|
|
857
|
+
const anchor = anchorFor(el, ev);
|
|
858
|
+
call("comments", "compose", { anchor, at: { x: ev.clientX, y: ev.clientY }, label: labelFor(el), click: true }).then((r) => {
|
|
859
|
+
fallbackDraft = r && r.opened ? anchor : null;
|
|
860
|
+
queuePlaced();
|
|
861
|
+
}).catch(() => {
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
function setFallback(on) {
|
|
865
|
+
if (on === fallbackOn) return;
|
|
866
|
+
fallbackOn = on;
|
|
867
|
+
if (on) {
|
|
868
|
+
document.addEventListener("click", fallbackClick, true);
|
|
869
|
+
document.addEventListener("mousemove", fallbackMove, true);
|
|
870
|
+
document.addEventListener("mouseleave", fallbackLeave);
|
|
871
|
+
document.addEventListener("scroll", fallbackLeave, true);
|
|
872
|
+
document.documentElement.style.cursor = COMMENT_CURSOR;
|
|
873
|
+
cursorStyle = document.createElement("style");
|
|
874
|
+
cursorStyle.textContent = `*, *::before, *::after { cursor: ${COMMENT_CURSOR} !important; }`;
|
|
875
|
+
document.head.append(cursorStyle);
|
|
876
|
+
watchLayout(true);
|
|
877
|
+
queuePlaced();
|
|
878
|
+
} else {
|
|
879
|
+
document.removeEventListener("click", fallbackClick, true);
|
|
880
|
+
document.removeEventListener("mousemove", fallbackMove, true);
|
|
881
|
+
document.removeEventListener("mouseleave", fallbackLeave);
|
|
882
|
+
document.removeEventListener("scroll", fallbackLeave, true);
|
|
883
|
+
document.documentElement.style.cursor = "";
|
|
884
|
+
cursorStyle?.remove();
|
|
885
|
+
cursorStyle = null;
|
|
886
|
+
fallbackLeave();
|
|
887
|
+
watchLayout(false);
|
|
888
|
+
fallbackDraft = null;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
function onCommentsEvent(d) {
|
|
892
|
+
const cb = anchors && anchors.callbacks;
|
|
893
|
+
if (d.op === "mode") {
|
|
894
|
+
commentsMode = !!d.on;
|
|
895
|
+
if (cb && typeof cb.mode === "function") safely(() => cb.mode?.(commentsMode));
|
|
896
|
+
else if (!anchors) setFallback(commentsMode);
|
|
897
|
+
if (commentsMode) queuePlaced();
|
|
898
|
+
} else if (d.op === "threads") {
|
|
899
|
+
const rows = Array.isArray(d.threads) ? d.threads : [];
|
|
900
|
+
shellThreads = rows.filter(isRecord).map((t) => ({ id: String(t.id), anchor: t.anchor, resolved: !!t.resolved, active: !!t.active }));
|
|
901
|
+
if (cb && typeof cb.threads === "function") safely(() => cb.threads?.(shellThreads.map((t) => ({ ...t }))));
|
|
902
|
+
queuePlaced();
|
|
903
|
+
} else if (d.op === "reveal") {
|
|
904
|
+
const id = d.id;
|
|
905
|
+
if (cb && typeof cb.reveal === "function" && typeof id === "string") safely(() => cb.reveal?.(id));
|
|
906
|
+
else if (!anchors) revealFallback(d.id);
|
|
907
|
+
} else if (d.op === "composing") {
|
|
908
|
+
if (d.state === false) fallbackDraft = null;
|
|
909
|
+
const state = typeof d.state === "boolean" ? d.state : null;
|
|
910
|
+
if (cb && typeof cb.composing === "function") safely(() => cb.composing?.(state));
|
|
911
|
+
} else if (d.op === "move") {
|
|
912
|
+
void answerMove(cb, d);
|
|
913
|
+
} else if (d.op === "send") {
|
|
914
|
+
if (typeof d.ticket !== "string" || !isRecord(d.payload)) return;
|
|
915
|
+
if (sendListeners.size) post({ __open_artifacts_comments_sent: true, ticket: d.ticket, pending: true });
|
|
916
|
+
void answerCommentSend(d.ticket, d.payload);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
function revealFallback(id) {
|
|
920
|
+
const t = shellThreads.find((x) => x.id === id);
|
|
921
|
+
if (!t || !isRecord(t.anchor)) return;
|
|
922
|
+
try {
|
|
923
|
+
const el = t.anchor.path ? document.querySelector(String(t.anchor.path)) : null;
|
|
924
|
+
el?.scrollIntoView({ block: "center", inline: "nearest" });
|
|
925
|
+
} catch {
|
|
926
|
+
}
|
|
927
|
+
queuePlaced(true);
|
|
928
|
+
}
|
|
929
|
+
async function answerMove(cb, d) {
|
|
930
|
+
const refuse = () => post({ __open_artifacts_comments_moved: true, n: d.n, refused: true });
|
|
931
|
+
if (!cb || typeof cb.move !== "function" || typeof d.x !== "number" || !Number.isFinite(d.x) || typeof d.y !== "number" || !Number.isFinite(d.y)) return refuse();
|
|
932
|
+
try {
|
|
933
|
+
const answer = await Promise.race([
|
|
934
|
+
Promise.resolve(cb.move(String(d.id), { x: d.x + window.scrollX, y: d.y + window.scrollY })),
|
|
935
|
+
new Promise((resolve) => setTimeout(() => resolve(null), 2e3))
|
|
936
|
+
]);
|
|
937
|
+
if (!answer || typeof answer !== "object" || typeof answer.anchor !== "string") return refuse();
|
|
938
|
+
post({
|
|
939
|
+
__open_artifacts_comments_moved: true,
|
|
940
|
+
n: d.n,
|
|
941
|
+
anchor: answer.anchor,
|
|
942
|
+
...typeof answer.label === "string" ? { label: answer.label } : {},
|
|
943
|
+
...typeof answer.detail === "string" ? { detail: answer.detail } : {}
|
|
944
|
+
});
|
|
945
|
+
} catch {
|
|
946
|
+
refuse();
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
document.addEventListener("keydown", (ev) => {
|
|
950
|
+
if (ev.key === "Escape" && commentsMode && !ev.defaultPrevented) post({ __frame_escape: true });
|
|
951
|
+
});
|
|
952
|
+
const comments = {
|
|
953
|
+
openComposer: (opts) => {
|
|
954
|
+
const el = opts && opts.element || null;
|
|
955
|
+
const r = el && el.getBoundingClientRect ? el.getBoundingClientRect() : null;
|
|
956
|
+
return call("comments", "compose", {
|
|
957
|
+
anchor: el ? anchorFor(el) : { path: "", x: 0.5, y: 0.5 },
|
|
958
|
+
at: r ? { x: r.left + r.width / 2, y: r.top + r.height / 2 } : null,
|
|
959
|
+
label: el ? labelFor(el) : "the page"
|
|
960
|
+
});
|
|
961
|
+
},
|
|
962
|
+
anchorFor: (el) => anchorFor(el),
|
|
963
|
+
create: (o) => call("comments", "create", { anchor: clone(o && o.anchor), text: o && o.text, label: o && o.label }).then((r) => ({ threadId: r.threadId, commentId: r.commentId })),
|
|
964
|
+
reply: (a, b) => {
|
|
965
|
+
const o = typeof a === "object" && a ? a : { threadId: a, text: b };
|
|
966
|
+
return call("comments", "reply", { threadId: o.threadId, text: o.text }).then((r) => ({ threadId: r.threadId, commentId: r.commentId }));
|
|
967
|
+
},
|
|
968
|
+
resolve: (threadId, resolved) => call("comments", "resolve", { threadId, resolved: resolved !== false }).then(() => {
|
|
969
|
+
}),
|
|
970
|
+
delete: (threadId, commentId) => call("comments", "delete", { threadId, commentId }).then(() => {
|
|
971
|
+
}),
|
|
972
|
+
list: () => call("comments", "list", {}).then((r) => r.threads),
|
|
973
|
+
sendToAgent: (o) => call("comments", "sendToAgent", clone(o || {})),
|
|
974
|
+
canSendToAgent: () => call("comments", "canSendToAgent", {}),
|
|
975
|
+
onSendToAgent: (fn) => {
|
|
976
|
+
sendListeners.add(fn);
|
|
977
|
+
return () => sendListeners.delete(fn);
|
|
978
|
+
},
|
|
979
|
+
customAnchors: (callbacks) => {
|
|
980
|
+
const mine = { callbacks: callbacks || {} };
|
|
981
|
+
anchors = mine;
|
|
982
|
+
placedDoc = null;
|
|
983
|
+
setFallback(false);
|
|
984
|
+
const ctl = {
|
|
985
|
+
// While registered, compose is the viewer's click (the shell turns comment mode on, or closes what is open).
|
|
986
|
+
compose: (anchor, at, opts) => {
|
|
987
|
+
const o = opts || {};
|
|
988
|
+
return call("comments", "compose", { anchor: clone(anchor), at: viewportPoint(at), label: o.label, detail: o.detail, area: !!o.area, click: true });
|
|
989
|
+
},
|
|
990
|
+
open: (id, at) => call("comments", "open", { id, at: viewportPoint(at) }),
|
|
991
|
+
// Kept in document points: reported now, and again on every scroll and resize.
|
|
992
|
+
placed: (map) => {
|
|
993
|
+
if (anchors !== mine) return;
|
|
994
|
+
const doc = {};
|
|
995
|
+
for (const k of Object.keys(map || {})) {
|
|
996
|
+
const v = map[k];
|
|
997
|
+
doc[k] = v && typeof v === "object" ? typeof Element !== "undefined" && v instanceof Element ? v : { x: Number("x" in v ? v.x : void 0), y: Number("y" in v ? v.y : void 0) } : null;
|
|
998
|
+
}
|
|
999
|
+
placedDoc = doc;
|
|
1000
|
+
queuePlaced();
|
|
1001
|
+
},
|
|
1002
|
+
domAnchor: (el, ev) => anchorFor(el, ev),
|
|
1003
|
+
exitMode: () => void call("comments", "mode", { on: false }).catch(() => {
|
|
1004
|
+
}),
|
|
1005
|
+
release: () => {
|
|
1006
|
+
if (anchors === mine) {
|
|
1007
|
+
anchors = null;
|
|
1008
|
+
placedDoc = null;
|
|
1009
|
+
setFallback(commentsMode);
|
|
1010
|
+
}
|
|
1011
|
+
call("comments", "custom", { on: false }).catch(() => {
|
|
1012
|
+
});
|
|
1013
|
+
},
|
|
1014
|
+
areas: void 0
|
|
1015
|
+
};
|
|
1016
|
+
return call("comments", "custom", { on: true, pins: callbacks && callbacks.pinsOutsideMode === true, move: !!callbacks && typeof callbacks.move === "function" }).then(() => ctl);
|
|
1017
|
+
}
|
|
1018
|
+
};
|
|
1019
|
+
let sampleModule = null;
|
|
1020
|
+
let sampleLoading = null;
|
|
1021
|
+
const sampleHost = {
|
|
1022
|
+
framed,
|
|
1023
|
+
config: () => configs.sample || {},
|
|
1024
|
+
budget: () => timeoutOf("sample", "sample")[0],
|
|
1025
|
+
id: () => {
|
|
1026
|
+
crypto.getRandomValues(salt);
|
|
1027
|
+
return `a${salt[0].toString(36)}.${++seq}`;
|
|
1028
|
+
},
|
|
1029
|
+
send: (id, method, args, activation) => {
|
|
1030
|
+
if (!framed) return false;
|
|
1031
|
+
const msg = { __frame_cap: true, cap: "sample", id, method, args };
|
|
1032
|
+
if (brokerGen !== void 0) msg.brokerGen = brokerGen;
|
|
1033
|
+
try {
|
|
1034
|
+
if (activation) parentWin.postMessage(msg, { targetOrigin: SHELL, includeUserActivation: true });
|
|
1035
|
+
else parentWin.postMessage(msg, SHELL);
|
|
1036
|
+
return true;
|
|
1037
|
+
} catch {
|
|
1038
|
+
return false;
|
|
1039
|
+
}
|
|
1040
|
+
},
|
|
1041
|
+
route: (id, handler) => {
|
|
1042
|
+
if (handler) sampleRoutes.set(id, handler);
|
|
1043
|
+
else sampleRoutes.delete(id);
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
function loadSample() {
|
|
1047
|
+
if (sampleModule) return Promise.resolve(sampleModule);
|
|
1048
|
+
if (sampleLoading) return sampleLoading;
|
|
1049
|
+
sampleLoading = new Promise((resolve) => {
|
|
1050
|
+
const slot = "__openArtifactsSample";
|
|
1051
|
+
let over = false;
|
|
1052
|
+
const done = () => {
|
|
1053
|
+
if (over) return;
|
|
1054
|
+
over = true;
|
|
1055
|
+
clearTimeout(timer);
|
|
1056
|
+
Reflect.deleteProperty(window, slot);
|
|
1057
|
+
if (!sampleModule) sampleLoading = null;
|
|
1058
|
+
resolve(sampleModule);
|
|
1059
|
+
};
|
|
1060
|
+
const timer = setTimeout(done, SAMPLE_LOAD_MS);
|
|
1061
|
+
Object.defineProperty(window, slot, {
|
|
1062
|
+
configurable: true,
|
|
1063
|
+
value: (factory) => {
|
|
1064
|
+
if (!sampleModule) sampleModule = factory(sampleHost);
|
|
1065
|
+
done();
|
|
1066
|
+
}
|
|
1067
|
+
});
|
|
1068
|
+
const script = document.createElement("script");
|
|
1069
|
+
script.src = SAMPLE_SRC;
|
|
1070
|
+
script.async = true;
|
|
1071
|
+
script.addEventListener("load", done);
|
|
1072
|
+
script.addEventListener("error", done);
|
|
1073
|
+
(document.head || document.documentElement).appendChild(script);
|
|
1074
|
+
});
|
|
1075
|
+
return sampleLoading;
|
|
1076
|
+
}
|
|
1077
|
+
const sampleMissing = () => Promise.reject({ code: "upstream_error", message: "The page side of sample did not load." });
|
|
1078
|
+
const abortedSignal = (options) => {
|
|
1079
|
+
try {
|
|
1080
|
+
return isRecord(options) && typeof AbortSignal !== "undefined" && options.signal instanceof AbortSignal && options.signal.aborted;
|
|
1081
|
+
} catch {
|
|
1082
|
+
return false;
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
let sampleEarly = 0;
|
|
1086
|
+
const sampleCall = (json) => (input, options) => {
|
|
1087
|
+
const aborted = abortedSignal(options);
|
|
1088
|
+
if (sampleModule) return sampleModule.call(input, options, json, aborted);
|
|
1089
|
+
if (sampleEarly >= SAMPLE_MAX_EARLY) {
|
|
1090
|
+
return Promise.reject({ code: "queue_overflow", message: `At most ${SAMPLE_MAX_EARLY} sample calls may wait while the page side of sample loads.` });
|
|
1091
|
+
}
|
|
1092
|
+
sampleEarly++;
|
|
1093
|
+
return loadSample().then(
|
|
1094
|
+
(m) => {
|
|
1095
|
+
sampleEarly--;
|
|
1096
|
+
return m ? m.call(input, options, json, aborted) : sampleMissing();
|
|
1097
|
+
},
|
|
1098
|
+
(error) => {
|
|
1099
|
+
sampleEarly--;
|
|
1100
|
+
throw error;
|
|
1101
|
+
}
|
|
1102
|
+
);
|
|
1103
|
+
};
|
|
1104
|
+
const sample = Object.freeze(
|
|
1105
|
+
Object.assign(sampleCall(false), {
|
|
1106
|
+
json: sampleCall(true),
|
|
1107
|
+
limits: () => sampleModule ? sampleModule.limits() : loadSample().then((m) => m ? m.limits() : sampleMissing())
|
|
1108
|
+
})
|
|
1109
|
+
);
|
|
1110
|
+
let mcpModule = null;
|
|
1111
|
+
let mcpLoading = null;
|
|
1112
|
+
const mcpHost = {
|
|
1113
|
+
framed,
|
|
1114
|
+
config: () => configs.mcp || {},
|
|
1115
|
+
id: () => {
|
|
1116
|
+
crypto.getRandomValues(salt);
|
|
1117
|
+
return `c${salt[0].toString(36)}.${++seq}`;
|
|
1118
|
+
},
|
|
1119
|
+
send: (id, method, args) => {
|
|
1120
|
+
if (!framed) return false;
|
|
1121
|
+
const msg = { __frame_cap: true, cap: "mcp", id, method, args };
|
|
1122
|
+
if (brokerGen !== void 0) msg.brokerGen = brokerGen;
|
|
1123
|
+
try {
|
|
1124
|
+
parentWin.postMessage(msg, SHELL);
|
|
1125
|
+
return true;
|
|
1126
|
+
} catch {
|
|
1127
|
+
return false;
|
|
1128
|
+
}
|
|
1129
|
+
},
|
|
1130
|
+
// The shell's answers about a call come back by its id, as sample's do.
|
|
1131
|
+
route: (id, handler) => sampleHost.route(id, handler)
|
|
1132
|
+
};
|
|
1133
|
+
function loadMcp() {
|
|
1134
|
+
if (mcpModule) return Promise.resolve(mcpModule);
|
|
1135
|
+
if (mcpLoading) return mcpLoading;
|
|
1136
|
+
mcpLoading = new Promise((resolve) => {
|
|
1137
|
+
const slot = "__openArtifactsMcp";
|
|
1138
|
+
let over = false;
|
|
1139
|
+
const done = () => {
|
|
1140
|
+
if (over) return;
|
|
1141
|
+
over = true;
|
|
1142
|
+
clearTimeout(timer);
|
|
1143
|
+
Reflect.deleteProperty(window, slot);
|
|
1144
|
+
if (!mcpModule) mcpLoading = null;
|
|
1145
|
+
resolve(mcpModule);
|
|
1146
|
+
};
|
|
1147
|
+
const timer = setTimeout(done, SAMPLE_LOAD_MS);
|
|
1148
|
+
Object.defineProperty(window, slot, {
|
|
1149
|
+
configurable: true,
|
|
1150
|
+
value: (factory) => {
|
|
1151
|
+
if (!mcpModule) mcpModule = factory(mcpHost);
|
|
1152
|
+
done();
|
|
1153
|
+
}
|
|
1154
|
+
});
|
|
1155
|
+
const script = document.createElement("script");
|
|
1156
|
+
script.src = MCP_SRC;
|
|
1157
|
+
script.async = true;
|
|
1158
|
+
script.addEventListener("load", done);
|
|
1159
|
+
script.addEventListener("error", done);
|
|
1160
|
+
(document.head || document.documentElement).appendChild(script);
|
|
1161
|
+
});
|
|
1162
|
+
return mcpLoading;
|
|
1163
|
+
}
|
|
1164
|
+
const mcpMissing = () => frameError("upstream_error", "The page side of mcp did not load.", { retryable: true }, "McpError");
|
|
1165
|
+
const viaMcp = (name) => (...args) => mcpModule ? mcpModule[name](...args) : loadMcp().then((m) => m ? m[name](...args) : Promise.reject(mcpMissing()));
|
|
1166
|
+
const mcpPermission = (server) => call("mcp", "state", {}).then(
|
|
1167
|
+
(state) => {
|
|
1168
|
+
const v = isRecord(state) && isRecord(state.servers) ? state.servers[server] : void 0;
|
|
1169
|
+
return v === "granted" || v === "denied" || v === "prompt" ? v : "unavailable";
|
|
1170
|
+
},
|
|
1171
|
+
() => "unavailable"
|
|
1172
|
+
);
|
|
1173
|
+
const mcp = Object.freeze({
|
|
1174
|
+
callTool: viaMcp("callTool"),
|
|
1175
|
+
listTools: viaMcp("listTools"),
|
|
1176
|
+
describeTool: viaMcp("describeTool"),
|
|
1177
|
+
invalidate: (...args) => {
|
|
1178
|
+
if (mcpModule) return mcpModule.invalidate(...args);
|
|
1179
|
+
void loadMcp().then((m) => m && m.invalidate(...args));
|
|
1180
|
+
},
|
|
1181
|
+
watchTool: (...args) => {
|
|
1182
|
+
if (mcpModule) return mcpModule.watchTool(...args);
|
|
1183
|
+
let stop = null;
|
|
1184
|
+
let off = false;
|
|
1185
|
+
void loadMcp().then((m) => {
|
|
1186
|
+
if (off) return;
|
|
1187
|
+
if (m) stop = m.watchTool(...args);
|
|
1188
|
+
else if (typeof args[3] === "function") args[3]({ type: "error", error: mcpMissing() });
|
|
1189
|
+
});
|
|
1190
|
+
return () => {
|
|
1191
|
+
off = true;
|
|
1192
|
+
stop?.();
|
|
1193
|
+
};
|
|
1194
|
+
},
|
|
1195
|
+
server: (name) => {
|
|
1196
|
+
if (typeof name !== "string" || !name) throw frameError("bad_request", "mcp.server(name): the connector's name, as declared.", null, "McpError");
|
|
1197
|
+
return new Proxy(Object.freeze({}), {
|
|
1198
|
+
get: (_t, tool) => {
|
|
1199
|
+
if (typeof tool !== "string" || tool === "then" || tool === "toJSON") return void 0;
|
|
1200
|
+
return (input, options) => mcp.callTool(name, tool, input, options).then((r) => isRecord(r) ? r.payload : r);
|
|
1201
|
+
}
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
function mcpStub() {
|
|
1206
|
+
const fail = (method) => () => call("mcp", method, {}, "McpError");
|
|
1207
|
+
const callTool = fail("callTool");
|
|
1208
|
+
return Object.freeze({
|
|
1209
|
+
callTool,
|
|
1210
|
+
listTools: fail("listTools"),
|
|
1211
|
+
describeTool: fail("describeTool"),
|
|
1212
|
+
invalidate: () => void 0,
|
|
1213
|
+
watchTool: (...args) => {
|
|
1214
|
+
const handler = args[3];
|
|
1215
|
+
if (typeof handler !== "function") throw frameError("bad_request", "watchTool(server, tool, input, handler, options?): handler is a function.", null, "McpError");
|
|
1216
|
+
let off = false;
|
|
1217
|
+
callTool().catch((error) => {
|
|
1218
|
+
if (off) return;
|
|
1219
|
+
try {
|
|
1220
|
+
handler({ type: "error", error });
|
|
1221
|
+
} catch (e) {
|
|
1222
|
+
console.error("openArtifacts.mcp.watchTool handler threw:", e);
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
return () => {
|
|
1226
|
+
off = true;
|
|
1227
|
+
};
|
|
1228
|
+
},
|
|
1229
|
+
server: (name) => {
|
|
1230
|
+
if (typeof name !== "string" || !name) throw frameError("bad_request", "mcp.server(name): the connector's name, as declared.", null, "McpError");
|
|
1231
|
+
return new Proxy(Object.freeze({}), {
|
|
1232
|
+
get: (_t, tool) => typeof tool !== "string" || tool === "then" || tool === "toJSON" ? void 0 : callTool
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
function stub(name) {
|
|
1238
|
+
if (name === "mcp") return mcpStub();
|
|
1239
|
+
return new Proxy(
|
|
1240
|
+
name === "sample" ? () => {
|
|
1241
|
+
} : {},
|
|
1242
|
+
{
|
|
1243
|
+
apply: () => call(name, "call", {}),
|
|
1244
|
+
get: (_t, prop) => {
|
|
1245
|
+
if (typeof prop === "symbol" || prop === "then" || prop === "toJSON") return void 0;
|
|
1246
|
+
if (prop === "available") return true;
|
|
1247
|
+
return () => call(name, String(prop), {});
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
);
|
|
1251
|
+
}
|
|
1252
|
+
const hot = Object.freeze({ data: void 0, from: null, gen: 0, signal: void 0, snapshot() {
|
|
1253
|
+
}, ready() {
|
|
1254
|
+
}, accept() {
|
|
1255
|
+
}, restart() {
|
|
1256
|
+
} });
|
|
1257
|
+
const namespaces = { db, artifact: self, assets, downloads, user, permissions, room, comments, network };
|
|
1258
|
+
const mounted = /* @__PURE__ */ Object.create(null);
|
|
1259
|
+
function namespaceOf(key) {
|
|
1260
|
+
if (stubs.indexOf(key) >= 0) return mounted[key] ||= stub(key);
|
|
1261
|
+
if (key === "sample") return sample;
|
|
1262
|
+
if (key === "mcp") return mcp;
|
|
1263
|
+
if (!Object.hasOwn(namespaces, key)) return null;
|
|
1264
|
+
if (!mounted[key]) {
|
|
1265
|
+
const ns = /* @__PURE__ */ Object.create(null);
|
|
1266
|
+
const src = namespaces[key];
|
|
1267
|
+
for (const k of Object.keys(src)) Object.defineProperty(ns, k, Object.getOwnPropertyDescriptor(src, k));
|
|
1268
|
+
delete ns.then;
|
|
1269
|
+
mounted[key] = Object.freeze(ns);
|
|
1270
|
+
}
|
|
1271
|
+
return mounted[key];
|
|
1272
|
+
}
|
|
1273
|
+
let pageVer = (/^\/_f\/([^/]{1,128})\//.exec(location.pathname) || [])[1] || "0";
|
|
1274
|
+
function want(cap) {
|
|
1275
|
+
return new Promise((resolve) => {
|
|
1276
|
+
const done = (value) => {
|
|
1277
|
+
clearTimeout(timer);
|
|
1278
|
+
wants.delete(cap);
|
|
1279
|
+
resolve(value);
|
|
1280
|
+
};
|
|
1281
|
+
const timer = setTimeout(() => done(null), WANT_TIMEOUT_MS);
|
|
1282
|
+
wants.set(cap, (g) => {
|
|
1283
|
+
if (typeof g.brokerGen === "number") brokerGen = g.brokerGen;
|
|
1284
|
+
if (!isRecord(g.grant) || cap === "network") return done(null);
|
|
1285
|
+
configs[cap] = isRecord(g.grant.config) ? g.grant.config : {};
|
|
1286
|
+
done(namespaceOf(cap));
|
|
1287
|
+
});
|
|
1288
|
+
post({ __frame_cap_want: true, cap: cap === "artifact" ? "self" : cap, ver: pageVer });
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
const slots = /* @__PURE__ */ new Map();
|
|
1292
|
+
const KNOWN = /^[a-z][a-z0-9]{0,23}$/;
|
|
1293
|
+
function use(name) {
|
|
1294
|
+
if (typeof name !== "string") return Promise.resolve(null);
|
|
1295
|
+
if (name === "hot") return Promise.resolve(hot);
|
|
1296
|
+
const key = name === "self" ? "artifact" : name;
|
|
1297
|
+
if (!KNOWN.test(key) || !Object.hasOwn(namespaces, key) && key !== "sample" && key !== "mcp" && stubs.indexOf(key) < 0) return Promise.resolve(null);
|
|
1298
|
+
let slot = slots.get(key);
|
|
1299
|
+
if (!slot) {
|
|
1300
|
+
slot = whenInit().then((got) => {
|
|
1301
|
+
if (!got) return null;
|
|
1302
|
+
if (stubs.indexOf(key) >= 0) return namespaceOf(key);
|
|
1303
|
+
if (got.grants.has(key)) return key === "sample" ? loadSample().then(() => namespaceOf(key)) : key === "mcp" ? loadMcp().then(() => namespaceOf(key)) : namespaceOf(key);
|
|
1304
|
+
if (got.capWants && got.usable.includes(key)) return want(key);
|
|
1305
|
+
return null;
|
|
1306
|
+
});
|
|
1307
|
+
if (boot.debug) slot.then((ns) => ns || post({ __open_artifacts_console: true, level: "warn", text: `use(${name}) → null` }));
|
|
1308
|
+
slots.set(key, slot);
|
|
1309
|
+
}
|
|
1310
|
+
return slot;
|
|
1311
|
+
}
|
|
1312
|
+
const openArtifacts = { __openArtifactsFrame: true, contract: boot.contract, use };
|
|
1313
|
+
for (const g of grants) {
|
|
1314
|
+
const ns = namespaceOf(g);
|
|
1315
|
+
if (ns) openArtifacts[g] = ns;
|
|
1316
|
+
}
|
|
1317
|
+
if (grants.indexOf("artifact") >= 0) openArtifacts.self = namespaceOf("artifact");
|
|
1318
|
+
openArtifacts.hot = hot;
|
|
1319
|
+
for (const s of stubs) openArtifacts[s] = namespaceOf(s);
|
|
1320
|
+
Object.defineProperty(window, "openArtifacts", { value: Object.freeze(openArtifacts), configurable: false, writable: false, enumerable: false });
|
|
1321
|
+
if (!Object.prototype.hasOwnProperty.call(window, "claude")) {
|
|
1322
|
+
Object.defineProperty(window, "claude", { value: w.openArtifacts, configurable: true, writable: false, enumerable: false });
|
|
1323
|
+
}
|
|
1324
|
+
if (!Object.prototype.hasOwnProperty.call(window, "openArtifact")) {
|
|
1325
|
+
Object.defineProperty(window, "openArtifact", { value: w.openArtifacts, configurable: true, writable: false, enumerable: false });
|
|
1326
|
+
}
|
|
1327
|
+
if (boot.debug && framed) {
|
|
1328
|
+
const relay = (level, args) => {
|
|
1329
|
+
const text = Array.prototype.map.call(args, (a) => {
|
|
1330
|
+
if (a instanceof Error) return a.stack || a.message;
|
|
1331
|
+
if (typeof a === "string") return a;
|
|
1332
|
+
try {
|
|
1333
|
+
return JSON.stringify(a);
|
|
1334
|
+
} catch {
|
|
1335
|
+
return String(a);
|
|
1336
|
+
}
|
|
1337
|
+
}).join(" ").slice(0, 4e3);
|
|
1338
|
+
post({ __open_artifacts_console: true, level, text });
|
|
1339
|
+
};
|
|
1340
|
+
for (const level of ["error", "warn"]) {
|
|
1341
|
+
const orig = console[level];
|
|
1342
|
+
console[level] = (...args) => {
|
|
1343
|
+
relay(level, args);
|
|
1344
|
+
orig.apply(console, args);
|
|
1345
|
+
};
|
|
1346
|
+
}
|
|
1347
|
+
window.addEventListener("error", (ev) => relay("error", [ev.error || ev.message]));
|
|
1348
|
+
window.addEventListener("unhandledrejection", (ev) => relay("error", ["unhandled rejection:", ev.reason]));
|
|
1349
|
+
}
|
|
1350
|
+
window.addEventListener("pagehide", (event) => {
|
|
1351
|
+
if (event.persisted) return;
|
|
1352
|
+
for (const id of [...dbSubs.keys()]) dbCall("unsubscribe", { sub: id }).catch(() => {
|
|
1353
|
+
});
|
|
1354
|
+
dbSubs.clear();
|
|
1355
|
+
sampleModule?.pagehide();
|
|
1356
|
+
mcpModule?.pagehide();
|
|
1357
|
+
});
|
|
1358
|
+
connect();
|
|
1359
|
+
const signalReady = () => post({ __frame_ready: true, gate: "init" });
|
|
1360
|
+
if (document.readyState === "complete") setTimeout(signalReady, 0);
|
|
1361
|
+
else window.addEventListener("load", signalReady, { once: true });
|
|
1362
|
+
})();
|
|
1363
|
+
})();
|