onionskin-cli 0.0.0-stage → 0.0.1

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 (117) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/INSTALL.md +17 -0
  3. package/LICENSE +21 -0
  4. package/NOTICE +46 -0
  5. package/README.md +88 -2
  6. package/docs/contracts/batch.schema.json +839 -0
  7. package/docs/contracts/history.schema.json +126 -0
  8. package/docs/contracts/ops.schema.json +541 -0
  9. package/package.json +54 -4
  10. package/scripts/checker/check.py +411 -0
  11. package/scripts/checker/requirements.txt +5 -0
  12. package/scripts/install-check.mjs +9 -0
  13. package/scripts/requirements.txt +5 -0
  14. package/scripts/rewriter/apple/main.swift +135 -0
  15. package/scripts/rewriter/apple/onionskin-fm +0 -0
  16. package/scripts/rewriter/apple/onionskin-fm.json +6 -0
  17. package/skills/onionskin/SKILL.md +117 -0
  18. package/skills/onionskin/reference/batch.md +94 -0
  19. package/skills/onionskin/reference/formats.md +15 -0
  20. package/skills/onionskin/reference/ops.md +253 -0
  21. package/skills/onionskin/reference/troubleshooting.md +73 -0
  22. package/skills/onionskin/reference/voice-guide.md +86 -0
  23. package/skills/onionskin/voice.example.md +51 -0
  24. package/src/agent-detect.js +149 -0
  25. package/src/agent-events.js +159 -0
  26. package/src/agent-prompt.js +27 -0
  27. package/src/agent-runner.js +593 -0
  28. package/src/analyze.js +17 -0
  29. package/src/anchors.js +190 -0
  30. package/src/apply.js +387 -0
  31. package/src/auth.js +130 -0
  32. package/src/batch.js +322 -0
  33. package/src/check-worker.js +8 -0
  34. package/src/checker.js +293 -0
  35. package/src/cli.js +516 -0
  36. package/src/constants.js +20 -0
  37. package/src/diff.js +267 -0
  38. package/src/doctor.js +247 -0
  39. package/src/docx.js +438 -0
  40. package/src/fmt.js +30 -0
  41. package/src/fsutil.js +348 -0
  42. package/src/history-worker.js +16 -0
  43. package/src/history.js +576 -0
  44. package/src/lease.js +79 -0
  45. package/src/local.js +242 -0
  46. package/src/merge-pptx.js +198 -0
  47. package/src/merge-xlsx.js +453 -0
  48. package/src/merge.js +410 -0
  49. package/src/offload.js +34 -0
  50. package/src/ops/common.js +48 -0
  51. package/src/ops/docx-table.js +323 -0
  52. package/src/ops/docx.js +503 -0
  53. package/src/ops/engine.js +41 -0
  54. package/src/ops/pptx.js +336 -0
  55. package/src/ops/run.js +115 -0
  56. package/src/ops/runs.js +127 -0
  57. package/src/ops/schema.js +109 -0
  58. package/src/ops/xlsx.js +277 -0
  59. package/src/package.js +189 -0
  60. package/src/paths.js +64 -0
  61. package/src/person.js +66 -0
  62. package/src/pptx.js +194 -0
  63. package/src/question.js +47 -0
  64. package/src/quick-plan.js +107 -0
  65. package/src/quick.js +164 -0
  66. package/src/redline-check.js +251 -0
  67. package/src/redline-worker.js +29 -0
  68. package/src/redline.js +438 -0
  69. package/src/reply.js +410 -0
  70. package/src/review.js +274 -0
  71. package/src/rewrite-check.js +1014 -0
  72. package/src/rewriter-cleanup.js +105 -0
  73. package/src/rewriter-setup.js +104 -0
  74. package/src/rewriter.js +396 -0
  75. package/src/sanitize.js +42 -0
  76. package/src/sentence-span.js +25 -0
  77. package/src/server-entry.js +13 -0
  78. package/src/server.js +576 -0
  79. package/src/session.js +1910 -0
  80. package/src/settings.js +161 -0
  81. package/src/setup.js +160 -0
  82. package/src/stamp-words.js +10 -0
  83. package/src/stamps.js +59 -0
  84. package/src/style.js +110 -0
  85. package/src/suggest-reply.js +84 -0
  86. package/src/suggest.js +261 -0
  87. package/src/text.js +31 -0
  88. package/src/tracked-words.js +43 -0
  89. package/src/voice-guide.js +182 -0
  90. package/src/voice-learn.js +314 -0
  91. package/src/voice-sample-worker.js +95 -0
  92. package/src/voice-samples.js +329 -0
  93. package/src/voice-store.js +305 -0
  94. package/src/voice-worker.js +28 -0
  95. package/src/voice.js +297 -0
  96. package/src/xlsx.js +454 -0
  97. package/src/xml-tree.js +118 -0
  98. package/src/xml.js +127 -0
  99. package/src/zip-write.js +74 -0
  100. package/src/zip.js +88 -0
  101. package/vendor/engine/DocViewer-BZLXUcxJ.js +15137 -0
  102. package/vendor/engine/THIRD_PARTY_LICENSES.txt +79 -0
  103. package/vendor/engine/collab-BVynXMqc.js +2591 -0
  104. package/vendor/engine/collab.js +2 -0
  105. package/vendor/engine/core.js +4 -0
  106. package/vendor/engine/default-worker-DogNT09A.js +35625 -0
  107. package/vendor/engine/embed.js +107 -0
  108. package/vendor/engine/index.js +5 -0
  109. package/vendor/engine/office-engine.embed.js +184 -0
  110. package/vendor/engine/office-engine.worker.js +36030 -0
  111. package/vendor/engine/xlsx-ops-SYAv6V0f.js +939 -0
  112. package/vendor/engine-node/LICENSE +21 -0
  113. package/vendor/engine-node/engine-node.mjs +46618 -0
  114. package/vendor/engine.lock.json +26 -0
  115. package/web/dist/assets/index-CFISATkn.js +197 -0
  116. package/web/dist/assets/index-spXE4oTz.css +1 -0
  117. package/web/dist/index.html +14 -0
