docxodus 6.2.0 → 6.4.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,607 @@
1
+ "use strict";
2
+ var DocxodusSession = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/session.ts
22
+ var session_exports = {};
23
+ __export(session_exports, {
24
+ ContextBoundary: () => ContextBoundary,
25
+ DocxSession: () => DocxSession,
26
+ PlaceholderKinds: () => PlaceholderKinds,
27
+ openDocxSession: () => openDocxSession
28
+ });
29
+
30
+ // src/types.ts
31
+ var PlaceholderKinds = {
32
+ BlankFill: 1,
33
+ AlternativeClause: 2,
34
+ Instruction: 4,
35
+ All: 7
36
+ };
37
+ var DiffFormat = {
38
+ Json: 0,
39
+ Unified: 1,
40
+ SideBySide: 2
41
+ };
42
+ var ContextBoundary = {
43
+ Char: 0,
44
+ Bracket: 1,
45
+ Sentence: 2,
46
+ Comma: 3
47
+ };
48
+
49
+ // src/session.ts
50
+ var DocxSession = class {
51
+ /** @internal */
52
+ constructor(handle, wasm) {
53
+ // ─── Raw escape hatch ────────────────────────────────────────────────
54
+ this.raw = {
55
+ getXml: (anchorId) => this.wasm.RawGetXml(this.handle, anchorId),
56
+ insertXml: (anchorId, position, xml) => JSON.parse(this.wasm.RawInsertXml(this.handle, anchorId, position, xml)),
57
+ replaceXml: (anchorId, xml) => JSON.parse(this.wasm.RawReplaceXml(this.handle, anchorId, xml))
58
+ };
59
+ this.handle = handle;
60
+ this.wasm = wasm;
61
+ }
62
+ // ─── View ────────────────────────────────────────────────────────────
63
+ project() {
64
+ return JSON.parse(this.wasm.Project(this.handle));
65
+ }
66
+ /**
67
+ * Project a slice of the document keyed off an anchor — useful for showing
68
+ * one section to an LLM at a time without paying the cost of projecting the
69
+ * whole document.
70
+ *
71
+ * - `ProjectionDepth.SelfOnly` — just the addressed block (one paragraph,
72
+ * row, etc.).
73
+ * - `ProjectionDepth.Subtree` — the block + descendants (e.g. a table with
74
+ * all its rows/cells, but no following content).
75
+ * - `ProjectionDepth.SubtreeAndFollowingSiblings` (default) — for headings
76
+ * this returns the whole section (heading + content up to the next same-
77
+ * or-higher heading); for non-headings it behaves like `Subtree`.
78
+ *
79
+ * @see docs/architecture/docx_mutation_api.md
80
+ */
81
+ projectAnchor(anchorId, depth = 2 /* SubtreeAndFollowingSiblings */) {
82
+ return JSON.parse(
83
+ this.wasm.ProjectAnchor(this.handle, anchorId, depth)
84
+ );
85
+ }
86
+ // ─── Tier A: text CRUD ───────────────────────────────────────────────
87
+ replaceText(anchorId, markdown) {
88
+ return JSON.parse(this.wasm.ReplaceText(this.handle, anchorId, markdown));
89
+ }
90
+ deleteBlock(anchorId) {
91
+ return JSON.parse(this.wasm.DeleteBlock(this.handle, anchorId));
92
+ }
93
+ /**
94
+ * Delete every top-level block-level sibling between `fromAnchorId` (inclusive)
95
+ * and `toAnchorIdExclusive` (exclusive). Both anchors must share a direct
96
+ * parent and live in the same package part. Returns a single `EditResult`
97
+ * whose `removed` lists every anchor that was deleted.
98
+ *
99
+ * Records ONE undo snapshot — `undo()` restores the entire range.
100
+ *
101
+ * @see docs/architecture/docx_mutation_api.md#deleterange
102
+ */
103
+ deleteRange(fromAnchorId, toAnchorIdExclusive) {
104
+ return JSON.parse(this.wasm.DeleteRange(this.handle, fromAnchorId, toAnchorIdExclusive));
105
+ }
106
+ /**
107
+ * Delete a heading and everything below it up to (but not including) the next
108
+ * heading at the same or higher level. The heading anchor must have `kind === "h"`.
109
+ *
110
+ * If the target is the last heading in its parent, the section extends to the
111
+ * end of the parent (heading + everything after).
112
+ *
113
+ * @see docs/architecture/docx_mutation_api.md#deletesection
114
+ */
115
+ deleteSection(headingAnchorId) {
116
+ return JSON.parse(this.wasm.DeleteSection(this.handle, headingAnchorId));
117
+ }
118
+ // ─── Tier B: structural ──────────────────────────────────────────────
119
+ insertParagraph(anchorId, position, markdown) {
120
+ return JSON.parse(this.wasm.InsertParagraph(this.handle, anchorId, position, markdown));
121
+ }
122
+ splitParagraph(anchorId, characterOffset) {
123
+ return JSON.parse(this.wasm.SplitParagraph(this.handle, anchorId, characterOffset));
124
+ }
125
+ mergeParagraphs(firstAnchorId, secondAnchorId) {
126
+ return JSON.parse(this.wasm.MergeParagraphs(this.handle, firstAnchorId, secondAnchorId));
127
+ }
128
+ // ─── Tier C: formatting ──────────────────────────────────────────────
129
+ applyFormat(anchorId, span, op) {
130
+ const spanJson = span ? JSON.stringify(span) : "";
131
+ return JSON.parse(this.wasm.ApplyFormat(this.handle, anchorId, spanJson, JSON.stringify(op)));
132
+ }
133
+ /**
134
+ * Convenience: find `substring` in the anchor's flat text and apply `op` to the
135
+ * first occurrence. Eliminates the offset-arithmetic trap from #138 — caller passes
136
+ * the visible text they want formatted, the WASM-side resolves it to a CharSpan.
137
+ */
138
+ applyFormatBySubstring(anchorId, substring, op) {
139
+ return JSON.parse(
140
+ this.wasm.ApplyFormatBySubstring(this.handle, anchorId, substring, JSON.stringify(op))
141
+ );
142
+ }
143
+ /**
144
+ * Convenience: apply `op` to the exact span of a {@link TextMatch} (typically from
145
+ * {@link grep}). The match's `enclosingAnchor.id` + `span` address one specific
146
+ * occurrence even when several identical needles share the same block.
147
+ */
148
+ applyFormatToMatch(match, op) {
149
+ const span = { start: match.span.start, length: match.span.length };
150
+ return this.applyFormat(match.enclosingAnchor.id, span, op);
151
+ }
152
+ setParagraphStyle(anchorId, styleId) {
153
+ return JSON.parse(this.wasm.SetParagraphStyle(this.handle, anchorId, styleId));
154
+ }
155
+ setListLevel(anchorId, levelDelta) {
156
+ return JSON.parse(this.wasm.SetListLevel(this.handle, anchorId, levelDelta));
157
+ }
158
+ removeListMembership(anchorId) {
159
+ return JSON.parse(this.wasm.RemoveListMembership(this.handle, anchorId));
160
+ }
161
+ // ─── Tier D: cell content ────────────────────────────────────────────
162
+ replaceCellContent(cellAnchorId, markdown) {
163
+ return JSON.parse(this.wasm.ReplaceCellContent(this.handle, cellAnchorId, markdown));
164
+ }
165
+ // ─── Search ──────────────────────────────────────────────────────────
166
+ /**
167
+ * Searches the flat text of every paragraph/heading/list-item in scope for
168
+ * matches of `pattern`, returning them in document order with the run
169
+ * fragments each match spans. Lets callers rewrite a match in place while
170
+ * preserving each fragment's formatting (bold/italic/hyperlink/etc.).
171
+ *
172
+ * `pattern` is a regular expression — use plain string equivalents wrapped
173
+ * in `^` / `$` or pass literal text escaped via a helper.
174
+ *
175
+ * @see docs/architecture/docx_mutation_api.md#grep
176
+ */
177
+ grep(pattern, options) {
178
+ return JSON.parse(this.wasm.Grep(this.handle, pattern, options ? JSON.stringify(options) : ""));
179
+ }
180
+ /**
181
+ * Like {@link grep}, but lets a single match span adjacent block-level
182
+ * siblings (paragraphs/headings/list items) under the same parent. Block
183
+ * boundaries appear in the matched text as `\n`, so `^`/`$` with the
184
+ * Multiline flag anchor at boundaries and `.` won't cross unless Singleline
185
+ * is set.
186
+ *
187
+ * Matches never cross OOXML package parts, container boundaries (body →
188
+ * table cell), or non-paragraph siblings (a table between two paragraphs
189
+ * breaks the run). Returned superset of {@link grep}: single-block matches
190
+ * still appear with one slice. Filter `slices.length > 1` for cross-block only.
191
+ *
192
+ * @see docs/architecture/docx_mutation_api.md#grepcrossblock
193
+ */
194
+ grepCrossBlock(pattern, options) {
195
+ return JSON.parse(
196
+ this.wasm.GrepCrossBlock(this.handle, pattern, options ? JSON.stringify(options) : "")
197
+ );
198
+ }
199
+ /**
200
+ * Finds every literal occurrence of `find` in the anchor's flat text and
201
+ * replaces it with `replace`, preserving the surrounding run formatting that
202
+ * the match didn't touch. Returns one `EditResult` per attempted match.
203
+ *
204
+ * Run-formatting contract: the replacement text inherits the formatting of
205
+ * the FIRST run the match spanned. Middle/trailing runs keep their `w:rPr`
206
+ * but lose the slice of text the match consumed.
207
+ *
208
+ * @see docs/architecture/docx_mutation_api.md#replacetextrange
209
+ */
210
+ replaceTextRange(anchorId, find, replace, options) {
211
+ return JSON.parse(
212
+ this.wasm.ReplaceTextRange(this.handle, anchorId, find, replace, options ? JSON.stringify(options) : "")
213
+ );
214
+ }
215
+ /**
216
+ * Replaces a specific Grep match in place — addresses the exact span by
217
+ * `enclosingAnchor.id` + `span.{start,length}`, so identical needles in the
218
+ * same paragraph (the template-fill case where five `[___]` placeholders
219
+ * each get a different value) don't collide.
220
+ */
221
+ replaceMatch(match, replace) {
222
+ return JSON.parse(
223
+ this.wasm.ReplaceTextAtSpan(this.handle, match.enclosingAnchor.id, match.span.start, match.span.length, replace)
224
+ );
225
+ }
226
+ /**
227
+ * Helper for {@link fillPlaceholders} `coalesceWhitespaceAroundEmptyFill` path —
228
+ * mirrors the .NET `ReplaceMatchCoalescingNeighbors` rules. Inspects the chars
229
+ * immediately surrounding the match via `match.contextBefore` / `contextAfter`
230
+ * (so the option requires `contextChars >= 1`, the default) and expands the
231
+ * deletion span to absorb whitespace / leading-space-before-punctuation /
232
+ * matched-brackets where the patterns match. Falls back to literal-delete
233
+ * when no neighbor pattern applies.
234
+ *
235
+ * Note: with `boundary: ContextBoundary.Bracket`, neighbor brackets are not
236
+ * captured in context, so the bracket-coalesce rule won't fire on the JS side.
237
+ * The .NET implementation reads flat text directly and handles that case;
238
+ * callers who care should leave `boundary` at the default `Char`.
239
+ */
240
+ replaceMatchCoalescingNeighbors(match) {
241
+ const fold = (c) => {
242
+ if (c === "\xA0" || c === "\u202F" || c === "\u2009") return " ";
243
+ return c;
244
+ };
245
+ const l = fold(match.contextBefore.length > 0 ? match.contextBefore[match.contextBefore.length - 1] : void 0);
246
+ const r = fold(match.contextAfter.length > 0 ? match.contextAfter[0] : void 0);
247
+ const isSpace = (c) => c === " " || c === " ";
248
+ const isClauseTerm = (c) => c === "." || c === "," || c === ";" || c === ":" || c === "!" || c === "?";
249
+ const isOpen = (c) => c === "(" || c === "[" || c === "{";
250
+ const isClose = (c) => c === ")" || c === "]" || c === "}";
251
+ let extendLeft = 0;
252
+ let extendRight = 0;
253
+ if (isSpace(l) && isSpace(r)) {
254
+ extendRight = 1;
255
+ } else if (isSpace(l) && isClauseTerm(r)) {
256
+ extendLeft = 1;
257
+ } else if (isOpen(l) && isClose(r)) {
258
+ extendLeft = 1;
259
+ extendRight = 1;
260
+ }
261
+ if (extendLeft === 0 && extendRight === 0) {
262
+ return this.replaceMatch(match, "");
263
+ }
264
+ return JSON.parse(
265
+ this.wasm.ReplaceTextAtSpan(
266
+ this.handle,
267
+ match.enclosingAnchor.id,
268
+ match.span.start - extendLeft,
269
+ match.span.length + extendLeft + extendRight,
270
+ ""
271
+ )
272
+ );
273
+ }
274
+ /**
275
+ * Replace the bracketed portion of a `TextMatch` with `newInner`, preserving any
276
+ * prefix or suffix outside the brackets. Designed for `findPlaceholders` matches
277
+ * like `$[___]` where the regex `\$?\[…\]` captures a leading `$`:
278
+ * `replaceInner(match, "0.20")` yields `$0.20`, not `0.20`.
279
+ *
280
+ * Returns `MalformedMarkdown` if the match text does not contain balanced brackets.
281
+ */
282
+ replaceInner(match, newInner) {
283
+ return JSON.parse(this.wasm.ReplaceInner(
284
+ this.handle,
285
+ match.text,
286
+ match.enclosingAnchor.id,
287
+ match.span.start,
288
+ match.span.length,
289
+ newInner
290
+ ));
291
+ }
292
+ /**
293
+ * Picker-driven template fill. For every placeholder matching `options.kinds`,
294
+ * calls `picker`; if the picker returns a non-null string, the placeholder is
295
+ * replaced (with optional `$`-prefix preservation). Iterates until no more
296
+ * placeholders match (or `maxPasses` is reached, or a pass makes zero changes)
297
+ * — handles nested brackets that surface only after the inner ones are stripped.
298
+ *
299
+ * The TypeScript implementation mirrors the .NET `DocxSession.FillPlaceholders`
300
+ * exactly.
301
+ *
302
+ * The picker is invoked synchronously by this loop on the JS side (it does
303
+ * NOT run inside the WASM module). Async pickers are not supported: returning
304
+ * a `Promise` will cause a `TypeError` at runtime inside the `$`-prefix
305
+ * preservation branch (`Promise.startsWith is not a function`). For async
306
+ * data, pre-build a lookup map before calling and have the picker read from
307
+ * it synchronously.
308
+ */
309
+ fillPlaceholders(picker, options) {
310
+ const opts = options ?? {};
311
+ const kinds = opts.kinds ?? PlaceholderKinds.All;
312
+ const scope = opts.scope ?? 1;
313
+ const maxPasses = opts.maxPasses ?? 8;
314
+ const preserveDollarPrefix = opts.preserveDollarPrefix ?? true;
315
+ const contextChars = opts.contextChars ?? 80;
316
+ const boundary = opts.boundary ?? ContextBoundary.Char;
317
+ const coalesceEmpty = opts.coalesceWhitespaceAroundEmptyFill ?? false;
318
+ if (maxPasses <= 0) {
319
+ throw new RangeError("FillOptions.maxPasses must be > 0");
320
+ }
321
+ let filled = 0;
322
+ let workPasses = 0;
323
+ const errors = [];
324
+ const unfilled = [];
325
+ const seenSkipKeys = /* @__PURE__ */ new Set();
326
+ for (let pass = 1; pass <= maxPasses; pass++) {
327
+ const placeholders = this.findPlaceholders(kinds, scope, contextChars, boundary).sort((a, b) => {
328
+ const cmp = b.match.enclosingAnchor.id.localeCompare(a.match.enclosingAnchor.id);
329
+ if (cmp !== 0) return cmp;
330
+ return b.match.span.start - a.match.span.start;
331
+ });
332
+ if (placeholders.length === 0) break;
333
+ let passChanges = 0;
334
+ for (const p of placeholders) {
335
+ const pick = picker(p);
336
+ if (pick == null) {
337
+ const key = `${p.match.enclosingAnchor.id}:${p.match.span.start}:${p.match.span.length}`;
338
+ if (!seenSkipKeys.has(key)) {
339
+ seenSkipKeys.add(key);
340
+ unfilled.push(p);
341
+ }
342
+ continue;
343
+ }
344
+ let replacement = pick;
345
+ if (preserveDollarPrefix && p.match.text.startsWith("$") && !replacement.startsWith("$")) {
346
+ replacement = "$" + replacement;
347
+ }
348
+ const r = coalesceEmpty && replacement.length === 0 ? this.replaceMatchCoalescingNeighbors(p.match) : this.replaceMatch(p.match, replacement);
349
+ if (r.success) {
350
+ filled++;
351
+ passChanges++;
352
+ } else if (r.error) {
353
+ errors.push(r.error);
354
+ }
355
+ }
356
+ if (passChanges > 0) workPasses = pass;
357
+ if (passChanges === 0) break;
358
+ }
359
+ const stillPresent = this.findPlaceholders(kinds, scope).length;
360
+ return {
361
+ filled,
362
+ skipped: unfilled.length,
363
+ stillPresent,
364
+ passes: workPasses,
365
+ unfilled,
366
+ errors
367
+ };
368
+ }
369
+ /**
370
+ * Enumerate template placeholders in the document. Thin classifier over
371
+ * {@link grep}: distinguishes `[___]` value blanks (`blank_fill`),
372
+ * `[bracketed alternative clauses]` (`alternative_clause`), and
373
+ * `[insert X]` / `[*italic hint*]` instructions (`instruction`).
374
+ *
375
+ * Combine kinds with bitwise OR: `PlaceholderKinds.BlankFill | PlaceholderKinds.Instruction`.
376
+ * Default is `PlaceholderKinds.All`; default scope is body only (1).
377
+ *
378
+ * @see docs/architecture/docx_mutation_api.md#findplaceholders
379
+ */
380
+ findPlaceholders(kinds = PlaceholderKinds.All, scope = 1, contextChars = 80, boundary = ContextBoundary.Char) {
381
+ return JSON.parse(
382
+ this.wasm.FindPlaceholders(this.handle, kinds, scope, contextChars, boundary)
383
+ );
384
+ }
385
+ /**
386
+ * Returns a snapshot of edit-state introspection signals — placeholder counts,
387
+ * underscore-run leftovers, footnote/comment counts. Useful for "am I done?"
388
+ * verification at the end of an edit pipeline.
389
+ */
390
+ getEditSummary() {
391
+ return JSON.parse(this.wasm.GetEditSummary(this.handle));
392
+ }
393
+ /**
394
+ * Discoverability alias for {@link findPlaceholders}. Same return shape.
395
+ */
396
+ remainingPlaceholders(kinds = PlaceholderKinds.All) {
397
+ return JSON.parse(this.wasm.RemainingPlaceholders(this.handle, kinds));
398
+ }
399
+ getDiff(format = DiffFormat.Json) {
400
+ const raw = this.wasm.GetDiff(this.handle, format);
401
+ if (format === DiffFormat.Json) {
402
+ return JSON.parse(raw);
403
+ }
404
+ return raw;
405
+ }
406
+ // ─── Annotation-based anchor discovery (#132) ────────────────────────
407
+ /**
408
+ * Resolves an annotation's range to the block-level markdown anchors covering
409
+ * it, in document order. The bridge between Docxodus' read-side annotation API
410
+ * and the write-side session: an agent that wants to edit "the indemnification
411
+ * clause" looks the annotation up by id and gets the anchors it can hand to
412
+ * {@link replaceText} / {@link deleteBlock} / {@link raw}. Returns an empty
413
+ * list when the id is unknown or its bookmark is missing.
414
+ *
415
+ * v1 returns the enclosing block anchors — every paragraph/heading/list-item/
416
+ * cell/row/table whose subtree overlaps the bookmark range. Filter by
417
+ * `kind === "p" | "h" | "li"` when you want only text-bearing blocks.
418
+ *
419
+ * @see docs/architecture/docx_mutation_api.md#findbyannotation
420
+ */
421
+ findByAnnotation(annotationId) {
422
+ return JSON.parse(this.wasm.FindByAnnotation(this.handle, annotationId));
423
+ }
424
+ /**
425
+ * Finds every annotation whose `labelId` matches and resolves each of their
426
+ * ranges. The result is keyed by annotation id so callers can disambiguate
427
+ * when the same label is applied to multiple regions (three "WARRANTY"
428
+ * annotations on different paragraphs become three entries). Annotations
429
+ * whose bookmark resolves to no anchors are omitted from the result.
430
+ */
431
+ findByLabel(labelId) {
432
+ return JSON.parse(this.wasm.FindByLabel(this.handle, labelId));
433
+ }
434
+ /**
435
+ * Resolves any bookmark in the main document part (Docxodus-managed or
436
+ * user-authored) to the block-level anchors covering its range, in document
437
+ * order. Empty when the bookmark name is unknown. Use this for raw bookmark
438
+ * names that didn't come from the annotation system.
439
+ */
440
+ findByBookmark(bookmarkName) {
441
+ return JSON.parse(this.wasm.FindByBookmark(this.handle, bookmarkName));
442
+ }
443
+ // ─── Text/kind-based anchor discovery (#171) ─────────────────────────
444
+ /**
445
+ * True when `anchorId` resolves to a live element in the current session.
446
+ * Cheap existence probe — use it to guard an anchor obtained from an earlier
447
+ * projection before handing it to a mutation (anchors can be invalidated by
448
+ * intervening edits; see the anchor lifecycle table in the mutation docs).
449
+ */
450
+ exists(anchorId) {
451
+ return this.wasm.Exists(this.handle, anchorId);
452
+ }
453
+ /**
454
+ * Find the first block-level anchor (in document order) whose flat text
455
+ * contains `needle`, or `null` when nothing matches. `options` tune case /
456
+ * whitespace handling and narrow the search by kind or scope. For all
457
+ * matches use {@link findAllByText}.
458
+ */
459
+ findByText(needle, options) {
460
+ return JSON.parse(
461
+ this.wasm.FindByText(this.handle, needle, options ? JSON.stringify(options) : "")
462
+ );
463
+ }
464
+ /**
465
+ * Like {@link findByText} but returns every matching anchor in document
466
+ * order (empty when nothing matches).
467
+ */
468
+ findAllByText(needle, options) {
469
+ return JSON.parse(
470
+ this.wasm.FindAllByText(this.handle, needle, options ? JSON.stringify(options) : "")
471
+ );
472
+ }
473
+ /**
474
+ * Find every block-level anchor whose flat text matches the regular
475
+ * expression `pattern`, in document order. `regexOptions` uses the numeric
476
+ * layout of .NET `RegexOptions` (e.g. `1` = IgnoreCase); `options` is the
477
+ * same shape as {@link findByText} (its `ignoreCase` composes with the regex
478
+ * flag). Defaults to `regexOptions = 0` (none).
479
+ */
480
+ findByRegex(pattern, regexOptions = 0, options) {
481
+ return JSON.parse(
482
+ this.wasm.FindByRegex(this.handle, pattern, regexOptions, options ? JSON.stringify(options) : "")
483
+ );
484
+ }
485
+ /**
486
+ * Return every anchor of the given `kind` (`"p"`, `"h"`, `"li"`, `"tbl"`,
487
+ * `"row"`, `"cell"`, …), in document order. Reads the projection's anchor
488
+ * index directly — no text scan. Pass `scope` (e.g. `"body"`) to restrict to
489
+ * a single part; omit it to span all scopes.
490
+ */
491
+ findByKind(kind, scope) {
492
+ return JSON.parse(
493
+ this.wasm.FindByKind(this.handle, kind, scope ?? "")
494
+ );
495
+ }
496
+ /**
497
+ * Look up a single anchor's preview info — `{ id, kind, scope, textPreview }`.
498
+ * Returns null when the anchor id is unknown.
499
+ *
500
+ * For iterating many anchors at once, prefer reading `textPreview` directly
501
+ * off the {@link MarkdownProjection.anchorIndex} entries (cheaper — no extra
502
+ * WASM round trip), or use {@link getAnchorInfos} for batched lookups.
503
+ */
504
+ getAnchorInfo(anchorId) {
505
+ const raw = this.wasm.GetAnchorInfo(this.handle, anchorId);
506
+ return JSON.parse(raw);
507
+ }
508
+ /**
509
+ * Bulk variant of {@link getAnchorInfo}: takes an array of anchor ids,
510
+ * returns a record where each unknown id maps to `null`.
511
+ */
512
+ getAnchorInfos(anchorIds) {
513
+ const raw = this.wasm.GetAnchorInfos(this.handle, JSON.stringify(anchorIds));
514
+ return JSON.parse(raw);
515
+ }
516
+ /**
517
+ * Resolve block-level metadata (style id+name, outline level, list membership,
518
+ * formatting probe) for an anchor. Returns null when the anchor doesn't exist.
519
+ */
520
+ getBlockMetadata(anchorId) {
521
+ const raw = this.wasm.GetBlockMetadata(this.handle, anchorId);
522
+ return JSON.parse(raw);
523
+ }
524
+ /**
525
+ * Bulk variant of {@link getBlockMetadata}. Unknown ids map to null;
526
+ * duplicates are deduped.
527
+ */
528
+ getBlockMetadatas(anchorIds) {
529
+ const raw = this.wasm.GetBlockMetadatas(this.handle, JSON.stringify(anchorIds));
530
+ return JSON.parse(raw);
531
+ }
532
+ /**
533
+ * Resolve the numbering facts for a list-item paragraph; returns null when
534
+ * the anchor has no w:numPr.
535
+ */
536
+ getListMembership(anchorId) {
537
+ const raw = this.wasm.GetListMembership(this.handle, anchorId);
538
+ return JSON.parse(raw);
539
+ }
540
+ /**
541
+ * Resolve page-layout info for the w:sectPr that governs an anchor.
542
+ * Returns null for anchors outside the body part.
543
+ */
544
+ getSectionInfo(anchorId) {
545
+ const raw = this.wasm.GetSectionInfo(this.handle, anchorId);
546
+ return JSON.parse(raw);
547
+ }
548
+ /**
549
+ * Enumerates every annotation persisted in the document. Lets an agent prime
550
+ * itself with "here are the labeled regions you can target" before committing
551
+ * to a specific id.
552
+ */
553
+ listAnnotations() {
554
+ return JSON.parse(this.wasm.ListAnnotations(this.handle));
555
+ }
556
+ // ─── Annotation write surface ────────────────────────────────────────
557
+ /**
558
+ * Annotate a range inside `anchorId`. When `span` is `null`/`undefined`
559
+ * the annotation wraps every inline run of the block. When
560
+ * `annotation.id` is `undefined`, a 16-char hex id is auto-generated and
561
+ * returned in `EditResult.annotationId`.
562
+ */
563
+ addAnnotation(anchorId, span, annotation) {
564
+ const spanJson = span ? JSON.stringify(span) : "";
565
+ return JSON.parse(
566
+ this.wasm.AddAnnotation(this.handle, anchorId, spanJson, JSON.stringify(annotation))
567
+ );
568
+ }
569
+ removeAnnotation(annotationId) {
570
+ return JSON.parse(this.wasm.SessionRemoveAnnotation(this.handle, annotationId));
571
+ }
572
+ updateAnnotation(annotationId, update) {
573
+ return JSON.parse(
574
+ this.wasm.UpdateAnnotation(this.handle, annotationId, JSON.stringify(update))
575
+ );
576
+ }
577
+ moveAnnotation(annotationId, newAnchorId, newSpan) {
578
+ const spanJson = newSpan ? JSON.stringify(newSpan) : "";
579
+ return JSON.parse(
580
+ this.wasm.MoveAnnotation(this.handle, annotationId, newAnchorId, spanJson)
581
+ );
582
+ }
583
+ // ─── Lifecycle ───────────────────────────────────────────────────────
584
+ undo() {
585
+ return this.wasm.Undo(this.handle);
586
+ }
587
+ redo() {
588
+ return this.wasm.Redo(this.handle);
589
+ }
590
+ save() {
591
+ return this.wasm.Save(this.handle);
592
+ }
593
+ close() {
594
+ this.wasm.CloseSession(this.handle);
595
+ }
596
+ // TypeScript 5.2+ disposable protocol
597
+ [Symbol.dispose]() {
598
+ this.close();
599
+ }
600
+ };
601
+ function openDocxSession(bytes, wasmExports, settings) {
602
+ const bridge = wasmExports.DocxSessionBridge;
603
+ const handle = bridge.OpenSession(bytes, settings ? JSON.stringify(settings) : "");
604
+ return new DocxSession(handle, bridge);
605
+ }
606
+ return __toCommonJS(session_exports);
607
+ })();
package/dist/session.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AnchorInfo, AnchorTargetRef, AnnotationUpdate, BlockMetadata, BulkEditResult, CharSpan, CrossBlockMatch, DiffEntry, DocumentAnnotation, DocxodusWasmExports, DocxSessionProjection, DocxSessionSettings, EditResult, EditSummary, FillOptions, FormatOp, GrepOptions, ListMembership, ReplaceOptions, SectionInfo, TemplatePlaceholder, TextMatch } from "./types.js";
1
+ import type { AnchorInfo, AnchorTargetRef, AnnotationUpdate, BlockMetadata, BulkEditResult, CharSpan, CrossBlockMatch, DiffEntry, DocumentAnnotation, DocxodusWasmExports, DocxSessionProjection, DocxSessionSettings, EditResult, EditSummary, FillOptions, FindOptions, FormatOp, GrepOptions, ListMembership, ReplaceOptions, SectionInfo, TemplatePlaceholder, TextMatch } from "./types.js";
2
2
  import { DiffFormat, ProjectionDepth } from "./types.js";
