@dinoxx/dinox-cli 2.16.1 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/cli.js +2 -0
  2. package/dist/commands/editor/index.d.ts +4 -0
  3. package/dist/commands/editor/index.js +155 -0
  4. package/dist/commands/notes/contentPatch.d.ts +23 -0
  5. package/dist/commands/notes/contentPatch.js +37 -0
  6. package/dist/commands/schema/renderSkills.js +1 -0
  7. package/dist/commands/schema/spec.js +2 -0
  8. package/dist/daemon/server.d.ts +2 -1
  9. package/dist/daemon/server.js +22 -2
  10. package/dist/dsh-plugin/cordis.patch.yml +3 -0
  11. package/dist/dsh-plugin/lib/client.js +2145 -0
  12. package/dist/dsh-plugin/lib/index.js +369 -0
  13. package/dist/dsh-plugin/package.json +32 -0
  14. package/dist/dsh-plugin/runtime.json +5 -0
  15. package/dist/editor/anchor.d.ts +46 -0
  16. package/dist/editor/anchor.js +129 -0
  17. package/dist/editor/blockIds.d.ts +21 -0
  18. package/dist/editor/blockIds.js +51 -0
  19. package/dist/editor/blocks.d.ts +47 -0
  20. package/dist/editor/blocks.js +236 -0
  21. package/dist/editor/compat.d.ts +32 -0
  22. package/dist/editor/compat.js +392 -0
  23. package/dist/editor/daemon.d.ts +10 -0
  24. package/dist/editor/daemon.js +56 -0
  25. package/dist/editor/document.d.ts +74 -0
  26. package/dist/editor/document.js +88 -0
  27. package/dist/editor/i18n.d.ts +23 -0
  28. package/dist/editor/i18n.js +61 -0
  29. package/dist/editor/install.d.ts +72 -0
  30. package/dist/editor/install.js +239 -0
  31. package/dist/editor/mcp.d.ts +22 -0
  32. package/dist/editor/mcp.js +222 -0
  33. package/dist/editor/meta.d.ts +70 -0
  34. package/dist/editor/meta.js +163 -0
  35. package/dist/editor/paths.d.ts +2 -0
  36. package/dist/editor/paths.js +13 -0
  37. package/dist/editor/persistence.d.ts +4 -0
  38. package/dist/editor/persistence.js +35 -0
  39. package/dist/editor/saveGuard.d.ts +9 -0
  40. package/dist/editor/saveGuard.js +38 -0
  41. package/dist/editor/schema.d.ts +14 -0
  42. package/dist/editor/schema.js +38 -0
  43. package/dist/editor/service.d.ts +326 -0
  44. package/dist/editor/service.js +1007 -0
  45. package/dist/editor-ui/mcp-app.html +765 -0
  46. package/dist/gateway/adapters/acp.d.ts +8 -0
  47. package/dist/gateway/adapters/acp.js +38 -2
  48. package/dist/gateway/agentTaskHost.d.ts +135 -0
  49. package/dist/gateway/agentTaskHost.js +410 -0
  50. package/dist/gateway/config.js +2 -2
  51. package/dist/gateway/deviceHost.d.ts +6 -1
  52. package/dist/gateway/deviceHost.js +22 -4
  53. package/dist/gateway/mcpCommandTools.d.ts +1 -1
  54. package/dist/gateway/mcpCommandTools.js +2 -2
  55. package/dist/gateway/processTree.d.ts +15 -0
  56. package/dist/gateway/processTree.js +60 -0
  57. package/dist/gateway/protocol.js +2 -1
  58. package/dist/gateway/service.d.ts +1 -1
  59. package/dist/gateway/service.js +3 -1
  60. package/dist/gateway/taskJournal.d.ts +14 -0
  61. package/dist/gateway/taskJournal.js +47 -0
  62. package/dist/gateway/threadStore.d.ts +7 -1
  63. package/dist/gateway/threadStore.js +14 -3
  64. package/dist/gateway/types.d.ts +7 -3
  65. package/dist/gateway/types.js +3 -1
  66. package/dist/integrations/dsh/host.d.ts +53 -0
  67. package/dist/integrations/dsh/host.js +237 -0
  68. package/dist/integrations/dsh/mcpClient.d.ts +66 -0
  69. package/dist/integrations/dsh/mcpClient.js +192 -0
  70. package/dist/utils/errorCodes.d.ts +28 -0
  71. package/dist/utils/errorCodes.js +7 -0
  72. package/dist/vendor/electron/shared/remote-device-agent.d.ts +2 -0
  73. package/package.json +9 -2