package/src/xlsx.js ADDED
@@ -0,0 +1,454 @@
1
+ import { colLetters, parseA1 } from "./ops/common.js";
2
+ import { untrusted } from "./sanitize.js";
3
+ import { exactHash, normText } from "./text.js";
4
+ import { walkXml } from "./xml.js";
5
+ import { openZip } from "./zip.js";
6
+
7
+ // XLSX durable anchors. Everything is read from the bytes with the small XML walker (no engine). Names are matched by local name,
8
+ // because writers differ in prefixes. Cell text is the text a user would see in the formula bar, as `onionskin apply` expects it:
9
+ // the formula (with a leading =) when the cell has one, else the stored value. A shared-formula child (no formula text of its own)
10
+ // falls back to its cached value (ceiling: its quote is then not the formula) and is marked `shared`: its text is a result that changes
11
+ // when another cell does, never something a person typed.
12
+
13
+ const local = (n) => n.slice(n.indexOf(":") + 1);
14
+ const attrOf = (attrs, name) => {
15
+ for (const k of Object.keys(attrs)) if (k.includes(":") && local(k) === name) return attrs[k];
16
+ return undefined;
17
+ };
18
+ const NUM = /^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
19
+ const EMPTY = exactHash("");
20
+ /** hash of a parsed cell's text, computed once per cell (resolution and the diff would otherwise hash every cell per anchor) */
21
+ export const ch = (cell) => (cell.h ??= exactHash(cell.text));
22
+ const short = (s, n = 80) => normText(s).slice(0, n);
23
+ const MAX_CELLS = 1_500_000;
24
+ const KEEP_ROW_CELLS = 64;
25
+
26
+ const relTarget = (base, target) => {
27
+ if (target.startsWith("/")) return target.slice(1);
28
+ const parts = base.split("/").slice(0, -1);
29
+ for (const seg of target.split("/")) {
30
+ if (seg === "..") parts.pop();
31
+ else if (seg !== ".") parts.push(seg);
32
+ }
33
+ return parts.join("/");
34
+ };
35
+
36
+ export function readRels(zip, part) {
37
+ const dir = part.split("/").slice(0, -1).join("/");
38
+ const rels = new Map();
39
+ const xml = zip.readText(`${dir ? `${dir}/` : ""}_rels/${part.split("/").pop()}.rels`);
40
+ if (xml == null) return rels;
41
+ walkXml(xml, {
42
+ onOpen(name, a) {
43
+ if (local(name) === "Relationship" && a.Id && a.Target) rels.set(a.Id, relTarget(part, a.Target));
44
+ },
45
+ });
46
+ return rels;
47
+ }
48
+ export { attrOf, local };
49
+
50
+ /** workbook.xml: sheets in order with sheetId, name, part path; defined names. Sheet cells are read lazily (`sheetCells`). */
51
+ export function parseWorkbook(bytes) {
52
+ const zip = openZip(bytes);
53
+ const xml = zip.readText("xl/workbook.xml");
54
+ if (xml == null) throw new Error("xl/workbook.xml missing");
55
+ const rels = readRels(zip, "xl/workbook.xml");
56
+ const sheets = [];
57
+ const names = [];
58
+ let curName = null;
59
+ walkXml(xml, {
60
+ onOpen(n, a) {
61
+ const l = local(n);
62
+ if (l === "sheet") sheets.push({ index: sheets.length, name: a.name ?? "", sheetId: a.sheetId ?? null, hidden: a.state === "hidden" || a.state === "veryHidden", part: rels.get(attrOf(a, "id")) || null });
63
+ else if (l === "definedName") curName = { name: a.name, ref: "" };
64
+ },
65
+ onText(t) {
66
+ if (curName) curName.ref += t;
67
+ },
68
+ onClose(n) {
69
+ if (local(n) === "definedName" && curName) {
70
+ names.push(curName);
71
+ curName = null;
72
+ }
73
+ },
74
+ });
75
+ let sst = null;
76
+ const sharedStrings = () => {
77
+ if (sst) return sst;
78
+ sst = [];
79
+ const sx = zip.readText("xl/sharedStrings.xml");
80
+ if (sx == null) return sst;
81
+ let cur = null;
82
+ let inT = false;
83
+ let phon = 0;
84
+ walkXml(sx, {
85
+ onOpen(n) {
86
+ const l = local(n);
87
+ if (l === "si") cur = "";
88
+ else if (l === "rPh") phon++;
89
+ else if (l === "t" && cur !== null && !phon) inT = true;
90
+ },
91
+ onText(t) {
92
+ if (inT) cur += t;
93
+ },
94
+ onClose(n) {
95
+ const l = local(n);
96
+ if (l === "t") inT = false;
97
+ else if (l === "rPh") phon = Math.max(0, phon - 1);
98
+ else if (l === "si") {
99
+ sst.push(cur ?? "");
100
+ cur = null;
101
+ }
102
+ },
103
+ });
104
+ return sst;
105
+ };
106
+ const cache = new Map();
107
+ const sheetCells = (s) => {
108
+ if (!cache.has(s.index)) cache.set(s.index, readSheet(zip, s, sharedStrings));
109
+ return cache.get(s.index);
110
+ };
111
+ // number formats: the style index of a cell -> its format code (xl/styles.xml cellXfs + numFmts, with the built-in ids)
112
+ let fmts = null;
113
+ const numberFormat = (styleIdx) => {
114
+ if (!fmts) {
115
+ fmts = { custom: new Map(), xf: [] };
116
+ const sx = zip.readText("xl/styles.xml");
117
+ let inXfs = false;
118
+ if (sx != null)
119
+ walkXml(sx, {
120
+ onOpen(n, a) {
121
+ const l = local(n);
122
+ if (l === "numFmt" && a.numFmtId != null) fmts.custom.set(Number(a.numFmtId), a.formatCode ?? "");
123
+ else if (l === "cellXfs") inXfs = true;
124
+ else if (l === "xf" && inXfs) fmts.xf.push(Number(a.numFmtId) || 0);
125
+ },
126
+ onClose(n) {
127
+ if (local(n) === "cellXfs") inXfs = false;
128
+ },
129
+ });
130
+ }
131
+ const id = fmts.xf[styleIdx] ?? 0;
132
+ return fmts.custom.get(id) ?? BUILTIN_FORMATS[id] ?? (id ? `format ${id}` : "General");
133
+ };
134
+ return { sheets, names, sheetCells, numberFormat };
135
+ }
136
+
137
+ const BUILTIN_FORMATS = { 0: "General", 1: "0", 2: "0.00", 3: "#,##0", 4: "#,##0.00", 9: "0%", 10: "0.00%", 11: "0.00E+00", 12: "# ?/?", 13: "# ??/??", 14: "mm-dd-yy", 15: "d-mmm-yy", 16: "d-mmm", 17: "mmm-yy", 18: "h:mm AM/PM", 19: "h:mm:ss AM/PM", 20: "h:mm", 21: "h:mm:ss", 22: "m/d/yy h:mm", 37: "#,##0 ;(#,##0)", 38: "#,##0 ;[Red](#,##0)", 39: "#,##0.00;(#,##0.00)", 40: "#,##0.00;[Red](#,##0.00)", 45: "mm:ss", 46: "[h]:mm:ss", 47: "mmss.0", 48: "##0.0E+0", 49: "@" };
138
+
139
+ const key = (r, c) => r * 16384 + c;
140
+
141
+ /** {cells: Map(r*16384+c -> {r,c,text}), rows: Map(r -> cells sorted by column), maxR, maxC, truncated, merges: [{r0,c0,r1,c1}]}. Empty cells are not kept. */
142
+ function readSheet(zip, sheet, sharedStrings) {
143
+ const cells = new Map();
144
+ const rows = new Map();
145
+ const out = { cells, rows, maxR: -1, maxC: -1, truncated: false, merges: [] };
146
+ const xml = sheet.part ? zip.readText(sheet.part) : null;
147
+ if (xml == null) return out;
148
+ let cur = null;
149
+ let field = null; // v | f | is
150
+ let inIs = false;
151
+ let phon = 0;
152
+ walkXml(xml, {
153
+ onOpen(n, a) {
154
+ const l = local(n);
155
+ if (l === "mergeCell") {
156
+ const q = parseA1(a.ref ?? "");
157
+ if (q && (q.r1 > q.r0 || q.c1 > q.c0)) out.merges.push(q);
158
+ } else if (l === "c" && a.r) {
159
+ const m = /^([A-Z]{1,3})(\d+)$/.exec(a.r);
160
+ cur = m ? { c: [...m[1]].reduce((x, ch) => x * 26 + ch.charCodeAt(0) - 64, 0) - 1, r: Number(m[2]) - 1, t: a.t || "n", s: Number(a.s) || 0, v: "", f: null, is: "" } : null;
161
+ } else if (!cur) return;
162
+ else if (l === "v") field = "v";
163
+ else if (l === "f") {
164
+ field = "f";
165
+ cur.f = "";
166
+ } else if (l === "is") inIs = true;
167
+ else if (l === "rPh") phon++;
168
+ else if (l === "t" && inIs && !phon) field = "is";
169
+ },
170
+ onText(t) {
171
+ if (cur && field) cur[field] += t;
172
+ },
173
+ onClose(n) {
174
+ const l = local(n);
175
+ if (l === "v" || l === "f" || l === "t") field = null;
176
+ else if (l === "is") inIs = false;
177
+ else if (l === "rPh") phon = Math.max(0, phon - 1);
178
+ else if (l === "c" && cur) {
179
+ if (cells.size >= MAX_CELLS) out.truncated = true;
180
+ else {
181
+ let text;
182
+ if (cur.f) text = `=${cur.f}`;
183
+ else if (cur.t === "s") text = sharedStrings()[Number(cur.v)] ?? "";
184
+ else if (cur.t === "inlineStr") text = cur.is;
185
+ else if (cur.t === "b") text = cur.v === "1" ? "TRUE" : "FALSE";
186
+ else if (cur.t === "n" && NUM.test(cur.v)) text = String(Number(cur.v));
187
+ else text = cur.v;
188
+ if (text !== "" && cur.c < 16384) {
189
+ const cell = { r: cur.r, c: cur.c, text, k: cur.f ? "formula" : cur.t === "s" || cur.t === "inlineStr" || cur.t === "str" ? "text" : cur.t === "b" ? "boolean" : cur.t === "e" ? "error" : "number", s: cur.s, ...(cur.f ? { cached: cur.v } : cur.f === "" ? { shared: true } : {}) }; // `cached`: the value a formula last computed (History shows it next to the formula)
190
+ cells.set(key(cur.r, cur.c), cell);
191
+ if (!rows.has(cur.r)) rows.set(cur.r, []);
192
+ rows.get(cur.r).push(cell);
193
+ if (cur.r > out.maxR) out.maxR = cur.r;
194
+ if (cur.c > out.maxC) out.maxC = cur.c;
195
+ }
196
+ }
197
+ cur = null;
198
+ }
199
+ },
200
+ });
201
+ for (const list of rows.values()) list.sort((a, b) => a.c - b.c);
202
+ return out;
203
+ }
204
+
205
+ // ---- ranges and context ---------------------------------------------------------------------------------------
206
+
207
+ export const a1 = (r, c) => `${colLetters(c)}${r + 1}`;
208
+ export const a1Range = (q) => (q.r0 === q.r1 && q.c0 === q.c1 ? a1(q.r0, q.c0) : `${a1(q.r0, q.c0)}:${a1(q.r1, q.c1)}`);
209
+ const at = (sd, r, c) => (r < 0 || c < 0 ? "" : sd.cells.get(key(r, c))?.text ?? "");
210
+
211
+ /** the text of a rectangle as `apply` expects it: cells joined by TAB, rows by LF (bounded) */
212
+ export function rangeText(sd, q) {
213
+ const rows = [];
214
+ for (let r = q.r0; r <= Math.min(q.r1, q.r0 + 2000); r++) {
215
+ const row = [];
216
+ for (let c = q.c0; c <= Math.min(q.c1, q.c0 + 200); c++) row.push(at(sd, r, c));
217
+ rows.push(row.join("\t"));
218
+ }
219
+ return rows.join("\n");
220
+ }
221
+
222
+ /** Per cell of a range (at most 20 x 10, like the evidence `values`): its kind (number, text, formula, boolean, error, empty) and number format. */
223
+ function cellMeta(wb, sd, q) {
224
+ const types = [];
225
+ const formats = [];
226
+ for (let r = q.r0; r <= Math.min(q.r1, q.r0 + 19); r++) {
227
+ const t = [];
228
+ const f = [];
229
+ for (let c = q.c0; c <= Math.min(q.c1, q.c0 + 9); c++) {
230
+ const cell = sd.cells.get(key(r, c));
231
+ t.push(cell ? cell.k : "empty");
232
+ f.push(cell ? wb.numberFormat(cell.s) : "General");
233
+ }
234
+ types.push(t);
235
+ formats.push(f);
236
+ }
237
+ return { types, formats };
238
+ }
239
+
240
+ /** The nearest non-empty cell above `r` in column `c`: the column header (the topmost one, which is the header row of a table). */
241
+ function colHeaderAt(sd, r, c) {
242
+ for (let i = 0; i < r; i++) {
243
+ const t = at(sd, i, c);
244
+ if (t !== "") return short(t);
245
+ }
246
+ return "";
247
+ }
248
+
249
+ /** What surrounds a range: neighbors, the row's other cells (hashes), the row's leftmost cell, the column's header. */
250
+ function contextOf(sd, q) {
251
+ const rowCells = [];
252
+ let rowHeader = "";
253
+ for (const cell of sd.rows.get(q.r0) || []) {
254
+ if (cell.c >= q.c0 && cell.c <= q.c1) continue;
255
+ if (!rowHeader && cell.c < q.c0) rowHeader = cell.text;
256
+ if (rowCells.length < KEEP_ROW_CELLS) rowCells.push(ch(cell));
257
+ }
258
+ return {
259
+ rowHeader: short(rowHeader),
260
+ colHeader: colHeaderAt(sd, q.r0, q.c0),
261
+ left: short(at(sd, q.r0, q.c0 - 1)),
262
+ right: short(at(sd, q.r0, q.c1 + 1)),
263
+ up: short(at(sd, q.r0 - 1, q.c0)),
264
+ down: short(at(sd, q.r1 + 1, q.c0)),
265
+ rowCells: rowCells.sort(),
266
+ };
267
+ }
268
+
269
+ /** Fraction of the remembered other cells of the row that row `r` still has (outside columns [c0,c1]). */
270
+ function rowOverlap(sd, ctx, r, c0, c1) {
271
+ if (!ctx.rowCells.length) return 0;
272
+ const have = new Map();
273
+ for (const cell of sd.rows.get(r) || []) {
274
+ if (cell.c >= c0 && cell.c <= c1) continue;
275
+ const h = ch(cell);
276
+ have.set(h, (have.get(h) || 0) + 1);
277
+ }
278
+ let hit = 0;
279
+ for (const h of ctx.rowCells) {
280
+ if (have.get(h) > 0) {
281
+ hit++;
282
+ have.set(h, have.get(h) - 1);
283
+ }
284
+ }
285
+ return hit / ctx.rowCells.length;
286
+ }
287
+ const hasRowInfo = (ctx) => ctx.rowCells.length > 0 || !!ctx.rowHeader;
288
+ const firstOutside = (sd, r, c0, c1) => (sd.rows.get(r) || []).find((x) => x.c < c0 || x.c > c1);
289
+ /** row `r` looks like the remembered row: most of its other cells are there, or its leftmost cell is the same */
290
+ const sameRow = (sd, ctx, r, c0, c1) => rowOverlap(sd, ctx, r, c0, c1) >= 0.6 || (!!ctx.rowHeader && short(firstOutside(sd, r, c0, c1)?.text) === ctx.rowHeader);
291
+
292
+ function neighborScore(sd, ctx, r, c, d) {
293
+ const eq = (a, b) => (a !== "" && a === b ? 0.5 : 0);
294
+ return eq(ctx.left, short(at(sd, r, c - 1))) + eq(ctx.right, short(at(sd, r, c + (d.c1 - d.c0) + 1))) + eq(ctx.up, short(at(sd, r - 1, c))) + eq(ctx.down, short(at(sd, r + (d.r1 - d.r0) + 1, c)));
295
+ }
296
+
297
+ // ---- anchors --------------------------------------------------------------------------------------------------
298
+
299
+ const bookRef = (ref) => {
300
+ const m = /^(?:'((?:[^']|'')+)'|([^!']+))!\$?([A-Z]{1,3})\$?(\d+)(?::\$?([A-Z]{1,3})\$?(\d+))?$/.exec(String(ref).trim());
301
+ if (!m) return null;
302
+ return { sheet: (m[1] ?? m[2]).replace(/''/g, "'"), a1: m[5] ? `${m[3]}${m[4]}:${m[5]}${m[6]}` : `${m[3]}${m[4]}` };
303
+ };
304
+ const pickSheet = (wb, { sheetName, sheetIndex }) => wb.sheets.find((s) => s.name === sheetName) || wb.sheets[sheetIndex] || null;
305
+
306
+ /**
307
+ * Engine location {sheetIndex, sheetName, range} -> durable anchor, from the written bytes. `range` is a cell or rectangle (the anchor
308
+ * remembers its text, the row's other cells and the neighbors) or whole rows / columns / the sheet (position only).
309
+ */
310
+ export function xlsxDurable(wb, loc) {
311
+ const sheet = pickSheet(wb, loc);
312
+ if (!sheet) return null;
313
+ const base = { format: "xlsx", sheetId: sheet.sheetId, sheetName: sheet.name, sheetIndex: sheet.index, range: loc.range || "" };
314
+ const q = parseA1(loc.range || "");
315
+ if (!q) return { ...base, cell: false, text: "", textHash: null, ctx: null, names: [] };
316
+ const sd = wb.sheetCells(sheet);
317
+ const text = rangeText(sd, q);
318
+ const full = a1Range(q);
319
+ return {
320
+ ...base,
321
+ cell: true,
322
+ r0: q.r0, c0: q.c0, r1: q.r1, c1: q.c1,
323
+ text, // typed text of the whole range
324
+ textHash: exactHash(at(sd, q.r0, q.c0)), // of the top-left cell: the identity
325
+ rangeHash: exactHash(text),
326
+ ctx: contextOf(sd, q),
327
+ ...cellMeta(wb, sd, q),
328
+ names: wb.names.filter((n) => { const b = bookRef(n.ref); return b && b.sheet === sheet.name && b.a1 === full; }).map((n) => n.name),
329
+ };
330
+ }
331
+
332
+ const RANK = { position: 4, value: 3, context: 2, name: 1 };
333
+
334
+ /**
335
+ * Re-resolve against new bytes. Strategies, first hit wins (the method is reported):
336
+ * sheet: sheetId when it agrees with the name; else the name, then the id (the better cell match decides), else the content.
337
+ * position: same address, same text, same row. value: the same text elsewhere, the context picks between equals.
338
+ * position (changed): same address, text changed, row and column header still agree.
339
+ * context: text changed and the cell moved: the row by its other cells or leftmost cell, the column by its header.
340
+ * name: a defined name that pointed at it. none: "moved or removed".
341
+ * Result: {method, sheetId, sheetName, sheetIndex, range, changed, moved, text, r0,c0,r1,c1}.
342
+ */
343
+ export function resolveXlsx(wb, d) {
344
+ if (!d) return { method: "none" };
345
+ const byId = d.sheetId != null ? wb.sheets.find((s) => s.sheetId === d.sheetId) : null;
346
+ const byName = wb.sheets.find((s) => s.name === d.sheetName) || null;
347
+ const cands = [];
348
+ if (byId && byName === byId) cands.push(byId);
349
+ else {
350
+ if (byName) cands.push(byName);
351
+ if (byId) cands.push(byId);
352
+ }
353
+ if (!cands.length) return contentSearch(wb, d);
354
+ let best = null;
355
+ for (const s of cands) {
356
+ const r = resolveIn(wb, s, d);
357
+ if (r.method !== "none" && (!best || (RANK[r.method] ?? 0) > (RANK[best.method] ?? 0))) best = r;
358
+ }
359
+ // an id that now belongs to another sheet (a renumbering writer) and a name that is gone: look for the content everywhere
360
+ return best || contentSearch(wb, d);
361
+ }
362
+
363
+ function resolveIn(wb, s, d) {
364
+ if (!d.cell) return { method: "position", sheetId: s.sheetId, sheetName: s.name, sheetIndex: s.index, range: d.range, changed: false, moved: false, text: "" };
365
+ const sd = wb.sheetCells(s);
366
+ const ctx = d.ctx;
367
+ const w = d.c1 - d.c0;
368
+ const hh = d.r1 - d.r0;
369
+ const shape = (r, c) => ({ r0: r, c0: c, r1: r + hh, c1: c + w });
370
+ const res = (method, q) => {
371
+ const text = rangeText(sd, q);
372
+ return { method, sheetId: s.sheetId, sheetName: s.name, sheetIndex: s.index, range: a1Range(q), changed: exactHash(text) !== d.rangeHash, moved: q.r0 !== d.r0 || q.c0 !== d.c0, text: text.slice(0, 200), ...q };
373
+ };
374
+ const noCtx = !hasRowInfo(ctx) && !ctx.left && !ctx.right && !ctx.up && !ctx.down;
375
+ const rowOk = (r, c) => sameRow(sd, ctx, r, c, c + w);
376
+ const colOk = (r, c) => !ctx.colHeader || colHeaderAt(sd, r, c) === ctx.colHeader;
377
+ const gate = (r, c) => (hasRowInfo(ctx) ? rowOk(r, c) : noCtx || neighborScore(sd, ctx, r, c, d) >= 1);
378
+ // 1. same address, same text, same row
379
+ if (exactHash(at(sd, d.r0, d.c0)) === d.textHash && gate(d.r0, d.c0)) return res("position", shape(d.r0, d.c0));
380
+ // 2. the same text somewhere else; the context picks between equal values
381
+ if (d.textHash !== EMPTY) {
382
+ const hits = [];
383
+ for (const cell of sd.cells.values()) if (ch(cell) === d.textHash) hits.push(cell);
384
+ // one other cell with the same text only counts when the row or column header agree with it (or the anchor never had any): an edited
385
+ // cell must not be stolen by an unrelated cell that happens to hold the old text; the in-place step below gets its chance first
386
+ const fits = (x) => (hasRowInfo(ctx) ? rowOk(x.r, x.c) || (!!ctx.colHeader && colHeaderAt(sd, x.r, x.c) === ctx.colHeader) : !ctx.colHeader || colHeaderAt(sd, x.r, x.c) === ctx.colHeader);
387
+ if (hits.length === 1 && fits(hits[0])) return res("value", shape(hits[0].r, hits[0].c));
388
+ if (hits.length > 1) {
389
+ const scored = hits
390
+ .map((x) => ({ x, score: (rowOk(x.r, x.c) ? 2 : 0) + (ctx.colHeader && colHeaderAt(sd, x.r, x.c) === ctx.colHeader ? 1.5 : 0) + neighborScore(sd, ctx, x.r, x.c, d) }))
391
+ .sort((a, b) => b.score - a.score);
392
+ if (scored[0].score > 0 && scored[0].score > scored[1].score) return res("value", shape(scored[0].x.r, scored[0].x.c));
393
+ }
394
+ }
395
+ // 3. edited in place: the text differs but the row and the column header still say it is the same cell
396
+ if (hasRowInfo(ctx) ? rowOk(d.r0, d.c0) && colOk(d.r0, d.c0) : !noCtx && neighborScore(sd, ctx, d.r0, d.c0, d) >= 1) return res("position", shape(d.r0, d.c0));
397
+ // 4. the text changed and the cell moved: the row by its other cells, the column by its header
398
+ if (hasRowInfo(ctx)) {
399
+ const rowsHit = [];
400
+ for (const r of sd.rows.keys()) {
401
+ const ov = rowOverlap(sd, ctx, r, -1, -1);
402
+ const hdr = !!ctx.rowHeader && short(sd.rows.get(r)[0]?.text) === ctx.rowHeader;
403
+ if (ov >= 0.6 || hdr) rowsHit.push({ r, score: ov + (hdr ? 0.5 : 0) });
404
+ }
405
+ rowsHit.sort((a, b) => b.score - a.score);
406
+ if (rowsHit.length && (rowsHit.length === 1 || rowsHit[0].score > rowsHit[1].score)) {
407
+ const row = rowsHit[0].r;
408
+ const cols = [];
409
+ if (ctx.colHeader) {
410
+ for (let c = 0; c <= sd.maxC; c++) if (colHeaderAt(sd, row, c) === ctx.colHeader) cols.push(c);
411
+ } else cols.push(d.c0);
412
+ if (cols.length === 1) return res("context", shape(row, cols[0]));
413
+ }
414
+ }
415
+ // 5. a defined name that pointed at this range; last, because a library that does not shift names leaves them stale
416
+ for (const nm of d.names || []) {
417
+ const def = wb.names.find((n) => n.name === nm);
418
+ const b = def ? bookRef(def.ref) : null;
419
+ const q = b && b.sheet === s.name ? parseA1(b.a1) : null;
420
+ // a name that moved was updated by the writer (trusted); one that still points at the old address is stale unless the cell checks out
421
+ const verified = q && (exactHash(at(sd, q.r0, q.c0)) === d.textHash || (hasRowInfo(ctx) ? sameRow(sd, ctx, q.r0, q.c0, q.c0 + w) : neighborScore(sd, ctx, q.r0, q.c0, d) >= 1));
422
+ if (q && (q.r0 !== d.r0 || q.c0 !== d.c0 || verified)) return res("name", q);
423
+ }
424
+ return { method: "none" };
425
+ }
426
+
427
+ /** The sheet is gone (renamed and renumbered): the cell by its text and context in every sheet; only one clear winner counts. */
428
+ function contentSearch(wb, d) {
429
+ if (!d.cell || d.textHash === EMPTY) return { method: "none" };
430
+ const found = [];
431
+ for (const s of wb.sheets) {
432
+ const r = resolveIn(wb, s, d);
433
+ if (r.method === "position" || r.method === "value") found.push(r);
434
+ }
435
+ return found.length === 1 ? { ...found[0], method: "value" } : { method: "none" };
436
+ }
437
+
438
+ /** Locator fields for the batch: the names the `apply` targets use. */
439
+ const RANGE_OK = /^([A-Za-z]{1,3}\d{1,7}(:[A-Za-z]{1,3}\d{1,7})?|\d{1,7}:\d{1,7}|[A-Za-z]{1,3}:[A-Za-z]{1,3})$/;
440
+ export const xlsxLocator = (d) =>
441
+ d
442
+ ? {
443
+ sheet: untrusted(d.sheetName, 100), // a sheet name is document text: control and bidi characters out, capped (Excel allows 31)
444
+ sheet_id: /^\d{1,10}$/.test(String(d.sheetId ?? "")) ? String(d.sheetId) : null,
445
+ range: RANGE_OK.test(d.range || "") ? d.range : null, // only the shapes the host speaks; anything else is a whole-sheet anchor
446
+ text_hash: d.textHash ?? null,
447
+ }
448
+ : null;
449
+
450
+ /** Rows of a sheet for the changed-region diff: [{r, cells:[{c,text}]}] in order. */
451
+ export function sheetRows(wb, s) {
452
+ const sd = wb.sheetCells(s);
453
+ return [...sd.rows.keys()].sort((a, b) => a - b).map((r) => ({ r, cells: sd.rows.get(r) }));
454
+ }
@@ -0,0 +1,118 @@
1
+ import { decodeEntities } from "./xml.js";
2
+
3
+ // A lossless element tree for one OOXML part: every node keeps its raw source text, so serialize(parse(x)) === x exactly and a builder
4
+ // can rewrite a few elements while every other byte stays as the writer left it. Refuses DTDs and entity declarations; depth 256.
5
+ // Nodes: {t: "el", name, open, close, kids, parent} (close is "" for a self-closing tag), {t: "text", raw}, {t: "raw", raw} (comment,
6
+ // processing instruction), {t: "cdata", raw}, and {t: "out", raw} or {t: "lazy", build} which only builders add.
7
+
8
+ const MAX_DEPTH = 256;
9
+
10
+ export function parse(xml) {
11
+ const root = { t: "root", kids: [], parent: null };
12
+ const stack = [root];
13
+ const n = xml.length;
14
+ let i = 0;
15
+ const top = () => stack[stack.length - 1];
16
+ const add = (node) => {
17
+ node.parent = top();
18
+ top().kids.push(node);
19
+ return node;
20
+ };
21
+ while (i < n) {
22
+ const lt = xml.indexOf("<", i);
23
+ if (lt < 0) {
24
+ add({ t: "text", raw: xml.slice(i) });
25
+ break;
26
+ }
27
+ if (lt > i) add({ t: "text", raw: xml.slice(i, lt) });
28
+ let end;
29
+ if (xml.startsWith("<!--", lt)) {
30
+ end = xml.indexOf("-->", lt + 4);
31
+ if (end < 0) throw new Error("unterminated comment");
32
+ add({ t: "raw", raw: xml.slice(lt, (end += 3)) });
33
+ } else if (xml.startsWith("<![CDATA[", lt)) {
34
+ end = xml.indexOf("]]>", lt + 9);
35
+ if (end < 0) throw new Error("unterminated CDATA");
36
+ add({ t: "cdata", raw: xml.slice(lt, (end += 3)) });
37
+ } else if (xml.startsWith("<?", lt)) {
38
+ end = xml.indexOf("?>", lt + 2);
39
+ if (end < 0) throw new Error("unterminated processing instruction");
40
+ add({ t: "raw", raw: xml.slice(lt, (end += 2)) });
41
+ } else if (xml.startsWith("<!", lt)) {
42
+ throw new Error("DTD or entity declarations are not allowed");
43
+ } else {
44
+ let j = lt + 1;
45
+ let q = "";
46
+ while (j < n) {
47
+ const c = xml[j];
48
+ if (q) {
49
+ if (c === q) q = "";
50
+ } else if (c === '"' || c === "'") q = c;
51
+ else if (c === ">") break;
52
+ j++;
53
+ }
54
+ if (j >= n) throw new Error("unterminated tag");
55
+ end = j + 1;
56
+ const tag = xml.slice(lt, end);
57
+ if (tag[1] === "/") {
58
+ const name = tag.slice(2, -1).trim();
59
+ const el = top();
60
+ if (el.t !== "el" || el.name !== name) throw new Error(`mismatched closing tag </${name}>`);
61
+ el.close = tag;
62
+ stack.pop();
63
+ } else {
64
+ const self = tag[tag.length - 2] === "/";
65
+ const m = /^<([^\s/>]+)/.exec(tag);
66
+ if (!m) throw new Error("bad tag");
67
+ const el = add({ t: "el", name: m[1], open: tag, close: "", kids: [] });
68
+ if (!self) {
69
+ stack.push(el);
70
+ if (stack.length - 1 > MAX_DEPTH) throw new Error("XML nesting too deep");
71
+ }
72
+ }
73
+ }
74
+ i = end;
75
+ }
76
+ if (stack.length !== 1) throw new Error("unclosed element");
77
+ return root;
78
+ }
79
+
80
+ export function serialize(node) {
81
+ switch (node.t) {
82
+ case "root":
83
+ return node.kids.map(serialize).join("");
84
+ case "el":
85
+ return node.open + node.kids.map(serialize).join("") + node.close;
86
+ case "lazy":
87
+ return node.build();
88
+ default:
89
+ return node.raw;
90
+ }
91
+ }
92
+
93
+ /** The attributes of an element's open tag, decoded, in source order: [[name, value]]. */
94
+ export function attrs(el) {
95
+ const out = [];
96
+ const re = /\s([^\s=/>]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
97
+ const body = el.open.slice(1 + el.name.length);
98
+ let m;
99
+ while ((m = re.exec(body))) out.push([m[1], decodeEntities(m[3] ?? m[4])]);
100
+ return out;
101
+ }
102
+ export const attr = (el, name) => attrs(el).find((a) => a[0] === name)?.[1];
103
+
104
+ /** The decoded text of a text or CDATA node. */
105
+ export const textOf = (node) => (node.t === "cdata" ? node.raw.slice(9, -3) : node.t === "text" ? decodeEntities(node.raw) : "");
106
+
107
+ export const elements = (el) => el.kids.filter((k) => k.t === "el");
108
+
109
+ export function* descendants(el) {
110
+ for (const k of el.kids || []) {
111
+ if (k.t !== "el") continue;
112
+ yield k;
113
+ yield* descendants(k);
114
+ }
115
+ }
116
+
117
+ export const escText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
118
+ export const escAttr = (s) => escText(s).replace(/"/g, "&quot;");