3
3
  /**
4
4
  * Stateful in-memory DOCX editing session keyed by markdown-projection anchor ids.
@@ -235,6 +235,40 @@ export declare class DocxSession {
235
235
  * names that didn't come from the annotation system.
236
236
  */
237
237
  findByBookmark(bookmarkName: string): AnchorTargetRef[];
238
+ /**
239
+ * True when `anchorId` resolves to a live element in the current session.
240
+ * Cheap existence probe — use it to guard an anchor obtained from an earlier
241
+ * projection before handing it to a mutation (anchors can be invalidated by
242
+ * intervening edits; see the anchor lifecycle table in the mutation docs).
243
+ */
244
+ exists(anchorId: string): boolean;
245
+ /**
246
+ * Find the first block-level anchor (in document order) whose flat text
247
+ * contains `needle`, or `null` when nothing matches. `options` tune case /
248
+ * whitespace handling and narrow the search by kind or scope. For all
249
+ * matches use {@link findAllByText}.
250
+ */
251
+ findByText(needle: string, options?: FindOptions): AnchorTargetRef | null;
252
+ /**
253
+ * Like {@link findByText} but returns every matching anchor in document
254
+ * order (empty when nothing matches).
255
+ */
256
+ findAllByText(needle: string, options?: FindOptions): AnchorTargetRef[];
257
+ /**
258
+ * Find every block-level anchor whose flat text matches the regular
259
+ * expression `pattern`, in document order. `regexOptions` uses the numeric
260
+ * layout of .NET `RegexOptions` (e.g. `1` = IgnoreCase); `options` is the
261
+ * same shape as {@link findByText} (its `ignoreCase` composes with the regex
262
+ * flag). Defaults to `regexOptions = 0` (none).
263
+ */
264
+ findByRegex(pattern: string, regexOptions?: number, options?: FindOptions): AnchorTargetRef[];
265
+ /**
266
+ * Return every anchor of the given `kind` (`"p"`, `"h"`, `"li"`, `"tbl"`,
267
+ * `"row"`, `"cell"`, …), in document order. Reads the projection's anchor
268
+ * index directly — no text scan. Pass `scope` (e.g. `"body"`) to restrict to
269
+ * a single part; omit it to span all scopes.
270
+ */
271
+ findByKind(kind: string, scope?: string): AnchorTargetRef[];
238
272
  /**
239
273
  * Look up a single anchor's preview info — `{ id, kind, scope, textPreview }`.
240
274
  * Returns null when the anchor id is unknown.
@@ -297,6 +331,6 @@ export declare class DocxSession {
297
331
  * {@link DocxSession.close} (or it is disposed).
298
332
  */
299
333
  export declare function openDocxSession(bytes: Uint8Array, wasmExports: DocxodusWasmExports, settings?: DocxSessionSettings): DocxSession;
300
- export type { AnchorInfo, AnchorRef, AnchorTargetRef, BlockSlice, CharSpan, CrossBlockMatch, DocumentAnnotation, DocxSessionProjection, DocxSessionSettings, EditError, EditErrorCode, EditResult, FormatOp, GrepOptions, MarkdownPatch, PlaceholderKind, ReplaceOptions, RunFormatting, RunFragment, TemplatePlaceholder, TextMatch } from "./types.js";
334
+ export type { AnchorInfo, AnchorRef, AnchorTargetRef, BlockSlice, CharSpan, CrossBlockMatch, DocumentAnnotation, DocxSessionProjection, DocxSessionSettings, EditError, EditErrorCode, EditResult, FindOptions, FormatOp, GrepOptions, MarkdownPatch, PlaceholderKind, ReplaceOptions, RunFormatting, RunFragment, TemplatePlaceholder, TextMatch } from "./types.js";
301
335
  export { ContextBoundary, PlaceholderKinds } from "./types.js";
302
336
  //# sourceMappingURL=session.d.ts.map