markloom 0.3.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,1076 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunkVVFIQLVRcjs = require('./chunk-VVFIQLVR.cjs');
10
+
11
+ // src/view/selection.ts
12
+ function rootEl(root) {
13
+ return _nullishCoalesce(root.querySelector(".loom-doc"), () => ( root));
14
+ }
15
+ function pointToDom(root, doc, pos) {
16
+ const path = pos.path;
17
+ if (path.length < 2)
18
+ return null;
19
+ let domNode = rootEl(root);
20
+ for (let i = 0; i < path.length - 1; i++) {
21
+ if (!domNode)
22
+ return null;
23
+ const child = elementChildren(domNode)[path[i]];
24
+ if (!child)
25
+ return null;
26
+ domNode = child;
27
+ }
28
+ if (!domNode)
29
+ return null;
30
+ return locateInLeaf(domNode, path[path.length - 1]);
31
+ }
32
+ function domToPoint(root, doc, container, domOffset) {
33
+ const top = rootEl(root);
34
+ const segs = [];
35
+ let node = container;
36
+ let charOffset = container.nodeType === 3 ? domOffset : 0;
37
+ const structural = node instanceof HTMLElement && node.nodeType !== 3 && !closestLeaf(node);
38
+ if (structural) {
39
+ const kids = elementChildren(node);
40
+ const at = kids[domOffset];
41
+ if (at) {
42
+ node = _nullishCoalesce(deepestText(at), () => ( at));
43
+ charOffset = 0;
44
+ } else if (kids.length > 0) {
45
+ const prev = kids[kids.length - 1];
46
+ const tail = _nullishCoalesce(deepestText(prev), () => ( prev));
47
+ node = tail;
48
+ charOffset = tail.nodeType === 3 ? _nullishCoalesce(_optionalChain([tail, 'access', _ => _.textContent, 'optionalAccess', _2 => _2.length]), () => ( 0)) : 0;
49
+ }
50
+ } else if (node && node.nodeType !== 3) {
51
+ const leaf = node instanceof HTMLElement ? deepestText(node) : null;
52
+ if (leaf) {
53
+ charOffset = node === leaf ? domOffset : 0;
54
+ node = leaf;
55
+ }
56
+ }
57
+ const leafEl = closestLeaf(node);
58
+ if (leafEl && node && node.nodeType === 3 && container.nodeType === 3)
59
+ charOffset = offsetWithinLeaf(leafEl, node, domOffset);
60
+ while (node && node !== top) {
61
+ const parent = node.parentNode;
62
+ if (node instanceof HTMLElement && (node.dataset.blockId !== void 0 || node.dataset.leaf !== void 0)) {
63
+ const sp = structuralParent(node);
64
+ if (sp)
65
+ segs.unshift(elementChildren(sp).indexOf(node));
66
+ }
67
+ node = parent;
68
+ }
69
+ if (segs.length === 0)
70
+ return null;
71
+ return { path: _chunkVVFIQLVRcjs.normalizeToLeaf.call(void 0, doc, segs.concat(charOffset)) };
72
+ }
73
+ function readSelection(root, doc) {
74
+ const sel = root.ownerDocument.getSelection();
75
+ if (!sel || sel.rangeCount === 0)
76
+ return null;
77
+ const anchor = domToPoint(root, doc, sel.anchorNode, sel.anchorOffset);
78
+ const head = domToPoint(root, doc, sel.focusNode, sel.focusOffset);
79
+ if (!anchor || !head)
80
+ return null;
81
+ return { anchor, head };
82
+ }
83
+ function writeSelection(root, doc, selection) {
84
+ const a = pointToDom(root, doc, selection.anchor);
85
+ const hd = pointToDom(root, doc, selection.head);
86
+ if (!a || !hd)
87
+ return;
88
+ const sel = root.ownerDocument.getSelection();
89
+ if (!sel)
90
+ return;
91
+ const host = editableHost(a.node, root);
92
+ if (host && host !== root.ownerDocument.activeElement)
93
+ host.focus({ preventScroll: true });
94
+ const range = root.ownerDocument.createRange();
95
+ range.setStart(a.node, a.offset);
96
+ range.setEnd(hd.node, hd.offset);
97
+ sel.removeAllRanges();
98
+ sel.addRange(range);
99
+ }
100
+ function editableHost(node, root) {
101
+ let el = node.nodeType === 3 ? node.parentElement : node;
102
+ while (el && el !== root) {
103
+ if (el.getAttribute("contenteditable") === "true")
104
+ return el;
105
+ el = el.parentElement;
106
+ }
107
+ return root.getAttribute("contenteditable") === "true" ? root : null;
108
+ }
109
+ var TRANSPARENT = /* @__PURE__ */ new Set(["TBODY", "TR", "THEAD", "TFOOT", "COLGROUP"]);
110
+ function isTransparent(el) {
111
+ return TRANSPARENT.has(el.tagName) || el.dataset.pass !== void 0;
112
+ }
113
+ function elementChildren(el) {
114
+ const out = [];
115
+ for (const c of el.children) {
116
+ if (!(c instanceof HTMLElement))
117
+ continue;
118
+ if (c.dataset.blockId !== void 0 || c.dataset.leaf !== void 0)
119
+ out.push(c);
120
+ else if (isTransparent(c))
121
+ out.push(...elementChildren(c));
122
+ }
123
+ return out;
124
+ }
125
+ function structuralParent(node) {
126
+ let p = node.parentElement;
127
+ while (p && isTransparent(p))
128
+ p = p.parentElement;
129
+ return p;
130
+ }
131
+ function deepestText(el) {
132
+ if (el.nodeType === 3)
133
+ return el;
134
+ let node = el.firstChild;
135
+ while (node) {
136
+ if (node.nodeType === 3)
137
+ return node;
138
+ const inner = deepestText(node);
139
+ if (inner)
140
+ return inner;
141
+ node = node.nextSibling;
142
+ }
143
+ return el.nodeType === 1 ? null : el;
144
+ }
145
+ function closestLeaf(node) {
146
+ let n = node;
147
+ while (n) {
148
+ if (n instanceof HTMLElement && n.dataset.leaf !== void 0)
149
+ return n;
150
+ n = n.parentNode;
151
+ }
152
+ return null;
153
+ }
154
+ function leafTextNodes(leaf) {
155
+ const out = [];
156
+ const walk = (n) => {
157
+ for (let c = n.firstChild; c; c = c.nextSibling) {
158
+ if (c.nodeType === 3)
159
+ out.push(c);
160
+ else walk(c);
161
+ }
162
+ };
163
+ walk(leaf);
164
+ return out;
165
+ }
166
+ var ZWSP = "\u200B";
167
+ function zwspFreeLen(s) {
168
+ return s.split(ZWSP).join("").length;
169
+ }
170
+ function offsetWithinLeaf(leaf, target, domOffset) {
171
+ let acc = 0;
172
+ for (const t of leafTextNodes(leaf)) {
173
+ const s = _nullishCoalesce(t.textContent, () => ( ""));
174
+ if (t === target)
175
+ return acc + zwspFreeLen(s.slice(0, domOffset));
176
+ acc += zwspFreeLen(s);
177
+ }
178
+ return acc;
179
+ }
180
+ function locateInLeaf(leaf, charOff) {
181
+ const texts = leafTextNodes(leaf);
182
+ if (texts.length === 0) {
183
+ const t = deepestText(leaf);
184
+ return { node: _nullishCoalesce(t, () => ( leaf)), offset: 0 };
185
+ }
186
+ let off = Math.max(0, charOff);
187
+ let prev = null;
188
+ for (const t of texts) {
189
+ const s = _nullishCoalesce(t.textContent, () => ( ""));
190
+ const len = zwspFreeLen(s);
191
+ if (s === "\n") {
192
+ if (off === 0)
193
+ return _nullishCoalesce(prev, () => ( { node: t, offset: 1 }));
194
+ off -= len;
195
+ continue;
196
+ }
197
+ if (off < len || len === 0 && off === 0) {
198
+ let dom = 0;
199
+ let seen = 0;
200
+ for (; dom < s.length && seen < off; dom++)
201
+ if (s[dom] !== ZWSP)
202
+ seen++;
203
+ if (len === 0)
204
+ dom = s.length;
205
+ return { node: t, offset: dom };
206
+ }
207
+ prev = { node: t, offset: s.length };
208
+ off -= len;
209
+ }
210
+ return _nullishCoalesce(prev, () => ( { node: texts[texts.length - 1], offset: _nullishCoalesce(_optionalChain([texts, 'access', _3 => _3[texts.length - 1], 'access', _4 => _4.textContent, 'optionalAccess', _5 => _5.length]), () => ( 0)) }));
211
+ }
212
+
213
+ // src/view/ai-write.ts
214
+ var newId = () => _nullishCoalesce(_optionalChain([crypto, 'optionalAccess', _6 => _6.randomUUID, 'optionalCall', _7 => _7()]), () => ( `ai${Math.random().toString(36).slice(2)}`));
215
+ function focusBlockId(ed) {
216
+ const sel = readSelection(ed.root, ed.doc);
217
+ const idx = _nullishCoalesce(_optionalChain([sel, 'optionalAccess', _8 => _8.head, 'access', _9 => _9.path, 'access', _10 => _10[0]]), () => ( Math.max(0, ed.doc.children.length - 1)));
218
+ const b = ed.doc.children[idx];
219
+ if (!b || _chunkVVFIQLVRcjs.isText.call(void 0, b) || !b.id)
220
+ return null;
221
+ return b.id;
222
+ }
223
+ function blockPlainText(doc, blockId) {
224
+ const b = doc.children.find((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === blockId);
225
+ if (!b)
226
+ return "";
227
+ return collectText(b);
228
+ }
229
+ function collectText(n) {
230
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, n))
231
+ return n.text;
232
+ return n.children.map(collectText).join("");
233
+ }
234
+ function emptyLike(block) {
235
+ if (block.type === "heading")
236
+ return { type: "heading", id: block.id, attrs: { ...block.attrs }, children: [{ text: "" }] };
237
+ if (block.type === "code")
238
+ return { type: "code", id: block.id, attrs: { ...block.attrs }, children: [{ text: "" }] };
239
+ if (block.type === "quote" || block.type === "callout") {
240
+ return {
241
+ type: block.type,
242
+ id: block.id,
243
+ attrs: block.attrs ? { ...block.attrs } : void 0,
244
+ children: [{ type: "paragraph", id: newId(), children: [{ text: "" }] }]
245
+ };
246
+ }
247
+ return { type: "paragraph", id: block.id, attrs: block.attrs ? { ...block.attrs } : void 0, children: [{ text: "" }] };
248
+ }
249
+ function streamTargetId(doc, blockId) {
250
+ const b = doc.children.find((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === blockId);
251
+ if (!b)
252
+ return blockId;
253
+ if (b.type === "quote" || b.type === "callout") {
254
+ const inner = b.children.find((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.type === "paragraph");
255
+ if (_optionalChain([inner, 'optionalAccess', _11 => _11.id]))
256
+ return inner.id;
257
+ }
258
+ return blockId;
259
+ }
260
+ function startAiWrite(ed, mode, blockId) {
261
+ if (ed.root.contentEditable === "false")
262
+ throw new Error("readonly");
263
+ const focus = _nullishCoalesce(blockId, () => ( focusBlockId(ed)));
264
+ if (!focus)
265
+ throw new Error("no focus block");
266
+ let targetId = focus;
267
+ let alive = true;
268
+ let opened = false;
269
+ const setup = () => {
270
+ if (opened)
271
+ return;
272
+ const doc = ed.doc;
273
+ if (mode === "continue") {
274
+ const id = newId();
275
+ const empty = { type: "paragraph", id, children: [{ text: "" }] };
276
+ ed.dispatch([_chunkVVFIQLVRcjs.insertAfter.call(void 0, doc, focus, [empty])]);
277
+ targetId = id;
278
+ } else {
279
+ const block = doc.children.find((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === focus);
280
+ if (!block)
281
+ throw new Error(`block not found: ${focus}`);
282
+ if (block.type === "table" || block.type === "image" || block.type === "embed" || block.type === "raw")
283
+ throw new Error(`cannot rewrite ${block.type}`);
284
+ const cleared = emptyLike(block);
285
+ ed.dispatch([_chunkVVFIQLVRcjs.rewriteNode.call(void 0, doc, focus, cleared)]);
286
+ targetId = streamTargetId(ed.doc, focus);
287
+ }
288
+ opened = true;
289
+ };
290
+ const push = (text) => {
291
+ if (!alive || !text)
292
+ return;
293
+ setup();
294
+ const step = _chunkVVFIQLVRcjs.appendText.call(void 0, ed.doc, targetId, text);
295
+ ed.dispatchStream([step]);
296
+ };
297
+ const finish = () => {
298
+ alive = false;
299
+ };
300
+ return {
301
+ mode,
302
+ get blockId() {
303
+ return targetId;
304
+ },
305
+ get alive() {
306
+ return alive;
307
+ },
308
+ push,
309
+ done: finish,
310
+ abort: finish
311
+ };
312
+ }
313
+
314
+ // src/ai/context.ts
315
+ function precedingPlainText(doc, blockIdx) {
316
+ const parts = [];
317
+ for (let i = 0; i < blockIdx && i < doc.children.length; i++) {
318
+ const b = doc.children[i];
319
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, b) || !b.id)
320
+ continue;
321
+ if (b.type === "image" || b.type === "table" || b.type === "embed" || b.type === "raw" || b.type === "ai")
322
+ continue;
323
+ if (_optionalChain([b, 'access', _12 => _12.attrs, 'optionalAccess', _13 => _13.aiDraft]))
324
+ continue;
325
+ const t = blockPlainText(doc, b.id);
326
+ if (t.trim())
327
+ parts.push(t);
328
+ }
329
+ return parts.join("\n\n");
330
+ }
331
+ function aiInstructionFromQuery(query) {
332
+ const q = query.trim();
333
+ if (!q.toLowerCase().startsWith("ai"))
334
+ return "";
335
+ return q.slice(2).trim();
336
+ }
337
+ var newAiId = () => _nullishCoalesce(_optionalChain([crypto, 'access', _14 => _14.randomUUID, 'optionalCall', _15 => _15()]), () => ( `ai${Math.random().toString(36).slice(2)}`));
338
+
339
+ // src/ai/controller.ts
340
+ var LoomAi = (_class = class {
341
+
342
+
343
+ __init() {this.abort = null}
344
+ __init2() {this.streamingId = null}
345
+ /** 当前 AI 写事务是否打开(begin 后 ~ accept/discard) */
346
+ __init3() {this.txOpen = false}
347
+ __init4() {this.txBlockId = null}
348
+ __init5() {this.raf = 0}
349
+ /** 流式累积的 Markdown 源(每帧物化成真·富文本块做预览) */
350
+ __init6() {this.pendingMd = ""}
351
+ constructor(getEditor, opts) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);_class.prototype.__init4.call(this);_class.prototype.__init5.call(this);_class.prototype.__init6.call(this);
352
+ this.getEditor = getEditor;
353
+ this.opts = opts;
354
+ }
355
+ destroy() {
356
+ _optionalChain([this, 'access', _16 => _16.abort, 'optionalAccess', _17 => _17.abort, 'call', _18 => _18()]);
357
+ this.clearRaf();
358
+ this.streamingId = null;
359
+ this.pendingMd = "";
360
+ this.txOpen = false;
361
+ this.txBlockId = null;
362
+ }
363
+ /**
364
+ * 停止生成:
365
+ * · 已有正文 → 留在事务内,进入 preview(可确认/可 undo 整笔)
366
+ * · 空 → undo 整笔事务(等同丢弃)
367
+ */
368
+ stop() {
369
+ _optionalChain([this, 'access', _19 => _19.abort, 'optionalAccess', _20 => _20.abort, 'call', _21 => _21()]);
370
+ this.abort = null;
371
+ this.clearRaf();
372
+ const id = this.streamingId;
373
+ const md = this.pendingMd;
374
+ this.pendingMd = "";
375
+ this.streamingId = null;
376
+ _optionalChain([this, 'access', _22 => _22.opts, 'access', _23 => _23.onBusy, 'optionalCall', _24 => _24(false)]);
377
+ if (!id)
378
+ return;
379
+ const ed = this.getEditor();
380
+ if (!ed)
381
+ return;
382
+ if (md.trim()) {
383
+ this.paintMd(ed, id, md, false);
384
+ this.patchAi(ed, id, { status: "preview" });
385
+ } else {
386
+ this.rollback();
387
+ }
388
+ }
389
+ clearRaf() {
390
+ if (this.raf) {
391
+ cancelAnimationFrame(this.raf);
392
+ this.raf = 0;
393
+ }
394
+ }
395
+ get busy() {
396
+ return this.streamingId != null;
397
+ }
398
+ /** 是否有未提交的 AI 写事务 */
399
+ get pending() {
400
+ return this.txOpen;
401
+ }
402
+ openAtFocus(mode) {
403
+ const ed = this.getEditor();
404
+ if (!ed || this.busy)
405
+ return;
406
+ const bid = focusBlockId(ed);
407
+ if (!bid) {
408
+ _optionalChain([this, 'access', _25 => _25.opts, 'access', _26 => _26.onError, 'optionalCall', _27 => _27("\u8BF7\u5148\u628A\u5149\u6807\u653E\u5728\u4E00\u6BB5\u6587\u5B57\u91CC")]);
409
+ return;
410
+ }
411
+ const doc = ed.doc;
412
+ const idx = doc.children.findIndex((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === bid);
413
+ if (idx < 0)
414
+ return;
415
+ const cur = doc.children[idx];
416
+ if (cur.type === "ai")
417
+ return;
418
+ if (mode === "rewrite") {
419
+ if (!blockPlainText(doc, bid).trim()) {
420
+ _optionalChain([this, 'access', _28 => _28.opts, 'access', _29 => _29.onError, 'optionalCall', _30 => _30("\u5F53\u524D\u6BB5\u6CA1\u6709\u53EF\u6539\u5199\u7684\u6587\u5B57")]);
421
+ return;
422
+ }
423
+ const seed = blockPlainText(doc, bid);
424
+ const id2 = newAiId();
425
+ const promptId2 = newAiId();
426
+ ed.dispatch(
427
+ [{
428
+ kind: "replaceNode",
429
+ path: [idx],
430
+ node: {
431
+ type: "ai",
432
+ id: id2,
433
+ attrs: { status: "compose", mode: "rewrite", seed },
434
+ children: [{ type: "paragraph", id: promptId2, children: [{ text: "" }] }]
435
+ }
436
+ }],
437
+ { anchor: { path: [idx, 0, 0, 0] }, head: { path: [idx, 0, 0, 0] } }
438
+ );
439
+ return;
440
+ }
441
+ const id = newAiId();
442
+ const promptId = newAiId();
443
+ ed.dispatch(
444
+ [{
445
+ kind: "spliceChildren",
446
+ path: [],
447
+ at: idx + 1,
448
+ remove: 0,
449
+ insert: [{
450
+ type: "ai",
451
+ id,
452
+ attrs: { status: "compose", mode: "continue" },
453
+ children: [{ type: "paragraph", id: promptId, children: [{ text: "" }] }]
454
+ }]
455
+ }],
456
+ { anchor: { path: [idx + 1, 0, 0, 0] }, head: { path: [idx + 1, 0, 0, 0] } }
457
+ );
458
+ }
459
+ openFromSlash(blockIdx, query) {
460
+ const ed = this.getEditor();
461
+ if (!ed || this.busy)
462
+ return;
463
+ const instruction = aiInstructionFromQuery(query);
464
+ const id = newAiId();
465
+ const promptId = newAiId();
466
+ const off = instruction.length;
467
+ ed.dispatch(
468
+ [{
469
+ kind: "replaceNode",
470
+ path: [blockIdx],
471
+ node: {
472
+ type: "ai",
473
+ id,
474
+ attrs: { status: "compose", mode: "continue" },
475
+ children: [{ type: "paragraph", id: promptId, children: [{ text: instruction }] }]
476
+ }
477
+ }],
478
+ { anchor: { path: [blockIdx, 0, 0, off] }, head: { path: [blockIdx, 0, 0, off] } }
479
+ );
480
+ }
481
+ /**
482
+ * begin 事务:dispatch 一次插入真段落;
483
+ * 之后 token / 状态 / accept 全走 amend,一笔 undo 整回退。
484
+ */
485
+ async run(blockId) {
486
+ const ed = this.getEditor();
487
+ if (!ed || this.busy)
488
+ return;
489
+ const found = this.findAi(ed, blockId);
490
+ if (!found)
491
+ return;
492
+ const { path, node } = found;
493
+ if (_optionalChain([node, 'access', _31 => _31.attrs, 'optionalAccess', _32 => _32.status]) === "loading")
494
+ return;
495
+ if (this.txOpen && this.txBlockId === blockId) {
496
+ _optionalChain([this, 'access', _33 => _33.abort, 'optionalAccess', _34 => _34.abort, 'call', _35 => _35()]);
497
+ this.abort = null;
498
+ this.clearRaf();
499
+ this.streamingId = null;
500
+ this.pendingMd = "";
501
+ this.rollback();
502
+ }
503
+ const live = this.findAi(ed, blockId);
504
+ if (!live)
505
+ return;
506
+ const { path: aiPath, node: aiNode } = live;
507
+ const mode = _optionalChain([aiNode, 'access', _36 => _36.attrs, 'optionalAccess', _37 => _37.mode]) === "rewrite" ? "rewrite" : "continue";
508
+ const instruction = promptText(aiNode).trim();
509
+ const seed = typeof _optionalChain([aiNode, 'access', _38 => _38.attrs, 'optionalAccess', _39 => _39.seed]) === "string" ? aiNode.attrs.seed : "";
510
+ const blockIdx = _nullishCoalesce(aiPath[0], () => ( 0));
511
+ const before = precedingPlainText(ed.doc, blockIdx);
512
+ const ctxBody = mode === "rewrite" ? seed || "\uFF08\u65E0\u539F\u6587\uFF09" : before.trim() || "\uFF08\u5C1A\u65E0\u4E0A\u6587\uFF09";
513
+ const context = instruction ? `${ctxBody}
514
+
515
+ [\u7528\u6237\u6307\u4EE4] ${instruction}` : ctxBody;
516
+ const prompt = _nullishCoalesce(aiNode.children[0], () => ( {
517
+ type: "paragraph",
518
+ id: newAiId(),
519
+ children: [{ text: "" }]
520
+ }));
521
+ const seedDraft = {
522
+ type: "paragraph",
523
+ id: `${blockId}_d0`,
524
+ attrs: { aiDraft: true, aiFrom: blockId, aiStream: true },
525
+ children: [{ text: "" }]
526
+ };
527
+ const aiNext = {
528
+ ...aiNode,
529
+ attrs: { ..._nullishCoalesce(aiNode.attrs, () => ( {})), status: "loading" },
530
+ children: [prompt]
531
+ };
532
+ delete aiNext.attrs.error;
533
+ delete aiNext.attrs.result;
534
+ delete aiNext.attrs.draftChars;
535
+ const steps = [];
536
+ const oldIdx = draftIndices(ed.doc, blockId);
537
+ for (let i = oldIdx.length - 1; i >= 0; i--)
538
+ steps.push({ kind: "spliceChildren", path: [], at: oldIdx[i], remove: 1, insert: [] });
539
+ let shift = 0;
540
+ for (const i of oldIdx) {
541
+ if (i < blockIdx)
542
+ shift++;
543
+ }
544
+ const aiIdxNow = blockIdx - shift;
545
+ steps.push({ kind: "replaceNode", path: [aiIdxNow], node: aiNext });
546
+ steps.push({ kind: "spliceChildren", path: [], at: aiIdxNow + 1, remove: 0, insert: [seedDraft] });
547
+ ed.dispatch(steps);
548
+ this.txOpen = true;
549
+ this.txBlockId = blockId;
550
+ this.streamingId = blockId;
551
+ this.pendingMd = "";
552
+ this.clearRaf();
553
+ _optionalChain([this, 'access', _40 => _40.opts, 'access', _41 => _41.onBusy, 'optionalCall', _42 => _42(true)]);
554
+ const ac = new AbortController();
555
+ this.abort = ac;
556
+ const flush = () => {
557
+ if (this.streamingId !== blockId)
558
+ return;
559
+ this.paintMd(ed, blockId, this.pendingMd, true);
560
+ };
561
+ try {
562
+ await this.opts.stream(
563
+ {
564
+ action: mode,
565
+ context,
566
+ docPreview: ctxBody.slice(0, 4e3),
567
+ signal: ac.signal
568
+ },
569
+ (t) => {
570
+ if (this.streamingId !== blockId)
571
+ return;
572
+ this.pendingMd += t;
573
+ if (!this.raf) {
574
+ this.raf = requestAnimationFrame(() => {
575
+ this.raf = 0;
576
+ flush();
577
+ });
578
+ }
579
+ }
580
+ );
581
+ if (this.streamingId !== blockId)
582
+ return;
583
+ this.clearRaf();
584
+ this.paintMd(ed, blockId, this.pendingMd, false);
585
+ this.patchAi(ed, blockId, { status: "preview" });
586
+ } catch (e) {
587
+ if (_optionalChain([e, 'optionalAccess', _43 => _43.name]) !== "AbortError") {
588
+ const msg = _optionalChain([e, 'optionalAccess', _44 => _44.message]) || String(e);
589
+ _optionalChain([this, 'access', _45 => _45.opts, 'access', _46 => _46.onError, 'optionalCall', _47 => _47(msg)]);
590
+ if (this.streamingId === blockId) {
591
+ this.clearRaf();
592
+ this.paintMd(ed, blockId, this.pendingMd, false);
593
+ this.patchAi(ed, blockId, { status: "error", error: msg });
594
+ }
595
+ }
596
+ } finally {
597
+ if (this.streamingId === blockId) {
598
+ this.streamingId = null;
599
+ this.abort = null;
600
+ _optionalChain([this, 'access', _48 => _48.opts, 'access', _49 => _49.onBusy, 'optionalCall', _50 => _50(false)]);
601
+ }
602
+ }
603
+ }
604
+ /**
605
+ * 提交事务:正文已在文档里 —— 去掉淡化 + 拆指令壳。
606
+ * 走 amend,与 begin/stream 同一笔 undo。
607
+ */
608
+ accept(blockId) {
609
+ const ed = this.getEditor();
610
+ if (!ed)
611
+ return;
612
+ const found = this.findAi(ed, blockId);
613
+ if (!found)
614
+ return;
615
+ if (_optionalChain([found, 'access', _51 => _51.node, 'access', _52 => _52.attrs, 'optionalAccess', _53 => _53.status]) !== "preview" && _optionalChain([found, 'access', _54 => _54.node, 'access', _55 => _55.attrs, 'optionalAccess', _56 => _56.status]) !== "error")
616
+ return;
617
+ const doc = ed.doc;
618
+ const steps = [];
619
+ for (let i = 0; i < doc.children.length; i++) {
620
+ const c = doc.children[i];
621
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, c) || _optionalChain([c, 'access', _57 => _57.attrs, 'optionalAccess', _58 => _58.aiFrom]) !== blockId)
622
+ continue;
623
+ const attrs = { ..._nullishCoalesce(c.attrs, () => ( {})) };
624
+ delete attrs.aiDraft;
625
+ delete attrs.aiFrom;
626
+ delete attrs.aiStream;
627
+ const clean = Object.keys(attrs).length ? attrs : void 0;
628
+ const next = {
629
+ type: c.type,
630
+ id: c.id,
631
+ children: c.children
632
+ };
633
+ if (clean)
634
+ next.attrs = clean;
635
+ steps.push({ kind: "replaceNode", path: [i], node: next });
636
+ }
637
+ const aiIdx0 = doc.children.findIndex((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === blockId);
638
+ if (aiIdx0 >= 0)
639
+ steps.push({ kind: "spliceChildren", path: [], at: aiIdx0, remove: 1, insert: [] });
640
+ if (!steps.length)
641
+ return;
642
+ const firstDraft = doc.children.findIndex((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && _optionalChain([c, 'access', _59 => _59.attrs, 'optionalAccess', _60 => _60.aiFrom]) === blockId);
643
+ let caretAt = firstDraft >= 0 ? firstDraft : Math.max(0, aiIdx0);
644
+ if (firstDraft > aiIdx0)
645
+ caretAt = firstDraft - 1;
646
+ else if (firstDraft < 0)
647
+ caretAt = Math.max(0, aiIdx0 - 1);
648
+ if (this.txOpen)
649
+ ed.dispatchStream(steps, {
650
+ anchor: { path: [Math.max(0, caretAt), 0, 0] },
651
+ head: { path: [Math.max(0, caretAt), 0, 0] }
652
+ });
653
+ else
654
+ ed.dispatch(steps, {
655
+ anchor: { path: [Math.max(0, caretAt), 0, 0] },
656
+ head: { path: [Math.max(0, caretAt), 0, 0] }
657
+ });
658
+ this.txOpen = false;
659
+ this.txBlockId = null;
660
+ }
661
+ /** 整笔撤回事务(= undo) */
662
+ discard(blockId) {
663
+ if (this.streamingId === blockId) {
664
+ _optionalChain([this, 'access', _61 => _61.abort, 'optionalAccess', _62 => _62.abort, 'call', _63 => _63()]);
665
+ this.abort = null;
666
+ this.clearRaf();
667
+ this.streamingId = null;
668
+ this.pendingMd = "";
669
+ _optionalChain([this, 'access', _64 => _64.opts, 'access', _65 => _65.onBusy, 'optionalCall', _66 => _66(false)]);
670
+ }
671
+ if (this.txOpen && (this.txBlockId === blockId || !this.txBlockId)) {
672
+ this.rollback();
673
+ return;
674
+ }
675
+ const ed = this.getEditor();
676
+ if (!ed)
677
+ return;
678
+ const found = this.findAi(ed, blockId);
679
+ if (!found)
680
+ return;
681
+ const steps = [];
682
+ const doc = ed.doc;
683
+ const idxs = draftIndices(doc, blockId);
684
+ for (let i = idxs.length - 1; i >= 0; i--)
685
+ steps.push({ kind: "spliceChildren", path: [], at: idxs[i], remove: 1, insert: [] });
686
+ let aiIdx = doc.children.findIndex((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === blockId);
687
+ let shift = 0;
688
+ for (const i of idxs) {
689
+ if (i < aiIdx)
690
+ shift++;
691
+ }
692
+ aiIdx -= shift;
693
+ if (aiIdx >= 0) {
694
+ steps.push({
695
+ kind: "replaceNode",
696
+ path: [aiIdx],
697
+ node: { type: "paragraph", id: found.node.id, children: [{ text: "" }] }
698
+ });
699
+ }
700
+ if (steps.length) {
701
+ ed.dispatch(steps, {
702
+ anchor: { path: [Math.max(0, aiIdx), 0, 0] },
703
+ head: { path: [Math.max(0, aiIdx), 0, 0] }
704
+ });
705
+ }
706
+ }
707
+ act(blockId, action) {
708
+ if (action === "accept")
709
+ this.accept(blockId);
710
+ else if (action === "discard")
711
+ this.discard(blockId);
712
+ else if (action === "retry" || action === "run")
713
+ void this.run(blockId);
714
+ else if (action === "stop")
715
+ this.stop();
716
+ }
717
+ rollback() {
718
+ const ed = this.getEditor();
719
+ if (ed)
720
+ ed.undo();
721
+ this.txOpen = false;
722
+ this.txBlockId = null;
723
+ }
724
+ findAi(ed, blockId) {
725
+ const path = _chunkVVFIQLVRcjs.pathOfId.call(void 0, ed.doc, blockId);
726
+ if (!path)
727
+ return null;
728
+ const node = path.reduce((n, i) => n.children[i], ed.doc);
729
+ if (!node || _chunkVVFIQLVRcjs.isText.call(void 0, node) || node.type !== "ai")
730
+ return null;
731
+ return { path, node };
732
+ }
733
+ /** 事务内改 ai attrs(永远 amend) */
734
+ patchAi(ed, blockId, patch) {
735
+ const found = this.findAi(ed, blockId);
736
+ if (!found)
737
+ return;
738
+ const { path, node } = found;
739
+ const attrs = { ..._nullishCoalesce(node.attrs, () => ( {})), ...patch };
740
+ if (attrs.error === "")
741
+ delete attrs.error;
742
+ if (attrs.result === "" || attrs.result == null)
743
+ delete attrs.result;
744
+ ed.dispatchStream([{ kind: "replaceNode", path, node: { ...node, attrs } }]);
745
+ }
746
+ /**
747
+ * 累积 Markdown → 物化顶层真块(heading/list/code/quote/marks…)。
748
+ * streaming 时 softClose 未闭合 fence/marks,末块带 aiStream 光标。
749
+ */
750
+ paintMd(ed, blockId, md, streaming) {
751
+ const doc = ed.doc;
752
+ const idxs = draftIndices(doc, blockId);
753
+ const aiIdx = doc.children.findIndex((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c) && c.id === blockId);
754
+ const at = idxs.length ? idxs[0] : aiIdx >= 0 ? aiIdx + 1 : -1;
755
+ if (at < 0)
756
+ return;
757
+ const span = idxs.length ? idxs[idxs.length - 1] - idxs[0] + 1 : 0;
758
+ const raw = md;
759
+ if (!raw.trim()) {
760
+ const empty = {
761
+ type: "paragraph",
762
+ id: `${blockId}_d0`,
763
+ attrs: {
764
+ aiDraft: true,
765
+ aiFrom: blockId,
766
+ ...streaming ? { aiStream: true } : {}
767
+ },
768
+ children: [{ text: "" }]
769
+ };
770
+ ed.dispatchStream([{
771
+ kind: "spliceChildren",
772
+ path: [],
773
+ at,
774
+ remove: span || 0,
775
+ insert: [empty]
776
+ }]);
777
+ this.patchAi(ed, blockId, { draftChars: 0 });
778
+ return;
779
+ }
780
+ const src = streaming ? softCloseMd(raw) : raw;
781
+ let blocks;
782
+ try {
783
+ const tops = _chunkVVFIQLVRcjs.mdToDoc.call(void 0, src).children.filter((c) => !_chunkVVFIQLVRcjs.isText.call(void 0, c));
784
+ blocks = tops.map((c, i) => stampDraft(c, blockId, `${blockId}_d${i}`, streaming && i === tops.length - 1));
785
+ } catch (e2) {
786
+ blocks = [{
787
+ type: "paragraph",
788
+ id: `${blockId}_d0`,
789
+ attrs: {
790
+ aiDraft: true,
791
+ aiFrom: blockId,
792
+ ...streaming ? { aiStream: true } : {}
793
+ },
794
+ children: [{ text: raw }]
795
+ }];
796
+ }
797
+ if (!blocks.length) {
798
+ blocks = [{
799
+ type: "paragraph",
800
+ id: `${blockId}_d0`,
801
+ attrs: { aiDraft: true, aiFrom: blockId },
802
+ children: [{ text: raw }]
803
+ }];
804
+ }
805
+ ed.dispatchStream([{
806
+ kind: "spliceChildren",
807
+ path: [],
808
+ at,
809
+ remove: span || 0,
810
+ insert: blocks
811
+ }]);
812
+ this.patchAi(ed, blockId, { draftChars: raw.length });
813
+ }
814
+ }, _class);
815
+ function softCloseMd(md) {
816
+ let out = md;
817
+ let fences = 0;
818
+ let i = 0;
819
+ while (i < out.length) {
820
+ if (out[i] === "`" && out[i + 1] === "`" && out[i + 2] === "`") {
821
+ fences++;
822
+ i += 3;
823
+ continue;
824
+ }
825
+ i++;
826
+ }
827
+ if (fences % 2 === 1)
828
+ out += "\n```";
829
+ let stars2 = 0;
830
+ for (let j = 0; j < out.length - 1; j++) {
831
+ if (out[j] === "*" && out[j + 1] === "*" && out[j - 1] !== "*") {
832
+ stars2++;
833
+ j++;
834
+ }
835
+ }
836
+ if (stars2 % 2 === 1)
837
+ out += "**";
838
+ let stars1 = 0;
839
+ for (let j = 0; j < out.length; j++) {
840
+ if (out[j] !== "*")
841
+ continue;
842
+ if (out[j + 1] === "*") {
843
+ j++;
844
+ continue;
845
+ }
846
+ if (out[j - 1] === "*")
847
+ continue;
848
+ stars1++;
849
+ }
850
+ if (stars1 % 2 === 1)
851
+ out += "*";
852
+ let ticks = 0;
853
+ for (let j = 0; j < out.length; j++) {
854
+ if (out[j] !== "`")
855
+ continue;
856
+ if (out[j + 1] === "`" && out[j + 2] === "`") {
857
+ j += 2;
858
+ continue;
859
+ }
860
+ ticks++;
861
+ }
862
+ if (ticks % 2 === 1)
863
+ out += "`";
864
+ const openLink = out.lastIndexOf("](");
865
+ const closeParen = out.lastIndexOf(")");
866
+ if (openLink >= 0 && closeParen < openLink)
867
+ out += ")";
868
+ return out;
869
+ }
870
+ function stampDraft(node, aiFrom, id, streamTail = false) {
871
+ const kids = node.children.map((c, i) => {
872
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, c))
873
+ return c;
874
+ return stampInner(c, `${id}_${i}`);
875
+ });
876
+ const attrs = { ..._nullishCoalesce(node.attrs, () => ( {})), aiDraft: true, aiFrom };
877
+ if (streamTail)
878
+ attrs.aiStream = true;
879
+ return { type: node.type, id, attrs, children: kids };
880
+ }
881
+ function stampInner(node, id) {
882
+ const kids = node.children.map((c, i) => {
883
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, c))
884
+ return c;
885
+ return stampInner(c, `${id}_${i}`);
886
+ });
887
+ return {
888
+ type: node.type,
889
+ id,
890
+ ...node.attrs ? { attrs: { ...node.attrs } } : {},
891
+ children: kids
892
+ };
893
+ }
894
+ function draftIndices(doc, aiId) {
895
+ const out = [];
896
+ for (let i = 0; i < doc.children.length; i++) {
897
+ const c = doc.children[i];
898
+ if (!_chunkVVFIQLVRcjs.isText.call(void 0, c) && _optionalChain([c, 'access', _67 => _67.attrs, 'optionalAccess', _68 => _68.aiFrom]) === aiId)
899
+ out.push(i);
900
+ }
901
+ return out;
902
+ }
903
+ function promptText(ai) {
904
+ const p = ai.children[0];
905
+ return p ? collectText2(p) : "";
906
+ }
907
+ function collectText2(n) {
908
+ if (_chunkVVFIQLVRcjs.isText.call(void 0, n))
909
+ return n.text;
910
+ return n.children.map(collectText2).join("");
911
+ }
912
+
913
+ // src/ai/stream.ts
914
+ function defaultSystem(action) {
915
+ if (action === "rewrite") {
916
+ return [
917
+ "\u4F60\u662F\u7B14\u8BB0\u6539\u5199\u52A9\u624B\u3002\u6839\u636E\u7528\u6237\u7ED9\u51FA\u7684\u539F\u6587,\u8F93\u51FA\u6539\u5199\u540E\u7684\u6B63\u6587\u3002",
918
+ "\u8981\u6C42:\u4FDD\u7559\u539F\u610F,\u6587\u5B57\u66F4\u6E05\u6670\u901A\u987A;\u4E0D\u8981\u89E3\u91CA\u3001\u4E0D\u8981\u6807\u9898\u524D\u7F00\u3001\u4E0D\u8981 markdown \u4EE3\u7801\u56F4\u680F;",
919
+ "\u76F4\u63A5\u8F93\u51FA\u6539\u5199\u7ED3\u679C\u7EAF\u6587\u672C(\u53EF\u4FDD\u7559\u7B80\u5355\u6362\u884C)\u3002"
920
+ ].join("");
921
+ }
922
+ return [
923
+ "\u4F60\u662F\u7B14\u8BB0\u7EED\u5199\u52A9\u624B\u3002\u6839\u636E\u5DF2\u6709\u4E0A\u4E0B\u6587,\u81EA\u7136\u7EED\u5199\u4E0B\u6587\u3002",
924
+ "\u8981\u6C42:\u6587\u98CE\u4E00\u81F4\u3001\u4E0D\u8981\u91CD\u590D\u5DF2\u6709\u5185\u5BB9\u3001\u4E0D\u8981\u89E3\u91CA\u3001\u4E0D\u8981\u6807\u9898\u524D\u7F00;",
925
+ "\u76F4\u63A5\u8F93\u51FA\u7EED\u5199\u7EAF\u6587\u672C(\u53EF\u4FDD\u7559\u7B80\u5355\u6362\u884C)\u3002"
926
+ ].join("");
927
+ }
928
+ function userPrompt(action, context, docPreview) {
929
+ const ctx = (context || "").slice(0, 8e3);
930
+ const prev = (docPreview || "").slice(0, 4e3);
931
+ if (action === "rewrite")
932
+ return `\u8BF7\u6539\u5199\u4EE5\u4E0B\u5185\u5BB9:
933
+
934
+ ${ctx}`;
935
+ return [
936
+ prev && prev !== ctx ? `\u5168\u6587\u6458\u5F55:
937
+ ${prev}
938
+
939
+ ` : "",
940
+ `\u8BF7\u7EED\u5199(\u63A5\u5728\u4E0B\u6587\u4E4B\u540E):
941
+
942
+ ${ctx}`
943
+ ].join("");
944
+ }
945
+ function completionsUrl(host) {
946
+ const base = String(host || "").replace(/\/+$/, "");
947
+ if (!base)
948
+ return "";
949
+ if (base.endsWith("/v1"))
950
+ return `${base}/chat/completions`;
951
+ return `${base}/v1/chat/completions`;
952
+ }
953
+ function resolveProvider(cfg) {
954
+ const p = typeof cfg.provider === "function" ? cfg.provider() : cfg.provider;
955
+ if (!_optionalChain([p, 'optionalAccess', _69 => _69.host]) || !_optionalChain([p, 'optionalAccess', _70 => _70.apiKey]) || !_optionalChain([p, 'optionalAccess', _71 => _71.model]))
956
+ return null;
957
+ return p;
958
+ }
959
+ async function readSse(res, onToken, mode) {
960
+ if (!res.body)
961
+ throw new Error("no stream body");
962
+ const reader = res.body.getReader();
963
+ const dec = new TextDecoder();
964
+ let buf = "";
965
+ while (true) {
966
+ const { done, value } = await reader.read();
967
+ if (done)
968
+ break;
969
+ buf += dec.decode(value, { stream: true });
970
+ let sep;
971
+ while ((sep = buf.indexOf("\n\n")) >= 0) {
972
+ const chunk = buf.slice(0, sep);
973
+ buf = buf.slice(sep + 2);
974
+ for (const line of chunk.split("\n")) {
975
+ if (!line.startsWith("data:"))
976
+ continue;
977
+ const data = line.slice(5).trim();
978
+ if (!data || data === "[DONE]")
979
+ continue;
980
+ try {
981
+ const j = JSON.parse(data);
982
+ if (j.error) {
983
+ const msg = typeof j.error === "string" ? j.error : j.error.message;
984
+ throw new Error(msg || "AI error");
985
+ }
986
+ if (mode === "proxy" && j.content)
987
+ onToken(j.content);
988
+ if (mode === "openai") {
989
+ const c = _optionalChain([j, 'access', _72 => _72.choices, 'optionalAccess', _73 => _73[0], 'optionalAccess', _74 => _74.delta, 'optionalAccess', _75 => _75.content]);
990
+ if (c)
991
+ onToken(c);
992
+ }
993
+ } catch (e) {
994
+ if (e instanceof SyntaxError)
995
+ continue;
996
+ throw e;
997
+ }
998
+ }
999
+ }
1000
+ }
1001
+ }
1002
+ function createAiStream(cfg) {
1003
+ if (cfg.stream)
1004
+ return cfg.stream;
1005
+ return async (input, onToken) => {
1006
+ const action = input.action;
1007
+ const system = _optionalChain([(action === "rewrite" ? cfg.rewriteSystem : cfg.continueSystem), 'optionalAccess', _76 => _76.trim, 'call', _77 => _77()]) || defaultSystem(action);
1008
+ const provider = resolveProvider(cfg);
1009
+ if (cfg.endpoint) {
1010
+ const res2 = await fetch(cfg.endpoint, {
1011
+ method: "POST",
1012
+ headers: { "content-type": "application/json" },
1013
+ body: JSON.stringify({
1014
+ action,
1015
+ context: input.context,
1016
+ docPreview: _nullishCoalesce(input.docPreview, () => ( "")),
1017
+ system,
1018
+ provider: provider ? { host: provider.host, apiKey: provider.apiKey, model: provider.model } : void 0
1019
+ }),
1020
+ signal: input.signal
1021
+ });
1022
+ if (!res2.ok) {
1023
+ let err = res2.statusText;
1024
+ try {
1025
+ const j = await res2.json();
1026
+ err = j.error || err;
1027
+ } catch (e3) {
1028
+ err = await res2.text().catch(() => err);
1029
+ }
1030
+ throw new Error(err || `AI ${res2.status}`);
1031
+ }
1032
+ await readSse(res2, onToken, "proxy");
1033
+ return;
1034
+ }
1035
+ if (!provider)
1036
+ throw new Error("AI \u672A\u914D\u7F6E:\u8BF7\u8BBE\u7F6E ai.provider \u6216 ai.endpoint");
1037
+ const url = completionsUrl(provider.host);
1038
+ const res = await fetch(url, {
1039
+ method: "POST",
1040
+ headers: {
1041
+ "content-type": "application/json",
1042
+ "authorization": `Bearer ${provider.apiKey}`
1043
+ },
1044
+ body: JSON.stringify({
1045
+ model: provider.model,
1046
+ stream: true,
1047
+ messages: [
1048
+ { role: "system", content: system },
1049
+ { role: "user", content: userPrompt(action, input.context, _nullishCoalesce(input.docPreview, () => ( ""))) }
1050
+ ]
1051
+ }),
1052
+ signal: input.signal
1053
+ });
1054
+ if (!res.ok) {
1055
+ const err = await res.text().catch(() => res.statusText);
1056
+ throw new Error(err || `AI ${res.status}`);
1057
+ }
1058
+ await readSse(res, onToken, "openai");
1059
+ };
1060
+ }
1061
+
1062
+
1063
+
1064
+
1065
+
1066
+
1067
+
1068
+
1069
+
1070
+
1071
+
1072
+
1073
+
1074
+
1075
+
1076
+ exports.rootEl = rootEl; exports.pointToDom = pointToDom; exports.domToPoint = domToPoint; exports.readSelection = readSelection; exports.writeSelection = writeSelection; exports.elementChildren = elementChildren; exports.focusBlockId = focusBlockId; exports.blockPlainText = blockPlainText; exports.startAiWrite = startAiWrite; exports.precedingPlainText = precedingPlainText; exports.aiInstructionFromQuery = aiInstructionFromQuery; exports.LoomAi = LoomAi; exports.createAiStream = createAiStream;