@kition/extensions 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.
package/dist/index.js ADDED
@@ -0,0 +1,438 @@
1
+ import { E as m, R as S, W as M } from "./chunks/runtime-BVJHE1Pg.js";
2
+ import { C as it } from "./chunks/runtime-BVJHE1Pg.js";
3
+ import { BatchError as T } from "@kition/kdm";
4
+ import { kitDescriptor as N, openDocument as O } from "@kition/script";
5
+ import "@kition/script/kits";
6
+ const Q = "KitExtensions 1.0", $ = "1.0";
7
+ class g extends Error {
8
+ constructor(e) {
9
+ super(`invalid extension.json: ${e.join("; ")}`), this.problems = e, this.name = "ManifestError";
10
+ }
11
+ }
12
+ const P = /^[a-z][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/, b = /^[a-zA-Z][\w-]*(\.[\w-]+)+$/, j = /^kit\.[a-z0-9][a-z0-9-]*$/, z = /^[a-z0-9]+$/, C = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/, R = /^[\w-]+(\/[\w.-]+)*\.(mjs|js)$/, D = /^[\w-]+(\/[\w.-]+)*\.html$/, _ = /^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/, q = /* @__PURE__ */ new Set(["localhost", "127.0.0.1"]), L = /* @__PURE__ */ new Set(["model.read", "model.write", "commands.run"]), h = (a) => typeof a == "object" && a !== null && !Array.isArray(a), f = (a, e = 200) => typeof a == "string" && a.trim() !== "" && a.length <= e;
13
+ function A(a) {
14
+ if (!a.startsWith("network:")) return null;
15
+ const e = a.slice(8), t = /^(?:(https|wss|http|ws):\/\/)?([^/:]+)(?::(\d{1,5}))?\/?$/.exec(e);
16
+ if (!t) return null;
17
+ const [, n, s, i] = t;
18
+ if (!_.test(s) || i && Number(i) > 65535 || (n === "http" || n === "ws") && !q.has(s)) return null;
19
+ const r = i ? `:${i}` : "";
20
+ return n ? [`${n}://${s}${r}`] : [`https://${s}${r}`, `wss://${s}${r}`];
21
+ }
22
+ function k(a) {
23
+ const e = a.flatMap((t) => A(t) ?? []);
24
+ return e.length ? [...new Set(e)].join(" ") : "'none'";
25
+ }
26
+ const y = (a, e) => a.includes(e);
27
+ function W(a) {
28
+ let e = a;
29
+ if (typeof a == "string")
30
+ try {
31
+ e = JSON.parse(a);
32
+ } catch (r) {
33
+ throw new g([`not JSON: ${r instanceof Error ? r.message : String(r)}`]);
34
+ }
35
+ const t = [];
36
+ if (!h(e)) throw new g(["the manifest is not an object"]);
37
+ const n = e;
38
+ n.kitExtensions !== $ && t.push(`kitExtensions must be "${$}"`), (typeof n.id != "string" || !P.test(n.id) || n.id.length > 100) && t.push("id must be a lower-case reverse domain name, such as com.example.title-case"), f(n.name, 80) || t.push("name is required (at most 80 characters)"), (typeof n.version != "string" || !C.test(n.version)) && t.push("version must be a semantic version, such as 1.0.0"), n.description !== void 0 && !f(n.description, 500) && t.push("description must be text (at most 500 characters)"), n.publisher !== void 0 && !f(n.publisher, 100) && t.push("publisher must be text (at most 100 characters)"), (typeof n.entry != "string" || !R.test(n.entry) || n.entry.split("/").some((r) => r === ".." || r === ".")) && t.push("entry must be a .mjs or .js file inside the package, such as extension.mjs");
39
+ const s = n.activation;
40
+ h(s) ? ((!Array.isArray(s.kits) || !s.kits.length || !s.kits.every((r) => typeof r == "string" && j.test(r))) && t.push("activation.kits must list kit ids, such as kit.slide"), s.formats !== void 0 && (!Array.isArray(s.formats) || !s.formats.every((r) => typeof r == "string" && z.test(r))) && t.push("activation.formats must list lower-case file extensions without a dot"), s.on !== void 0 && s.on !== "open" && s.on !== "command" && t.push('activation.on must be "open" or "command"')) : t.push("activation is required");
41
+ const i = n.contributes;
42
+ if (!h(i) || !Array.isArray(i.commands)) t.push("contributes.commands is required (it may be empty)");
43
+ else {
44
+ const r = /* @__PURE__ */ new Set();
45
+ for (const c of i.commands) {
46
+ if (!h(c) || typeof c.id != "string" || !b.test(c.id)) {
47
+ t.push("each contributed command needs a namespaced id, such as titleCase.apply");
48
+ continue;
49
+ }
50
+ r.has(c.id) && t.push(`command ${c.id} is contributed twice`), r.add(c.id), f(c.title, 80) || t.push(`command ${c.id} needs a title (at most 80 characters)`), c.description !== void 0 && !f(c.description, 300) && t.push(`command ${c.id} has an invalid description`);
51
+ }
52
+ if (i.panels !== void 0)
53
+ if (!Array.isArray(i.panels)) t.push("contributes.panels must be a list");
54
+ else {
55
+ const c = /* @__PURE__ */ new Set(), d = h(s) && Array.isArray(s.kits) ? s.kits : [];
56
+ for (const o of i.panels) {
57
+ if (!h(o) || typeof o.id != "string" || !b.test(o.id) || !f(o.title, 80) || typeof o.entry != "string" || !D.test(o.entry) || o.entry.split("/").some((l) => l === ".." || l === ".")) {
58
+ t.push("each panel needs a namespaced id, a title, and an .html entry inside the package");
59
+ continue;
60
+ }
61
+ c.has(o.id) && t.push(`panel ${o.id} is contributed twice`), c.add(o.id), o.kits !== void 0 && (!Array.isArray(o.kits) || !o.kits.length || !o.kits.every((l) => typeof l == "string" && d.includes(l))) && t.push(`panel ${o.id}: kits must list some of activation.kits`);
62
+ }
63
+ }
64
+ }
65
+ if (!Array.isArray(n.permissions)) t.push("permissions is required (it may be empty)");
66
+ else {
67
+ for (const r of n.permissions)
68
+ typeof r != "string" ? t.push("permissions must be strings") : r.startsWith("network:") ? A(r) || t.push(`${r} is not an origin (network:api.example.com, network:https://api.example.com:8443)`) : L.has(r) || t.push(`unknown permission ${r}`);
69
+ n.permissions.includes("model.write") && !n.permissions.includes("model.read") && t.push("model.write needs model.read");
70
+ }
71
+ if (t.length) throw new g(t);
72
+ return e;
73
+ }
74
+ const K = (a) => {
75
+ const e = a.split("/").pop() ?? a, t = e.lastIndexOf(".");
76
+ return t > 0 ? e.slice(t + 1).toLowerCase() : "";
77
+ };
78
+ function w(a, e) {
79
+ if (!a.activation.kits.includes(e.kitId)) return !1;
80
+ const t = a.activation.formats;
81
+ return !t?.length || e.path === void 0 ? !0 : t.includes(K(e.path));
82
+ }
83
+ function x(a, e, t) {
84
+ return w(a, t) && (!e.kits?.length || e.kits.includes(t.kitId));
85
+ }
86
+ const B = "command";
87
+ function E(a, e, t) {
88
+ return new m("permission-denied", `${a} may not ${t}: it does not have the ${e} permission`, { permission: e });
89
+ }
90
+ function v(a, e, t, n) {
91
+ if (!y(e, t)) throw E(a, t, n);
92
+ }
93
+ async function F(a, e, t, n) {
94
+ if (!t || typeof t != "object") throw new m("invalid", "a batch is an object");
95
+ const s = Array.isArray(t.ops) ? t.ops : [];
96
+ t.load?.length && v(a, e, "model.read", "read the document");
97
+ const i = s.filter((c) => c?.op === B);
98
+ if (s.length > i.length && v(a, e, "model.write", "change the document"), !i.length || (v(a, e, "commands.run", "run commands"), y(e, "model.write"))) return;
99
+ const r = new Map((await n()).map((c) => [c.id, c]));
100
+ for (const c of i)
101
+ if (r.get(String(c.id))?.mutates !== !1) throw E(a, "model.write", `run ${String(c.id)}, which changes the document`);
102
+ }
103
+ const G = ["model.read", "model.write", "commands.run"], H = (a) => a instanceof Error ? a.message : String(a);
104
+ class I {
105
+ constructor(e) {
106
+ this.options = e;
107
+ }
108
+ loaded = /* @__PURE__ */ new Map();
109
+ documents = /* @__PURE__ */ new Map();
110
+ scripts = 0;
111
+ panelSessions = 0;
112
+ /** Checks and loads an extension (its code runs when it is first activated); replaces one with its id. */
113
+ load(e) {
114
+ const t = W(e.manifest);
115
+ if (typeof e.source != "string" || !e.source.trim()) throw new m("invalid", `${t.id} has no code in ${t.entry}`);
116
+ const n = /* @__PURE__ */ new Map();
117
+ for (const s of t.contributes.panels ?? []) {
118
+ const i = e.files?.[s.entry];
119
+ if (typeof i != "string" || !i.trim()) throw new m("invalid", `${t.id} has no ${s.entry} for its panel ${s.id}`);
120
+ n.set(s.id, i);
121
+ }
122
+ this.unload(t.id), this.loaded.set(t.id, { manifest: t, source: e.source, panels: n, principal: `ext:${t.id}`, running: null, activating: /* @__PURE__ */ new Map() });
123
+ for (const s of this.documents.values())
124
+ t.activation.on === "open" && w(t, s.document) && this.activateReporting(t.id, s.document.id);
125
+ return t;
126
+ }
127
+ /** Deactivates an extension everywhere and stops its sandbox. */
128
+ unload(e) {
129
+ const t = this.loaded.get(e);
130
+ t && (this.loaded.delete(e), this.stop(t));
131
+ }
132
+ extensions() {
133
+ return [...this.loaded.values()].map((e) => e.manifest);
134
+ }
135
+ /** Offers a document to extensions; those that activate on open do. Answers `closeDocument`. */
136
+ openDocument(e) {
137
+ this.closeDocument(e.id), this.documents.set(e.id, { document: e, model: null });
138
+ for (const t of this.loaded.values())
139
+ t.manifest.activation.on === "open" && w(t.manifest, e) && this.activateReporting(t.manifest.id, e.id);
140
+ return () => {
141
+ this.documents.get(e.id)?.document === e && this.closeDocument(e.id);
142
+ };
143
+ }
144
+ /** Deactivates every extension on the document. */
145
+ closeDocument(e) {
146
+ const t = this.documents.get(e);
147
+ if (t) {
148
+ this.documents.delete(e);
149
+ for (const n of this.loaded.values()) this.deactivate(n, e);
150
+ t.model?.then((n) => n.close()).catch(() => {
151
+ });
152
+ }
153
+ }
154
+ /** The commands loaded extensions contribute to a document, in load order. */
155
+ commandsFor(e) {
156
+ const t = this.documents.get(e);
157
+ return t ? [...this.loaded.values()].filter((n) => w(n.manifest, t.document)).flatMap((n) => n.manifest.contributes.commands.map((s) => ({ ...s, extension: n.manifest.id, extensionName: n.manifest.name }))) : [];
158
+ }
159
+ /** The panels loaded extensions contribute to a document, in load order. */
160
+ panelsFor(e) {
161
+ const t = this.documents.get(e);
162
+ return t ? [...this.loaded.values()].flatMap(
163
+ (n) => (n.manifest.contributes.panels ?? []).filter((s) => x(n.manifest, s, t.document)).map((s) => ({ ...s, extension: n.manifest.id, extensionName: n.manifest.name }))
164
+ ) : [];
165
+ }
166
+ /** A contributed panel's HTML and the network origins its frame may reach (the extension's). */
167
+ panelContent(e, t) {
168
+ const n = this.require(e), s = n.manifest.contributes.panels?.find((r) => r.id === t), i = n.panels.get(t);
169
+ if (!s || i === void 0) throw new m("not-found", `${e} contributes no panel ${t}`);
170
+ return { html: i, connect: k(n.manifest.permissions), title: s.title };
171
+ }
172
+ /**
173
+ * Opens a contributed panel on a document: activates the extension there first when needed, then
174
+ * hands its worker `port`, the worker's end of the panel's channel (the panel's frame gets the
175
+ * other end). Answers the session; closing the document or the extension closes it too.
176
+ */
177
+ async openPanel(e, t, n, s) {
178
+ const i = this.require(t), r = i.manifest.contributes.panels?.find((l) => l.id === n);
179
+ if (!r) throw new m("not-found", `${t} contributes no panel ${n}`);
180
+ const c = this.documents.get(e);
181
+ if (!c) throw new m("not-found", `no open document ${e}`);
182
+ if (!x(i.manifest, r, c.document)) throw new m("invalid", `${t}'s panel ${n} does not apply to ${c.document.kitId} documents`);
183
+ await this.activate(t, e);
184
+ const d = await i.running, o = `panel-${++this.panelSessions}`;
185
+ return await d.peer.request("panel/open", { documentId: e, panel: n, session: o }, 2e4, [s]), {
186
+ session: o,
187
+ close: () => void d.peer.request("panel/close", { session: o }, 5e3).catch(() => {
188
+ })
189
+ };
190
+ }
191
+ /** Runs a contributed command on a document, activating its extension first when needed. */
192
+ async runCommand(e, t, n) {
193
+ const s = this.require(t);
194
+ if (!s.manifest.contributes.commands.some((c) => c.id === n)) throw new m("not-found", `${t} contributes no command ${n}`);
195
+ if (!(await this.activate(t, e)).commands.has(n)) throw new m("not-found", `${t} did not register ${n} when it activated`);
196
+ return (await s.running).peer.request("extension/command", { documentId: e, command: n });
197
+ }
198
+ /** Activates an extension on a document (once); answers when its `activate` has returned. */
199
+ activate(e, t) {
200
+ const n = this.require(e), s = n.activating.get(t);
201
+ if (s) return s;
202
+ const i = (async () => {
203
+ const r = this.documents.get(t);
204
+ if (!r) throw new m("not-found", `no open document ${t}`);
205
+ if (!w(n.manifest, r.document)) throw new m("invalid", `${e} does not apply to ${r.document.kitId} documents`);
206
+ const c = await this.model(t), d = await this.start(n), o = { commands: /* @__PURE__ */ new Set(), unsubscribe: () => {
207
+ } };
208
+ d.activations.set(t, o), o.unsubscribe = c.on("changed", (l) => d.peer.notify("document/changed", { documentId: t, origin: l.origin }));
209
+ try {
210
+ const { commands: l } = await d.peer.request("extension/activate", this.info(r.document, n.manifest.permissions, c));
211
+ for (const u of l) o.commands.add(u);
212
+ } catch (l) {
213
+ throw o.unsubscribe(), d.activations.get(t) === o && d.activations.delete(t), l;
214
+ }
215
+ return o;
216
+ })();
217
+ return n.activating.set(t, i), i.catch(() => {
218
+ n.activating.get(t) === i && n.activating.delete(t);
219
+ }), i;
220
+ }
221
+ /**
222
+ * Runs a script (an ES module whose default export, or `run`, takes the same `ctx` as
223
+ * `activate`) once against a document, in a sandbox of its own with `permissions`. Answers what
224
+ * it answers.
225
+ */
226
+ async runScript(e, t, n = G) {
227
+ const s = this.documents.get(t);
228
+ if (!s) throw new m("not-found", `no open document ${t}`);
229
+ const i = (e.name ?? "script").replace(/[^\w.-]+/g, "-").slice(0, 60) || "script", d = { manifest: {
230
+ kitExtensions: "1.0",
231
+ id: `script-${++this.scripts}`,
232
+ name: i,
233
+ version: "0.0.0",
234
+ entry: "script.mjs",
235
+ activation: { kits: [s.document.kitId] },
236
+ contributes: { commands: [] },
237
+ permissions: n
238
+ }, source: e.source, panels: /* @__PURE__ */ new Map(), principal: `script:${i}`, running: null, activating: /* @__PURE__ */ new Map() };
239
+ try {
240
+ const o = await this.start(d, "script"), l = await this.model(t);
241
+ return o.activations.set(t, { commands: /* @__PURE__ */ new Set(), unsubscribe: () => {
242
+ } }), await o.peer.request("script/run", this.info(s.document, n, l));
243
+ } finally {
244
+ await this.stop(d);
245
+ }
246
+ }
247
+ /** Stops every sandbox and forgets every document. */
248
+ dispose() {
249
+ for (const e of [...this.loaded.keys()]) this.unload(e);
250
+ for (const e of [...this.documents.keys()]) this.closeDocument(e);
251
+ }
252
+ require(e) {
253
+ const t = this.loaded.get(e);
254
+ if (!t) throw new m("not-found", `no extension ${e} is loaded`);
255
+ return t;
256
+ }
257
+ info(e, t, n) {
258
+ const s = !y(t, "model.write") || (e.port.readOnly?.() ?? !1), i = e.path?.split("/").pop();
259
+ return { documentId: e.id, kitId: e.kitId, ...i ? { name: i } : {}, schema: n.schema, readOnly: s };
260
+ }
261
+ async activateReporting(e, t) {
262
+ try {
263
+ await this.activate(e, t);
264
+ } catch (n) {
265
+ this.report(e, n);
266
+ }
267
+ }
268
+ report(e, t) {
269
+ this.options.notify?.({ extension: e, level: "error", title: this.loaded.get(e)?.manifest.name ?? e, description: H(t) });
270
+ }
271
+ /** The document's object model, opened once and shared by every extension on it. */
272
+ model(e) {
273
+ const t = this.documents.get(e);
274
+ if (!t) return Promise.reject(new m("not-found", `no open document ${e}`));
275
+ if (!t.model) {
276
+ const { document: n } = t, s = n.schema ?? this.options.schema?.(n.kitId) ?? N(n.kitId)?.schema;
277
+ t.model = s ? O(n.port, { schema: s }) : Promise.reject(new m("invalid", `extensions cannot work on ${n.kitId} documents yet: the host knows no schema for that kit`)), t.model.catch(() => {
278
+ this.documents.get(e) === t && (t.model = null);
279
+ });
280
+ }
281
+ return t.model;
282
+ }
283
+ /** The sandbox of an extension, started once. */
284
+ start(e, t = "extension") {
285
+ if (e.running) return e.running;
286
+ const n = (async () => {
287
+ const s = await this.options.sandbox({ id: e.manifest.id, connect: k(e.manifest.permissions) }), i = new S(s.port), r = { peer: i, connection: s, activations: /* @__PURE__ */ new Map() };
288
+ this.serve(e, r);
289
+ try {
290
+ await i.request("extension/start", { manifest: e.manifest, source: e.source, kind: t }, this.options.startTimeoutMs ?? 2e4);
291
+ } catch (c) {
292
+ throw i.close(), s.dispose(), c;
293
+ }
294
+ return r;
295
+ })();
296
+ return e.running = n, n.catch(() => {
297
+ e.running === n && (e.running = null);
298
+ }), n;
299
+ }
300
+ async stop(e) {
301
+ const t = await e.running?.catch(() => null);
302
+ if (e.running = null, !!t) {
303
+ for (const n of [...t.activations.keys()]) await this.deactivate(e, n, t);
304
+ t.peer.close("the extension was stopped"), t.connection.dispose();
305
+ }
306
+ }
307
+ async deactivate(e, t, n) {
308
+ e.activating.delete(t);
309
+ const s = n ?? await e.running?.catch(() => null), i = s?.activations.get(t);
310
+ !s || !i || (s.activations.delete(t), i.unsubscribe(), await s.peer.request("extension/deactivate", { documentId: t }, 5e3).catch(() => {
311
+ }));
312
+ }
313
+ /** What the extension's worker may ask of the host. */
314
+ serve(e, t) {
315
+ const { manifest: n, principal: s } = e, i = n.id, r = n.permissions, c = async (o) => {
316
+ if (typeof o != "string" || !t.activations.has(o)) throw new m("not-found", `${i} is not active on ${String(o)}`);
317
+ return this.model(o);
318
+ }, d = { kind: "extension", principal: s };
319
+ t.peer.handle("model/batch", async ({ documentId: o, request: l }) => {
320
+ const u = await c(o);
321
+ await F(i, r, l, () => u.commands.list());
322
+ try {
323
+ return await u.batch({ ops: l.ops ?? [], load: l.load ?? [], origin: d });
324
+ } catch (p) {
325
+ throw p instanceof T ? new m(p.code, p.message, { index: p.index }) : p;
326
+ }
327
+ }).handle("model/describe", async ({ documentId: o }) => {
328
+ const l = await c(o);
329
+ return v(i, r, "model.read", "read the document"), l.describe();
330
+ }).handle("model/commands", async ({ documentId: o }) => {
331
+ const l = await c(o);
332
+ return y(r, "commands.run") || v(i, r, "model.read", "list the commands"), l.commands.list();
333
+ }).handle("commands/register", ({ documentId: o, command: l }) => {
334
+ const u = t.activations.get(o);
335
+ if (!u) throw new m("not-found", `${i} is not active on ${o}`);
336
+ if (!n.contributes.commands.some((p) => p.id === l))
337
+ throw new m("invalid", `${i} does not contribute ${l}: declare it in extension.json contributes.commands`);
338
+ return u.commands.add(l), null;
339
+ }).handle("host/notify", (o) => {
340
+ const l = ["info", "success", "warning", "error"].includes(o?.level) ? o.level : "info", u = String(o?.title ?? "").slice(0, 200);
341
+ if (!u) return null;
342
+ const p = o.description === void 0 ? void 0 : String(o.description).slice(0, 1e3);
343
+ return this.options.notify?.({ extension: i, level: l, title: u, ...p ? { description: p } : {} }), null;
344
+ });
345
+ }
346
+ }
347
+ const Y = "kition-ext-sandbox/1", Z = "kition-ext-panel/1";
348
+ function tt(a) {
349
+ return async ({ id: e, connect: t }) => {
350
+ const n = document.createElement("iframe");
351
+ n.setAttribute("sandbox", "allow-scripts"), n.setAttribute("aria-hidden", "true"), n.setAttribute("tabindex", "-1"), n.title = `Extension ${e}`, n.dataset.kitionExtension = e, n.style.display = "none", n.referrerPolicy = "no-referrer";
352
+ const s = new Promise((c, d) => {
353
+ const o = setTimeout(() => d(new Error(`the sandbox page for ${e} did not load from ${a.url}`)), a.loadTimeoutMs ?? 15e3);
354
+ n.addEventListener(
355
+ "load",
356
+ () => {
357
+ clearTimeout(o), c();
358
+ },
359
+ { once: !0 }
360
+ );
361
+ });
362
+ n.src = a.url, (a.container ?? document.body).appendChild(n);
363
+ try {
364
+ await s;
365
+ } catch (c) {
366
+ throw n.remove(), c;
367
+ }
368
+ const i = new MessageChannel(), r = { tag: Y, type: "start", runtime: M, connect: t };
369
+ return n.contentWindow.postMessage(r, "*", [i.port2]), {
370
+ port: i.port1,
371
+ dispose: () => {
372
+ i.port1.close(), n.remove();
373
+ }
374
+ };
375
+ };
376
+ }
377
+ async function et(a, e, t) {
378
+ const n = a.panelContent(e.extension, e.panel), s = document.createElement("iframe");
379
+ s.setAttribute("sandbox", "allow-scripts"), s.title = n.title, s.dataset.kitionPanel = `${e.extension}:${e.panel}`, s.referrerPolicy = "no-referrer", s.style.cssText = "display:block;width:100%;height:100%;border:0";
380
+ const i = new Promise((o, l) => {
381
+ const u = setTimeout(() => l(new Error(`the panel page for ${e.extension} did not load from ${t.url}`)), t.loadTimeoutMs ?? 15e3);
382
+ s.addEventListener(
383
+ "load",
384
+ () => {
385
+ clearTimeout(u), o();
386
+ },
387
+ { once: !0 }
388
+ );
389
+ });
390
+ s.src = t.url, t.container.appendChild(s);
391
+ let r = null, c = !1;
392
+ const d = () => {
393
+ c || (c = !0, r?.close(), s.remove());
394
+ };
395
+ try {
396
+ await i;
397
+ const o = new MessageChannel();
398
+ if (r = await a.openPanel(e.documentId, e.extension, e.panel, o.port2), c)
399
+ throw r.close(), new Error("the panel was closed while it opened");
400
+ const l = {
401
+ tag: Z,
402
+ type: "start",
403
+ html: n.html,
404
+ connect: n.connect,
405
+ ...t.theme ? { theme: t.theme } : {},
406
+ info: { extension: e.extension, panel: e.panel, documentId: e.documentId, title: n.title, ...t.locale ? { locale: t.locale } : {} }
407
+ };
408
+ s.contentWindow.postMessage(l, "*", [o.port1]), s.addEventListener("load", () => {
409
+ d(), t.onNavigated?.();
410
+ });
411
+ } catch (o) {
412
+ throw d(), o;
413
+ }
414
+ return { frame: s, dispose: d };
415
+ }
416
+ export {
417
+ it as CHANNEL_TAG,
418
+ m as ExtensionError,
419
+ I as ExtensionHost,
420
+ Q as KIT_EXTENSIONS_CAPABILITY,
421
+ $ as MANIFEST_VERSION,
422
+ g as ManifestError,
423
+ Z as PANEL_TAG,
424
+ S as RpcPeer,
425
+ Y as SANDBOX_TAG,
426
+ G as SCRIPT_PERMISSIONS,
427
+ w as appliesTo,
428
+ F as checkBatch,
429
+ k as connectSources,
430
+ y as hasPermission,
431
+ tt as iframeSandbox,
432
+ A as networkSources,
433
+ et as openPanelFrame,
434
+ x as panelAppliesTo,
435
+ W as parseManifest,
436
+ E as permissionDenied,
437
+ v as requirePermission
438
+ };
@@ -0,0 +1,208 @@
1
+ <!doctype html>
2
+ <!-- Generated by packages/extensions/scripts/build-runtime.mjs from src/runtime/panel.ts. Do not edit; rebuild it. -->
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <meta http-equiv="Content-Security-Policy" content="script-src 'sha256-lUDRnQHOSSPBkoRKk24W3cjUk6Lgr27mXYsx4wjvFs4=' blob:; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; worker-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; manifest-src 'none'">
7
+ <meta name="referrer" content="no-referrer">
8
+ <meta name="viewport" content="width=device-width, initial-scale=1">
9
+ <title>Kition extension panel</title>
10
+ <style>html{color-scheme:light;font-family:var(--kit-font-sans,system-ui,sans-serif);font-size:14px;color:var(--kit-text,#1a1a1a);background:var(--kit-surface,#fff)}body{margin:0}</style>
11
+ <script>(function() {
12
+ "use strict";
13
+ const PANEL_TAG = "kition-ext-panel/1";
14
+ const CHANNEL_TAG = "kition-ext/1";
15
+ class ExtensionError extends Error {
16
+ constructor(code, message, data) {
17
+ super(message);
18
+ this.code = code;
19
+ this.data = data;
20
+ this.name = code === "permission-denied" ? "PermissionError" : "ExtensionError";
21
+ }
22
+ toJSON() {
23
+ return { code: this.code, message: this.message, ...this.data ? { data: this.data } : {} };
24
+ }
25
+ }
26
+ const isMessage = (value) => typeof value === "object" && value !== null && value.tag === CHANNEL_TAG;
27
+ function wireError(error) {
28
+ if (error instanceof ExtensionError) return error.toJSON();
29
+ const coded = error;
30
+ if (error instanceof Error && typeof coded.code === "string") {
31
+ return { code: coded.code, message: error.message, ...coded.index !== void 0 ? { data: { index: coded.index } } : {} };
32
+ }
33
+ return { code: "failed", message: error instanceof Error ? error.message : String(error) };
34
+ }
35
+ class RpcPeer {
36
+ constructor(port) {
37
+ this.port = port;
38
+ port.onmessage = (event) => this.receive(event.data, event.ports ?? []);
39
+ port.start?.();
40
+ }
41
+ next = 1;
42
+ pending = /* @__PURE__ */ new Map();
43
+ handlers = /* @__PURE__ */ new Map();
44
+ closed = false;
45
+ /** Answers `method` with `handler` (its result, or the error it throws). */
46
+ handle(method, handler) {
47
+ this.handlers.set(method, handler);
48
+ return this;
49
+ }
50
+ /** Asks `method`; `transfer` (a `MessagePort`, …) goes with the request. */
51
+ request(method, params, timeoutMs = 0, transfer) {
52
+ if (this.closed) return Promise.reject(new ExtensionError("failed", "the extension channel is closed"));
53
+ const id = this.next++;
54
+ return new Promise((resolve, reject) => {
55
+ let timer = null;
56
+ this.pending.set(id, {
57
+ resolve: (value) => {
58
+ if (timer) clearTimeout(timer);
59
+ resolve(value);
60
+ },
61
+ reject: (error) => {
62
+ if (timer) clearTimeout(timer);
63
+ reject(error);
64
+ }
65
+ });
66
+ if (timeoutMs > 0) {
67
+ timer = setTimeout(() => {
68
+ this.pending.delete(id);
69
+ reject(new ExtensionError("failed", `${method} did not answer within ${timeoutMs} ms`));
70
+ }, timeoutMs);
71
+ }
72
+ const message = { tag: CHANNEL_TAG, id, method, params };
73
+ if (transfer?.length) this.port.postMessage(message, transfer);
74
+ else this.port.postMessage(message);
75
+ });
76
+ }
77
+ notify(method, params) {
78
+ if (!this.closed) this.port.postMessage({ tag: CHANNEL_TAG, method, params });
79
+ }
80
+ /** Fails every request still waiting and stops listening. */
81
+ close(reason = "the extension channel is closed") {
82
+ if (this.closed) return;
83
+ this.closed = true;
84
+ this.port.onmessage = null;
85
+ this.port.close?.();
86
+ for (const { reject } of this.pending.values()) reject(new ExtensionError("failed", reason));
87
+ this.pending.clear();
88
+ }
89
+ receive(data, ports) {
90
+ if (!isMessage(data) || this.closed) return;
91
+ if (data.method !== void 0) {
92
+ void this.answer(data, ports);
93
+ return;
94
+ }
95
+ if (data.id === void 0) return;
96
+ const waiting = this.pending.get(data.id);
97
+ if (!waiting) return;
98
+ this.pending.delete(data.id);
99
+ if (data.error) waiting.reject(new ExtensionError(data.error.code, data.error.message, data.error.data));
100
+ else waiting.resolve(data.result);
101
+ }
102
+ async answer(message, ports) {
103
+ const handler = this.handlers.get(message.method);
104
+ let reply;
105
+ try {
106
+ if (!handler) throw new ExtensionError("not-found", `${message.method} is not served here`);
107
+ const result = await handler(message.params, ports);
108
+ reply = { tag: CHANNEL_TAG, id: message.id, result: result === void 0 ? null : result };
109
+ } catch (error) {
110
+ reply = { tag: CHANNEL_TAG, id: message.id, error: wireError(error) };
111
+ }
112
+ if (message.id === void 0 || this.closed) return;
113
+ try {
114
+ this.port.postMessage(reply);
115
+ } catch (error) {
116
+ this.port.postMessage({ tag: CHANNEL_TAG, id: message.id, error: { code: "failed", message: `${message.method} answered a value that cannot be sent: ${error instanceof Error ? error.message : String(error)}` } });
117
+ }
118
+ }
119
+ }
120
+ const SOURCE = /^(?:'none'|(?:(?:https|wss|http|ws):\/\/(?:\*\.)?[a-z0-9.-]+(?::\d{1,5})?)(?: (?:https|wss|http|ws):\/\/(?:\*\.)?[a-z0-9.-]+(?::\d{1,5})?)*)$/;
121
+ const THEME_NAME = /^--[a-zA-Z0-9-]{1,64}$/;
122
+ const JAVASCRIPT = /* @__PURE__ */ new Set(["", "text/javascript", "application/javascript", "text/ecmascript", "application/ecmascript"]);
123
+ function addPolicy(content) {
124
+ const policy = document.createElement("meta");
125
+ policy.httpEquiv = "Content-Security-Policy";
126
+ policy.content = content;
127
+ document.head.appendChild(policy);
128
+ }
129
+ function applyTheme(theme) {
130
+ if (!theme || typeof theme !== "object") return;
131
+ for (const [name, value] of Object.entries(theme)) {
132
+ if (THEME_NAME.test(name) && typeof value === "string" && value.length <= 300) document.documentElement.style.setProperty(name, value);
133
+ }
134
+ }
135
+ function render(html) {
136
+ const parsed = new DOMParser().parseFromString(html, "text/html");
137
+ const scripts = [];
138
+ for (const script of [...parsed.querySelectorAll("script")]) {
139
+ const type = (script.getAttribute("type") ?? "").trim().toLowerCase();
140
+ if (!JAVASCRIPT.has(type)) {
141
+ if (type !== "module") continue;
142
+ console.warn("[kition-panel] module scripts do not run in a panel; bundle them into a classic script");
143
+ script.remove();
144
+ continue;
145
+ }
146
+ if (script.hasAttribute("src")) {
147
+ console.warn("[kition-panel] scripts with src do not run in a panel; put the code inline");
148
+ script.remove();
149
+ continue;
150
+ }
151
+ const placeholder = parsed.createElement("template");
152
+ placeholder.dataset.kitionScript = String(scripts.length);
153
+ scripts.push(script.textContent ?? "");
154
+ script.replaceWith(placeholder);
155
+ }
156
+ for (const element of [...parsed.querySelectorAll('base, meta[http-equiv="refresh" i]')]) element.remove();
157
+ for (const attribute of [...parsed.documentElement.attributes]) document.documentElement.setAttribute(attribute.name, attribute.value);
158
+ for (const child of [...parsed.head.childNodes]) document.head.appendChild(document.importNode(child, true));
159
+ document.body.replaceWith(document.importNode(parsed.body, true));
160
+ for (const placeholder of [...document.querySelectorAll("template[data-kition-script]")]) {
161
+ const script = document.createElement("script");
162
+ script.async = false;
163
+ script.src = URL.createObjectURL(new Blob([scripts[Number(placeholder.dataset.kitionScript)]], { type: "text/javascript" }));
164
+ script.addEventListener("load", () => URL.revokeObjectURL(script.src), { once: true });
165
+ placeholder.replaceWith(script);
166
+ }
167
+ }
168
+ let started = false;
169
+ addEventListener("message", (event) => {
170
+ const data = event.data;
171
+ if (started || event.source !== parent || !data || data.tag !== PANEL_TAG || data.type !== "start") return;
172
+ const port = event.ports[0];
173
+ const info = data.info;
174
+ if (!port || typeof data.html !== "string" || typeof data.connect !== "string" || !SOURCE.test(data.connect) || !info || typeof info !== "object") return;
175
+ started = true;
176
+ addPolicy(`connect-src ${data.connect}`);
177
+ applyTheme(data.theme);
178
+ if (typeof info.locale === "string") document.documentElement.lang = info.locale;
179
+ const peer = new RpcPeer(port);
180
+ const listeners = /* @__PURE__ */ new Set();
181
+ peer.handle("panel/message", (message) => {
182
+ for (const listener of [...listeners]) {
183
+ try {
184
+ listener(message);
185
+ } catch (error) {
186
+ console.error("[kition-panel] a message listener failed", error);
187
+ }
188
+ }
189
+ });
190
+ const panel = Object.freeze({
191
+ info: Object.freeze({ extension: String(info.extension), panel: String(info.panel), documentId: String(info.documentId), title: String(info.title), ...typeof info.locale === "string" ? { locale: info.locale } : {} }),
192
+ request: (message) => peer.request("panel/request", message),
193
+ onMessage: (listener) => {
194
+ if (typeof listener !== "function") throw new TypeError("onMessage takes a function");
195
+ listeners.add(listener);
196
+ return () => {
197
+ listeners.delete(listener);
198
+ };
199
+ }
200
+ });
201
+ Object.defineProperty(window, "kitionPanel", { value: panel, enumerable: true });
202
+ render(data.html);
203
+ });
204
+ })();
205
+ </script>
206
+ </head>
207
+ <body></body>
208
+ </html>