@@ -0,0 +1,392 @@
1
+ import { Extension, Mark, Node, commands } from '@tiptap/core';
2
+ import { DOMSerializer } from '@tiptap/pm/model';
3
+ import { BLOCK_ID_TYPES } from './blockIds.js';
4
+ const BLOCK_ID_TYPE_SET = new Set(BLOCK_ID_TYPES);
5
+ export function analyze(doc, baseSchema) {
6
+ const extraAttrs = Object.create(null), unknownNodes = new Set(), unknownMarks = Object.create(null);
7
+ const attrs = (value, type, target) => {
8
+ for (const key of Object.keys(value.attrs || {}))
9
+ if (!type?.attrs[key])
10
+ (target[value.type] ||= new Set()).add(key);
11
+ };
12
+ const walk = (node) => {
13
+ const type = baseSchema.nodes[node.type];
14
+ if (!type)
15
+ unknownNodes.add(node.type);
16
+ else
17
+ attrs(node, type, extraAttrs);
18
+ for (const mark of node.marks || []) {
19
+ const type = baseSchema.marks[mark.type];
20
+ if (!type) {
21
+ unknownMarks[mark.type] ||= new Set();
22
+ attrs(mark, null, unknownMarks);
23
+ }
24
+ else
25
+ attrs(mark, type, extraAttrs);
26
+ }
27
+ (node.content || []).forEach(walk);
28
+ };
29
+ walk(doc);
30
+ return { extraAttrs: Object.fromEntries(Object.entries(extraAttrs).map(([k, v]) => [k, [...v]])), unknownNodes: [...unknownNodes], unknownMarks: Object.fromEntries(Object.entries(unknownMarks).map(([k, v]) => [k, [...v]])) };
31
+ }
32
+ const rawOf = (node) => {
33
+ try {
34
+ return typeof node.attrs?.raw === 'string' ? JSON.parse(node.attrs.raw) : node;
35
+ }
36
+ catch {
37
+ return {};
38
+ }
39
+ };
40
+ // Pictures only from the web or inline data; never script or file URLs.
41
+ const safeImageSrc = (value) => typeof value === 'string' && /^(https?:\/\/|data:image\/)/i.test(value) ? value : null;
42
+ // The panel installs the emoji table (name or shortcode → character); without it an emoji shows as `:name:`.
43
+ let emojiLookup = () => undefined;
44
+ export function setEmojiLookup(lookup) { emojiLookup = lookup; }
45
+ function emojiOf(attrs) {
46
+ const name = String(attrs?.name || '');
47
+ return String(attrs?.emoji || attrs?.native || (name && emojiLookup(name)) || (name ? `:${name}:` : attrs?.label || 'emoji'));
48
+ }
49
+ /** Plain text of a stored node, atoms included as their labels. */
50
+ function textOf(node) {
51
+ if (!node || typeof node !== 'object')
52
+ return '';
53
+ if (node.type === 'text')
54
+ return String(node.text ?? '');
55
+ if (node.type === 'hardBreak')
56
+ return '\n';
57
+ if (!Array.isArray(node.content)) {
58
+ // Leaves with a meaningful label (tags, links, emoji, pictures) read as it; structural ones (rules, empty blocks) as nothing.
59
+ const label = node.type ? opaqueLabel(node) : '';
60
+ return label === node.type ? '' : label;
61
+ }
62
+ return node.content.map(textOf).join('');
63
+ }
64
+ export function opaqueLabel(node) {
65
+ const raw = rawOf(node);
66
+ if (raw.type === 'emoji')
67
+ return emojiOf(raw.attrs);
68
+ const attrs = raw.attrs ?? {};
69
+ switch (raw.type) {
70
+ case 'hashtag': return `#${attrs.label || attrs.id || ''}`;
71
+ case 'bidlink':
72
+ case 'mention': return String(attrs.label || attrs.id || raw.type);
73
+ case 'image': return String(attrs.alt || attrs.title || '圖片');
74
+ case 'bookmark': return String(attrs.title || attrs.url || '網頁書籤');
75
+ case 'text': return String(raw.text ?? '');
76
+ case 'iframe': return `內嵌網頁 ${attrs.src ?? ''}`.trim();
77
+ case 'pdfAnnotation': return String(attrs.text || 'PDF 註記');
78
+ case 'citation': return String(attrs.citekey ? `引用 ${attrs.citekey}` : '引用');
79
+ case 'details': return textOf((raw.content ?? []).find((child) => child?.type === 'detailsSummary')) || '摺疊區塊';
80
+ case 'detailsSummary':
81
+ case 'detailsContent': return textOf(raw);
82
+ case 'math':
83
+ case 'mathBlock': return String(attrs.content || '公式');
84
+ case 'tableOfContentsNode': return '目錄';
85
+ case 'columns': return '分欄';
86
+ case 'blockGroup':
87
+ case 'blockContainer': return '舊版區塊';
88
+ case 'imageBlock':
89
+ case 'image-block':
90
+ case 'imageUpload': return '圖片';
91
+ default: return String(raw.type);
92
+ }
93
+ }
94
+ // Deliberately restrictive, DOM-free CSS color allowlist: no URL, variables or declarations.
95
+ const cssColor = (value) => typeof value === 'string' && /^(#[\da-f]{3,8}|[a-z]+|(?:rgb|hsl)a?\([\d\s.,%+\-/]+\))$/i.test(value) ? value : null;
96
+ const ALIGNS = new Set(['left', 'center', 'right', 'justify']);
97
+ const VALIGNS = new Set(['top', 'middle', 'bottom']);
98
+ const ALIGN_KEYS = new Set(['textAlign', 'nodeTextAlign', 'textAlignment']);
99
+ // The desktop's named palette (`var(--tt-color-highlight-yellow)`); the panel maps each name onto its own light/dark tint.
100
+ const tintOf = (value) => typeof value === 'string' ? /^var\(--tt-color-highlight-(yellow|green|blue|purple|red|gray|brown|orange|pink)(?:-contrast)?\)$/.exec(value)?.[1] ?? null : null;
101
+ const TRANSPARENT = /^(transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i;
102
+ /**
103
+ * How a desktop presentation attribute shows in the panel. Block backgrounds
104
+ * apply only from the desktop palette: other values are mostly white or
105
+ * near-black page colors pasted from the web, which would fight the theme.
106
+ */
107
+ export function presentationOf(type, key, value) {
108
+ if (value === null || value === undefined)
109
+ return {};
110
+ if (ALIGN_KEYS.has(key) || (key === 'align' && (type === 'tableCell' || type === 'tableHeader'))) {
111
+ return typeof value === 'string' && ALIGNS.has(value) && value !== 'left' ? { style: `text-align: ${value}` } : {};
112
+ }
113
+ if (key === 'nodeVerticalAlign')
114
+ return typeof value === 'string' && VALIGNS.has(value) ? { style: `vertical-align: ${value}` } : {};
115
+ if (key === 'backgroundColor') {
116
+ const tint = tintOf(value);
117
+ return tint ? { 'data-dx-tint': tint } : {};
118
+ }
119
+ if (type === 'highlight' && key === 'color') {
120
+ const tint = tintOf(value);
121
+ if (tint)
122
+ return { 'data-dx-tint': tint };
123
+ const color = cssColor(value);
124
+ return color && !TRANSPARENT.test(color) ? { 'data-dx-color': '', style: `background-color: ${color}` } : {};
125
+ }
126
+ return {};
127
+ }
128
+ const attrSpecs = (type, keys) => Object.fromEntries(keys.map(key => [key, {
129
+ default: null, keepOnSplit: false,
130
+ renderHTML: (attributes) => presentationOf(type, key, attributes[key]),
131
+ }]));
132
+ export function compatExtensions(analysis) {
133
+ return [Extension.create({ name: 'dxCompatAttrs', addGlobalAttributes() { return Object.entries(analysis.extraAttrs).map(([type, keys]) => ({ types: [type], attributes: attrSpecs(type, keys) })); },
134
+ // Tiptap 3.20 only applies keepOnSplit at block ends. Supply the same
135
+ // declared policy for its mid-block split path as well.
136
+ addCommands() {
137
+ return { splitBlock: options => props => {
138
+ const { tr } = props, before = tr.steps.length;
139
+ const ok = commands.splitBlock(options)(props);
140
+ if (ok && props.dispatch && tr.steps.length > before) {
141
+ const { $from } = tr.selection;
142
+ const type = $from.parent.type.name;
143
+ // Block ids too: the second half is a new block (UniqueID gives it an id).
144
+ const keys = [...(analysis.extraAttrs[type] || []), ...(BLOCK_ID_TYPE_SET.has(type) ? ['id'] : [])];
145
+ if (keys.length && $from.depth) {
146
+ const attrs = { ...$from.parent.attrs };
147
+ for (const key of keys)
148
+ attrs[key] = null;
149
+ tr.setNodeMarkup($from.before(), undefined, attrs);
150
+ }
151
+ }
152
+ return ok;
153
+ } };
154
+ }
155
+ }),
156
+ ...Object.entries(analysis.unknownMarks).map(([name, keys]) => Mark.create({ name, addAttributes: () => attrSpecs(name, keys), renderHTML({ mark }) { const color = name === 'textStyle' && cssColor(mark.attrs.color); return ['span', { 'data-dx-mark': name, ...(color ? { style: `color: ${color}` } : {}) }, 0]; } })),
157
+ ...[false, true].map(inline => Node.create({ name: inline ? 'dxOpaqueInline' : 'dxOpaqueBlock', group: inline ? 'inline' : 'block', inline, atom: true, selectable: true, draggable: false,
158
+ addAttributes: () => ({ raw: { default: '', rendered: false } }),
159
+ renderHTML: ({ node }) => opaqueSpec(node, inline),
160
+ // A real view so a reader can open a collapsible section without the editor re-reading the atom.
161
+ addNodeView: () => ({ node }) => {
162
+ // Node views only run in a browser; `globalThis` keeps this module free of DOM typings for the CLI.
163
+ const { dom } = DOMSerializer.renderSpec(globalThis.document, opaqueSpec(node, inline));
164
+ return { dom, ignoreMutation: () => true, stopEvent: event => Boolean(event.target?.closest?.('summary')) };
165
+ },
166
+ renderText: ({ node }) => opaqueLabel(node), renderMarkdown: (node) => opaqueLabel(node),
167
+ }))];
168
+ }
169
+ const KEPT = '這個區塊請在 Dinox 中編輯;存檔時會原樣保留';
170
+ /**
171
+ * The UI words what it shows in the user's language. `opaqueLabel` itself stays
172
+ * in the source language: anchors and the model's Markdown depend on it.
173
+ */
174
+ let translateLabel = (text) => text;
175
+ export function setLabelTranslator(translate) {
176
+ translateLabel = translate;
177
+ }
178
+ const kept = () => translateLabel(KEPT);
179
+ const shown = (node) => {
180
+ const raw = rawOf(node);
181
+ const label = opaqueLabel(node);
182
+ const prefixed = raw?.type === 'iframe' || raw?.type === 'citation' ? /^(\S+) (.*)$/s.exec(label) : null;
183
+ return prefixed ? `${translateLabel(prefixed[1])} ${prefixed[2]}` : translateLabel(label);
184
+ };
185
+ const safeLink = (value) => typeof value === 'string' && /^https?:\/\//i.test(value) ? value : null;
186
+ const blockText = (block) => {
187
+ if (Array.isArray(block?.content) && ['bulletList', 'orderedList', 'taskList'].includes(block.type)) {
188
+ return ['ul', {}, ...block.content.map((item) => ['li', {}, textOf(item)])];
189
+ }
190
+ if (block?.type === 'horizontalRule')
191
+ return ['hr', {}];
192
+ return ['p', {}, textOf(block)];
193
+ };
194
+ /** What an opaque atom shows. Everything is derived from the stored JSON and rendered as text or vetted URLs only. */
195
+ function opaqueSpec(node, inline) {
196
+ const raw = rawOf(node);
197
+ const attrs = raw?.attrs ?? {};
198
+ const base = { contenteditable: 'false', 'data-dx-opaque': 'true', 'data-kind': String(raw?.type ?? '') };
199
+ const src = ['image', 'imageBlock', 'image-block'].includes(raw?.type) ? safeImageSrc(attrs.src) : null;
200
+ if (src)
201
+ return [inline ? 'span' : 'div', { ...base, class: inline ? 'dx-opaque-image is-inline' : 'dx-opaque-image' }, ['img', { src, alt: shown(node), loading: 'lazy' }]];
202
+ if (raw?.type === 'emoji' && inline)
203
+ return ['span', { ...base, class: 'dx-emoji', title: attrs.name ? `:${attrs.name}:` : 'emoji' }, emojiOf(attrs)];
204
+ if (raw?.type === 'details' && !inline) {
205
+ const body = (raw.content ?? []).find((child) => child?.type === 'detailsContent')?.content ?? [];
206
+ return ['details', { ...base, class: 'dx-details', ...(attrs.open ? { open: '' } : {}), title: kept() },
207
+ ['summary', {}, shown(node)],
208
+ ['div', { class: 'dx-details-body' }, ...body.slice(0, 200).map(blockText)]];
209
+ }
210
+ if (raw?.type === 'bookmark' && !inline) {
211
+ const href = safeLink(attrs.url);
212
+ const image = safeImageSrc(attrs.imageUrl);
213
+ const site = String(attrs.siteName || attrs.domain || (href ? new URL(href).hostname : ''));
214
+ return [href ? 'a' : 'div', { ...base, class: 'dx-bookmark', ...(href ? { href, target: '_blank', rel: 'noopener noreferrer' } : {}), title: href ?? kept() },
215
+ ['span', { class: 'dx-bookmark-text' },
216
+ ['span', { class: 'dx-bookmark-title' }, String(attrs.title || href || translateLabel('網頁書籤'))],
217
+ ...(attrs.description ? [['span', { class: 'dx-bookmark-desc' }, String(attrs.description)]] : []),
218
+ ['span', { class: 'dx-bookmark-site' }, site]],
219
+ ...(image ? [['span', { class: 'dx-bookmark-image' }, ['img', { src: image, alt: '', loading: 'lazy' }]]] : [])];
220
+ }
221
+ return [inline ? 'span' : 'div', { ...base, class: inline ? 'dx-chip' : 'dx-atom', title: kept() }, shown(node)];
222
+ }
223
+ const OPAQUE_TYPES = new Set(['dxOpaqueBlock', 'dxOpaqueInline']);
224
+ const opaque = (node, inline) => ({ type: inline ? 'dxOpaqueInline' : 'dxOpaqueBlock', attrs: { raw: JSON.stringify(node) } });
225
+ /** Two marks of a type that excludes itself cannot coexist; stored notes sometimes repeat one (`bold, bold`). */
226
+ function dedupeMarks(marks, schema) {
227
+ const seen = new Set();
228
+ return marks.filter(mark => {
229
+ const type = schema.marks[mark.type];
230
+ if (!type || !type.excludes(type))
231
+ return true;
232
+ if (seen.has(mark.type))
233
+ return false;
234
+ seen.add(mark.type);
235
+ return true;
236
+ });
237
+ }
238
+ /**
239
+ * Prepares a stored document for the editor schema. Unknown nodes become
240
+ * opaque atoms (restored verbatim on save). With the full editor schema
241
+ * (one that has the opaque types), nodes the desktop tolerates but the schema
242
+ * forbids in their position (an image inside a paragraph, a note link at the
243
+ * top level, an empty list item) are wrapped the same way, escalating to the
244
+ * nearest ancestor that can hold an opaque atom, so the rest of the note
245
+ * stays editable. Empty text nodes and repeated marks, which carry nothing,
246
+ * are dropped.
247
+ */
248
+ export function wrapUnknown(doc, schema) {
249
+ const repair = Boolean(schema.nodes.dxOpaqueBlock && schema.nodes.dxOpaqueInline);
250
+ const prepare = (node, inline) => {
251
+ const type = schema.nodes[node.type ?? ''];
252
+ if (!type)
253
+ return opaque(node, inline);
254
+ const out = { ...node };
255
+ if (node.marks)
256
+ out.marks = dedupeMarks(node.marks, schema);
257
+ if (!node.content)
258
+ return out;
259
+ const originals = node.content.filter(child => child.type !== 'text' || child.text);
260
+ const children = originals.map(child => prepare(child, type.inlineContent) ?? opaque(child, type.inlineContent));
261
+ out.content = repair ? fit(type, originals, children) ?? undefined : children;
262
+ return out.content ? out : null;
263
+ };
264
+ // Lays children into the parent's content expression, wrapping any that do not fit; null when even that fails.
265
+ const fit = (type, originals, children) => {
266
+ let match = type.contentMatch;
267
+ const placed = [];
268
+ for (let i = 0; i < children.length; i++) {
269
+ let child = children[i];
270
+ const childType = schema.nodes[child.type ?? ''];
271
+ const marksOk = (child.marks ?? []).every(mark => { const markType = schema.marks[mark.type]; return !markType || type.allowsMarkType(markType); });
272
+ let next = childType && marksOk ? match.matchType(childType) : null;
273
+ if (!next && !OPAQUE_TYPES.has(child.type ?? '')) {
274
+ child = opaque(originals[i], type.inlineContent);
275
+ next = match.matchType(schema.nodes[child.type]);
276
+ }
277
+ if (!next)
278
+ return null;
279
+ placed.push(child);
280
+ match = next;
281
+ }
282
+ return match.validEnd ? placed : null;
283
+ };
284
+ if (doc.type === 'doc' && doc.content?.length === 0)
285
+ return { ...doc, content: [{ type: 'paragraph' }] };
286
+ return prepare(doc, false) ?? doc;
287
+ }
288
+ export function unwrapOpaque(doc) {
289
+ if (['dxOpaqueBlock', 'dxOpaqueInline'].includes(doc.type ?? ''))
290
+ return JSON.parse(doc.attrs.raw);
291
+ return { ...doc, ...(doc.content ? { content: doc.content.map(unwrapOpaque) } : {}) };
292
+ }
293
+ const equal = (a, b) => a === b || (a && b && typeof a === 'object' && typeof b === 'object' && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(k => Object.hasOwn(b, k) && equal(a[k], b[k])));
294
+ function declaredDefault(schema, type, attr) {
295
+ if (!type)
296
+ return undefined;
297
+ const owner = (schema.nodes[type] ?? schema.marks[type]);
298
+ return owner?.attrs?.[attr]?.default;
299
+ }
300
+ /**
301
+ * The same document the way ProseMirror writes it back: marks deduplicated
302
+ * and in schema order, adjacent text with the same marks merged, empty text
303
+ * nodes and empty content arrays dropped. None of that changes what the note
304
+ * says, so it must not count as a loss.
305
+ */
306
+ function canonical(node, schema) {
307
+ if (!node || typeof node !== 'object' || Array.isArray(node))
308
+ return node;
309
+ const out = { ...node };
310
+ if (Array.isArray(node.marks)) {
311
+ const unique = node.marks.filter((mark, i) => node.marks.findIndex((other) => equal(other, mark)) === i);
312
+ const rank = (mark) => schema.marks[mark?.type]?.rank ?? Number.MAX_SAFE_INTEGER;
313
+ out.marks = unique.map((mark, i) => [mark, i]).sort((a, b) => rank(a[0]) - rank(b[0]) || a[1] - b[1]).map(([mark]) => mark);
314
+ if (!out.marks.length)
315
+ delete out.marks;
316
+ }
317
+ if (Array.isArray(node.content)) {
318
+ const merged = [];
319
+ for (const child of node.content.map((item) => canonical(item, schema))) {
320
+ if (child?.type === 'text' && !child.text)
321
+ continue;
322
+ const last = merged[merged.length - 1];
323
+ const plain = (value) => value?.type === 'text' && Object.keys(value).every(key => key === 'type' || key === 'text' || key === 'marks');
324
+ if (plain(last) && plain(child) && equal(last.marks ?? [], child.marks ?? []))
325
+ merged[merged.length - 1] = { ...last, text: last.text + child.text };
326
+ else
327
+ merged.push(child);
328
+ }
329
+ if (merged.length)
330
+ out.content = merged;
331
+ else
332
+ delete out.content;
333
+ }
334
+ return out;
335
+ }
336
+ export function losslessCompare(storedInput, roundTripped, schema) {
337
+ const result = [];
338
+ let rt = unwrapOpaque(roundTripped);
339
+ if (storedInput.type === 'doc' && storedInput.content?.length === 0 && rt.content?.length === 1 && rt.content[0].type === 'paragraph' && !rt.content[0].content?.length && !Object.values(rt.content[0].attrs || {}).some(v => v !== null))
340
+ rt = { ...rt, content: [] };
341
+ const stored = canonical(storedInput, schema);
342
+ rt = canonical(rt, schema);
343
+ const walk = (a, b, path, owner, attr = false) => {
344
+ if (equal(a, b))
345
+ return;
346
+ if (Array.isArray(a)) {
347
+ if (!Array.isArray(b)) {
348
+ result.push(path);
349
+ return;
350
+ }
351
+ if (a.length !== b.length)
352
+ result.push(path + '.length');
353
+ a.forEach((v, i) => walk(v, b[i], `${path}[${i}]`));
354
+ return;
355
+ }
356
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
357
+ for (const k of Object.keys(a)) {
358
+ if (!Object.hasOwn(b, k))
359
+ result.push(path + '.' + k);
360
+ else
361
+ walk(a[k], b[k], path + '.' + k, a, k === 'attrs');
362
+ }
363
+ for (const k of Object.keys(b))
364
+ if (!Object.hasOwn(a, k)) {
365
+ if (k === 'attrs')
366
+ walk({}, b[k], path + '.attrs', a, true);
367
+ else if (!(attr && (b[k] === null || equal(b[k], declaredDefault(schema, owner?.type, k)))))
368
+ result.push(path + '.' + k);
369
+ }
370
+ return;
371
+ }
372
+ result.push(path);
373
+ };
374
+ walk(stored, rt, '$');
375
+ return result;
376
+ }
377
+ export function cleanForSave(doc, _schema) {
378
+ const clean = (node) => {
379
+ const out = { ...node };
380
+ if (node.attrs) {
381
+ out.attrs = Object.fromEntries(Object.entries(node.attrs).filter(([, v]) => v !== null));
382
+ if (!Object.keys(out.attrs).length)
383
+ delete out.attrs;
384
+ }
385
+ if (node.content)
386
+ out.content = node.content.map(clean);
387
+ if (node.marks)
388
+ out.marks = node.marks.map(mark => clean(mark));
389
+ return out;
390
+ };
391
+ return clean(unwrapOpaque(doc));
392
+ }
@@ -0,0 +1,10 @@
1
+ import type { AbstractPowerSyncDatabase } from '@powersync/common';
2
+ import { EditorService } from './service.js';
3
+ /** The daemon's editor service, bound to its open database. */
4
+ export declare function createDaemonEditorService(db: AbstractPowerSyncDatabase, options: {
5
+ userId: string;
6
+ log: (message: string, details?: Record<string, unknown>) => void;
7
+ }): Promise<EditorService>;
8
+ export declare const EDITOR_METHODS: Set<string>;
9
+ /** Dispatches one `editor.*` daemon request. An explicit allowlist: never property lookup. */
10
+ export declare function handleEditorRequest(service: EditorService | null, method: string, params: unknown, signal?: AbortSignal): Promise<unknown>;
@@ -0,0 +1,56 @@
1
+ import { waitForUploadQueueEmpty } from '../powersync/runtime.js';
2
+ import { DinoxError } from '../utils/errors.js';
3
+ import { createEditorStore } from './document.js';
4
+ import { createFilePersistence, editorSessionsPath } from './persistence.js';
5
+ import { EditorService } from './service.js';
6
+ /** The daemon's editor service, bound to its open database. */
7
+ export async function createDaemonEditorService(db, options) {
8
+ const service = new EditorService({
9
+ store: createEditorStore(db, {
10
+ userId: options.userId,
11
+ waitForUpload: async (timeoutMs) => (await waitForUploadQueueEmpty(db, timeoutMs)).ok,
12
+ }),
13
+ persistence: createFilePersistence(editorSessionsPath(options.userId)),
14
+ watchNotes: onChange => db.onChange({ onChange }, { tables: ['c_note'], throttleMs: 200 }),
15
+ log: options.log,
16
+ });
17
+ await service.restore();
18
+ return service;
19
+ }
20
+ export const EDITOR_METHODS = new Set([
21
+ 'editor.open',
22
+ 'editor.state',
23
+ 'editor.read',
24
+ 'editor.suggest',
25
+ 'editor.search',
26
+ 'editor.sync',
27
+ 'editor.save',
28
+ 'editor.resolve',
29
+ 'editor.log',
30
+ 'editor.catalog',
31
+ 'editor.updateMeta',
32
+ 'editor.watchOpens',
33
+ ]);
34
+ /** Dispatches one `editor.*` daemon request. An explicit allowlist: never property lookup. */
35
+ export async function handleEditorRequest(service, method, params, signal) {
36
+ if (!service) {
37
+ throw new DinoxError('The editor needs a signed-in Dinox daemon.', { code: 'AUTH_REQUIRED', recoverable: true });
38
+ }
39
+ const input = (params && typeof params === 'object' && !Array.isArray(params) ? params : {});
40
+ const session = input.session;
41
+ switch (method) {
42
+ case 'editor.open': return service.open(session, input);
43
+ case 'editor.state': return service.state(session);
44
+ case 'editor.read': return service.read(session, input);
45
+ case 'editor.suggest': return service.suggest(session, input);
46
+ case 'editor.search': return service.search(input);
47
+ case 'editor.sync': return service.sync(session, input, signal);
48
+ case 'editor.save': return service.save(session, input);
49
+ case 'editor.resolve': return service.resolve(session, input);
50
+ case 'editor.log': return service.note(session, input);
51
+ case 'editor.catalog': return service.catalog();
52
+ case 'editor.updateMeta': return service.updateMeta(session, input);
53
+ case 'editor.watchOpens': return service.watchOpens(input, signal);
54
+ default: throw new DinoxError(`Unknown editor method: ${method}`, { code: 'USAGE_ERROR' });
55
+ }
56
+ }
@@ -0,0 +1,74 @@
1
+ import type { AbstractPowerSyncDatabase } from '@powersync/common';
2
+ import type { JSONContent } from '@tiptap/core';
3
+ import { type EditorCatalog, type EditorMeta, type EditorMetaPatch } from './meta.js';
4
+ export type EditorNote = {
5
+ noteId: string;
6
+ title: string;
7
+ document: JSONContent;
8
+ hash: string;
9
+ version: number | null;
10
+ updatedAt: string | null;
11
+ markdown: string;
12
+ plainText: string;
13
+ };
14
+ export type EditorSaveResult = {
15
+ status: 'saved' | 'unchanged';
16
+ hash: string;
17
+ version: number | null;
18
+ updatedAt: string | null;
19
+ } | {
20
+ status: 'conflict';
21
+ current: {
22
+ hash: string;
23
+ version: number | null;
24
+ updatedAt: string | null;
25
+ };
26
+ };
27
+ export type EditorSearchHit = {
28
+ id: string;
29
+ title: string;
30
+ snippet: string;
31
+ updatedAt: string | null;
32
+ };
33
+ /** Database operations the editor service needs; the daemon binds them to its open PowerSync db. */
34
+ export type EditorStore = {
35
+ load(noteId: string): Promise<EditorNote>;
36
+ save(input: {
37
+ noteId: string;
38
+ baseHash: string;
39
+ baseVersion: number | null;
40
+ document: JSONContent;
41
+ }): Promise<EditorSaveResult>;
42
+ search(query: string, limit: number): Promise<EditorSearchHit[]>;
43
+ /** Content hash of every listed note that still exists (deleted notes are omitted). */
44
+ hashes(noteIds: string[]): Promise<Map<string, {
45
+ hash: string;
46
+ version: number | null;
47
+ }>>;
48
+ /** Resolves when local writes reached the server, or rejects/returns false on timeout. */
49
+ waitForUpload(timeoutMs: number): Promise<boolean>;
50
+ /** Title, tags, boxes and properties; stores without them show a body-only header. */
51
+ meta?(noteId: string): Promise<EditorMeta>;
52
+ catalog?(): Promise<EditorCatalog>;
53
+ updateMeta?(noteId: string, patch: EditorMetaPatch): Promise<{
54
+ changed: string[];
55
+ meta: EditorMeta;
56
+ }>;
57
+ };
58
+ type NoteRow = {
59
+ id: string;
60
+ title: string | null;
61
+ content_json: string | null;
62
+ content_md: string | null;
63
+ version: number | string | null;
64
+ updated_at: string | null;
65
+ is_del: number | null;
66
+ };
67
+ /** Plain text exactly as the editor UI projects it (see anchor.ts). */
68
+ export declare function editorPlainText(document: JSONContent): string;
69
+ export declare function noteFromRow(row: NoteRow): EditorNote;
70
+ export declare function createEditorStore(db: AbstractPowerSyncDatabase, options: {
71
+ userId: string;
72
+ waitForUpload: (timeoutMs: number) => Promise<boolean>;
73
+ }): EditorStore;
74
+ export {};
@@ -0,0 +1,88 @@
1
+ import { getNoteContentHash, parseStoredNoteDocument, serializeNoteContentMarkdown, } from '../commands/notes/contentEngine.js';
2
+ import { replaceNoteDocument } from '../commands/notes/contentPatch.js';
3
+ import { searchNotesPage } from '../commands/notes/repo/search.js';
4
+ import { DinoxError } from '../utils/errors.js';
5
+ import { buildTextIndex } from './anchor.js';
6
+ import { guardSave } from './saveGuard.js';
7
+ import { createMetaStore } from './meta.js';
8
+ import { baseEditorSchema, parseEditorDocument } from './schema.js';
9
+ function normalizeVersion(value) {
10
+ const version = Number(value);
11
+ return value !== null && value !== undefined && Number.isFinite(version) ? version : null;
12
+ }
13
+ /** Plain text exactly as the editor UI projects it (see anchor.ts). */
14
+ export function editorPlainText(document) {
15
+ try {
16
+ return buildTextIndex(parseEditorDocument(document).node).text;
17
+ }
18
+ catch {
19
+ return '';
20
+ }
21
+ }
22
+ export function noteFromRow(row) {
23
+ const document = parseStoredNoteDocument({ contentJson: row.content_json, contentMd: row.content_md });
24
+ return {
25
+ noteId: row.id,
26
+ title: row.title?.trim() ?? '',
27
+ document,
28
+ hash: getNoteContentHash(document),
29
+ version: normalizeVersion(row.version),
30
+ updatedAt: row.updated_at ?? null,
31
+ markdown: serializeNoteContentMarkdown(document),
32
+ plainText: editorPlainText(document),
33
+ };
34
+ }
35
+ const NOTE_COLUMNS = 'id, title, content_json, content_md, version, updated_at, is_del';
36
+ export function createEditorStore(db, options) {
37
+ const readRow = async (noteId) => {
38
+ const row = await db.getOptional(`SELECT ${NOTE_COLUMNS} FROM c_note WHERE id = ?`, [noteId]);
39
+ if (!row || Number(row.is_del ?? 0) !== 0) {
40
+ throw new DinoxError(`Note not found: ${noteId}`, { code: 'NOTE_NOT_FOUND', recoverable: true });
41
+ }
42
+ return row;
43
+ };
44
+ const meta = createMetaStore(db, options.userId);
45
+ return {
46
+ meta: meta.meta,
47
+ catalog: meta.catalog,
48
+ updateMeta: meta.update,
49
+ async load(noteId) {
50
+ return noteFromRow(await readRow(noteId));
51
+ },
52
+ async save({ noteId, baseHash, baseVersion, document }) {
53
+ const stored = noteFromRow(await readRow(noteId));
54
+ guardSave(stored.document, document, baseEditorSchema());
55
+ const result = await replaceNoteDocument(db, { id: noteId, userId: options.userId, baseHash, baseVersion, document });
56
+ if (result.status === 'conflict')
57
+ return { status: 'conflict', current: result.current };
58
+ return { status: result.status, hash: result.hash, version: result.version, updatedAt: result.updatedAt };
59
+ },
60
+ async search(query, limit) {
61
+ const { rows } = await searchNotesPage(db, query, { includeDeleted: false, limit, offset: 0 });
62
+ if (!rows.length)
63
+ return [];
64
+ const dates = await db.getAll(`SELECT id, updated_at FROM c_note WHERE id IN (${rows.map(() => '?').join(',')})`, rows.map(row => row.id));
65
+ const updated = new Map(dates.map(row => [row.id, row.updated_at]));
66
+ return rows.map(row => ({
67
+ id: row.id,
68
+ title: row.title?.trim() ?? '',
69
+ snippet: String(row.summary ?? '').slice(0, 160),
70
+ updatedAt: updated.get(row.id) ?? null,
71
+ }));
72
+ },
73
+ async hashes(noteIds) {
74
+ const result = new Map();
75
+ if (!noteIds.length)
76
+ return result;
77
+ const rows = await db.getAll(`SELECT ${NOTE_COLUMNS} FROM c_note WHERE id IN (${noteIds.map(() => '?').join(',')})`, noteIds);
78
+ for (const row of rows) {
79
+ if (Number(row.is_del ?? 0) !== 0)
80
+ continue;
81
+ const document = parseStoredNoteDocument({ contentJson: row.content_json, contentMd: row.content_md });
82
+ result.set(row.id, { hash: getNoteContentHash(document), version: normalizeVersion(row.version) });
83
+ }
84
+ return result;
85
+ },
86
+ waitForUpload: options.waitForUpload,
87
+ };
88
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Editor UI language. The source strings are Traditional Chinese and double as
3
+ * keys; a dictionary (`editor-ui/src/strings.ts`) maps each to Simplified
4
+ * Chinese and English. DOM-free: the daemon uses it to word activity entries,
5
+ * which carry a message (key + params) so every panel shows them in its own
6
+ * language.
7
+ */
8
+ export declare const LOCALES: readonly ["zh-Hant", "zh-Hans", "en"];
9
+ export type Locale = (typeof LOCALES)[number];
10
+ export type MessageParam = string | number | readonly string[] | readonly Message[];
11
+ export type Message = {
12
+ key: string;
13
+ params?: Record<string, MessageParam>;
14
+ };
15
+ export type Dictionary = Record<string, readonly [hans: string, en: string]>;
16
+ /** The first of the user's preferred languages that the editor speaks; English otherwise. */
17
+ export declare function resolveLocale(tags: ReadonlyArray<string | null | undefined>): Locale;
18
+ /** Fills `{name}` placeholders; arrays join with the locale's list (or, for `{clauses}`, clause) separator. Unknown placeholders stay as written. */
19
+ export declare function translate(dictionary: Dictionary, locale: Locale, key: string, params?: Record<string, MessageParam>): string;
20
+ export declare function renderMessage(dictionary: Dictionary, locale: Locale, message: Message): string;
21
+ /** A message in the source language, for logs and clients that predate messages. */
22
+ export declare function sourceText(message: Message): string;
23
+ export declare function isMessage(value: unknown): value is Message;