@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.
@@ -0,0 +1,997 @@
1
+ const i = "kition-ext/1";
2
+ class a extends Error {
3
+ constructor(e, n, s) {
4
+ super(n), this.code = e, this.data = s, this.name = e === "permission-denied" ? "PermissionError" : "ExtensionError";
5
+ }
6
+ toJSON() {
7
+ return { code: this.code, message: this.message, ...this.data ? { data: this.data } : {} };
8
+ }
9
+ }
10
+ const h = (t) => typeof t == "object" && t !== null && t.tag === i;
11
+ function m(t) {
12
+ if (t instanceof a) return t.toJSON();
13
+ const e = t;
14
+ return t instanceof Error && typeof e.code == "string" ? { code: e.code, message: t.message, ...e.index !== void 0 ? { data: { index: e.index } } : {} } : { code: "failed", message: t instanceof Error ? t.message : String(t) };
15
+ }
16
+ class f {
17
+ constructor(e) {
18
+ this.port = e, e.onmessage = (n) => this.receive(n.data, n.ports ?? []), e.start?.();
19
+ }
20
+ next = 1;
21
+ pending = /* @__PURE__ */ new Map();
22
+ handlers = /* @__PURE__ */ new Map();
23
+ closed = !1;
24
+ /** Answers `method` with `handler` (its result, or the error it throws). */
25
+ handle(e, n) {
26
+ return this.handlers.set(e, n), this;
27
+ }
28
+ /** Asks `method`; `transfer` (a `MessagePort`, …) goes with the request. */
29
+ request(e, n, s = 0, o) {
30
+ if (this.closed) return Promise.reject(new a("failed", "the extension channel is closed"));
31
+ const r = this.next++;
32
+ return new Promise((u, l) => {
33
+ let d = null;
34
+ this.pending.set(r, {
35
+ resolve: (c) => {
36
+ d && clearTimeout(d), u(c);
37
+ },
38
+ reject: (c) => {
39
+ d && clearTimeout(d), l(c);
40
+ }
41
+ }), s > 0 && (d = setTimeout(() => {
42
+ this.pending.delete(r), l(new a("failed", `${e} did not answer within ${s} ms`));
43
+ }, s));
44
+ const p = { tag: i, id: r, method: e, params: n };
45
+ o?.length ? this.port.postMessage(p, o) : this.port.postMessage(p);
46
+ });
47
+ }
48
+ notify(e, n) {
49
+ this.closed || this.port.postMessage({ tag: i, method: e, params: n });
50
+ }
51
+ /** Fails every request still waiting and stops listening. */
52
+ close(e = "the extension channel is closed") {
53
+ if (!this.closed) {
54
+ this.closed = !0, this.port.onmessage = null, this.port.close?.();
55
+ for (const { reject: n } of this.pending.values()) n(new a("failed", e));
56
+ this.pending.clear();
57
+ }
58
+ }
59
+ receive(e, n) {
60
+ if (!h(e) || this.closed) return;
61
+ if (e.method !== void 0) {
62
+ this.answer(e, n);
63
+ return;
64
+ }
65
+ if (e.id === void 0) return;
66
+ const s = this.pending.get(e.id);
67
+ s && (this.pending.delete(e.id), e.error ? s.reject(new a(e.error.code, e.error.message, e.error.data)) : s.resolve(e.result));
68
+ }
69
+ async answer(e, n) {
70
+ const s = this.handlers.get(e.method);
71
+ let o;
72
+ try {
73
+ if (!s) throw new a("not-found", `${e.method} is not served here`);
74
+ const r = await s(e.params, n);
75
+ o = { tag: i, id: e.id, result: r === void 0 ? null : r };
76
+ } catch (r) {
77
+ o = { tag: i, id: e.id, error: m(r) };
78
+ }
79
+ if (!(e.id === void 0 || this.closed))
80
+ try {
81
+ this.port.postMessage(o);
82
+ } catch (r) {
83
+ this.port.postMessage({ tag: i, id: e.id, error: { code: "failed", message: `${e.method} answered a value that cannot be sent: ${r instanceof Error ? r.message : String(r)}` } });
84
+ }
85
+ }
86
+ }
87
+ const g = "3071d6975d6f0993907c0a6ea5c8bc97769cd3b4bba46377ebfd63b1404baf6c", w = `(function() {
88
+ "use strict";
89
+ const SANDBOX_TAG = "kition-ext-sandbox/1";
90
+ const CHANNEL_TAG = "kition-ext/1";
91
+ class ExtensionError extends Error {
92
+ constructor(code, message, data) {
93
+ super(message);
94
+ this.code = code;
95
+ this.data = data;
96
+ this.name = code === "permission-denied" ? "PermissionError" : "ExtensionError";
97
+ }
98
+ toJSON() {
99
+ return { code: this.code, message: this.message, ...this.data ? { data: this.data } : {} };
100
+ }
101
+ }
102
+ const isMessage = (value) => typeof value === "object" && value !== null && value.tag === CHANNEL_TAG;
103
+ function wireError(error) {
104
+ if (error instanceof ExtensionError) return error.toJSON();
105
+ const coded = error;
106
+ if (error instanceof Error && typeof coded.code === "string") {
107
+ return { code: coded.code, message: error.message, ...coded.index !== void 0 ? { data: { index: coded.index } } : {} };
108
+ }
109
+ return { code: "failed", message: error instanceof Error ? error.message : String(error) };
110
+ }
111
+ class RpcPeer {
112
+ constructor(port) {
113
+ this.port = port;
114
+ port.onmessage = (event) => this.receive(event.data, event.ports ?? []);
115
+ port.start?.();
116
+ }
117
+ next = 1;
118
+ pending = /* @__PURE__ */ new Map();
119
+ handlers = /* @__PURE__ */ new Map();
120
+ closed = false;
121
+ /** Answers \`method\` with \`handler\` (its result, or the error it throws). */
122
+ handle(method, handler) {
123
+ this.handlers.set(method, handler);
124
+ return this;
125
+ }
126
+ /** Asks \`method\`; \`transfer\` (a \`MessagePort\`, …) goes with the request. */
127
+ request(method, params, timeoutMs = 0, transfer) {
128
+ if (this.closed) return Promise.reject(new ExtensionError("failed", "the extension channel is closed"));
129
+ const id = this.next++;
130
+ return new Promise((resolve, reject) => {
131
+ let timer = null;
132
+ this.pending.set(id, {
133
+ resolve: (value) => {
134
+ if (timer) clearTimeout(timer);
135
+ resolve(value);
136
+ },
137
+ reject: (error) => {
138
+ if (timer) clearTimeout(timer);
139
+ reject(error);
140
+ }
141
+ });
142
+ if (timeoutMs > 0) {
143
+ timer = setTimeout(() => {
144
+ this.pending.delete(id);
145
+ reject(new ExtensionError("failed", \`\${method} did not answer within \${timeoutMs} ms\`));
146
+ }, timeoutMs);
147
+ }
148
+ const message = { tag: CHANNEL_TAG, id, method, params };
149
+ if (transfer?.length) this.port.postMessage(message, transfer);
150
+ else this.port.postMessage(message);
151
+ });
152
+ }
153
+ notify(method, params) {
154
+ if (!this.closed) this.port.postMessage({ tag: CHANNEL_TAG, method, params });
155
+ }
156
+ /** Fails every request still waiting and stops listening. */
157
+ close(reason = "the extension channel is closed") {
158
+ if (this.closed) return;
159
+ this.closed = true;
160
+ this.port.onmessage = null;
161
+ this.port.close?.();
162
+ for (const { reject } of this.pending.values()) reject(new ExtensionError("failed", reason));
163
+ this.pending.clear();
164
+ }
165
+ receive(data, ports) {
166
+ if (!isMessage(data) || this.closed) return;
167
+ if (data.method !== void 0) {
168
+ void this.answer(data, ports);
169
+ return;
170
+ }
171
+ if (data.id === void 0) return;
172
+ const waiting = this.pending.get(data.id);
173
+ if (!waiting) return;
174
+ this.pending.delete(data.id);
175
+ if (data.error) waiting.reject(new ExtensionError(data.error.code, data.error.message, data.error.data));
176
+ else waiting.resolve(data.result);
177
+ }
178
+ async answer(message, ports) {
179
+ const handler = this.handlers.get(message.method);
180
+ let reply;
181
+ try {
182
+ if (!handler) throw new ExtensionError("not-found", \`\${message.method} is not served here\`);
183
+ const result = await handler(message.params, ports);
184
+ reply = { tag: CHANNEL_TAG, id: message.id, result: result === void 0 ? null : result };
185
+ } catch (error) {
186
+ reply = { tag: CHANNEL_TAG, id: message.id, error: wireError(error) };
187
+ }
188
+ if (message.id === void 0 || this.closed) return;
189
+ try {
190
+ this.port.postMessage(reply);
191
+ } catch (error) {
192
+ 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)}\` } });
193
+ }
194
+ }
195
+ }
196
+ class PropertyNotLoadedError extends Error {
197
+ constructor(type, field) {
198
+ super(\`\${type}.\${field} is not loaded: call load(['\${field}']) and await sync() first\`);
199
+ this.name = "PropertyNotLoadedError";
200
+ }
201
+ }
202
+ class NotSyncedError extends Error {
203
+ constructor(what) {
204
+ super(\`\${what} is known after the next sync()\`);
205
+ this.name = "NotSyncedError";
206
+ }
207
+ }
208
+ const STATE = Symbol("kition.object");
209
+ const isProxy = (value) => typeof value === "object" && value !== null && STATE in value;
210
+ function wire(value) {
211
+ if (isProxy(value)) return value[STATE].target;
212
+ if (Array.isArray(value)) return value.map(wire);
213
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, wire(item)]));
214
+ return value;
215
+ }
216
+ class RequestContext {
217
+ constructor(schema, send, origin) {
218
+ this.schema = schema;
219
+ this.send = send;
220
+ this.origin = origin;
221
+ this.root = this.proxy({ target: "root", type: schema.root, id: null, fields: /* @__PURE__ */ new Map() });
222
+ this.commands = {
223
+ run: (id, params) => {
224
+ let value;
225
+ let done = false;
226
+ this.pending.push({
227
+ index: this.ops.length,
228
+ set: (result) => {
229
+ value = result;
230
+ done = true;
231
+ }
232
+ });
233
+ this.ops.push({ op: "command", id, ...params === void 0 ? {} : { params: wire(params) } });
234
+ return {
235
+ get value() {
236
+ if (!done) throw new NotSyncedError(\`the result of \${id}\`);
237
+ return value;
238
+ }
239
+ };
240
+ }
241
+ };
242
+ }
243
+ ops = [];
244
+ loads = [];
245
+ created = [];
246
+ pending = [];
247
+ proxies = /* @__PURE__ */ new Map();
248
+ refs = 0;
249
+ /** The document's root object. */
250
+ root;
251
+ commands;
252
+ /** A proxy of an existing object of type \`type\`. */
253
+ object(id, type) {
254
+ const known = this.proxies.get(id);
255
+ if (known) return known;
256
+ if (!this.schema.types[type]) throw new Error(\`the kit has no type \\\`\${type}\\\`\`);
257
+ const proxy = this.proxy({ target: id, type, id, fields: /* @__PURE__ */ new Map() });
258
+ this.proxies.set(id, proxy);
259
+ return proxy;
260
+ }
261
+ /** Whether operations or reads wait for \`sync()\`. */
262
+ get queued() {
263
+ return this.ops.length > 0 || this.loads.length > 0;
264
+ }
265
+ /** Sends the queued operations and reads as one batch, then fills the loaded proxies. */
266
+ async sync() {
267
+ const ops = this.ops;
268
+ const loads = this.loads;
269
+ const created = this.created;
270
+ const pending = this.pending;
271
+ this.ops = [];
272
+ this.loads = [];
273
+ this.created = [];
274
+ this.pending = [];
275
+ if (ops.length === 0 && loads.length === 0) return;
276
+ const result = await this.send({
277
+ ...this.origin ? { origin: this.origin } : {},
278
+ ops,
279
+ load: loads.map(({ state, fields }) => ({ target: state.target, ...fields ? { fields } : {} }))
280
+ });
281
+ for (const state of created) {
282
+ const id = result.refs[state.target];
283
+ if (id === void 0) continue;
284
+ state.id = id;
285
+ state.target = id;
286
+ this.proxies.set(id, this.proxyOf(state));
287
+ }
288
+ for (const { index, set } of pending) set(result.results[index]);
289
+ loads.forEach(({ state }, index) => this.fill(state, result.loaded[index]));
290
+ }
291
+ fill(state, loaded) {
292
+ if (!loaded) return;
293
+ state.id = loaded.id;
294
+ state.type = loaded.type;
295
+ if (state.target === "root") this.proxies.set(loaded.id, this.proxyOf(state));
296
+ for (const [field, value] of Object.entries(loaded.fields)) state.fields.set(field, value);
297
+ }
298
+ byState = /* @__PURE__ */ new WeakMap();
299
+ proxyOf(state) {
300
+ return this.byState.get(state) ?? this.proxy(state);
301
+ }
302
+ push(op) {
303
+ this.ops.push(op);
304
+ }
305
+ field(state, name) {
306
+ return this.schema.types[state.type]?.fields[name];
307
+ }
308
+ proxy(state) {
309
+ const context = this;
310
+ const children = /* @__PURE__ */ new Map();
311
+ const base = {
312
+ [STATE]: state,
313
+ get id() {
314
+ if (state.id === null) throw new NotSyncedError(\`the id of a new \${state.type}\`);
315
+ return state.id;
316
+ },
317
+ get type() {
318
+ return state.type;
319
+ },
320
+ load(fields) {
321
+ context.loads.push({ state, ...fields ? { fields } : {} });
322
+ return proxy;
323
+ },
324
+ delete() {
325
+ context.push({ op: "delete", target: state.target });
326
+ },
327
+ isLoaded(field) {
328
+ return state.fields.has(field);
329
+ },
330
+ toJSON() {
331
+ return { id: state.id, type: state.type, ...Object.fromEntries(state.fields) };
332
+ }
333
+ };
334
+ const proxy = new Proxy(base, {
335
+ get(target, prop, receiver) {
336
+ if (typeof prop === "symbol" || prop in target) return Reflect.get(target, prop, receiver);
337
+ const def = context.field(state, prop);
338
+ if (!def) return void 0;
339
+ if (def.kind === "list" || def.kind === "text" || def.kind === "map" || def.kind === "tree") {
340
+ let child = children.get(prop);
341
+ if (!child) children.set(prop, child = context.container(state, prop, def, proxy));
342
+ return child;
343
+ }
344
+ if (!state.fields.has(prop)) throw new PropertyNotLoadedError(state.type, prop);
345
+ return state.fields.get(prop);
346
+ },
347
+ set(_target, prop, value) {
348
+ if (typeof prop === "symbol") return false;
349
+ const def = context.field(state, prop);
350
+ if (!def) throw new Error(\`\${state.type} has no field \\\`\${prop}\\\`\`);
351
+ if (def.kind === "text") {
352
+ context.push({ op: "text.set", target: state.target, field: prop, text: String(value) });
353
+ return true;
354
+ }
355
+ if (def.kind === "list" || def.kind === "map" || def.kind === "tree") throw new Error(\`\${state.type}.\${prop} is a \${def.kind}; use its methods\`);
356
+ const sent = wire(value);
357
+ context.push({ op: "set", target: state.target, field: prop, value: sent ?? null });
358
+ state.fields.set(prop, sent ?? null);
359
+ return true;
360
+ },
361
+ has(target, prop) {
362
+ return prop in target || typeof prop === "string" && context.field(state, prop) !== void 0;
363
+ }
364
+ });
365
+ this.byState.set(state, proxy);
366
+ return proxy;
367
+ }
368
+ container(state, field, def, owner) {
369
+ const context = this;
370
+ const loaded = () => {
371
+ if (!state.fields.has(field)) throw new PropertyNotLoadedError(state.type, field);
372
+ return state.fields.get(field);
373
+ };
374
+ const target = () => state.target;
375
+ if (def.kind === "list") {
376
+ const of = def.of ?? "";
377
+ const list = {
378
+ add(fields, options) {
379
+ const ref = \`$\${context.refs += 1}\`;
380
+ const created = { target: ref, type: of, id: null, fields: /* @__PURE__ */ new Map() };
381
+ context.created.push(created);
382
+ context.push({ op: "create", type: of, in: \`\${target()}.\${field}\`, ref, ...fields ? { fields: wire(fields) } : {}, ...options?.at !== void 0 ? { at: options.at } : {} });
383
+ return context.proxy(created);
384
+ },
385
+ insert(index, item) {
386
+ context.push({ op: "list.insert", target: target(), field, index, item: typeof item === "string" ? item : wire(item) });
387
+ },
388
+ move(from, to) {
389
+ context.push({ op: "list.move", target: target(), field, from, to });
390
+ },
391
+ remove(index) {
392
+ context.push({ op: "list.remove", target: target(), field, index });
393
+ },
394
+ load() {
395
+ owner.load([field]);
396
+ return list;
397
+ },
398
+ get items() {
399
+ return loaded().map((id) => context.object(id, of));
400
+ },
401
+ get length() {
402
+ return loaded().length;
403
+ },
404
+ at(index) {
405
+ const id = loaded()[index];
406
+ if (id === void 0) throw new RangeError(\`\${state.type}.\${field} has no item \${index}\`);
407
+ return context.object(id, of);
408
+ }
409
+ };
410
+ return list;
411
+ }
412
+ if (def.kind === "tree") {
413
+ const of = def.of ?? "";
414
+ const parentOf = (options) => options?.parent === void 0 || options.parent === null ? {} : { parent: typeof options.parent === "string" ? options.parent : wire(options.parent) };
415
+ const nodes = () => loaded();
416
+ const objectOf = (id, type) => context.object(id, type);
417
+ const tree = {
418
+ add(fields, options) {
419
+ const ref = \`$\${context.refs += 1}\`;
420
+ const created = { target: ref, type: of, id: null, fields: /* @__PURE__ */ new Map() };
421
+ context.created.push(created);
422
+ context.push({ op: "create", type: of, in: \`\${target()}.\${field}\`, ref, ...fields ? { fields: wire(fields) } : {}, ...parentOf(options) });
423
+ return context.proxy(created);
424
+ },
425
+ insert(item, options) {
426
+ context.push({ op: "tree.insert", target: target(), field, item: typeof item === "string" ? item : wire(item), ...parentOf(options) });
427
+ },
428
+ move(item, parent) {
429
+ context.push({ op: "tree.move", target: target(), field, item: typeof item === "string" ? item : wire(item), parent: parent === null ? null : typeof parent === "string" ? parent : wire(parent) });
430
+ },
431
+ load() {
432
+ owner.load([field]);
433
+ return tree;
434
+ },
435
+ get nodes() {
436
+ return nodes().map((node) => ({ object: objectOf(node.object, of), parent: node.parent === null ? null : objectOf(node.parent, of) }));
437
+ },
438
+ children(parent) {
439
+ const id = parent === void 0 || parent === null ? null : typeof parent === "string" ? parent : parent.id;
440
+ return nodes().filter((node) => node.parent === id).map((node) => objectOf(node.object, of));
441
+ }
442
+ };
443
+ return tree;
444
+ }
445
+ if (def.kind === "text") {
446
+ const text = {
447
+ insert(index, value) {
448
+ context.push({ op: "text.insert", target: target(), field, index, text: value });
449
+ },
450
+ delete(index, count) {
451
+ context.push({ op: "text.delete", target: target(), field, index, count });
452
+ },
453
+ set(value) {
454
+ context.push({ op: "text.set", target: target(), field, text: value });
455
+ },
456
+ mark(start, end, key, value) {
457
+ context.push({ op: "text.mark", target: target(), field, start, end, key, value: wire(value) });
458
+ },
459
+ unmark(start, end, key) {
460
+ context.push({ op: "text.unmark", target: target(), field, start, end, key });
461
+ },
462
+ load() {
463
+ owner.load([field]);
464
+ return text;
465
+ },
466
+ get value() {
467
+ return loaded();
468
+ },
469
+ toString() {
470
+ const value = loaded();
471
+ return typeof value === "string" ? value : value.map((run) => run.insert).join("");
472
+ }
473
+ };
474
+ return text;
475
+ }
476
+ const map = {
477
+ set(key, value) {
478
+ context.push({ op: "map.set", target: target(), field, key, value: wire(value) });
479
+ },
480
+ delete(key) {
481
+ context.push({ op: "map.delete", target: target(), field, key });
482
+ },
483
+ load() {
484
+ owner.load([field]);
485
+ return map;
486
+ },
487
+ get(key) {
488
+ return loaded()[key];
489
+ },
490
+ get value() {
491
+ return loaded();
492
+ }
493
+ };
494
+ return map;
495
+ }
496
+ }
497
+ class ExtensionDocument {
498
+ constructor(info, peer) {
499
+ this.peer = peer;
500
+ this.id = info.documentId;
501
+ this.kitId = info.kitId;
502
+ this.name = info.name;
503
+ this.readOnly = info.readOnly;
504
+ this.schema = info.schema;
505
+ }
506
+ listeners = /* @__PURE__ */ new Set();
507
+ id;
508
+ kitId;
509
+ /** The document's file name, when the host gives it. */
510
+ name;
511
+ /** Whether writes are refused (a read-only document, or no \`model.write\` permission). */
512
+ readOnly;
513
+ schema;
514
+ /** Runs \`script\` with a new request context; what it queued and did not \`sync()\` is sent when it returns. */
515
+ async run(script) {
516
+ const context = this.context();
517
+ const value = await script(context);
518
+ if (context.queued) await context.sync();
519
+ return value;
520
+ }
521
+ context() {
522
+ return new RequestContext(this.schema, (request) => this.batch(request));
523
+ }
524
+ /** One \`model/batch\` in its wire form (the host sets its origin). */
525
+ batch(request) {
526
+ return this.peer.request("model/batch", { documentId: this.id, request });
527
+ }
528
+ describe() {
529
+ return this.peer.request("model/describe", { documentId: this.id });
530
+ }
531
+ commands = {
532
+ list: () => this.peer.request("model/commands", { documentId: this.id }),
533
+ enabled: async (id) => (await this.commands.list()).some((command) => command.id === id && command.enabled !== false),
534
+ run: async (id, params) => (await this.batch({ ops: [{ op: "command", id, ...params === void 0 ? {} : { params } }] })).results[0]
535
+ };
536
+ on(event, listener) {
537
+ if (event !== "changed") throw new Error(\`unknown event \\\`\${event}\\\`\`);
538
+ this.listeners.add(listener);
539
+ return () => {
540
+ this.listeners.delete(listener);
541
+ };
542
+ }
543
+ /** The host's \`document/changed\`. */
544
+ emit(event) {
545
+ for (const listener of [...this.listeners]) {
546
+ try {
547
+ listener(event);
548
+ } catch (error) {
549
+ console.error("[kition-extension] a changed listener failed", error);
550
+ }
551
+ }
552
+ }
553
+ close() {
554
+ this.listeners.clear();
555
+ }
556
+ }
557
+ const isFunction = (value) => typeof value === "function";
558
+ function startRuntime(port, load) {
559
+ const peer = new RpcPeer(port);
560
+ let manifest = null;
561
+ let module = null;
562
+ let kind = "extension";
563
+ const activations = /* @__PURE__ */ new Map();
564
+ const sessions = /* @__PURE__ */ new Map();
565
+ const closeSession = (id) => {
566
+ const session = sessions.get(id);
567
+ if (!session) return;
568
+ sessions.delete(id);
569
+ session.peer.close("the panel closed");
570
+ for (const listener of [...session.closed, ...session.dispose ? [session.dispose] : []]) {
571
+ try {
572
+ listener();
573
+ } catch (error) {
574
+ console.error("[kition-extension] a panel close listener failed", error);
575
+ }
576
+ }
577
+ };
578
+ const context = (info, pending, handlers, panels) => {
579
+ const document = new ExtensionDocument(info, peer);
580
+ const { id, name, version, permissions } = manifest;
581
+ return {
582
+ extension: { id, name, version, permissions: [...permissions] },
583
+ document,
584
+ commands: {
585
+ register: (command, handler) => {
586
+ if (typeof command !== "string" || !isFunction(handler)) throw new TypeError("commands.register takes a command id and a function");
587
+ if (kind === "script") throw new ExtensionError("invalid", "a script cannot register commands");
588
+ if (!manifest.contributes.commands.some((contributed) => contributed.id === command)) {
589
+ throw new ExtensionError("invalid", \`\${id} does not contribute \${command}: declare it in extension.json contributes.commands\`);
590
+ }
591
+ handlers.set(command, handler);
592
+ pending.push(peer.request("commands/register", { documentId: info.documentId, command }));
593
+ return () => {
594
+ if (handlers.get(command) === handler) handlers.delete(command);
595
+ };
596
+ }
597
+ },
598
+ panels: {
599
+ register: (panel, handler) => {
600
+ if (typeof panel !== "string" || !isFunction(handler)) throw new TypeError("panels.register takes a panel id and a function");
601
+ if (kind === "script") throw new ExtensionError("invalid", "a script cannot serve panels");
602
+ if (!manifest.contributes.panels?.some((contributed) => contributed.id === panel)) {
603
+ throw new ExtensionError("invalid", \`\${id} does not contribute the panel \${panel}: declare it in extension.json contributes.panels\`);
604
+ }
605
+ panels.set(panel, handler);
606
+ return () => {
607
+ if (panels.get(panel) === handler) panels.delete(panel);
608
+ };
609
+ }
610
+ },
611
+ notify: (notice, options) => {
612
+ const full = typeof notice === "string" ? { level: options?.level ?? "info", title: notice, ...options?.description ? { description: options.description } : {} } : notice;
613
+ peer.notify("host/notify", full);
614
+ },
615
+ subscriptions: []
616
+ };
617
+ };
618
+ const loaded = () => {
619
+ if (!manifest || !module) throw new ExtensionError("failed", "the extension has not started");
620
+ return { manifest, module };
621
+ };
622
+ peer.handle("extension/start", async (params) => {
623
+ if (module) throw new ExtensionError("invalid", "the extension has already started");
624
+ manifest = params.manifest;
625
+ kind = params.kind ?? "extension";
626
+ const imported = await load(params.source);
627
+ if (kind === "script" ? !isFunction(imported.default) && !isFunction(imported.run) : !isFunction(imported.activate)) {
628
+ throw new ExtensionError("invalid", kind === "script" ? "a script exports a default function (or run)" : \`\${manifest.entry} exports no activate function\`);
629
+ }
630
+ module = imported;
631
+ return null;
632
+ }).handle("extension/activate", async (info) => {
633
+ const { module: module2 } = loaded();
634
+ if (activations.has(info.documentId)) return { commands: [...activations.get(info.documentId).handlers.keys()] };
635
+ const pending = [];
636
+ const handlers = /* @__PURE__ */ new Map();
637
+ const panels = /* @__PURE__ */ new Map();
638
+ const ctx = context(info, pending, handlers, panels);
639
+ const activation = { context: ctx, handlers, panels, disposeActivate: null };
640
+ activations.set(info.documentId, activation);
641
+ try {
642
+ const answer = await module2.activate(ctx);
643
+ if (isFunction(answer)) activation.disposeActivate = answer;
644
+ await Promise.all(pending);
645
+ } catch (error) {
646
+ activations.delete(info.documentId);
647
+ for (const registration of pending) registration.catch(() => void 0);
648
+ throw error;
649
+ }
650
+ return { commands: [...handlers.keys()] };
651
+ }).handle("extension/command", async ({ documentId, command }) => {
652
+ const handler = activations.get(documentId)?.handlers.get(command);
653
+ if (!handler) throw new ExtensionError("not-found", \`\${command} is not registered on \${documentId}\`);
654
+ return await handler() ?? null;
655
+ }).handle("extension/deactivate", async ({ documentId }) => {
656
+ const activation = activations.get(documentId);
657
+ if (!activation) return null;
658
+ activations.delete(documentId);
659
+ for (const [id, session] of [...sessions]) if (session.documentId === documentId) closeSession(id);
660
+ const { context: context2 } = activation;
661
+ try {
662
+ await module?.deactivate?.(context2);
663
+ await activation.disposeActivate?.();
664
+ } finally {
665
+ for (const dispose of context2.subscriptions.splice(0)) {
666
+ try {
667
+ dispose();
668
+ } catch (error) {
669
+ console.error("[kition-extension] a subscription failed to dispose", error);
670
+ }
671
+ }
672
+ context2.document.close();
673
+ }
674
+ return null;
675
+ }).handle("script/run", async (info) => {
676
+ const { module: module2 } = loaded();
677
+ const run = isFunction(module2.default) ? module2.default : module2.run;
678
+ const ctx = context(info, [], /* @__PURE__ */ new Map(), /* @__PURE__ */ new Map());
679
+ activations.set(info.documentId, { context: ctx, handlers: /* @__PURE__ */ new Map(), panels: /* @__PURE__ */ new Map(), disposeActivate: null });
680
+ return await run(ctx) ?? null;
681
+ }).handle("document/changed", ({ documentId, origin }) => {
682
+ activations.get(documentId)?.context.document.emit({ origin });
683
+ }).handle("panel/open", async ({ documentId, panel, session }, ports) => {
684
+ const activation = activations.get(documentId);
685
+ if (!activation) throw new ExtensionError("not-found", \`the extension is not active on \${documentId}\`);
686
+ const port2 = ports[0];
687
+ if (!port2) throw new ExtensionError("invalid", "a panel opens with its port");
688
+ if (sessions.has(session)) throw new ExtensionError("invalid", \`the panel session \${session} is open already\`);
689
+ const panelPeer = new RpcPeer(port2);
690
+ let answer = null;
691
+ panelPeer.handle("panel/request", async (message) => {
692
+ if (!answer) throw new ExtensionError("not-found", \`the extension does not answer the panel \${panel}\`);
693
+ return await answer(message) ?? null;
694
+ });
695
+ const open = { documentId, peer: panelPeer, closed: /* @__PURE__ */ new Set(), dispose: null };
696
+ sessions.set(session, open);
697
+ const connection = {
698
+ id: panel,
699
+ session,
700
+ post: (message) => panelPeer.notify("panel/message", message),
701
+ onRequest: (handler2) => {
702
+ if (!isFunction(handler2)) throw new TypeError("onRequest takes a function");
703
+ answer = handler2;
704
+ },
705
+ onClose: (listener) => {
706
+ open.closed.add(listener);
707
+ return () => {
708
+ open.closed.delete(listener);
709
+ };
710
+ }
711
+ };
712
+ const handler = activation.panels.get(panel);
713
+ try {
714
+ const dispose = handler ? await handler(connection) : null;
715
+ if (isFunction(dispose)) open.dispose = dispose;
716
+ } catch (error) {
717
+ closeSession(session);
718
+ throw error;
719
+ }
720
+ return null;
721
+ }).handle("panel/close", ({ session }) => {
722
+ closeSession(session);
723
+ return null;
724
+ });
725
+ return peer;
726
+ }
727
+ const scope = self;
728
+ scope.onmessage = (event) => {
729
+ const data = event.data;
730
+ if (!data || data.tag !== SANDBOX_TAG || data.type !== "port" || !event.ports[0]) return;
731
+ scope.onmessage = null;
732
+ startRuntime(event.ports[0], async (source) => {
733
+ const url = URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
734
+ try {
735
+ return await import(
736
+ /* @vite-ignore */
737
+ url
738
+ );
739
+ } finally {
740
+ URL.revokeObjectURL(url);
741
+ }
742
+ });
743
+ };
744
+ })();
745
+ `, y = `<!doctype html>
746
+ <!-- Generated by packages/extensions/scripts/build-runtime.mjs from sandbox/bootstrap.js. Do not edit; rebuild it. -->
747
+ <html lang="en">
748
+ <head>
749
+ <meta charset="utf-8">
750
+ <meta http-equiv="Content-Security-Policy" content="script-src 'sha256-w5PK36FENsjJixOfZqEByZ2fjQ+2p/KZc2ZsgQ9e4rs=' blob:; worker-src blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; img-src 'none'; media-src 'none'; font-src 'none'; style-src 'none'; manifest-src 'none'">
751
+ <meta name="referrer" content="no-referrer">
752
+ <title>Kition extension sandbox</title>
753
+ <script>// The extension sandbox page's only script (its CSP allows it by hash). The host posts it the
754
+ // worker runtime, the extension's allowed connect-src, and the channel's port; it adds the
755
+ // connect-src policy, starts the worker from a blob, and hands the worker the port.
756
+ ;(() => {
757
+ 'use strict'
758
+ const TAG = 'kition-ext-sandbox/1'
759
+ const SOURCE = /^(?:'none'|(?:(?:https|wss|http|ws):\\/\\/(?:\\*\\.)?[a-z0-9.-]+(?::\\d{1,5})?)(?: (?:https|wss|http|ws):\\/\\/(?:\\*\\.)?[a-z0-9.-]+(?::\\d{1,5})?)*)$/
760
+ let started = false
761
+ addEventListener('message', (event) => {
762
+ const data = event.data
763
+ if (started || event.source !== parent || !data || data.tag !== TAG || data.type !== 'start') return
764
+ const port = event.ports[0]
765
+ if (!port || typeof data.runtime !== 'string' || typeof data.connect !== 'string' || !SOURCE.test(data.connect)) return
766
+ started = true
767
+ const policy = document.createElement('meta')
768
+ policy.httpEquiv = 'Content-Security-Policy'
769
+ policy.content = \`connect-src \${data.connect}\`
770
+ document.head.appendChild(policy)
771
+ const url = URL.createObjectURL(new Blob([data.runtime], { type: 'text/javascript' }))
772
+ const worker = new Worker(url, { name: 'kition-extension' })
773
+ worker.postMessage({ tag: TAG, type: 'port' }, [port])
774
+ })
775
+ })()
776
+ <\/script>
777
+ </head>
778
+ <body></body>
779
+ </html>
780
+ `, x = `<!doctype html>
781
+ <!-- Generated by packages/extensions/scripts/build-runtime.mjs from src/runtime/panel.ts. Do not edit; rebuild it. -->
782
+ <html lang="en">
783
+ <head>
784
+ <meta charset="utf-8">
785
+ <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'">
786
+ <meta name="referrer" content="no-referrer">
787
+ <meta name="viewport" content="width=device-width, initial-scale=1">
788
+ <title>Kition extension panel</title>
789
+ <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>
790
+ <script>(function() {
791
+ "use strict";
792
+ const PANEL_TAG = "kition-ext-panel/1";
793
+ const CHANNEL_TAG = "kition-ext/1";
794
+ class ExtensionError extends Error {
795
+ constructor(code, message, data) {
796
+ super(message);
797
+ this.code = code;
798
+ this.data = data;
799
+ this.name = code === "permission-denied" ? "PermissionError" : "ExtensionError";
800
+ }
801
+ toJSON() {
802
+ return { code: this.code, message: this.message, ...this.data ? { data: this.data } : {} };
803
+ }
804
+ }
805
+ const isMessage = (value) => typeof value === "object" && value !== null && value.tag === CHANNEL_TAG;
806
+ function wireError(error) {
807
+ if (error instanceof ExtensionError) return error.toJSON();
808
+ const coded = error;
809
+ if (error instanceof Error && typeof coded.code === "string") {
810
+ return { code: coded.code, message: error.message, ...coded.index !== void 0 ? { data: { index: coded.index } } : {} };
811
+ }
812
+ return { code: "failed", message: error instanceof Error ? error.message : String(error) };
813
+ }
814
+ class RpcPeer {
815
+ constructor(port) {
816
+ this.port = port;
817
+ port.onmessage = (event) => this.receive(event.data, event.ports ?? []);
818
+ port.start?.();
819
+ }
820
+ next = 1;
821
+ pending = /* @__PURE__ */ new Map();
822
+ handlers = /* @__PURE__ */ new Map();
823
+ closed = false;
824
+ /** Answers \`method\` with \`handler\` (its result, or the error it throws). */
825
+ handle(method, handler) {
826
+ this.handlers.set(method, handler);
827
+ return this;
828
+ }
829
+ /** Asks \`method\`; \`transfer\` (a \`MessagePort\`, …) goes with the request. */
830
+ request(method, params, timeoutMs = 0, transfer) {
831
+ if (this.closed) return Promise.reject(new ExtensionError("failed", "the extension channel is closed"));
832
+ const id = this.next++;
833
+ return new Promise((resolve, reject) => {
834
+ let timer = null;
835
+ this.pending.set(id, {
836
+ resolve: (value) => {
837
+ if (timer) clearTimeout(timer);
838
+ resolve(value);
839
+ },
840
+ reject: (error) => {
841
+ if (timer) clearTimeout(timer);
842
+ reject(error);
843
+ }
844
+ });
845
+ if (timeoutMs > 0) {
846
+ timer = setTimeout(() => {
847
+ this.pending.delete(id);
848
+ reject(new ExtensionError("failed", \`\${method} did not answer within \${timeoutMs} ms\`));
849
+ }, timeoutMs);
850
+ }
851
+ const message = { tag: CHANNEL_TAG, id, method, params };
852
+ if (transfer?.length) this.port.postMessage(message, transfer);
853
+ else this.port.postMessage(message);
854
+ });
855
+ }
856
+ notify(method, params) {
857
+ if (!this.closed) this.port.postMessage({ tag: CHANNEL_TAG, method, params });
858
+ }
859
+ /** Fails every request still waiting and stops listening. */
860
+ close(reason = "the extension channel is closed") {
861
+ if (this.closed) return;
862
+ this.closed = true;
863
+ this.port.onmessage = null;
864
+ this.port.close?.();
865
+ for (const { reject } of this.pending.values()) reject(new ExtensionError("failed", reason));
866
+ this.pending.clear();
867
+ }
868
+ receive(data, ports) {
869
+ if (!isMessage(data) || this.closed) return;
870
+ if (data.method !== void 0) {
871
+ void this.answer(data, ports);
872
+ return;
873
+ }
874
+ if (data.id === void 0) return;
875
+ const waiting = this.pending.get(data.id);
876
+ if (!waiting) return;
877
+ this.pending.delete(data.id);
878
+ if (data.error) waiting.reject(new ExtensionError(data.error.code, data.error.message, data.error.data));
879
+ else waiting.resolve(data.result);
880
+ }
881
+ async answer(message, ports) {
882
+ const handler = this.handlers.get(message.method);
883
+ let reply;
884
+ try {
885
+ if (!handler) throw new ExtensionError("not-found", \`\${message.method} is not served here\`);
886
+ const result = await handler(message.params, ports);
887
+ reply = { tag: CHANNEL_TAG, id: message.id, result: result === void 0 ? null : result };
888
+ } catch (error) {
889
+ reply = { tag: CHANNEL_TAG, id: message.id, error: wireError(error) };
890
+ }
891
+ if (message.id === void 0 || this.closed) return;
892
+ try {
893
+ this.port.postMessage(reply);
894
+ } catch (error) {
895
+ 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)}\` } });
896
+ }
897
+ }
898
+ }
899
+ const SOURCE = /^(?:'none'|(?:(?:https|wss|http|ws):\\/\\/(?:\\*\\.)?[a-z0-9.-]+(?::\\d{1,5})?)(?: (?:https|wss|http|ws):\\/\\/(?:\\*\\.)?[a-z0-9.-]+(?::\\d{1,5})?)*)$/;
900
+ const THEME_NAME = /^--[a-zA-Z0-9-]{1,64}$/;
901
+ const JAVASCRIPT = /* @__PURE__ */ new Set(["", "text/javascript", "application/javascript", "text/ecmascript", "application/ecmascript"]);
902
+ function addPolicy(content) {
903
+ const policy = document.createElement("meta");
904
+ policy.httpEquiv = "Content-Security-Policy";
905
+ policy.content = content;
906
+ document.head.appendChild(policy);
907
+ }
908
+ function applyTheme(theme) {
909
+ if (!theme || typeof theme !== "object") return;
910
+ for (const [name, value] of Object.entries(theme)) {
911
+ if (THEME_NAME.test(name) && typeof value === "string" && value.length <= 300) document.documentElement.style.setProperty(name, value);
912
+ }
913
+ }
914
+ function render(html) {
915
+ const parsed = new DOMParser().parseFromString(html, "text/html");
916
+ const scripts = [];
917
+ for (const script of [...parsed.querySelectorAll("script")]) {
918
+ const type = (script.getAttribute("type") ?? "").trim().toLowerCase();
919
+ if (!JAVASCRIPT.has(type)) {
920
+ if (type !== "module") continue;
921
+ console.warn("[kition-panel] module scripts do not run in a panel; bundle them into a classic script");
922
+ script.remove();
923
+ continue;
924
+ }
925
+ if (script.hasAttribute("src")) {
926
+ console.warn("[kition-panel] scripts with src do not run in a panel; put the code inline");
927
+ script.remove();
928
+ continue;
929
+ }
930
+ const placeholder = parsed.createElement("template");
931
+ placeholder.dataset.kitionScript = String(scripts.length);
932
+ scripts.push(script.textContent ?? "");
933
+ script.replaceWith(placeholder);
934
+ }
935
+ for (const element of [...parsed.querySelectorAll('base, meta[http-equiv="refresh" i]')]) element.remove();
936
+ for (const attribute of [...parsed.documentElement.attributes]) document.documentElement.setAttribute(attribute.name, attribute.value);
937
+ for (const child of [...parsed.head.childNodes]) document.head.appendChild(document.importNode(child, true));
938
+ document.body.replaceWith(document.importNode(parsed.body, true));
939
+ for (const placeholder of [...document.querySelectorAll("template[data-kition-script]")]) {
940
+ const script = document.createElement("script");
941
+ script.async = false;
942
+ script.src = URL.createObjectURL(new Blob([scripts[Number(placeholder.dataset.kitionScript)]], { type: "text/javascript" }));
943
+ script.addEventListener("load", () => URL.revokeObjectURL(script.src), { once: true });
944
+ placeholder.replaceWith(script);
945
+ }
946
+ }
947
+ let started = false;
948
+ addEventListener("message", (event) => {
949
+ const data = event.data;
950
+ if (started || event.source !== parent || !data || data.tag !== PANEL_TAG || data.type !== "start") return;
951
+ const port = event.ports[0];
952
+ const info = data.info;
953
+ if (!port || typeof data.html !== "string" || typeof data.connect !== "string" || !SOURCE.test(data.connect) || !info || typeof info !== "object") return;
954
+ started = true;
955
+ addPolicy(\`connect-src \${data.connect}\`);
956
+ applyTheme(data.theme);
957
+ if (typeof info.locale === "string") document.documentElement.lang = info.locale;
958
+ const peer = new RpcPeer(port);
959
+ const listeners = /* @__PURE__ */ new Set();
960
+ peer.handle("panel/message", (message) => {
961
+ for (const listener of [...listeners]) {
962
+ try {
963
+ listener(message);
964
+ } catch (error) {
965
+ console.error("[kition-panel] a message listener failed", error);
966
+ }
967
+ }
968
+ });
969
+ const panel = Object.freeze({
970
+ 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 } : {} }),
971
+ request: (message) => peer.request("panel/request", message),
972
+ onMessage: (listener) => {
973
+ if (typeof listener !== "function") throw new TypeError("onMessage takes a function");
974
+ listeners.add(listener);
975
+ return () => {
976
+ listeners.delete(listener);
977
+ };
978
+ }
979
+ });
980
+ Object.defineProperty(window, "kitionPanel", { value: panel, enumerable: true });
981
+ render(data.html);
982
+ });
983
+ })();
984
+ <\/script>
985
+ </head>
986
+ <body></body>
987
+ </html>
988
+ `;
989
+ export {
990
+ i as C,
991
+ a as E,
992
+ x as P,
993
+ f as R,
994
+ y as S,
995
+ w as W,
996
+ g as a
997
+ };