feat(desktop): draft child-text selectors, member counts and attribute text, and fold in a third batch's findings (#9132)

* fix(desktop): follow a database mapping and own limitation text

A selected database keeps its log when a parent folder moves or the file
sits outside the home. Trash and seed-lock tests compare the owning notice
with the paths, and launch options that are not captured paths stay as written.

* test(desktop): pass the selected log into the draft

The export's selected home paths decide which log stays in the draft.
The line-guard test now names that log instead of relying on its reason.

* fix(desktop): retarget a settings folder that holds captured files

A nested profile directory is a captured path when a seeded file is inside
it. An option value that only resolves under the home stays as written.

* fix(desktop): keep a program word and a directory's neighbor

The program after env stays the program even when a captured file sits in a
folder of that name. A selected directory is not a database, so a neighboring
file keeps the parent folder's spelling.

* fix(desktop): record whether a selected path is a directory

Capture stores the walked path's kind. A neighboring file of a selected
directory keeps the parent folder's spelling even when that directory never
changes and its children are not content roots.

* fix(desktop): mark containing paths without a pairwise scan

A recorded path marks its known ancestors as directories in one walk up
the path, instead of comparing every recorded path with every other.

* fix(desktop): keep a selected folder that is named like a database log

A folder the caller selected stays a selected root when its name ends in
-journal or -wal. A generated log beside a database file still does not.

* fix(desktop): refuse a build command that exceeds the argument vector

Splitting one argument still leaves the whole command under Linux's E2BIG
limit. A request past that budget is refused before the process starts.

* fix(desktop): remap a captured path in an env assignment

The program word stays the program. A NAME=value assignment keeps its name
and follows a captured path value when that path's spelling moves.

* fix(desktop): keep oversized text out of draft guards

A value or line longer than the draft's text bound is not copied into a
guard, so one large frame cannot fill the task by itself.

* docs(desktop): correct dconf and check-preview guidance

A dconf version kept without its bytes is unreadable, not an empty key
list. A values preview is copied into a check only when it is an uncut scalar.

* fix(desktop): keep an empty env value empty

An empty assignment is not a path. Resolving it named the working directory
and rewrote the value when that directory's spelling moved.

* fix(desktop): keep a run's font on the run, not the frame's text

A formatting attribute such as Scribus FONT is not the document's words.
Joining it across runs made a frame-wide text check of ItalicBold that
failed when a run was split. The font stays a value check on its own run.

* fix(desktop): do not pair JSON records by a selector-shaped field

A field named @record_id matched the id suffix and became [@record_id=one],
which reads an XML attribute. Records paired while their pointers matched
nothing. Names that start with @ or > are not id fields.

* fix(desktop): count a save-numbered id once when pairing members

xml:id and draw:id values such as id123456 were both generated and
numbered, so the same selector was counted twice and refused. A text
edit of two elements keyed only by those ids now keeps its check.

* fix(desktop): preserve selected state directory aliases

* fix(desktop): align nested state selections with aliases

* fix(desktop): check build runtime export capability

* fix(desktop): provide complete runtime repack command

* fix(desktop): retain runtime probe failures

* test(desktop): identify capture independently of schema preflight

* fix(desktop): preserve document URLs and value formats

* fix(desktop): bound added checks and omit noisy text guards

* fix(desktop): exclude unseeded locks from task checks

* fix(desktop): preserve draft bounds and launch URLs

* fix(desktop): render draft values using their source format

* fix(desktop): preserve launch URLs and JSON draft values

* fix(desktop): recognize captured file URL documents

* fix(desktop): render captured file URLs for runtime home

* fix(desktop): distinguish phone numbers from save metadata

* fix(desktop): preserve launch URLs and user text

* fix(desktop): preserve captured URLs and user text

* fix(desktop): preserve local file URL authority

* fix(desktop): preserve local file URL authority

* fix(desktop): preserve local file URL authority

* fix(desktop): render captured file URLs at launch

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): classify numeric timestamps using field context

* fix(desktop): retain context for generated draft values

* fix(desktop): retain context for generated draft values

* fix(desktop): retain context for generated draft values

* test(desktop): cover generated IDs in text guards

* test(desktop): cover generated IDs in text guards

* test(desktop): cover generated IDs in text guards

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): isolate launcher URL encoding

* fix(desktop): retain clean text in noisy record fields

* fix(desktop): classify added line values in one pass

* fix(desktop): apply XML quote rules to text drafts

* fix(desktop): distinguish XML attributes from quoted text

* fix(desktop): preserve parsed XML line context

* fix(desktop): retain partial XML syntax facts

* fix(desktop): recognize markdown autolinks in drafts

* fix(desktop): reuse export exclusions in task drafts

* docs(desktop): clarify gzip scrub limits

* style(desktop): format the noisy-record draft files with the pinned oxfmt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(desktop): move launch execution to boundary suite

* fix(desktop): redact build schema failure output

* refactor(desktop): normalize schema failure once

* fix(desktop): omit unsafe schema parser snippets

* fix(desktop): preserve draft change and selected path evidence

* test(desktop): group retained dconf note regressions

* fix(desktop): respect archive entry format in draft checks

* test(desktop): separate unowned-file draft note cases

* fix(desktop): preserve explicitly selected journal documents

* fix(xml): avoid scanning selected ancestors per tag

* fix(desktop): exclude covered text runs from draft counts

* fix: preserve text when drafting desktop checks

* fix: restore nested desktop state aliases

* refactor: share UUID recognition across draft checks

* fix: retain multiline XML attribute context

* fix: retain relationship identifiers in task drafts

* docs: clarify desktop draft identifier handling

* test(desktop): type formatting run cases as pairs

* test(desktop): separate markup boundary regression group

* docs(desktop): clarify task checks before scratch export

* fix(desktop): respell selected paths in file URLs

* test(desktop): group captured document spelling cases

* fix(desktop): bound draft preview serialization

* fix(desktop): restore selected state aliases

* fix(desktop): respect entry format in draft noise

* test(desktop): match exported alias evidence at its JSON boundary

* fix(desktop): retain app state logs in exported seeds

* fix: align desktop numeric seed comparisons

* test(desktop): keep one draft exclusion fixture import

* test(desktop): retain log eligibility across draft test groups

* style: fix desktop launch test formatting

* style: format native command path schema

* fix(desktop): map selected external launch paths

* style(desktop): format seed document regressions

* test(desktop): group launch URL regressions

* fix(desktop): omit redundant nested state aliases

* fix(desktop): compare added free text as a whole

* fix(desktop): check recompressed seeds as shipped

* docs(desktop): clarify recovered seed format

* test(desktop): group shipped gzip seed checks

* fix: retain quoted identifier text in task drafts

* fix: recognize Unicode XML in desktop state readers

* fix(desktop): bound nested draft checks

* fix(desktop): explain missing arrays in truncated views

* fix(desktop): find XML type references in archives

* test(desktop): remove duplicated capture assertions

* fix(desktop): retain nested omitted text boundaries

* style(desktop): format draft value imports

* test(desktop): group model and draft value checks

* fix(desktop): map captured launch paths once

* refactor: remove unused whole-text guard state

* refactor: stop passing unused text children

* test: align free-text checks with whole-note policy

* fix: validate recompressed desktop archive seeds

* style(desktop): format archive seed regression

* fix(desktop): retain placed-item sibling guards

* fix(desktop): redact runtime schema errors

* fix(desktop): normalize captured file URLs

* fix(desktop): report seeded files by capture path

* fix(desktop): retain startup readiness failure stage

* fix(desktop): retain JSON date checks

* fix(desktop): preserve archive formatting checks

* fix(desktop): preserve explicitly selected journal files

* fix(desktop): report build command transport limits

* docs(desktop): clarify unreadable dconf versions

* style(desktop): format capture review fixes

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-09 22:56:44 +08:00
1 parent 0dcd0dfc20
commit 012861ce1d
76 files changed
+8810 -1329

No files matched your search

@@ -183,6 +183,19 @@ the first source that has the app:
only at a clean exit. It writes `<map>.vym.lock` while a map is open, so
close the map before `seed`. Press A only after clicking a branch on the
canvas: keys typed in the tree editor run other shortcuts.
- KmPlot: Create → Cartesian Plot, then edit the formula in the Function
tab and press Return. It stores minus as U+2212 (`−`). Its file:// title
still names the file.
- RedNotebook keeps each month in `~/.rednotebook/data/YYYY-MM.txt`, YAML
read as text, folded at about column 80: pick check phrases the fold keeps
on one line.
- Qt5 apps saving with QDom, such as KmPlot, write attributes in a random
order in each process, so check their XML by element, never by whole line.
- Parley's title shows the collection's title, so name the file in
`state_paths`. A new collection starts with 15 blank entries. While a
document is open KDE keeps an autosave and its `.lock` in
`~/.local/share/stalefiles/parley/`, and there is no File → Close: before
`seed`, use File → New, then reopen the collection from Open Recent.
- Sigil unpacks the open book into
`.local/share/sigil-ebook/sigil/workspace/Sigil-XXXXXX/` and deletes it on
exit; naming the whole `sigil-ebook` folder seeds that stale copy, so name
@@ -197,6 +210,23 @@ the first source that has the app:
- Dismiss first-run dialogs, such as a welcome screen, before `seed`. A
choice the app saves only later, such as Inkscape's "show this every
time", may not reach the seed, so expect the dialog in the witness too.
- Some apps write their settings late: Freeplane writes
`~/.config/freeplane/1.7.x/auto.properties` only once Preferences is
confirmed, and a seed without it reopens its documentation map. Before
`seed`, open the app's preferences and confirm them, then read a probe
checkpoint's `changed_files` to see the settings file written.
- Before `seed`, click into the document to clear any selection the app
would save: Gnote saves its cursor and selection with the note.
- An app whose state folder is named after it, such as
`~/.local/share/gnote`, or after it and its version, such as TreeLine's
`~/.treeline-3.1`, is found without `state_paths`.
- TreeLine: Ctrl+A adds a child node even while a field has focus. Clicking
a node already selected starts an inline rename, so Ctrl+X then cuts its
text: cut a node from its context menu. It saves nodes sorted by their
generated uid1, so their order changes from run to run.
- After an app crashes, capture again on a fresh computer, so the seed
carries no crash-recovery state, such as MyPaint's "Recover interrupted
work?".
- Give what the task changes a stable name where the app has one, such as an
id in Inkscape's Object Properties, so a check can select it.
- Expect apps to split text into runs: Writer's revision ids split an
@@ -204,6 +234,13 @@ the first source that has the app:
`P1`, and AbiWord wraps each insertion in `<c>`. Check such text whole
with `text_equals` (see Write the task), and find the paragraph by
something the edit keeps, such as AbiWord's `xid`.
- Freeplane's first launch opens a documentation map: close it with Ctrl+W.
Its Ctrl+N asks for a template.
- MyPaint 2.0.1 crashes on brush strokes on the build computer: build its
seed with flood fill and layer operations.
- GnuCash's Ctrl+S on a new book opens a Save dialog with no format choice:
use File > Save As to pick XML. Close the book (File > New File) before
`seed`, so its `.LCK` lock is not seeded.
## Build the seed and the edit
@@ -257,7 +294,8 @@ the first source that has the app:
- The app's own compressed format works when it is gzip, such as
Gnumeric's `.gnumeric`, Dia's `.dia` or Inkscape's `.svgz`: REA reads
the document inside, and checks point into it as into the same
document uncompressed. A format REA reads as binary, such as one
document uncompressed. Compression may be off by default: Dia's
"Compress diagram files" is unticked, which REA reads as plain XML. A format REA reads as binary, such as one
compressed with xz, has no view: save in a format the app offers that
REA reads, then reopen the file once and check that a plain Ctrl+S
keeps that format.
@@ -331,11 +369,15 @@ Write `{"name", "prompt", "checks"}` from the draft and what you did.
`text_equals` or `text_contains`.
Only XML files, archives, JSON and key files have values: a text file's
or SQLite database's `change` already lists its lines and rows.
`refers_to` says what a number stands for, such as `category="44"`
naming `<cat key="44" name="Groceries"/>`; use it for the prompt's words.
`refers_to` says what a number or id stands for, such as `category="44"`
naming `<cat key="44" name="Groceries"/>`, or a new KMyMoney
transaction's splits naming their account and payee; use it for the
prompt's words. `alternatives` gives a changed value's pointer by the
element's other names, such as a label beside an id, to pick another key
without another export.
Skip entries whose `note` is `by_position` (no check can use that
pointer) or noise (`view_state`, `renumbered`, `volatile`,
`timestamp`, `upkeep`). `values_cut` means a limit left some out.
`timestamp`, `upkeep`, `layout`). `values_cut` means a limit left some out.
- Select elements by what they hold, never by position: SVG text by id,
`/root/children/[name=g][@inkscape:label=Layer 1]/children/[name=text][@id=headline]/children/[name=tspan]/children/0`,
or an ODF paragraph by style,
@@ -358,8 +400,10 @@ Write `{"name", "prompt", "checks"}` from the draft and what you did.
unchanged element is in `draft.guards` when it is a like sibling of a
changed one, and otherwise use the app's usual numbering, such as another
paragraph's `xid`, and let the export confirm it.
- In an ODS spreadsheet no attribute names a row or a cell. Name the sheet
in the seed, and check its whole text: `text_equals` on
- In an ODS spreadsheet no attribute names a row: the draft names it by its
label cell, `[name=table:table-row][>table:table-cell=February]`. Where no
cell names it alone, name the sheet in the seed, and check its whole
text: `text_equals` on
`/entries/[name=content.xml]/view/root/children/[name=office:body]/children/[name=office:spreadsheet]/children/[name=table:table][@table:name=Q1 Sales]`,
or a stretch of it with `text_contains`. Cell texts join with nothing
between, so a row reads `February23100`.
@@ -367,6 +411,9 @@ Write `{"name", "prompt", "checks"}` from the draft and what you did.
draft compares the whole text with `text_equals`. This rejects longer or
negated items, but can reject a correct edit with different ordering or
spacing. Report that limitation when the task permits such variations.
- For a note placed by its own `x` and `y`, such as Xournal++'s `<text>`
on a layer, the draft checks its text on the layer with `text_contains`,
which passes wherever the user puts it, and guards each note it kept.
- Some apps keep text in an attribute, one element per run, such as
Scribus's `<ITEXT CH=...>`: add `"text_attribute": "CH"` to `text_equals`
or `text_contains` on the frame,
+23 -7
View File
@@ -190,16 +190,32 @@ def start(arguments: dict) -> int:
argv += ["--package-file", arguments["package_file"]]
# Reading and writing, so the capture never reads the end of its input between requests.
reader = os.open(control, os.O_RDWR)
process = None
try:
with open(os.path.join(capture, "capture.out"), "wb") as out, \
open(os.path.join(capture, "progress.log"), "wb") as progress:
process = subprocess.Popen(
["sh", "-c", 'done=$1; shift; "$@"; code=$?; printf "%s" "$code" > "$done.tmp" && mv "$done.tmp" "$done"',
"sh", os.path.join(capture, "exit"), *argv],
cwd=os.path.expanduser("~"), env=_environment(work), stdin=reader, stdout=out, stderr=progress,
start_new_session=True)
try:
with open(os.path.join(capture, "capture.out"), "wb") as out, \
open(os.path.join(capture, "progress.log"), "wb") as progress:
process = subprocess.Popen(
["sh", "-c", 'done=$1; shift; "$@"; code=$?; printf "%s" "$code" > "$done.tmp" && mv "$done.tmp" "$done"',
"sh", os.path.join(capture, "exit"), *argv],
cwd=os.path.expanduser("~"), env=_environment(work), stdin=reader, stdout=out, stderr=progress,
start_new_session=True)
except Exception as cause:
# Nothing will write exit. Record one and drop the FIFO, so stop does not wait on it.
try:
with open(os.path.join(capture, "exit"), "w", encoding="utf-8") as handle:
handle.write("1")
except OSError:
pass
try:
os.unlink(control)
except OSError:
pass
return _say({"error": f"the capture did not start: {cause}"})
finally:
os.close(reader)
if process is None:
return _say({"error": "the capture did not start"})
waited = _wait(capture, 0, {"window_open"}, None, arguments.get("timeout_s", 120))
return _say({"pid": process.pid, "apt": apt, **waited})
+4 -1
View File
@@ -328,7 +328,10 @@ dot-folder named after the package, the executable, the desktop entry's full
id and its last part, and the entry's name, with whether each existed at the
start. A folder in those places whose name is one of these in another letter
case joins them, such as GIMP's `~/.config/GIMP` for the `gimp` package; only
the whole name is compared, so `~/.config/GIMPshop` does not. Dotfiles in the
the whole name is compared, so `~/.config/GIMPshop` does not. A file under a
folder the application creates during the capture beside one of them, with
the same name in another letter case or with a version added (`-3.1` or
`3`), as TreeLine's `~/.treeline-3.1`, is its state too. Dotfiles in the
home named after the application (`.<name>rc`, or
`.<name>` followed by `-`, `.` or `_`, for a name of three or more characters)
that exist at the start join them, since an application may only read such a
+6 -3
View File
@@ -160,7 +160,8 @@ The class declares:
README and the result's limitations say the sandbox is off.
- `paths`: the state directories holding the application's state files and the
folders holding its documents, nested folders collapsed. A folder beside a
state directory whose name differs from it only in letter case is owned
state directory whose name differs from it only in letter case, or that
adds a version, as TreeLine's `~/.treeline-3.1` beside `~/.treeline`, is owned
whole in the files' spelling, so a `~/.config/GIMP` profile GIMP created
during the capture beside the candidate `~/.config/gimp` is owned as
`.config/GIMP`, not as the folder of its first file. The home itself and
@@ -355,8 +356,10 @@ export removes them from what the bundle ships:
example and template files an app copies on first run do not bury the
document scrubbed; one already in that form ships as captured. The class copies it at
boot as it is, so the home it holds stays `/home/user`. One that does not
decompress ships as captured, its bytes searched, and one the state view did
not read is only searched. One whose document needs no edit but a member of
decompress within the scrub limit ships as captured, its bytes searched.
A document the state view did not read can still be decompressed and
recompressed under the separate 256 MiB scrub limit; its content is searched
even when its format cannot be scrubbed. One whose document needs no edit but a member of
which has an extra field, where BGZF (`.vcf.gz`, `.bam`) and dictzip
(`.dict.dz`) files index their blocks, also ships as captured, its bytes
searched, so its blocks stay where its index says; one whose document
+8 -1
View File
@@ -85,7 +85,7 @@ whether the file was present, the SHA-256 of its retained bytes, and a view:
| `dconf` | The `GVariant` header | Groups whose path names the application, plus the names of the other groups |
| `zip` | A zip local file header, `PK\x03\x04`, whatever the name | Its file entries in archive order, each with its own format and view |
| `json` | A `.json` name or a leading `{` or `[` that parses | The parsed value, from files up to 4 MiB nested up to 500 levels |
| `xml` | An XML name or declaration that parses | An element tree (`name`, `attributes`, `children`); text kept exactly, DTDs never read |
| `xml` | An XML name, a declaration or a leading element that parses | An element tree (`name`, `attributes`, `children`); text kept exactly, DTDs never read |
| `keyfile` | Only `[group]`, `key=value` and comment lines, with at least one group | Groups of `key` → string value, from files up to 4 MiB |
| `text` | Other UTF-8 text | Lines, up to 5,000 |
| `binary` | NUL bytes or invalid UTF-8 | None |
@@ -93,6 +93,13 @@ whether the file was present, the SHA-256 of its retained bytes, and a view:
A gzip file is read as the document inside it; see
[compressed documents](#compressed-documents).
Text that opens with an element, such as a Freeplane map's
`<map version="freeplane 1.7.0">` with no declaration, or with a DOCTYPE that
has no internal subset and then an element, such as a KmPlot plot's
`<!DOCTYPE kmpdoc>` before `<kmpdoc version="4">`, is XML when the whole text
is well formed, whatever the file is called, a `.txt` file included;
otherwise it stays text. The exported verifier makes the same choice.
A JSON value holding a number JavaScript would round, such as an integer above
2^53, is not read rather than shown rounded.
+305 -61
View File
@@ -58,12 +58,34 @@ operation `describe_desktop_application_task` and predicate type
JSON file's members or a key file's keys, each whole once. A value only
position reaches has `note: "by_position"`, and its pointer cannot go into a
check; noise an app writes as it saves has `view_state`, `renumbered`,
`volatile`, `timestamp` or `upkeep` (see `task`). `refers_to` names up to
three other elements a value equals the `key` or `id` of, with the
`volatile`, `timestamp`, `upkeep` or `layout` (see `task`). A record of
text fields added to a list of its kind, as GnuCash's
`<gnc:transaction>`, is listed field by field, and a field that lists
records, as its `<trn:splits>`, record by record, so the cut never hides
one. `refers_to` names up to
five other elements a value equals the `key` or `id` (`xmi:id` among them)
of, outside a view the app keeps of the document, as Umbrello's
`listview` mirroring its model by id, with the
`attribute` holding it, as HomeBank's `category="44"` names
`<cat key="44" name="Groceries"/>`; where several elements share that key,
the one whose tag shares the attribute's stem, as `payee` and `<pay>`. What a check can
name comes first, then what only position reaches, then noise. A file lists
`<cat key="44" name="Groceries"/>`, or the id a child element holds, as a
GnuCash split's `<split:account>` names the account whose `<act:id>` it
is, shown with its name, `<gnc:account …><act:name>Groceries</act:name>…`;
an element added whole lists those of the records of attributes it nests
too, as a KMyMoney transaction's splits name their `<ACCOUNT>` and
`<PAYEE>`, each once. Where several elements share that key, the one
whose tag shares the attribute's stem, as `payee` and `<pay>`, and of
those the one named for the attribute, as `account` an `<ACCOUNT>` before
an `<ACCOUNTID>`. A plain number names an element only through an
attribute so named or ending in `id`, `ref` or `key`, so a list's
`count="5"` names no `<FIXVERSION id="5"/>`. A value that changed lists,
in `alternatives`, its pointer naming the element by each other identifier
or name-like attribute it holds alone among its tag's members, up to
three, as an Inkscape text's `[@inkscape:label=Headline]` beside its
`[@id=text12]`, for a check to name it by instead; an element its tag
alone names inside the first one a condition names, as an EPUB chapter's
`h1`, by its `[@id=chapter-two]`. What a check can
name comes first, text an edit changed before the rest, so no cut drops
the edit, then what only position reaches, then noise. A file lists
at most 20 values and 8 KB, the draft 24 KB, and `values_cut` says when a
limit left some out. Values cover XML, archives, JSON and key files; a text
or SQLite file's change and suggestions already carry its lines and rows.
@@ -74,8 +96,31 @@ operation `describe_desktop_application_task` and predicate type
in `.log` remain eligible for checks.
A text file gains `lines_present` for its new lines and `lines_absent` for
lines it lost (when either is at most ten), and `line_count` for each line
holding a letter whose count changed; JSON and key files gain
`value_equals` and `value_absent` by pointer; SQLite tables gain rows added,
holding a letter whose count changed; a new line holding a value REA
recognizes as generated, such as a named epoch time or `ID_329023692`, gets a
`line_count` of the lines `contains` its text up to that value, as
`<node TEXT="Water filter" ID="`, at the end's number, where both views
hold the whole file, instead of a `lines_present` another save would
fail, or a `volatile_lines` note when no text comes before it. UUID-shaped
text stays exact because its shape alone does not show that it was generated;
JSON and key files gain
`value_equals` and `value_absent` by pointer, a JSON array's records named
by an id field each holds alone at both ends (`id`, `uid`, `uuid`, `guid`,
`key` or a name ending in `_id` or `Id`), as TreeLine's
`/nodes/[uid=7584d494d9f511f1a873edd4f1920549]`, whatever order the app
saves them in, and by position only where nothing names a record, as a
new record whose only id the app generated, with a `by_position` note
listing those checks; never a value that is a uid the app generates (a
GUID, or 32 hex digits as TreeLine's uuid1), nor a check the seed already
passes, as a new record's `format` where another record of that kind held
its place; a removed record is checked gone by its own pointer, as
`/lists/[id=chores]`, and only where the end holds nothing there, so a
record only position reached, whose place another took, is left to the
count; `member_count` checks of the
arrays whose members were added or removed, of the members' kind where
records share a `type`, `kind`, `format` or `category` field, as `/nodes`
matching `[format=BOOK]`, and a count guard of the innermost array an edit
went through, as for XML; SQLite tables gain rows added,
changed and removed, by primary key, and their new row count. An XML file,
and the JSON, key file and XML views of a zip archive's entries, gain checks
by [selectors](#pointers-and-selectors) and never through an element by
@@ -87,19 +132,62 @@ operation `describe_desktop_application_task` and predicate type
`id`, `xid`, `xml:id`), then by one other attribute, a name-like key such
as Scribus's `ANNAME` or `inkscape:label`, a worded value or an integer of
up to five digits first, then by two such attributes together, as
Gnumeric's cells by `[@Col=3][@Row=2]`, and last by a coordinate, a long
number or a token, such as `XPOS` or `ItemID`, or an attribute naming
view state, such as which layer is `selected`. A pair counts every
member holding both its values, whichever attributes that member ranks
first. An element with identifiers is named by those alone. The selector
must name the member alone at both ends, with the same values. An
element whose one identifier changed, at its place among its tag's
members, with every other attribute and its children alike, is that
element renamed, as a MyPaint layer renamed from `Untitled` to `Sun`: it
is named by its first other attribute naming it alone at both ends, as
`[@src=data/layer-00.png]`, so the rename reads as its `name` changed,
and the old name gets a check that it names nothing, unless its change
is noise, as an id the app renumbered.
Gnumeric's cells by `[@Col=3][@Row=2]`, then by a coordinate, a long
number, a length with its unit, as `svg:height="2.629cm"`, an `xml:id`
or `draw:id` of the form `id2` that LibreOffice numbers anew as it saves,
so a Draw shape is named by its `draw:name`, or a token,
such as `XPOS` or `ItemID`, or an id of random case, as Umbrello's
`ubcgF2AWfBmHh` (`u` and twelve letters and digits), an automatic style name an app numbers as it
saves and renumbers on reload, as LibreOffice's
`presentation:style-name="pr1"` (`P1`, `T1`, `MT1`, `L2` on a
`*:style-name`), so a slide's frames are named by `presentation:class`,
or an attribute naming
view state, such as which layer is `selected`, and last by a child
element's text, `[>CHILD=VALUE]`, a name-like tag first, as Osmo's
record by `[>first_name=Delphine]`, MuseScore's `<Text>` by
`[>style=Title]`, a spreadsheet row by its label cell, or GnuCash's
transaction by `[>trn:description=Greenleaf Market]`: text of at most 64
characters, never a time or a token or id a program generates. A pair
counts every member holding both its values, whichever attributes that
member ranks first. An element with identifiers is named by those alone;
an id the app generates, as Freeplane's `ID_329023692`, or a GUID in
any attribute, braced or not, as VYM's `uuid="{18eadb5d-…}"`, ranks
last, after a child's text, so a new node is named by its `TEXT` and a
new VYM branch by `[>heading=Sunset boat tour]`, while a member
both versions hold pairs by such an id first, so records that keep their
UUIDs and swap titles read as two title edits. A value that stands for
none, as Grisbi's `Id="(null)"` on every transaction, names nothing, so a
new transaction is named by its `Nb`. A child's text is
counted on every sibling, one an identifier names included, so a title
two records share names neither. The selector must name the
member alone at both ends, with the same values; a child's text names a
member that is in one version only when the list's length changed, so a
row whose one cell an edit changed stays that row. An element whose one
identifier changed, at its place among its tag's members, with every
other attribute and its children alike, is that element renamed, as a
MyPaint layer renamed from `Layer` to `Sun`: it is paired by its first
other attribute naming it alone at both ends, as
`[@src=data/sun.png]`, so the rename reads as its `name` changed, and
the old name gets a check that it names nothing, unless its change is
noise, as an id the app renumbered. Where that attribute's values number
the members in document order, as MyPaint 2 writes `src` as
`data/layer-00.png`, `data/layer-01.png` and on along the stack and
renumbers them when a layer moves, each version is named by its own
value of the renamed identifier instead, `[@name=Sun]` and
`[@name=Layer]`.
- A child of the document's root that its tag alone names, and that holds
a list (two or more elements of one tag and no text of its own) and has
an identifier, also gets a condition that keeps it named if the app adds
a sibling of its tag, as Dia adds an empty `Background` layer each time
it reopens and saves a diagram: an id other than `name` both ends hold,
as Inkscape's `[name=g][@id=layer1]`, which a new sibling would not
share; else the text of a child both ends hold, as Dia's
`[name=dia:layer][>dia:object=#Receive order#]`, which an empty sibling
lacks; else its `name`, which a new one may repeat. Deeper, a member of
a list named for its tag, as Gnumeric's `gnm:Sheet` in `gnm:Sheets`,
holding elements and its tag alone naming it, gets an id, else a
name-like child's text, `[name=gnm:Sheet][>gnm:Name=Budget]`, else its
`name`. Other steps, and elements with neither, stay as they are.
An identifier the app numbers by position names nothing: where the
members of a tag hold it as 1..N (or 0..N-1) in document order at both
ends, members were inserted or removed, and every member another
@@ -107,11 +195,28 @@ operation `describe_desktop_application_task` and predicate type
the count did, one at least, as Planner's task `id` after a task is
inserted, members are paired by their other attributes, so an insertion
reads as one task added. A value two members swap, or an id appended at
the end, as Tellico's next `<entry id="4">`, leaves the ids identity.
the end, as Tellico's next `<entry id="4">`, leaves the ids identity. An
identifier numbering the members 0..N-1 in document order at both ends,
where members came or went, as Parley numbers its `<entry id="6">` by
where it saves it, ranks after a child's text where a member has one, so
a new entry is `[>translation=library]` and its kept neighbours are named
alike; Tellico's ids, which count from 1, Tiled's and Rosegarden's,
whose members hold no text, stay identity. An element a change added that
holds nothing but the id of a record it added elsewhere, as Parley's
lesson membership `<entry id="6"/>`, is `upkeep`, listed with `refers_to`
on that record, never a check or a count.
- The text check names the paragraph rather than a run inside it: it goes up
from an element sitting in its parent's text, and from one named by its
tag or position alone to the nearest ancestor named by an attribute, as
AbiWord's `p` by its `xid`; where no attribute names one, to the nearest
AbiWord's `p` by its `xid`, unless it is a field its tag names in a
record of two or more fields holding text, as QElectroTech's `<text>`
beside `<info_name>` in a `<dynamic_elmt_text>`, or KmPlot's
`<equation-0>` beside `<arg-min>`, which is checked itself rather than
the record whose text joins its fields; one line of text the app lays
out between line breaks, as KmPlot's formula before the next element, is
checked, and its siblings guarded, with `normalize_whitespace: true`,
and text whose whitespace alone changed, as a formula the app moved to
an indented line of its own, gets no check; where no attribute names one, to the nearest
ancestor within three levels its tag names with no step by position, as
MuseScore's `VBox` around untitled `<Text>` elements; and where only
position reaches the element, to the ancestor above the outermost step by
@@ -124,7 +229,19 @@ operation `describe_desktop_application_task` and predicate type
number instead. Free text that gains a line, such as a shopping list,
uses `text_equals` on the whole text: the current XML checks cannot
compare an unstructured line as a whole item. This can reject a correct
edit that puts the item elsewhere or changes spacing. A record added
edit that puts the item elsewhere or changes spacing. Text an app keeps in an attribute, one element per run, as Scribus's
`<StoryText><ITEXT CH="Spring "/><ITEXT CH="Fair"/>`, gets a `text_equals`
with `text_attribute` on the nearest ancestor an attribute names, as
`[name=PAGEOBJECT][@ANNAME=Headline]` with `"text_attribute": "CH"`, where
that ancestor holds no text nodes and the attribute's holders are runs,
none inside another and none carrying an identifier or a name-like
attribute beside it, as Umbrello's `<ownedAttribute xmi:id="…"
name="email" visibility="private"/>`, a record whose attributes are
checked one by one, two or more or one holding words with a space: an
element's own attribute, as a Freeplane node's `TEXT` beside the nodes in
it, or a lone value, as `<Bool value="false"/>`, is checked where it is.
The check covers that attribute and the runs holding it; another change
in the frame, as a run's `FONT`, keeps its own check. A record added
or removed whole, an element holding only elements, its fields, such as
Tellico's `<entry>` or a record of repeated `<field>` elements, never
makes the list holding records of its kind a check, whose text would hold
@@ -132,49 +249,136 @@ operation `describe_desktop_application_task` and predicate type
position names, whose absence only the list's text shows. Text made of
runs is no record: an element whose tag names a paragraph or a piece of
text (`p`, Writer's `text:p` and `text:h`, `h1` to `h6`, `li`, `para`,
SVG's `text` and `tspan`, a `span` or an `a`), or whose runs split a
sentence at a space, as `Meet ` and a linked `Monday`. Nor does an
element holding a date the app stamps in parts take a text check.
SVG's `text` and `tspan`, a `span` or an `a`), one inside such an
element, as Word's `<w:r>` run in its `<w:p>`, one whose elements are all
inline formatting (`b`, `i`, `u`, `em`, `strong`, `bold`, `italic`, a
`span`, `a`, `code`, `sub`, `sup` and the like, Gnote's `size:` and
`link:` runs), as `<list-item><bold>olive oil</bold></list-item>`, or
whose runs split a sentence at a space, as `Meet ` and a linked
`Monday`. Nor does an element holding a date the app stamps in parts
take a text check.
- An element added to a list, where another element of its tag is at either
end, gets a `value_equals` for each of its attributes, best ranked first,
at most six, leaving out its selector's attributes, identifiers, times,
volatile values and view state, as HomeBank's new `<ope>` gets its
`amount`, `category` and `payee`. An element whose other attributes, two
volatile values, view state and values standing for none, as HomeBank's
new `<ope>` gets its `amount`, `category` and `payee`; a value two or
more like siblings all hold, as Grisbi's `Cu="1"`, comes after those
that vary, as its `Pa`, `Ca`, `Dt` and `Am`. Records of attributes
alone that it nests, as a KMyMoney `<TRANSACTION>` its `<SPLITS>` of
`<SPLIT>`, get a `value_equals` of each attribute whose values vary among
the like records, its own and those under its like siblings, at most
three a record and six in all, as each split's `value` and `payee`, but
not one every split holds alike, as `price="1/1"`, nor one each holds
equal to an earlier one, as `shares` repeats `value`. Each record is
named by an identifier that the app neither generates nor numbers anew
in every record holding such a list, as KMyMoney's `S0001` in every
transaction, else by its best ranked attribute short of a coordinate or
an amount, as `[name=SPLIT][@account=A000001]`. An element whose other attributes, two
or more, a like sibling holds every one of, as a new Planner task copies
its neighbour's defaults, and any other element added whole, get a check
that it exists. A record added to a list that a selector names, as
Tellico's `<entry id="4">`, gets a `text_equals` for each field, at most
five, each by its selector among the record's fields, as `[name=title]`,
leaving out a field repeating the record's identifier, a date the app
stamps in parts, and blank text or times. A record only position names,
such as Osmo's `<record>` of fields, also gets a `text_contains` for each
new field of three or more characters, at most five, at the nearest
ancestor a check can name, each absent from that ancestor's text at the
seed.
that it exists; of those copied, an attribute naming an element the seed
holds by an id that is no plain number, as an Umbrello attribute's
`type` its data type, is the user's choice and keeps its check. A record added to a list that a selector names, as
Tellico's `<entry id="4">` or Osmo's `<record>` by its first name, gets
a `text_equals` for each field, at most five, each by its selector among
the record's fields, as `[name=title]`, leaving out a field repeating the
record's identifier, the field its selector names it by unless it is
the only one left, as a new VYM branch's `<heading>`, a value every
like record holds in that field, as Osmo's `<group>None</group>`, noise,
a field holding ids of its own, a date the app stamps in parts, and blank
text or times; a field that lists records, as GnuCash's `<trn:splits>`,
gets its records' fields instead, each record by its own selector. An
attribute every like record holds alike, as GnuCash's `version`, is the
format's and gets no check. A record only position names also gets a
`text_contains` for each new field of three or more characters, at most
five, at the nearest ancestor a check can name, each absent from that
ancestor's text at the seed.
- Where members of a list were added or removed, a `member_count` of the
list's members of their tag, and of their kind where they share one
(`type`, `kind` or `shape`, as `[name=dia:object][@type=Flowchart - Box]`),
unless every member of the tag holds a value of its own, as Tiled's
objects a free-form `type` (`well`, `door`, `gate`), which labels each
rather than grouping them,
equal to the end's number, which differs from the seed's: at most two a
file, the shallowest lists first, after the other checks. None for a
list of one member at both ends, as a style an app adds for a run, for
members of an element a text check reads, which are runs of its text,
for an element in mixed content, or for noise.
- A decimal written as text, such as `146.83`, is suggested as a number
with `tolerance: 0.001`, unless the seed's value is that close too.
with `tolerance: 0.001`, unless the seed's value, read as the evaluator
reads a number (`10` and `1e1` included), is that close too. A
`value_equals` that would pass on the seed's value is not suggested.
- An element placed by its own position, holding numeric `x` and `y` as a
like sibling does, as Xournal++ places each `<text>` note on a layer, is
an item of its own, never a run of the others' text: one added whole
gets a `text_contains` of its text on the element holding the items,
which passes wherever it is placed, and that list's `member_count`.
- Noise leaves the suggestions when the file's change holds anything
else, a change only position reaches included: view state, which a tag
or attribute on the way names (the cursor, a selection, scrolling, zoom,
the viewport, windows, splitters, Inkscape's `namedview`, view and
or attribute on the way names (the cursor, a selection, as VYM's
`<select>`, the layer, frame,
view or colour the app has current, as Pencil2D's `currentLayer`,
scrolling, zoom, the viewport, windows, splitters, a list or tree view
mirroring the document, as Umbrello's `listview`, Inkscape's `namedview`, view and
configuration settings, the printer, a save's history, edit time,
editing duration and cycles, last-saved time, the generator and
document statistics), or the value of a name-like attribute or `key` on
document statistics, and a preview or thumbnail the app renders, as
Xournal++'s `<preview>`), or the value of a name-like attribute or `key` on
the way, when it is one token of several words, as LibreOffice's
`config:config-item[@config:name=CursorPositionX]` inside
`[@config:name=ooo:view-settings]`; an attribute ending in `ID` or `Id`,
or an `rsid`, that the app renumbered, with everything else in its
element, as Gnumeric empties a formula cell whose shared expression it
renumbers, and an identifier the app numbers by position; volatile
values, UUIDs and epoch times, and durations and counts under a
document's metadata; times the app stamps, also as a date written in
`[@config:name=ooo:view-settings]`, or a settings path ending in how a
panel shows (`visible`, `hidden`, `expanded`, `geometry`, `size` and the
like), as VYM's `<setting key="/treeeditor/visible">`; an identifier the
app numbers by position. An `Id` suffix alone does not show that an
attribute is generated, so relationship fields such as `accountId` are
retained; other save-generated IDs may need manual review; volatile
values, UUIDs and epoch times, binary data encoded as base64 (a PNG's
`iVBORw0KGgo`, or 256 or more base64 characters mixing cases and
digits), an id counter (`uniqueid`, `nextobjectid`), a value equal to an
id the change gave a new element where a counter or that element holds
it, as Umbrello's `lastobject` holds the new attribute's `xmi:id`, but
never a reference on an element both ends hold, as a KMyMoney split
moved to a new account, and durations and counts under a document's metadata; times the app stamps, also as a date written in
parts whose tag, or one it sits in, names when the app made, changed or
saved something, as Tellico's `<cdate>` of `<year>`, `<month>` and
`<day>` (`cdate`, `mdate`, `created`, `modified`, `saved`, `updated`),
`<day>` (`cdate`, `mdate`, `created`, `modified`, `saved`, `updated`,
`entered`), or written whole under such a tag, as GnuCash's
`<trn:date-entered><ts:date>2026-11-06 08:53:08 +0000`,
which no check ever reads, while a date a user enters in parts, as a
birthday, is an edit like any other; and `upkeep`, the
`loext:tab-stop-distance` attributes LibreOffice fills in `styles.xml`
while another archive entry holds an edit. However much noise
birthday, is an edit like any other; an id the app assigns, an `id`
element with `type="guid"`, as GnuCash's `<trn:id>`, and text of control
characters, as its unset options hold; `upkeep`, a change inside an
app's `slots`, as GnuCash's `book:slots`, which it adds to and fills on
reopening a book, a count an app keeps of its members, an attribute
whose key ends in `count` or an element whose tag names a count, whose
integer changed and at each end equals how many elements of one tag it,
or the element holding the text, holds there, the counter left out, as
VYM's root `branchCount`, KMyMoney's `<TRANSACTIONS count="5">` or
GnuCash's `<gnc:count-data>`, or, for a counter the change added, how
many of one tag, more than one, it holds as children, as FreeCAD's
`<ObjectDeps Count="2">`, while a count a user enters, as an item's
`<count>`, is an edit, and the `loext:tab-stop-distance` attributes
LibreOffice fills in `styles.xml` while another entry holds the edit,
and, while a change outside them is the edit, any
change in `styles.xml`, in a document's style containers or its master,
handout and notes pages, or to an attribute naming an automatic style
(`P1`, `MT1`) at both ends, as Impress after a reload wraps its master pages' fields in a new `MT1` style and
rewrites list style `L2`, and a text showing another field that changed
alike, its element beside a field naming that one's key, as
QElectroTech's `<dynamic_elmt_text>` shows a component's label in its
`<text>` beside `<info_name>label</info_name>`; and `layout`, attributes holding a list of
numbers, as Dia's `obj_bb` `6.3225,6.15;12.5775,8.15`, or a number a
name on its way calls layout (a position, point, box, corner, width,
height, side or offset, as `elem_width`), that changed in an element up
to three levels below one whose text changed, below the root's own
children, while their own element's text did not, as Dia moves and
resizes a box around its new text, or below an element whose tag names a
diagram, widget, canvas or scene while the model change is elsewhere, as
Umbrello grows a class's `classwidget` `height` when an attribute is
added; an order's `<amount value="12"/>` beside its new description is
content. Geometry that changed with
no text beside it, as a CAD sketch's, is content. However much noise
comes first, it never takes a check's place. When the change holds
nothing else, the checks stay and a note flags them: up to three in a
document, and as many as fit in the app's own state, where a view
@@ -187,15 +391,49 @@ operation `describe_desktop_application_task` and predicate type
- `guards`: checks an author may add to show the edit left the rest alone,
kept out of `task.checks`, with ids `guard-1` and on: for each suggested
`value_equals` or `text_equals` on a member of a list, a field on up to
two like siblings, nearest first, at its seed value, which the end holds
too: the check's own field where like siblings hold different values in
two like siblings, those sharing most of the attributes its selector
names it by and its type, as a cell's `Row` or `Col` and `ValueType`,
then the nearest first, at its seed value, which the end holds
too, trying at most the 16 nearest, so a guard costs the same among
thousands of siblings; for a member named as a field, by a name-like attribute alone, as
QElectroTech's `elementInformation[@name=label]`, the like siblings of
the nearest record out that hold that field too come first, so the other
components' labels guard a component's label rather than its other
fields: the check's own field where like siblings hold different values in
it, and otherwise one that varies among them, as Planner's `work` rather
than the `type="normal"` every task shares; never through a sibling only
position or a renumbered id pairs. A text file gets a `lines_present` of the
unchanged list items beside its first new line with the same marker, as
Zim's other `[ ]` action items, or else its nearest lines with words in
them. At most four a file. They pass on the seed, which the export allows,
since one check failing there is enough.
than the `type="normal"` every task shares, but not one numbering the
members in order, as MyPaint's `src`; never through a sibling only
position pairs. A guard never selects its sibling by
what it reads: a sibling its selector names by the attribute the guard
checks, or by a value that is or holds the text it reads, as Glade's
`[>object=CancelTrueTrueTrue]` for a button's `Cancel` label, is named by
another identifier, name-like attribute or child's text it holds alone
at both ends instead, as Tiled's objects by `[@id=2]` rather than the
`name` the guard reads, or Glade's button by `[>packing=TrueTrue0]`, or
else the guard reads another field, or there is none. A `text_equals` with `text_attribute`
reads its siblings the same way. A text file gets a `lines_present` of the
nearest two unchanged lines of its first new line's kind, list items with the same
marker, as Zim's other `[ ]` action items, or lines the same command
opens, as the other headings after LyX's `\begin_layout Section`, or lines
of the same keyword or `key:` in other records, as a gettext catalogue's
other `msgstr` lines rather than the edited entry's own `msgid`, or else
its nearest lines with words in them; each text both ends hold once, never
a line with no text of its own, a command such as `\end_layout`, tags
alone such as `<fonts>` or `</node>`, or a key alone such as a RedNotebook
day's `24:`, nor a line that repeats; an item placed by its own position
that an edit added, a `text_contains` of each of up to four kept items'
text, nearest first. Where members were only edited, a
`member_count` of the innermost list holding the edited element that an
edit goes through by a member with like siblings, a record rather than a
field of one (a member named by a name-like attribute alone that the
record's like siblings hold too), of the edited member's tag and kind, at
the seed's number, as Dia's boxes in their layer, MyPaint's layers in
their stack or Glade's buttons in their button box: no member of the kind
added or removed; never of runs in an element a text check reads, and
only where the end holds the same number. A guard of a coordinate comes
after those of text. At most four a file besides the count guard, which
sits outside that cap, so sibling guards never squeeze it out. They pass
on the seed, which the export allows, since one check failing there is enough.
- `notes`: why `files` is empty, or why a file's suggestions are thin. Each
note has a `code` and a `message`. For a draft with no files: `no_change`
when no file under the home changed between the two checkpoints and nor
@@ -218,8 +456,14 @@ operation `describe_desktop_application_task` and predicate type
`view_state_only` when every change is noise, the checks kept in
`pointers`; `long_text` when an element's text changed past the 2,000
characters a text check compares, the elements in `pointers`; `cut_view`
when the views hold only part of the file; and `unreadable_view` when no
check can read it, as a document REA reads as binary.
when the views hold only part of the file; `unreadable_view` when no
check can read it, as a document REA reads as binary;
`volatile_lines` when a text file gained lines holding a value the app
generates with no text before it to count them by; and `read_as_text`
when a text file opens like XML, with a declaration, a DOCTYPE or an
element, but reads as text because its DOCTYPE has an internal subset or
it is not well formed, so its checks compare lines that hold attributes in
the order the app wrote them.
The suggestions are a starting point. Keep the ones that say what the user
did; drop the ones that only follow from how the app saves its file. Read
+9 -6
View File
@@ -82,7 +82,8 @@ See [desktop builds](https://github.com/morluto/rea/blob/main/.agents/skills/rev
the values the change added, changed and removed with what each was and
became, at the pointer a check names it by; suggested checks with a
placeholder prompt; and `guards`, optional checks that the rest kept its
seed values. The draft's
seed values: like siblings' fields, each line kept beside new text, and
the count of a list whose members were only edited. The draft's
[task section](desktop-application-tasks.md#describe-the-change) describes
each. `notes`, each with a `code` and a `message`, say why a draft has no
files: `no_change` when no file under the home changed between them and
@@ -90,14 +91,16 @@ See [desktop builds](https://github.com/morluto/rea/blob/main/.agents/skills/rev
none under the owned paths, listing up to five in `files` with their
roles, desktop files last, and counting the rest in `more`;
`uncheckable_changes` when the app's keys in dconf were read and changed,
listing the database in `files`, since no check reads dconf;
listing the database in `files`, since no check reads dconf (a version
the capture kept no copy of, as it keeps none of the database at the
start, is `unreadable_changes`, not an empty key list);
`unreadable_changes` when a dconf database changed but REA could not read
it, such as without `dconf-cli` or when a present version's bytes were
not retained, with the read `error`, so whose keys changed is unknown;
and `no_document` when no file has the document role.
it, such as without `dconf-cli`, with the read `error`, so whose keys
changed is unknown; and `no_document` when no file has the document role.
`unowned_changes` and `no_document` point at `state_paths`. They also say,
for a drafted `file`, why its suggestions are thin: `by_position`,
`view_state_only`, `long_text`, `cut_view` or `unreadable_view`.
`view_state_only`, `long_text`, `cut_view`, `unreadable_view`,
`volatile_lines` or `read_as_text`.
6. Write the task: its name, the prompt in the user's own words naming the
app (a solving agent's own shell cannot see the computer's files, and the
export's limitations say when a prompt names neither the app's title,
+2
View File
@@ -214,6 +214,7 @@ npm. Допълнителните инструменти и поддържани
| Rust бинарни файлове | Вградени от cargo-auditable имена на crate-ове, версии, източници и връзки между зависимостите | Вградена статична проверка на ELF/PE/thin Mach-O; [Rust бинарни файлове](../rust-binaries.md) |
| PE сертификати | Записи Authenticode WIN_CERTIFICATE и полета за самоличност на подписващия от PKCS#7/X.509 | Вградена статична проверка на PE; [PE сертификати](../pe-certificates.md) |
| PE импорти | Имена на импортирани и отложено зареждани (delay-load) DLL библиотеки, ординали, IAT RVA адреси и pefile хеш на импортите | Вградена статична проверка на PE; [PE импорти](../pe-imports.md) |
| Windows преки пътища | Цел, аргументи, работна директория и данни от Shell Link | Вградена статична проверка на LNK; [Windows преки пътища](../guides/native/windows-shortcut.md) |
| ELF бележки | Собственици и типове на PT_NOTE/SHT_NOTE, полета GNU build-id и ABI-tag | Вградена статична проверка на ELF; [ELF бележки](../elf-notes.md) |
| Защита на бинарни файлове | PIE, NX, RELRO, CFG и свързаните с тях флагове в заглавните части на ELF, PE и Mach-O | Вградена статична проверка на заглавните части; [защита на бинарни файлове](../binary-hardening.md) |
| Сривове на Apple (IPS) | Метаданни от .ips, нишки, образи, регистри и документирани класове сривове | Вградена статична проверка на JSON; [Apple IPS](../apple-ips.md) |
@@ -240,6 +241,7 @@ npm. Допълнителните инструменти и поддържани
| Пакети и ресурси | Описи на файлове, хешове, plist файлове, устройство на Apple пакети (bundles) и извлечени ресурси | [Ръководство за артефакти и JavaScript](../guides/javascript/javascript-artifact-reconstruction.md), [Apple приложения](../guides/apple/apple-application-analysis.md) |
| Поведение на процеси | Изход в терминала, взаимодействия, наблюдения на изхода от процеса и на файловата система и сравнения между изпълнения | Linux/macOS с нативен PTY; [запис на процеси](../guides/runtime/process-capture.md) |
| PyInstaller изпълними файлове | Членове на CArchive, версия на Python, входни скриптове и извлечен байткод | Няма (само статичен анализ); [пакетирани Python приложения](../python-packaged-applications.md) |
| Изпълними файлове на Deno | Виртуални файлове, входна точка, опции и размер на npm снимката | Няма (само статичен анализ); [изпълними файлове на Deno](../deno-standalone.md) |
Статичната проверка на JavaScript и .NET чете предоставените файлове, без да
стартира приложението. Записът по време на изпълнение стартира избраната цел или
@@ -55,9 +55,9 @@ and the recording and writes the record as Evidence.
A draft with no files carries `notes`, coded `no_change`,
`unowned_changes` (up to five changed home paths with their roles, and a
count of the rest), `uncheckable_changes` (dconf databases whose app keys
were read and changed, which no check reads), `unreadable_changes` (dconf
databases that changed but could not be read, including a present version
whose bytes were not retained, with the read `error`) and
were read and changed, which no check reads; a version kept without its
bytes is unreadable, not empty), `unreadable_changes` (dconf
databases that changed but could not be read, with the read `error`) and
`no_document`; a drafted file whose suggestions are thin carries one
naming its `file`, coded `by_position`, `view_state_only`, `long_text`,
`cut_view` or `unreadable_view`.
@@ -8,29 +8,6 @@ import {
import { readOutput } from "./DesktopBuildCommands.js";
import { endedCapture } from "./DesktopBuildCaptureFailure.js";
describe("endedCapture", () => {
it("returns the size refusal instead of a generic exit when the capture output is too large", async () => {
const error = await endedCapture(
{
homeFiles: () => Promise.resolve(new Map()),
redacted: (text) => text,
exec: () => Promise.reject(new Error("unused")),
},
{
operation: "desktop.capture",
when: "before checkpoint seed",
afterAppExit: "unused",
folder: "/tmp/capture",
},
{ exited: 0, output_bytes: Number.MAX_SAFE_INTEGER },
new AbortController().signal,
);
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(error.message).toContain("max-old-space-size");
});
});
describe("readOutput", () => {
it("does not fetch a command output whose reported size exceeds the host answer ceiling", async () => {
let fetched = false;
@@ -56,6 +56,7 @@ type DraftValue = {
readonly value: string;
readonly element: string;
}[];
readonly alternatives?: string[];
};
/** A draft's note as the stop returns it. */
@@ -78,6 +79,7 @@ const draftValue = ({
after,
note,
refers_to,
alternatives,
}: z.infer<typeof draftValueSchema>): DraftValue => ({
pointer,
kind,
@@ -93,6 +95,7 @@ const draftValue = ({
element,
})),
}),
...(alternatives === undefined ? {} : { alternatives }),
});
/** A note without the optional fields the draft left out. */
@@ -24,7 +24,7 @@ const BUDGET = "Documents/Budget.gnumeric";
const HOSTNAME = "e81232be457d";
const SEED = "envs/notes/seed/Documents/Budget.gnumeric";
const CELLS =
"/root/children/[name=gnm:Sheets]/children/[name=gnm:Sheet]/children/[name=gnm:Cells]/children";
"/root/children/[name=gnm:Sheets]/children/[name=gnm:Sheet][>gnm:Name=Budget]/children/[name=gnm:Cells]/children";
/** A Gnumeric workbook's XML with its rent, author and any comment as given. */
const workbook = (
@@ -409,34 +409,4 @@ describe("draftDesktopApplicationTask notes for an incomplete checkpoint", () =>
expect(draft.notes.map(({ code }) => code)).toContain("incomplete_capture");
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
});
it("does not call the ends unchanged when a checkpoint between them left a deletion unconfirmed", async () => {
const base = withEnd(seedEndCapture(), { changes: [], kept: [] });
const seedAt = base.state.checkpoints.findIndex(
(point) => point.name === "seed",
);
const seed = base.state.checkpoints[seedAt];
if (seed === undefined) throw new Error("the fixture has a seed");
const partial: DesktopApplicationCapture = {
...base,
state: {
...base.state,
checkpoints: [
...base.state.checkpoints.slice(0, seedAt + 1),
{
...seed,
name: "during",
trigger: "request",
unconfirmed_changes: 1,
changes: [],
},
...base.state.checkpoints.slice(seedAt + 1),
],
},
};
const draft = await notesOf(partial);
expect(draft.notes.map(({ code }) => code)).toContain("incomplete_capture");
expect(draft.notes.map(({ code }) => code)).not.toContain("no_change");
});
});
@@ -422,6 +422,56 @@ describe("exportDesktopApplication with a task's prompt", () => {
});
describe("draftDesktopApplicationTask", () => {
it("uses the export's state-directory exclusion for a lone lock", async () => {
const base = capture();
const lock = "/home/ada/.config/notes/editor.lock";
const checkpoints = base.state.checkpoints.map((checkpoint) =>
checkpoint.trigger === "baseline"
? {
...checkpoint,
retained: [...checkpoint.retained, retained(lock, "first\n")],
}
: {
...checkpoint,
changes: [
...checkpoint.changes.filter(({ path }) => path !== NOTE_PATH),
change(
lock,
{ before: "first\n", after: "second\n" },
{ state: true },
),
],
retained: [
...checkpoint.retained.filter(({ path }) => path !== NOTE_PATH),
retained(lock, "second\n"),
],
},
);
const folder = await writeCaptureFolder(
{ ...base, state: { ...base.state, checkpoints } },
undefined,
["first\n", "second\n"],
);
const result = await draftDesktopApplicationTask(folder, readers);
if (result instanceof Error) throw result;
const draft = result.normalized_result as {
task: { checks: { file?: string }[] };
files: { file: string }[];
};
expect(draft.files.map(({ file }) => file)).toContain(
".config/notes/editor.lock",
);
expect(
draft.task.checks.some(
({ file }) => file === ".config/notes/editor.lock",
),
).toBe(false);
expect(
draft.task.checks.some(
({ file }) => file === ".config/notes/settings.ini",
),
).toBe(true);
});
it("drafts checks of the document that changed, which the export then accepts", async () => {
const folder = await writeCaptureFolder(capture());
+32 -1
View File
@@ -1,3 +1,4 @@
import { XML_ELEMENT_OPENING } from "../xmlDocument.js";
import { PYTHON_JSON_READER } from "./appExportPythonJson.js";
import { PYTHON_XML_READER } from "./appExportPythonXml.js";
import { PYTHON_ZIP_HELPERS } from "./appExportPythonZip.js";
@@ -38,9 +39,37 @@ from agentenv_protocol.computer.app_data import INITIAL, add, get, in_thread, ke
from agentenv_protocol.types import DataPart
`;
/** Translate the shared XML grammar's code point escapes into Python regex escapes. */
const PYTHON_XML_ELEMENT_OPENING = XML_ELEMENT_OPENING.replaceAll(
/\\u\{([0-9a-f]+)\}/giu,
(_, code: string) => `\\U${code.padStart(8, "0")}`,
);
/** Python helpers the class uses to seed the home, load dconf keys and read typed views. */
export const PYTHON_HELPERS = String.raw`
XML_SUFFIXES = (".xml", ".xbel", ".plist", ".svg", ".ui")
XML_ELEMENT_OPENING = re.compile(r"${PYTHON_XML_ELEMENT_OPENING}")
def _opens_element(text: str) -> bool:
"""Whether text opens with an element, after a DOCTYPE with no internal subset or none. A '[' inside a quoted id is not a subset."""
if XML_ELEMENT_OPENING.match(text):
return True
declared = re.match(r"(?:<\?xml[^>]*>\s*)?<!DOCTYPE\b", text)
if declared is None:
return False
quote = ""
for index in range(declared.end(), len(text)):
character = text[index]
if quote:
if character == quote:
quote = ""
continue
if character in ('"', "'"):
quote = character
elif character == "[":
return False
elif character == ">":
return XML_ELEMENT_OPENING.match(text[index + 1:].lstrip()) is not None
return False
GROUP_HEADER = re.compile(r"^\[([^\]]+)\]$")
LINE_BREAK = re.compile(r"\r?\n")
SQLITE_HEADER = b"SQLite format 3\x00"
@@ -304,7 +333,9 @@ def _text_view(name: str, text: str, size: int) -> dict:
if view is not None:
return view
lowered = name.lower()
if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml"):
# Text that opens with an element, after a DOCTYPE with no internal subset or none, is XML if it parses, whatever
# the file is called, as a Freeplane map or KmPlot's <!DOCTYPE kmpdoc> plot.
if lowered.endswith(XML_SUFFIXES) or trimmed.startswith("<?xml") or _opens_element(trimmed):
view = _xml_view(text)
return _text(text) if view is None else {"format": "xml", "view": view, "truncated": view["truncated"]}
if _is_keyfile(text):
@@ -216,6 +216,31 @@ export const CHECK_VIEWS: Readonly<Record<string, TaskFileView>> = {
truncated: false,
},
},
"Documents/people.xml": {
format: "xml",
view: {
root: element("people", {}, [
element("person", {}, [
element("details", {}, [
"Delphine",
element("modified", {}, ["Thu Nov 5 09:20:31 2026"]),
]),
element("date", {}, ["2026-11-07T10:12:00Z"]),
]),
element("person", {}, [
element("details", {}, ["Ada"]),
element("date", {}, ["2026-11-08T09:00:00Z"]),
]),
element("person", {}, [
element("details", {}, [
"Alpha",
element("saved", {}, ["٢٠٢٦-١١-٠٧T١٠:١٢:٠٠Z"]),
]),
]),
]),
truncated: false,
},
},
"Documents/flyer.sla": {
format: "xml",
view: {
@@ -1225,6 +1250,46 @@ const ledger = "Documents/ledger.json";
/** Members named by a child element's text, its whitespace collapsed, alone or with other conditions. */
const CHILD_TEXT_CASES: readonly (readonly [DesktopTaskCheckInput, boolean])[] =
[
[
{
kind: "member_count",
file: "Documents/people.xml",
pointer: "/root/children",
matching: "[>details=Alpha٢٠٢٦-١١-٠٧T١٠:١٢:٠٠Z]",
equals: 1,
},
true,
],
[
{
kind: "member_count",
file: "Documents/people.xml",
pointer: "/root/children",
matching: "[>date=2026-11-07T10:12:00Z]",
equals: 1,
},
true,
],
[
{
kind: "member_count",
file: "Documents/people.xml",
pointer: "/root/children",
matching: "[>details=Delphine]",
equals: 1,
},
true,
],
[
{
kind: "member_count",
file: "Documents/people.xml",
pointer: "/root/children",
matching: "[>date=1999-01-01T00:00:00Z]",
equals: 1,
},
false,
],
[
{
kind: "text_equals",
@@ -1309,6 +1374,24 @@ const MEMBER_COUNT_CASES: readonly (readonly [
DesktopTaskCheckInput,
boolean,
])[] = [
[
{
kind: "member_count",
file: "Documents/cut.xml",
pointer: "/root/missing",
equals: 0,
},
false,
],
[
{
kind: "member_count",
file: "Documents/listing.zip",
pointer: "/entries/1/view/root/missing",
equals: 0,
},
false,
],
[
{
kind: "member_count",
+20
View File
@@ -832,6 +832,26 @@ describe("evaluateTaskChecks attribute text, child-text selectors and member cou
expectOutcome(outcome(check), cut, [check.file]);
});
it("explains that a missing array in a cut view is undecided", () => {
for (const [file, pointer] of [
["Documents/cut.xml", "/root/missing"],
["Documents/listing.zip", "/entries/1/view/root/missing"],
] as const) {
const result = outcome({
kind: "member_count",
file,
pointer,
equals: 0,
});
expect(result).toEqual({
id: "c",
passed: false,
undecided: true,
description: `the view of ${file} is truncated, so what it leaves out is unknown`,
});
}
});
it("decides a failure on what the view holds, and says what it found", () => {
expectOutcome(
outcome({
+9 -5
View File
@@ -99,11 +99,13 @@ export const sameJson = (
/** A decimal numeral as FreeCAD and other apps write numbers in text, such as `5.0000000000000000`. */
const NUMERAL = /^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/u;
/** A number, or a numeral string read as one; undefined for anything else or a numeral past the doubles. */
/** A number, or a whitespace-trimmed numeral string read as one; undefined for anything else or a numeral past the doubles. */
export const numberOf = (value: JsonValue): number | undefined => {
if (typeof value === "number") return value;
if (typeof value !== "string" || !NUMERAL.test(value)) return undefined;
const number = Number(value);
if (typeof value !== "string") return undefined;
const text = value.trim();
if (!NUMERAL.test(text)) return undefined;
const number = Number(text);
return Number.isFinite(number) ? number : undefined;
};
@@ -230,7 +232,8 @@ const nearVerdict = (
tolerance: number,
join: boolean,
): Verdict => {
const number = numberOf(join ? elementText(found) : found);
const read = join ? elementText(found) : found;
const number = numberOf(read);
const within = `within ${shown(tolerance)} of ${shown(expected)}`;
if (number === undefined)
return fail(`${at} is ${shown(found)}, not a number`);
@@ -444,7 +447,8 @@ const memberVerdict = (
entry?.format === "zip"
? zipArrayLeavesOut(read.view, pointer)
: read.truncated;
if (located.kind === "none") return noValue(at, located, cut);
if (located.kind === "none")
return cut ? undecided(check.file) : noValue(at, located, false);
const items = located.value;
if (!Array.isArray(items))
return fail(`${at} is ${shown(items)}, not an array`);
+1 -1
View File
@@ -1,8 +1,8 @@
import type { JsonValue } from "../jsonValue.js";
import { leftOutFiles } from "./appExportUnowned.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
import { draftTaskFiles, type TaskDraftFile } from "./appTaskDraft.js";
import { leftOutFiles } from "./appExportUnowned.js";
import type { DesktopStatePath } from "./desktopState.js";
import { xmlView } from "./stateFormats.js";
+56 -16
View File
@@ -4,10 +4,10 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { leftOutFiles } from "./appExportUnowned.js";
import type { DesktopTaskCheck } from "./appTask.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
import { draftTaskFiles, type TaskDraftFile } from "./appTaskDraft.js";
import { leftOutFiles } from "./appExportUnowned.js";
import type { DesktopStatePath } from "./desktopState.js";
import { xmlView } from "./stateFormats.js";
import { locatePointer } from "./viewPointer.js";
@@ -243,7 +243,7 @@ describe("draftTaskFiles for structured views", () => {
{
kind: "value_equals",
file: ".config/app/state.json",
pointer: "/recent/0/name",
pointer: "/recent/[name=a.txt]/name",
value: "a.txt",
},
{
@@ -375,7 +375,8 @@ describe("draftTaskFiles for XML that uses namespaces", () => {
describe("draftTaskFiles for an AbiWord document", () => {
const FIXTURES = join(import.meta.dirname, "../../../tests/fixtures");
const PARAGRAPH = "/root/children/[name=section]/children/[name=p][@xid=3]";
const PARAGRAPH =
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=3]";
it("suggests an AbiWord paragraph's whole text first, no save time, and nothing by position", async () => {
const [before, after] = await Promise.all(
@@ -435,7 +436,8 @@ describe("draftTaskFiles for text split into runs", () => {
]),
truncated: false,
});
const sixth = "/root/children/[name=section]/children/[name=p][@xid=6]";
const sixth =
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=6]";
const edits: readonly (readonly [JsonValue[], JsonValue[], string])[] = [
// Text replaced by a run, as AbiWord types into a reopened document.
[["Meeting at 2:00"], [run("Meeting at 3:30")], "Meeting at 3:30"],
@@ -653,7 +655,8 @@ describe("draftTaskFiles for runs added or removed whole", () => {
{
kind: "text_equals",
file: "Documents/note.abw",
pointer: "/root/children/[name=section]/children/[name=p][@xid=6]",
pointer:
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=6]",
value: text,
},
]);
@@ -852,7 +855,7 @@ describe("draftTaskFiles for text in an element its tag names alone", () => {
});
expect(saved?.suggested).toEqual(
check(
"/root/children/[name=g]/children/[name=text][@id=headline]",
"/root/children/[name=g][@id=layer1]/children/[name=text][@id=headline]",
"Summer Bake Sale",
),
);
@@ -890,7 +893,8 @@ describe("draftTaskFiles for elements added whole holding text", () => {
{
kind: "text_equals",
file: "Documents/note.abw",
pointer: "/root/children/[name=section]/children/[name=p][@xid=6]",
pointer:
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=6]",
value: "Meeting at 3:30",
},
]);
@@ -907,10 +911,14 @@ describe("draftTaskFiles for elements added whole holding text", () => {
it("checks a new paragraph's text at a section short enough to check, and otherwise its own, rather than that it is there", () => {
const sections = [
["Agenda", "/root/children/[name=section]", "AgendaBring the minutes"],
[
"Agenda",
"/root/children/[name=section][@xid=1]",
"AgendaBring the minutes",
],
[
"Agenda. ".repeat(300),
"/root/children/[name=section]/children/[name=p][@xid=7]",
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=7]",
"Bring the minutes",
],
] as const;
@@ -930,13 +938,34 @@ describe("draftTaskFiles for elements added whole holding text", () => {
),
});
expect(file?.suggested).toEqual([
{ kind: "text_equals", file: "Documents/note.abw", pointer, value },
]);
expect(file?.suggested[0]).toEqual({
kind: "text_equals",
file: "Documents/note.abw",
pointer,
value,
});
// A paragraph the section's own check covers is a run of its text; one checked apart is counted.
expect(file?.suggested.slice(1)).toEqual(
pointer.endsWith("[@xid=7]")
? [
{
kind: "member_count",
file: "Documents/note.abw",
pointer: "/root/children/[name=section][@xid=1]/children",
matching: "[name=p]",
equals: 2,
},
]
: [],
);
expect(
[[minutes("Bring the minutes")], [minutes("Bring the agenda")], []].map(
(added) =>
passing("Documents/note.abw", file?.suggested, note(added)),
passing(
"Documents/note.abw",
file?.suggested.slice(0, 1),
note(added),
),
),
).toEqual([[true], [false], [false]]);
}
@@ -1019,7 +1048,8 @@ describe("draftTaskFiles for elements without text beside a text edit", () => {
]),
truncated: false,
});
const sixth = "/root/children/[name=section]/children/[name=p][@xid=6]";
const sixth =
"/root/children/[name=section][@xid=1]/children/[name=p][@xid=6]";
const image = xmlElement("image", { dataid: "image_1" });
const brk = xmlElement("br");
const edits = [
@@ -1526,7 +1556,7 @@ describe("draftTaskFiles archives added to whole", () => {
]);
});
it("suggests no element by its position, even at the last step", () => {
it("suggests no element by its position, even at the last step, and counts the paragraphs instead", () => {
const page = (paragraphs: string[]) =>
listing([
zipEntry("page.xml", "xml", {
@@ -1548,7 +1578,17 @@ describe("draftTaskFiles archives added to whole", () => {
),
});
expect(file).toMatchObject({ change: { kind: "values" }, suggested: [] });
expect(file).toMatchObject({
change: { kind: "values" },
suggested: [
{
kind: "member_count",
pointer: "/entries/[name=page.xml]/view/root/children",
matching: "[name=p]",
equals: 2,
},
],
});
});
});
+89 -24
View File
@@ -1,15 +1,20 @@
import type { JsonValue } from "../jsonValue.js";
import { isTimestamp, type DesktopTaskCheckInput } from "./appTask.js";
import { fileNotes, type FileNote } from "./appTaskDraftFileNotes.js";
import { lineGuards } from "./appTaskDraftLineGuards.js";
import { isGeneratedUid } from "./attributeRank.js";
import {
ARCHIVE,
innermost,
namedDraft,
presenceValues,
XML_FILE,
type NamedFacts,
} from "./appTaskDraftNamed.js";
decisive,
jsonCounts,
outermost,
positionalNotes,
} from "./appTaskDraftJson.js";
import {
fileNotes,
readAsTextNotes,
type FileNote,
} from "./appTaskDraftFileNotes.js";
import { addedLineChecks, lineGuards } from "./appTaskDraftLineGuards.js";
import { innermost, namedDraft, type NamedFacts } from "./appTaskDraftNamed.js";
import { ARCHIVE, presenceValues, XML_FILE } from "./appTaskDraftTree.js";
import { rowSuggestions } from "./appTaskDraftRows.js";
import {
draftValues,
@@ -105,18 +110,49 @@ const textSuggestions = (
file: string,
baseline: Version,
final: Version,
): Suggestion[] => {
): { suggestions: Suggestion[]; notes: FileNote[] } => {
const before = new Set(baseline.present ? linesOf(baseline) : []);
const after = new Set(linesOf(final));
const added = [...after].filter((line) => !before.has(line));
const gone = [...before].filter((line) => !after.has(line));
const suggestions: Suggestion[] = [];
if (added.length > 0 && added.length <= MAX_SUGGESTIONS)
suggestions.push({ kind: "lines_present", file, lines: added });
const truncated = [baseline, final].some(
(version) => isRecord(version.view) && version.view.truncated === true,
);
if (truncated) return suggestions;
// A count is decided only on views that hold the whole file.
const gained =
added.length > 0 && added.length <= MAX_SUGGESTIONS
? addedLineChecks(
file,
{
before: baseline.present ? linesOf(baseline) : [],
after: linesOf(final),
},
{ added, counted: !truncated },
)
: { checks: [], notes: [] };
suggestions.push(...gained.checks);
const formatNotes = readAsTextNotes(file, linesOf(final));
const unreadableAttributes = gained.notes.find(
({ code }) => code === "read_as_text",
);
const result = {
suggestions,
notes: [
...gained.notes.filter(({ code }) => code !== "read_as_text"),
...(unreadableAttributes !== undefined && formatNotes.length === 0
? [unreadableAttributes]
: formatNotes.map((note) =>
unreadableAttributes === undefined
? note
: {
...note,
message: `${note.message} ${unreadableAttributes.message}`,
},
)),
],
};
if (truncated) return result;
if (gone.length > 0 && gone.length <= MAX_SUGGESTIONS)
suggestions.push({ kind: "lines_absent", file, lines: gone });
// A line of digits and punctuation is usually a value a rewrite renumbers, not something the user made.
@@ -124,7 +160,7 @@ const textSuggestions = (
({ line }) => /\p{L}/u.test(line),
))
suggestions.push({ kind: "line_count", file, exact: line, equals: n });
return suggestions;
return result;
};
/** `group/key` entries of key file views as JSON pointers into the view. */
@@ -151,6 +187,7 @@ interface FileDraft {
readonly valuesCut: boolean;
readonly guards: readonly Suggestion[];
readonly facts?: NamedFacts;
readonly notes?: readonly FileNote[];
}
const NO_VALUES = { values: [], valuesCut: false, guards: [] } as const;
@@ -233,36 +270,54 @@ const valueSuggestions = (
}
if (format !== "json" && format !== "keyfile")
return { suggested: [], ...NO_VALUES };
const change = diffStateViews(format, baseline.view, final.view);
// JSON records are named by an id field each holds, not their place.
const change = diffStateViews(format, baseline.view, final.view, {
named: true,
});
const pointers = keyPointers([baseline.view, final.view]);
const pointer = (entry: string) =>
format === "keyfile" ? pointers.get(entry) : entry;
// Key file entries are flat; a group may hold `/`, so prefixes mean nothing there.
const leaves = (entries: readonly string[]) =>
format === "keyfile" ? entries : innermost(entries);
const suggestions: Suggestion[] = [];
const wholes = (entries: readonly string[]) =>
format === "keyfile" ? entries : outermost(entries);
const listed: Suggestion[] = [];
for (const entry of leaves([...change.added, ...change.changed])) {
const at = pointer(entry);
const value = at === undefined ? undefined : resolvePointer(final.view, at);
// An id the app generates, as TreeLine's uuid1 `uid`, holds nothing another save repeats.
if (
at !== undefined &&
at !== "" &&
value !== undefined &&
!isTimestamp(value)
!isTimestamp(value) &&
!(typeof value === "string" && isGeneratedUid(value))
)
suggestions.push({ kind: "value_equals", file, pointer: at, value });
listed.push({ kind: "value_equals", file, pointer: at, value });
}
for (const entry of leaves(change.removed)) {
for (const entry of wholes(change.removed)) {
const at = pointer(entry);
if (at !== undefined && at !== "")
suggestions.push({ kind: "value_absent", file, pointer: at });
listed.push({ kind: "value_absent", file, pointer: at });
}
const suggestions = decisive(listed, versions(baseline, final));
const { values, cut } = plainValues(
plainChange(format, baseline, final),
baseline,
final,
);
return { suggested: suggestions, values, valuesCut: cut, guards: [] };
if (format === "keyfile")
return { suggested: suggestions, values, valuesCut: cut, guards: [] };
const counts = jsonCounts(file, change, versions(baseline, final));
const suggested = [...suggestions, ...counts.checks];
return {
suggested,
values,
valuesCut: cut,
guards: counts.guards,
notes: positionalNotes(file, suggested, final.view),
};
};
/** Checks that express how a file changed from its baseline to its final version, with the values, guards and facts beside them. */
@@ -281,11 +336,16 @@ const suggestedChecks = (
const created: Suggestion[] = baseline.present
? []
: [{ kind: "file_present", file }];
const content: FileDraft =
const lines =
final.format === "text"
? textSuggestions(file, baseline, final)
: undefined;
const content: FileDraft =
lines !== undefined
? {
...NO_VALUES,
suggested: textSuggestions(file, baseline, final),
suggested: lines.suggestions,
notes: lines.notes,
guards: baseline.present
? lineGuards(file, linesOf(baseline), linesOf(final))
: [],
@@ -417,6 +477,8 @@ export const draftTaskFiles = (
const role = considered.some(({ path }) => path.role === "document")
? "document"
: "application_state";
// A file absent from the seed cannot supply a useful check. The same owner
// keeps explicitly selected files, including a selected lock.
return withinDraftBudget(
changed.map(({ home, path, baseline, final, change }) => {
const drafted = path.role === role && !isLeftOut(home);
@@ -434,7 +496,10 @@ export const draftTaskFiles = (
values_cut: draft.valuesCut,
guards: draft.guards,
notes: drafted
? fileNotes(home, changeShape(change, final), draft.facts)
? [
...fileNotes(home, changeShape(change, final), draft.facts),
...(draft.notes ?? []),
]
: [],
};
}),
+378 -88
View File
@@ -6,6 +6,31 @@ import { passing, xml, xmlDraft } from "./appTaskDraft.fixture.js";
const FILE = "Documents/doc.xml";
it("checks clean and partially noisy fields of the same added record", () => {
const before = '<doc><record id="old"><title>Old</title></record></doc>';
const after =
'<doc><record id="old"><title>Old</title></record><record id="new"><title>Shopping</title><details><name>Water filter</name><modified>1793870600</modified></details></record></doc>';
const checks = xmlDraft(before, after).suggested;
expect(checks).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: "Shopping" }),
expect.objectContaining({ kind: "text_contains", value: "Water filter" }),
]),
);
expect(
passing(FILE, xml(after.replace("1793870600", "1793870700")), checks).every(
Boolean,
),
).toBe(true);
expect(
passing(
FILE,
xml(after.replace("Water filter", "Wrong item")),
checks,
).every(Boolean),
).toBe(false);
});
it("does not include a sibling generated UUID when a record field changes", () => {
const before =
'<doc><record id="one"><value>Old text</value><session>123e4567-e89b-12d3-a456-426614174000</session></record></doc>';
@@ -41,31 +66,6 @@ it("keeps stable added field text while omitting nested save times and generated
expect(passing(FILE, xml(later), checks).every(Boolean)).toBe(true);
});
it("checks clean and partially noisy fields of the same added record", () => {
const before = '<doc><record id="old"><title>Old</title></record></doc>';
const after =
'<doc><record id="old"><title>Old</title></record><record id="new"><title>Shopping</title><details><name>Water filter</name><modified>1793870600</modified></details></record></doc>';
const checks = xmlDraft(before, after).suggested;
expect(checks).toEqual(
expect.arrayContaining([
expect.objectContaining({ value: "Shopping" }),
expect.objectContaining({ kind: "text_contains", value: "Water filter" }),
]),
);
expect(
passing(FILE, xml(after.replace("1793870600", "1793870700")), checks).every(
Boolean,
),
).toBe(true);
expect(
passing(
FILE,
xml(after.replace("Water filter", "Wrong item")),
checks,
).every(Boolean),
).toBe(false);
});
it("keeps a nested phone number that resembles an epoch timestamp", () => {
const before =
'<doc><contact name="old"><phone><country>+1</country><number>2125550100</number></phone></contact></doc>';
@@ -130,13 +130,18 @@ it("omits oversized added attributes while retaining shorter checks and reportin
});
describe("draftTaskFiles for elements no attribute names", () => {
/** A score whose title frame holds untitled texts, as MuseScore 3 saves one. */
const score = (title: string, composer: string) =>
`<museScore><Score><Staff><VBox><height>10</height><Text><style>Title</style><text>${title}</text></Text><Text><style>Composer</style><text>${composer}</text></Text></VBox><Measure><Chord>C</Chord></Measure></Staff></Score></museScore>`;
/** A score whose title frame holds untitled texts, as MuseScore 3 saves one, each with its style or none. */
const score = (title: string, composer: string, styled = true) => {
const text = (style: string, value: string) =>
`<Text>${styled ? `<style>${style}</style>` : ""}<text>${value}</text></Text>`;
return `<museScore><Score><Staff><VBox><height>10</height>${text("Title", title)}${text("Composer", composer)}</VBox><Measure><Chord>C</Chord></Measure></Staff></Score></museScore>`;
};
const FRAME =
"/root/children/[name=Score]/children/[name=Staff]/children/[name=VBox]";
it("checks the whole text of the nearest ancestor its tag names, within three levels", () => {
const before = score("Morning Song", "Theo Ashby");
const after = score("Evening Lullaby", "Clara Hollis");
const before = score("Morning Song", "Theo Ashby", false);
const after = score("Evening Lullaby", "Clara Hollis", false);
const file = xmlDraft(before, after);
@@ -144,15 +149,35 @@ describe("draftTaskFiles for elements no attribute names", () => {
{
kind: "text_equals",
file: FILE,
pointer:
"/root/children/[name=Score]/children/[name=Staff]/children/[name=VBox]",
value: "10TitleEvening LullabyComposerClara Hollis",
pointer: FRAME,
value: "10Evening LullabyClara Hollis",
},
]);
expect(passing(FILE, xml(before), file.suggested)).toEqual([false]);
expect(passing(FILE, xml(after), file.suggested)).toEqual([true]);
});
it("checks each text by the child that names it, as MuseScore's by its style, rather than the frame's whole text", () => {
const before = score("Morning Song", "Theo Ashby");
const after = score("Evening Lullaby", "Clara Hollis");
const file = xmlDraft(before, after);
expect(file.suggested).toEqual(
[
["Title", "Evening Lullaby"],
["Composer", "Clara Hollis"],
].map(([style, value]) => ({
kind: "text_equals",
file: FILE,
pointer: `${FRAME}/children/[name=Text][>style=${style}]/children/[name=text]`,
value,
})),
);
expect(passing(FILE, xml(before), file.suggested)).toEqual([false, false]);
expect(passing(FILE, xml(after), file.suggested)).toEqual([true, true]);
});
/** An address book of records with no attributes, as Osmo keeps its contacts. */
const contacts = (...records: string[]) =>
`<osmo_contacts><contacts_records>${records
@@ -166,7 +191,7 @@ describe("draftTaskFiles for elements no attribute names", () => {
const DELPHINE =
"<first_name>Delphine</first_name><last_name>Moreau</last_name><cell_phone_1>555-0163</cell_phone_1><email_1>delphine.moreau@example.com</email_1>";
it("checks each new field of a record added whole, each absent from the list's text at the seed, and never the list's whole text", () => {
it("names a record added whole by a child's text and checks each field it entered, never a default every record holds, then counts the records", () => {
const before = contacts(HANNAH);
const after = contacts(HANNAH, DELPHINE);
@@ -176,27 +201,26 @@ describe("draftTaskFiles for elements no attribute names", () => {
});
const list = "/root/children/[name=contacts_records]";
expect(
file.suggested.map((check) => [
check.kind,
"pointer" in check ? check.pointer : undefined,
]),
).toEqual([
["text_contains", list],
["text_contains", list],
["text_contains", list],
["text_contains", list],
]);
// Not "None" or "0": the seed's text already holds them.
expect(
file.suggested.flatMap((check) =>
check.kind === "text_contains" ? [check.value] : [],
),
).toEqual([
"Delphine",
"Moreau",
"555-0163",
"delphine.moreau@example.com",
const record = `${list}/children/[name=record][>first_name=Delphine]`;
// Not "None" or "0", every record's, nor the first name that names it.
expect(file.suggested).toEqual([
...[
["last_name", "Moreau"],
["cell_phone_1", "555-0163"],
["email_1", "delphine.moreau@example.com"],
].map(([field, value]) => ({
kind: "text_equals",
file: ".local/share/osmo/contacts.xml",
pointer: `${record}/children/[name=${field}]`,
value,
})),
{
kind: "member_count",
file: ".local/share/osmo/contacts.xml",
pointer: `${list}/children`,
matching: "[name=record]",
equals: 2,
},
]);
const file_ = ".local/share/osmo/contacts.xml";
expect(passing(file_, xml(before), file.suggested)).toEqual([
@@ -226,9 +250,9 @@ describe("draftTaskFiles for elements no attribute names", () => {
file: home,
});
const values = file.suggested.flatMap((check) =>
check.kind === "text_contains" ? [check.value] : [],
"value" in check && typeof check.value === "string" ? [check.value] : [],
);
expect(values).toContain("Delphine");
expect(values.some((value) => value.includes("Delphine"))).toBe(true);
expect(values).not.toContain("124");
expect(values).not.toContain("2026");
expect(values.some((value) => value.includes(essay))).toBe(false);
@@ -277,7 +301,7 @@ describe("draftTaskFiles for a named record that also holds a save time", () =>
});
});
describe("draftTaskFiles for a record only position names, removed whole", () => {
describe("draftTaskFiles for a record removed whole", () => {
const contacts = (...names: string[]) =>
`<osmo_contacts><contacts_records>${names
.map(
@@ -286,7 +310,7 @@ describe("draftTaskFiles for a record only position names, removed whole", () =>
)
.join("")}</contacts_records></osmo_contacts>`;
it("checks the list's text, the one check that can tell the record is gone", () => {
it("checks the record a child names is gone, and the records' count", () => {
const before = contacts("Hannah", "Delphine");
const after = contacts("Hannah");
@@ -295,23 +319,29 @@ describe("draftTaskFiles for a record only position names, removed whole", () =>
file: ".local/share/osmo/contacts.xml",
});
const list = "/root/children/[name=contacts_records]";
expect(file.suggested).toMatchObject([
{
kind: "text_equals",
pointer: "/root/children/[name=contacts_records]",
kind: "value_absent",
pointer: `${list}/children/[name=record][>first_name=Delphine]`,
},
{ kind: "member_count", pointer: `${list}/children`, equals: 1 },
]);
const home = ".local/share/osmo/contacts.xml";
expect(
[before, after, contacts("Delphine")].map((text) =>
passing(home, xml(text), file.suggested),
),
).toEqual([[false], [true], [false]]);
).toEqual([
[false, false],
[true, true],
[false, true],
]);
});
});
describe("draftTaskFiles for records whatever their fields are called", () => {
it("checks each new field of a record of repeated <field> children only position names, in a list at the root", () => {
it("names a record of repeated <field> children by a field's text and checks its whole text, in a list at the root", () => {
const records = (...people: [string, string][]) =>
`<records>${people
.map(
@@ -324,14 +354,21 @@ describe("draftTaskFiles for records whatever their fields are called", () => {
const file = xmlDraft(before, after);
expect(file.suggested).toEqual(
["Delphine", "Moreau"].map((value) => ({
kind: "text_contains",
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: "/root",
value,
})),
);
pointer: "/root/children/[name=record][>field=Delphine]",
value: "DelphineMoreau",
},
{
kind: "member_count",
file: FILE,
pointer: "/root/children",
matching: "[name=record]",
equals: 2,
},
]);
expect(
[before, after].map((text) => passing(FILE, xml(text), file.suggested)),
).toEqual([
@@ -375,6 +412,23 @@ describe("draftTaskFiles for records whatever their fields are called", () => {
).toBe(true);
});
it.each([
"<person><name>Delphine</name><modified>2026-11-07T10:12:00Z</modified></person><name>Moreau</name>",
"<name>Delphine</name><person><modified>2026-11-07T10:12:00Z</modified><name>Moreau</name></person>",
])("keeps a nested omitted timestamp as a text boundary", (details) => {
const records = (extra: string) =>
`<records><record><field>Hannah</field></record>${extra}</records>`;
const after = records(`<record><details>${details}</details></record>`);
const checks = xmlDraft(records(""), after).suggested;
const values = checks.flatMap((check) =>
check.kind === "text_contains" ? [check.value] : [],
);
expect(values).toEqual(["Delphine", "Moreau"]);
expect(passing(FILE, xml(after), checks).every(Boolean)).toBe(true);
});
});
describe("draftTaskFiles for truncated and linked records", () => {
it("suggests no check a cut view leaves undecided for a record only position names, added before the cut", () => {
const book = (...people: string[]) =>
`<book><contacts>${people
@@ -447,6 +501,13 @@ describe("draftTaskFiles for records whatever their fields are called", () => {
pointer: `${bookmark}/children/[name=link]`,
value: "https://example.com/notes",
},
{
kind: "member_count",
file: FILE,
pointer: "/root/children",
matching: "[name=bookmark]",
equals: 2,
},
]);
});
});
@@ -472,9 +533,15 @@ describe("draftTaskFiles for an identified record's own text", () => {
expect(shown).toEqual(["Delphine", "Moreau"]);
expect(
file.suggested.every(
(check) => "pointer" in check && check.pointer.includes("[@id=two]"),
),
file.suggested
.filter(
(check) =>
"value" in check &&
(check.value === "Delphine" || check.value === "Moreau"),
)
.every(
(check) => "pointer" in check && check.pointer.includes("[@id=two]"),
),
).toBe(true);
expect(
file.suggested.some(
@@ -512,6 +579,48 @@ describe("draftTaskFiles for an identified record's own text", () => {
false,
);
});
it("checks a field by the text the file saved, line breaks included", () => {
const records = (people: readonly (readonly [string, string])[]) =>
`<records>${people
.map(
([id, name]) =>
`<record id="${id}"><details>${name}</details></record>`,
)
.join("")}</records>`;
const before = records([["one", "Ada"]]);
const after = records([
["one", "Ada"],
["two", "\nMoreau\n"],
]);
const file = xmlDraft(before, after);
expect(
file.suggested.some(
(check) =>
"value" in check &&
check.value === "Moreau" &&
"normalize_whitespace" in check &&
check.normalize_whitespace === true,
),
).toBe(true);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
expect(
passing(
FILE,
xml(
records([
["one", "Ada"],
["two", "\nSomeone\n"],
]),
),
file.suggested,
).some((passed) => !passed),
).toBe(true);
expect(
passing(FILE, xml(before), file.suggested).some((passed) => !passed),
).toBe(true);
});
});
describe("draftTaskFiles for an added record whose words the seed already has", () => {
@@ -531,9 +640,11 @@ describe("draftTaskFiles for an added record whose words the seed already has",
]);
const file = xmlDraft(before, after);
expect(file.suggested.map(({ kind }) => kind)).toEqual(["text_equals"]);
expect(passing(FILE, xml(before), file.suggested)).toEqual([false]);
expect(passing(FILE, xml(after), file.suggested)).toEqual([true]);
expect(file.suggested.map(({ kind }) => kind)).toContain("text_equals");
expect(passing(FILE, xml(before), file.suggested).every(Boolean)).toBe(
false,
);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
});
it("keeps a save time out of the list check and still requires the added record", () => {
@@ -577,8 +688,8 @@ describe("draftTaskFiles for an added record whose words the seed already has",
passing(FILE, xml(before), file.suggested).some((passed) => !passed),
).toBe(true);
expect(
passing(FILE, xml(dated([["Lin", "Ada", later]])), file.suggested).every(
Boolean,
passing(FILE, xml(dated([["Lin", "Ada", later]])), file.suggested).some(
(passed) => !passed,
),
).toBe(true);
const duplicate = xmlDraft(
@@ -678,6 +789,53 @@ describe("draftTaskFiles for a paragraph made of runs", () => {
).toContain(false);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
});
it("checks a Word paragraph's whole text where an edit appends a run of elements beside a kept run, not the run as a record", () => {
const paragraph = (runs: string) =>
`<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>Meeting at </w:t></w:r>${runs}</w:p></w:body></w:document>`;
const bold = (text: string) =>
`<w:r><w:rPr><w:b/></w:rPr><w:t>${text}</w:t></w:r>`;
const file = xmlDraft(paragraph(""), paragraph(bold("3:30")));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: "/root/children/[name=w:body]/children/[name=w:p]",
value: "Meeting at 3:30",
},
]);
expect(
[bold("3:30"), bold("13:30")].map((runs) =>
passing(FILE, xml(paragraph(runs)), file.suggested),
),
).toEqual([[true], [false]]);
});
it("checks a list's whole text where an edit appends an item that only formats its text, which a wrong item fails", () => {
const list = (items: string) =>
`<note><text><note-content><list><list-item>bread</list-item><list-item>eggs</list-item>${items}</list></note-content></text></note>`;
const item = (text: string) =>
`<list-item><bold>${text}</bold></list-item>`;
const file = xmlDraft(list(""), list(item("olive oil")));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer:
"/root/children/[name=text]/children/[name=note-content]/children/[name=list]",
value: "breadeggsolive oil",
},
]);
expect(
[item("olive oil"), item("no olive oil")].map((items) =>
passing(FILE, xml(list(items)), file.suggested),
),
).toEqual([[true], [false]]);
});
});
describe("draftTaskFiles for an element added to a list", () => {
@@ -711,6 +869,13 @@ describe("draftTaskFiles for an element added to a list", () => {
check("date", "739924"),
// A decimal the app writes as text is checked by its number.
check("amount", -64.18, 0.001),
{
kind: "member_count",
file: FILE,
pointer: "/root/children",
matching: "[name=ope]",
equals: 2,
},
]);
});
@@ -719,7 +884,9 @@ describe("draftTaskFiles for an element added to a list", () => {
.map((key) => `${key}="value ${key}"`)
.join(" ")} wording="Weekly groceries"/>`;
const added = xmlDraft(ledger(RENT), ledger(RENT + wide));
expect(added.suggested).toHaveLength(6);
expect(
added.suggested.filter(({ kind }) => kind === "value_equals"),
).toHaveLength(6);
const alone = xmlDraft(ledger(""), ledger('<budget year="2026"/>'));
expect(alone.suggested).toEqual([
@@ -733,6 +900,95 @@ describe("draftTaskFiles for an element added to a list", () => {
});
});
describe("draftTaskFiles for a transaction appended to a Grisbi file", () => {
/** Transactions as Grisbi writes them: attributes only, numbered by `Nb`, every `Id` the placeholder `(null)`. */
const accounts = (
...rows: (readonly [string, string, string, string, string])[]
) =>
`<Grisbi>${rows
.map(
([nb, date, amount, party, category]) =>
`<Transaction Ac="1" Nb="${nb}" Id="(null)" Dt="${date}" Cu="1" Am="${amount}" Exb="0" Pa="${party}" Ca="${category}" Sca="8" No="(null)" Ma="0" />`,
)
.join("")}<Party Nb="4" Na="Clearwater Utilities" /></Grisbi>`;
const KEPT = [
["1", "10/02/2026", "-1150.00", "1", "18"],
["2", "10/05/2026", "-86.40", "2", "6"],
["3", "09/21/2026", "-41.30", "4", "18"],
] as const;
it("names the new transaction by its number, not the placeholder id every one holds, and checks what was entered before the defaults", () => {
const before = accounts(...KEPT);
const after = accounts(...KEPT, ["4", "10/21/2026", "-58.75", "4", "18"]);
const file = xmlDraft(before, after);
const at = (key: string) =>
`/root/children/[name=Transaction][@Nb=4]/attributes/${key}`;
expect(file.suggested.slice(0, 4)).toEqual([
{ kind: "value_equals", file: FILE, pointer: at("Pa"), value: "4" },
{ kind: "value_equals", file: FILE, pointer: at("Ca"), value: "18" },
{
kind: "value_equals",
file: FILE,
pointer: at("Dt"),
value: "10/21/2026",
},
{
kind: "value_equals",
file: FILE,
pointer: at("Am"),
value: -58.75,
tolerance: 0.001,
},
]);
expect(file.suggested.at(-1)).toMatchObject({
kind: "member_count",
equals: 4,
});
expect(file.notes).toEqual([]);
expect(passing(FILE, xml(before), file.suggested)).not.toContain(true);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
});
});
describe("draftTaskFiles for decimals near a seed the evaluator reads as a number", () => {
it.each([
["element text", (value: string) => `<doc><total>${value}</total></doc>`],
["attribute", (value: string) => `<doc><total amount="${value}"/></doc>`],
])(
"retains an exact check when %s has a whitespace-padded seed within tolerance",
(_kind, document) => {
const before = document(" 10 ");
const after = document("10.0005");
const draft = xmlDraft(before, after);
expect(draft.suggested).not.toEqual([]);
expect(draft.suggested.some((check) => "tolerance" in check)).toBe(false);
expect(passing(FILE, xml(before), draft.suggested)).not.toContain(true);
expect(passing(FILE, xml(after), draft.suggested).every(Boolean)).toBe(
true,
);
},
);
it("suggests no check by number that the seed's value, as `10` or `1e1`, already passes", () => {
for (const seed of ["10", "1e1"]) {
const value = (text: string) =>
`<doc><total>${text}</total><note>x</note></doc>`;
const file = xmlDraft(value(seed), value("10.0005"));
expect(file.suggested).not.toEqual([]);
expect(passing(FILE, xml(value(seed)), file.suggested)).not.toContain(
true,
);
expect(
passing(FILE, xml(value("10.0005")), file.suggested).every(Boolean),
).toBe(true);
}
});
});
describe("draftTaskFiles for decimals", () => {
it("checks a decimal the app writes as text by its number within 0.001, unless the seed's is that close too", () => {
const shape = (x: string, y: string, size: string) =>
@@ -787,7 +1043,13 @@ describe("draftTaskFiles for decimals", () => {
"437.<span>8</span>",
])
expect(passes(same)).toEqual([true]);
expect(passes("\n437.80000000000001\n")).toEqual([true]);
expect(passes("437.89")).toEqual([false]);
const padded = xmlDraft(cell("1"), cell("\n437.80000000000001\n"));
expect(padded.suggested).toMatchObject([
{ kind: "value_equals", value: 437.8, tolerance: 0.001 },
]);
expect(passing(FILE, xml(cell("437.8")), padded.suggested)).toEqual([true]);
expect(passes("four hundred")).toEqual([false]);
});
@@ -804,6 +1066,18 @@ describe("draftTaskFiles for decimals", () => {
[before, after].map((text) => passing(FILE, xml(text), file.suggested)),
).toEqual([[false], [true]]);
});
it("does not give a line-broken decimal a tolerance the trimmed seed already meets", () => {
const sheet = (rate: string) =>
`<Cells><Cell Row="2" Col="3">${rate}</Cell><Cell Row="3" Col="3">5</Cell></Cells>`;
const before = sheet("\n10\n");
const after = sheet("\n10.0005\n");
const file = xmlDraft(before, after);
expect(file.suggested.some((check) => "tolerance" in check)).toBe(false);
expect(passing(FILE, xml(before), file.suggested)).toContain(false);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
});
});
describe("draftTaskFiles for records in a list, as Tellico keeps books", () => {
@@ -839,15 +1113,30 @@ describe("draftTaskFiles for records in a list, as Tellico keeps books", () => {
const file = xmlDraft(before, after);
expect(file.values.map(({ pointer }) => pointer)).toEqual([entry("3")]);
expect(file.suggested).toEqual(
["title", "authors", "publisher", "pub_year"].map((field, index) => ({
// Field by field, so no cut hides one; the id and the dates the app stamps last.
expect(file.values.map(({ pointer, note }) => [pointer, note])).toEqual([
...["title", "authors", "publisher", "pub_year", "id"].map((field) => [
`${entry("3")}/children/[name=${field}]`,
undefined,
]),
[`${entry("3")}/children/[name=cdate]`, "timestamp"],
[`${entry("3")}/children/[name=mdate]`, "timestamp"],
]);
expect(file.suggested).toEqual([
...["title", "authors", "publisher", "pub_year"].map((field, index) => ({
kind: "text_equals",
file: FILE,
pointer: `${entry("3")}/children/[name=${field}]`,
value: ORCHARD[index],
})),
);
{
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=collection]/children",
matching: "[name=entry]",
equals: 3,
},
]);
// The same edit saved on another day passes too.
const later = books(
book("1", LANTERN),
@@ -859,9 +1148,9 @@ describe("draftTaskFiles for records in a list, as Tellico keeps books", () => {
passing(FILE, xml(text), file.suggested),
),
).toEqual([
[false, false, false, false],
[true, true, true, true],
[true, true, true, true],
[false, false, false, false, false],
[true, true, true, true, true],
[true, true, true, true, true],
]);
});
@@ -905,11 +1194,12 @@ describe("draftTaskFiles for records in a list, as Tellico keeps books", () => {
books(book("1", LANTERN), book("2", SALT, ["06", "07"])),
);
// The field itself, not the record whose text would join its other fields.
expect(edited.suggested).toEqual([
{
kind: "value_equals",
kind: "text_equals",
file: FILE,
pointer: `${entry("2")}/children/[name=title]/children/0`,
pointer: `${entry("2")}/children/[name=title]`,
value: "Salt Road",
},
]);
+249 -90
View File
@@ -1,7 +1,6 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { collapseWhitespace, type DesktopTaskCheckInput } from "./appTask.js";
import {
isRenumberedKey,
isBookkeeping,
isBookkeepingName,
inSplitDate,
@@ -9,23 +8,21 @@ import {
isVolatileValue,
} from "./appTaskDraftNoise.js";
import { valueEqualsCheck } from "./appTaskDraftScalars.js";
import {
holdsFields,
holdsNoisyText,
wholeTextCheck,
} from "./appTaskDraftText.js";
import { holdsFields, isRecordAt, wholeTextCheck } from "./appTaskDraftText.js";
import {
isIdentifyingAttribute,
isPlaceholder,
isViewStateName,
rankAttributes,
} from "./attributeRank.js";
import { pairMembers } from "./memberPairing.js";
import {
elementText,
escapeToken,
isXmlElement,
pairMembers,
resolvePointer,
} from "./viewPointer.js";
import { selectorOf } from "./viewSelector.js";
type Suggestion = DesktopTaskCheckInput;
@@ -48,10 +45,25 @@ export interface AddedContext {
};
readonly named: (view: JsonValue | null, pointer: string) => boolean;
readonly chars: number;
/** XML views owning identifiers the seed may reference. */
readonly referenceRoots: () => readonly JsonValue[];
/** Whether a change at a pointer is noise, which no field check takes. */
readonly noisy?: (pointer: string) => boolean;
/** Fields left unchecked because their text is past `chars`. */
readonly long?: string[];
}
/** Record a field omitted because its whole value exceeds the check limit. */
export const checkFits = (
context: Pick<AddedContext, "chars" | "long">,
pointer: string,
value: string,
): boolean => {
if (value.length <= context.chars) return true;
context.long?.push(pointer);
return false;
};
type Element = Extract<JsonValue, Record<string, JsonValue>> & {
readonly name: string;
readonly children: JsonValue[];
@@ -101,6 +113,27 @@ const copiesSibling = (
);
});
/** The values of the `id`, `xmi:id` and `key` attributes of the elements in a view, outside a view the app keeps of it: what another element's attribute may refer to. */
const idsIn = (roots: readonly JsonValue[]): ReadonlySet<string> => {
const ids = new Set<string>();
const pending: JsonValue[] = [];
for (const root of roots) pending.push(root);
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
if (isXmlElement(node)) {
if (isViewStateName(node.name)) continue;
for (const [key, value] of Object.entries(node.attributes))
if (typeof value === "string" && /^(?:[^:]*:)?(?:id|key)$/iu.test(key))
ids.add(value);
for (const child of node.children) pending.push(child);
} else if (isRecord(node)) {
for (const child of Object.values(node)) pending.push(child);
} else if (Array.isArray(node)) {
for (const child of node) pending.push(child);
}
}
return ids;
};
/** The attribute keys the last segment of a pointer selects by. */
const selectorKeys = (pointer: string): ReadonlySet<string> => {
const segment = (pointer.split("/").at(-1) ?? "")
@@ -120,7 +153,9 @@ const selectorKeys = (pointer: string): ReadonlySet<string> => {
* values and view state are left out. Empty for an element with no like
* sibling at either end, or whose other attributes a like sibling holds
* every one of, as a new Planner task copies its neighbour's defaults; such
* an element keeps the check that it is there.
* an element keeps the check that it is there. An attribute naming an
* element the seed holds by an id other than a plain number, as an Umbrello
* attribute's `type` its data type, is a choice, never a default copied.
*/
export const attributeChecks = (
context: AddedContext,
@@ -143,23 +178,49 @@ export const attributeChecks = (
? [{ key, value }]
: [],
);
if (copiesSibling(context, pointer, element, own)) return [];
const eligible = own.filter(
// Copied from a sibling, only a reference to an element the seed holds by an id, not a plain number, is the user's.
let fields = own;
if (copiesSibling(context, pointer, element, own)) {
const ids = idsIn(context.referenceRoots());
fields = own.filter(
({ value }) => ids.has(value) && !/^-?\d+$/u.test(value),
);
if (fields.length === 0) return [];
}
// A record's data is in its fields; an attribute every like record holds alike, as GnuCash's `version`, is its format's.
const nested = element.children.some(isXmlElement);
const list = resolvePointer(ends.final, listOf(pointer));
const likes = (Array.isArray(list) ? list : []).filter(
(item) =>
item !== element && isXmlElement(item) && item.name === element.name,
);
const everywhere = (key: string, value: string) =>
likes.every(
(item) => isXmlElement(item) && attributesOf(item)[key] === value,
);
// A value two or more like siblings all hold, as Grisbi's `Cu="1"`, is a default: it comes after what varies.
const usual = (key: string, value: string) =>
likes.length > 1 && everywhere(key, value) ? 1 : 0;
const eligible = fields.filter(
({ key, value }) =>
!(nested && everywhere(key, value)) &&
!isPlaceholder(value) &&
!isStamp(value) &&
!isVolatileValue(
value,
isBookkeeping(element) || isBookkeepingName(key),
) &&
!isViewStateName(key) &&
!isRenumberedKey(key),
!isViewStateName(key),
);
for (const { key, value } of eligible)
if (value.length > context.chars)
context.long?.push(`${pointer}/attributes/${escapeToken(key)}`);
return rankAttributes(
eligible.filter(({ value }) => value.length <= context.chars),
eligible.filter(({ key, value }) =>
checkFits(context, `${pointer}/attributes/${escapeToken(key)}`, value),
),
)
.toSorted(
(left, right) =>
usual(left.key, left.value) - usual(right.key, right.value),
)
.slice(0, MAX_ATTRIBUTE_CHECKS)
.map(({ key, value }) =>
valueEqualsCheck(
@@ -176,48 +237,43 @@ export const attributeChecks = (
* joining them would look for text the file never contains.
*/
const keptFieldPieces = (node: JsonValue, bookkeeping = false): string[] => {
if (typeof node === "string")
return isStamp(node) || isVolatileValue(node.trim(), bookkeeping)
? []
: [node];
if (!isXmlElement(node)) return [];
const inBookkeeping = bookkeeping || isBookkeeping(node);
const pieces: string[] = [];
let run = "";
const flush = () => {
if (run !== "") pieces.push(run);
run = "";
};
for (const child of node.children) {
if (typeof child === "string") {
if (isStamp(child) || isVolatileValue(child.trim(), inBookkeeping))
const visit = (value: JsonValue, inBookkeeping: boolean): void => {
if (typeof value === "string") {
if (isStamp(value) || isVolatileValue(value.trim(), inBookkeeping))
flush();
else run += child;
continue;
else run += value;
return;
}
if (!isXmlElement(child)) continue;
if (isStamp(elementText(child))) {
if (!isXmlElement(value)) return;
if (isStamp(elementText(value))) {
flush();
continue;
return;
}
const nested = keptFieldPieces(child, inBookkeeping);
if (nested.length !== 1) {
flush();
pieces.push(...nested);
continue;
}
run += nested[0] ?? "";
}
const nestedBookkeeping = inBookkeeping || isBookkeeping(value);
for (const child of value.children) visit(child, nestedBookkeeping);
};
visit(node, bookkeeping);
flush();
return pieces;
};
/** An element's text with save-time leaves removed, in document order. */
const plainText = (node: JsonValue | null): string => {
if (typeof node === "string") return isStamp(node) ? "" : node;
const plainText = (node: JsonValue | null, bookkeeping = false): string => {
if (typeof node === "string")
return isStamp(node) || isVolatileValue(node.trim(), bookkeeping)
? ""
: node;
if (!isXmlElement(node)) return "";
if (isStamp(elementText(node))) return "";
return node.children.map((child) => plainText(child)).join("");
return node.children
.map((child) => plainText(child, bookkeeping || isBookkeeping(node)))
.join("");
};
/** The nearest ancestor both ends hold that a check names without a step by position. */
@@ -255,7 +311,10 @@ export const fieldChecks = (
element: Element,
): Suggestion[] => {
const { ends, file } = context;
if (!holdsFields(element) || likeCount(ends.final, pointer, element.name) < 2)
if (
!isRecordAt(ends.final, pointer, element) ||
likeCount(ends.final, pointer, element.name) < 2
)
return [];
const at = keptNamedAncestor(context, pointer);
if (at === undefined) return [];
@@ -271,7 +330,12 @@ export const fieldChecks = (
if (!isXmlElement(field)) return;
const key = keys[index] ?? String(index);
const fieldAt = `${pointer}/children/${key.startsWith("[") ? escapeToken(key) : key}`;
if (ID_FIELD.test(field.name) || inSplitDate(ends.final, fieldAt)) return;
if (
ID_FIELD.test(field.name) ||
inSplitDate(ends.final, fieldAt) ||
context.noisy?.(fieldAt) === true
)
return;
for (const value of keptFieldPieces(field)) {
const text = value.trim();
if (
@@ -325,66 +389,161 @@ export const fieldChecks = (
: [];
};
/** Each field's text that every like sibling at the end holds in a field of its tag, as Osmo's `<group>None</group>` on every record: a default, not what the user entered. */
const sharedFields = (
{ ends }: AddedContext,
pointer: string,
element: Element,
) => {
const list = resolvePointer(ends.final, listOf(pointer));
const likes = (Array.isArray(list) ? list : []).filter(
(item) =>
item !== element && isXmlElement(item) && item.name === element.name,
);
const fields = likes.map(
(item) =>
new Set(
(isXmlElement(item) ? item.children : []).flatMap((field) =>
isXmlElement(field)
? [`${field.name}\u0000${elementText(field)}`]
: [],
),
),
);
const [first, ...rest] = fields;
return new Set(
[...(first ?? [])].filter((field) => rest.every((own) => own.has(field))),
);
};
/** The child fields a pointer's last selector names its member by, `[>first_name=Delphine]`, as tag NUL text. */
const selectorFields = (pointer: string): ReadonlySet<string> =>
new Set(
(
selectorOf(
(pointer.split("/").at(-1) ?? "")
.replaceAll("~1", "/")
.replaceAll("~0", "~"),
) ?? []
)
.filter(({ prefix }) => prefix === ">")
.map(({ key, value }) => `${key}\u0000${value}`),
);
/**
* A check per field of a record added whole to a list that a selector names,
* as Tellico adds an `<entry id="4">` of `<title>`, `<authors>`, `<publisher>`
* and `<pub_year>`: each child element a selector names among the record's
* children, by its whole text as `wholeTextCheck` checks one, at most five;
* leaving out a field repeating the record's identifier, a date the app
* stamps in parts, and text that is blank, a time, a volatile value or past
* the limit. Empty for an element that `holdsFields` says is no record, or
* that has no like sibling.
* leaving out a field repeating the record's identifier, the field its
* selector names it by, unless no other is left, a default a like sibling
* holds too, a date the app stamps in parts, and text that is blank, a time,
* a volatile value or past the limit. Empty for an element that
* `holdsFields` says is no record, or that has no like sibling.
*/
export const recordChecks = (
context: AddedContext,
pointer: string,
element: Element,
): Suggestion[] => {
const { ends, file } = context;
const { ends } = context;
if (
!holdsFields(element) ||
!isRecordAt(ends.final, pointer, element) ||
(likeCount(ends.final, pointer, element.name) < 2 &&
likeCount(ends.baseline, pointer, element.name) === 0)
)
return [];
const { keys } = pairMembers(element.children, []).newer;
return element.children
.flatMap<Suggestion>((field, index) => {
const key = keys[index] ?? "";
const at = `${pointer}/children/${escapeToken(key)}`;
if (
!isXmlElement(field) ||
!key.startsWith("[") ||
ID_FIELD.test(field.name) ||
inSplitDate(ends.final, at) ||
!context.named(ends.final, at)
)
return [];
const value = elementText(field);
if (holdsNoisyText(field))
return keptFieldPieces(field).flatMap((piece) => {
const text = piece.trim();
return text.length < MIN_FIELD_CHARS ||
text.length > context.chars ||
!/[\p{L}\d]/u.test(text) ||
isStamp(text) ||
isVolatileValue(text, isBookkeeping(field))
? []
: [
{
kind: "text_contains" as const,
file,
pointer: at,
value: text,
},
];
});
return value.trim() === "" ||
value.length > context.chars ||
isStamp(value) ||
isVolatileValue(value, isBookkeeping(field))
? []
: [wholeTextCheck(file, at, value, undefined)];
})
.slice(0, MAX_FIELD_CHECKS);
const fields = fieldsOf(context, pointer, element, { nested: true });
// A record whose one field is the one its selector names it by, as a VYM branch its heading, is checked by that field.
return (
fields.length > 0
? fields
: fieldsOf(context, pointer, element, { nested: true, selector: true })
).slice(0, MAX_FIELD_CHECKS);
};
/** Whether an element holds an identifier of its own among its descendants, as GnuCash's `<trn:splits>` holds each split's `<split:id>`, so its whole text holds ids a later save makes anew. */
const holdsIds = (element: Element): boolean =>
element.children.some(
(child) =>
isXmlElement(child) && (ID_FIELD.test(child.name) || holdsIds(child)),
);
/** Whether a field is a list of records of one tag, as `<trn:splits>` of `<trn:split>`, whose records are checked field by field instead. */
const recordList = (field: Element): boolean => {
const records = field.children.filter(isXmlElement);
return (
records.length > 0 &&
records.every(
(record) => record.name === records[0]?.name && holdsFields(record),
)
);
};
/** The checks of a record's fields, as `recordChecks` says; a field that lists records, with `nested`, gives its records' own instead, and with `selector` the field its selector names it by is checked too. */
const fieldsOf = (
context: AddedContext,
pointer: string,
element: Element,
{ nested, selector = false }: { nested: boolean; selector?: boolean },
): Suggestion[] => {
const { ends, file } = context;
const { keys } = pairMembers(element.children, []).newer;
const skipped = new Set([
...sharedFields(context, pointer, element),
...(selector ? [] : selectorFields(pointer)),
]);
return element.children.flatMap((field, index): Suggestion[] => {
const key = keys[index] ?? "";
const at = `${pointer}/children/${escapeToken(key)}`;
if (
!isXmlElement(field) ||
!key.startsWith("[") ||
ID_FIELD.test(field.name) ||
context.noisy?.(at) === true ||
[elementText(field), collapseWhitespace(elementText(field))].some(
(text) => skipped.has(`${field.name}\u0000${text}`),
) ||
inSplitDate(ends.final, at) ||
!context.named(ends.final, at)
)
return [];
if (nested && recordList(field)) {
const records = pairMembers(field.children, []).newer.keys;
return field.children.flatMap((record, place) =>
isXmlElement(record)
? fieldsOf(
context,
`${at}/children/${escapeToken(records[place] ?? "")}`,
record,
{ nested: false },
)
: [],
);
}
const pieces = keptFieldPieces(field).filter((piece) => {
const text = piece.trim();
return (
text !== "" &&
!isStamp(text) &&
!isVolatileValue(text, isBookkeeping(field))
);
});
if (pieces.length === 0 || holdsIds(field)) return [];
// The evaluator reads the field's text as saved, including the line breaks around it.
const whole = elementText(field);
if (pieces.length === 1 && pieces[0]?.trim() === whole.trim()) {
const value = whole;
if (value.length > context.chars) {
context.long?.push(at);
return [];
}
return [wholeTextCheck(file, at, value, undefined)];
}
return pieces.flatMap((value) =>
value.length > context.chars
? []
: [{ kind: "text_contains" as const, file, pointer: at, value }],
) satisfies Suggestion[];
});
};
@@ -0,0 +1,91 @@
import type { JsonValue } from "../jsonValue.js";
import { isStamp } from "./appTaskDraftNoise.js";
import {
attributeTier,
isIdentifyingAttribute,
isPlaceholder,
isSaveNumberedId,
} from "./attributeRank.js";
import { escapeToken, isXmlElement, resolvePointer } from "./viewPointer.js";
import { selectorOf, spellCondition } from "./viewSelector.js";
/** Other pointers a value's entry lists. */
const MAX_ALTERNATIVES = 3;
const unescape = (token: string) =>
token.replaceAll("~1", "/").replaceAll("~0", "~");
/**
* The value's pointer naming its element another way, for an author to pick
* a key without another export: the innermost member a pointer selects by a
* condition, or one inside it its tag alone names, as an EPUB chapter's `h1`
* by its `id`, by each other identifier or name-like attribute it holds, as
* a shape by `draw:name` beside its `xml:id`, that names it alone among its
* list's members of its tag, at most three. Never the attribute the pointer
* reads, an id an ODF app numbers anew on each save, a time or a placeholder.
*/
export const alternativePointers = (
view: JsonValue | null,
pointer: string,
): string[] => {
const segments = pointer.split("/");
for (let index = segments.length - 1; index >= 2; index -= 1) {
const conditions =
segments[index - 1] === "children"
? selectorOf(unescape(segments[index] ?? ""))
: undefined;
if (conditions === undefined) continue;
// A step its tag alone names, as an XHTML `h1` holding `id="chapter-two"`, gives way outward when nothing else names it.
const tagOnly = conditions.every(({ prefix }) => prefix === "");
const list = resolvePointer(view, segments.slice(0, index).join("/"));
const element = resolvePointer(
view,
segments.slice(0, index + 1).join("/"),
);
if (!Array.isArray(list) || !isXmlElement(element)) {
if (tagOnly) continue;
return [];
}
const used = new Set(
conditions.flatMap(({ prefix, key }) => (prefix === "@" ? [key] : [])),
);
const reads =
segments[index + 1] === "attributes" && index + 3 === segments.length
? unescape(segments[index + 2] ?? "")
: undefined;
const alone = (key: string, value: string) =>
list.filter(
(item) =>
isXmlElement(item) &&
item.name === element.name &&
item.attributes[key] === value,
).length === 1;
const found = Object.entries(element.attributes)
.flatMap(([key, value]) =>
typeof value === "string" &&
(isIdentifyingAttribute(key) || attributeTier(key, value) === 0) &&
!used.has(key) &&
key !== reads &&
!/[=[\]]/u.test(key) &&
!value.includes("][") &&
value.trim() !== "" &&
!isStamp(value) &&
!isPlaceholder(value) &&
!isSaveNumberedId(key, value) &&
alone(key, value)
? [
[
...segments.slice(0, index),
escapeToken(
`[name=${element.name}]${spellCondition({ prefix: "@", key, value })}`,
),
...segments.slice(index + 1),
].join("/"),
]
: [],
)
.slice(0, MAX_ALTERNATIVES);
if (found.length > 0 || !tagOnly) return found;
}
return [];
};
@@ -0,0 +1,179 @@
import { describe, expect, it } from "vitest";
import { passing, pointerOf, xml, xmlDraft } from "./appTaskDraft.fixture.js";
const FILE = "Documents/doc.xml";
describe("draftTaskFiles for text an app keeps in an attribute", () => {
/** A flyer's frame as Scribus saves it: its text in `ITEXT` runs, one per run of formatting. */
const flyer = (...runs: string[]) =>
`<SCRIBUSUTF8NEW><DOCUMENT><PAGEOBJECT ANNAME="Headline" XPOS="10.5" ItemID="3"><StoryText><DefaultStyle/>${runs
.map(
(text, index) =>
`<ITEXT FONT="${index === 0 ? "Regular" : "Bold"}" CH="${text}"/>`,
)
.join(
"",
)}<para/></StoryText></PAGEOBJECT><PAGEOBJECT ANNAME="Details" XPOS="10.5" ItemID="4"><StoryText><ITEXT CH="Saturday at 7 PM"/></StoryText></PAGEOBJECT></DOCUMENT></SCRIBUSUTF8NEW>`;
const FRAME =
"/root/children/[name=DOCUMENT]/children/[name=PAGEOBJECT][@ANNAME=Headline]";
it("checks the frame's text read from its runs' CH, which holds however a later save splits them", () => {
const before = flyer("Spring ", "Fair");
const after = flyer("Summer ", "Fair");
const file = xmlDraft(before, after);
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: FRAME,
value: "Summer Fair",
text_attribute: "CH",
},
]);
expect(
[
before,
after,
flyer("Summer Fair"),
flyer("Sum", "mer ", "Fair"),
flyer("Summer ", "Fete"),
].map((text) => passing(FILE, xml(text), file.suggested)),
).toEqual([[false], [true], [true], [true], [false]]);
const checks = [...file.suggested, ...file.guards];
expect(
file.guards.some(
(guard) =>
"matching" in guard && String(guard.matching).includes("ITEXT"),
),
).toBe(false);
expect(
passing(FILE, xml(flyer("Summer Fair")), checks).every(Boolean),
).toBe(true);
expect(
passing(FILE, xml(flyer("Sum", "mer ", "Fair")), checks).every(Boolean),
).toBe(true);
});
it("does not count formatting runs when the edit splits or merges them", () => {
for (const [before, after] of [
[flyer("Spring Fair"), flyer("Summer ", "Fair")],
[flyer("Spring ", "Fair"), flyer("Summer Fair")],
] as const) {
const file = xmlDraft(before, after);
const checks = [...file.suggested, ...file.guards];
expect(
checks.some(
(check) =>
check.kind === "text_equals" && check.text_attribute === "CH",
),
).toBe(true);
expect(passing(FILE, xml(before), file.suggested).every(Boolean)).toBe(
false,
);
expect(passing(FILE, xml(after), checks).every(Boolean)).toBe(true);
expect(
passing(FILE, xml(flyer("Summer Fair")), checks).every(Boolean),
).toBe(true);
expect(
passing(FILE, xml(flyer("Sum", "mer ", "Fair")), checks).every(Boolean),
).toBe(true);
expect(
passing(FILE, xml(flyer("Summer Fete")), file.suggested).every(Boolean),
).toBe(false);
}
});
it("keeps a check of a run's formatting the text check does not read, beside it", () => {
const styled = (first: string, font: string) =>
`<SCRIBUSUTF8NEW><DOCUMENT><PAGEOBJECT ANNAME="Headline"><StoryText><ITEXT FONT="Regular" CH="${first}"/><ITEXT FONT="${font}" CH="Fair"/></StoryText></PAGEOBJECT><PAGEOBJECT ANNAME="Details"/></DOCUMENT></SCRIBUSUTF8NEW>`;
const file = xmlDraft(
styled("Spring ", "Bold"),
styled("Summer ", "Italic"),
);
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: FRAME,
value: "Summer Fair",
text_attribute: "CH",
},
{
kind: "value_equals",
file: FILE,
pointer: `${FRAME}/children/[name=StoryText]/children/[name=ITEXT][@CH=Fair]/attributes/FONT`,
value: "Italic",
},
]);
});
it("checks a mind map's node by the TEXT it holds itself, not the TEXT of the nodes in it, and names a new node by its text rather than the id the app made, a kept one by that id", () => {
const map = (packing: readonly (readonly string[])[]) =>
`<map version="freeplane 1.7.0"><node TEXT="Weekend Trip" ID="ID_1360674148"><node TEXT="Packing" ID="ID_1965352635">${packing
.map(
([text, id]) =>
`<node TEXT="${text ?? ""}" ID="${id ?? ""}" CREATED="1793955120032" MODIFIED="1793955121800"/>`,
)
.join("")}</node><node TEXT="Food" ID="ID_523079613"/></node></map>`;
// The trip, the map's one root node, holds its id as a hold against another root node.
const TRIP = "/root/children/[name=node][@ID=ID_1360674148]";
const tent = ["Tent", "ID_1749680464"];
const bags = ["Sleeping bags", "ID_1227863932"];
const renamed = xmlDraft(
map([tent, bags]),
map([["Big tent", "ID_1749680464"], bags]),
);
const added = xmlDraft(
map([tent, bags]),
map([tent, bags, ["Water filter", "ID_329023692"]]),
);
expect(renamed.suggested.map(pointerOf)).toEqual([
`${TRIP}/children/[name=node][@ID=ID_1965352635]/children/[name=node][@ID=ID_1749680464]/attributes/TEXT`,
]);
const packing = `${TRIP}/children/[name=node][@ID=ID_1965352635]/children`;
expect(added.suggested).toEqual([
{
kind: "value_equals",
file: FILE,
pointer: `${packing}/[name=node][@TEXT=Water filter]/name`,
value: "node",
},
{
kind: "member_count",
file: FILE,
pointer: packing,
matching: "[name=node]",
equals: 3,
},
]);
// Another save of the same edit gives the node another id and times.
const solved = map([tent, bags, ["Water filter", "ID_1048576333"]]);
expect(passing(FILE, xml(solved), added.suggested)).toEqual([true, true]);
});
});
describe("draftTaskFiles for a run's formatting", () => {
const flyer = (font: string) =>
`<SCRIBUSUTF8NEW><DOCUMENT><PAGEOBJECT ANNAME="Headline" XPOS="10.5" ItemID="3"><StoryText><ITEXT FONT="${font}" CH="Spring "/><ITEXT FONT="Bold" CH="Fair"/></StoryText></PAGEOBJECT><PAGEOBJECT ANNAME="Details" XPOS="10.5" ItemID="4"><StoryText><ITEXT CH="Saturday at 7 PM"/></StoryText></PAGEOBJECT></DOCUMENT></SCRIBUSUTF8NEW>`;
it("keeps a font change on the run that holds it, rather than joining every run's font into the frame's text", () => {
const file = xmlDraft(flyer("Regular"), flyer("Italic"));
expect(file.suggested).toEqual([
{
kind: "value_equals",
file: FILE,
pointer:
"/root/children/[name=DOCUMENT]/children/[name=PAGEOBJECT][@ANNAME=Headline]/children/[name=StoryText]/children/[name=ITEXT][@CH=Spring ]/attributes/FONT",
value: "Italic",
},
]);
});
});
@@ -0,0 +1,203 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import {
attributeKeyOf,
isStamp,
type NoiseReason,
} from "./appTaskDraftNoise.js";
import { isIdentifyingAttribute, isNameLikeKey } from "./attributeRank.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import {
elementText,
escapeToken,
isXmlElement,
resolvePointer,
} from "./viewPointer.js";
/** How far a text check climbs from a run to the element an attribute names. */
const MAX_CLIMB = 3;
/** A run's formatting, such as Scribus's `FONT`, not the words it holds. */
const isFormattingAttribute = (key: string) =>
/(?:font(?:name|size|family)?|face|features|colou?r|weight|size|family|style)$/iu.test(
key.split(":").at(-1) ?? key,
);
/** The element a member of `children` sits in; none for the root. */
const parentOf = (pointer: string): string | undefined =>
/^(?<parent>.+)\/children\/[^/]+$/u.exec(pointer)?.groups?.parent;
/** Whether a pointer's last step names its element by an attribute, as `[name=PAGEOBJECT][@ANNAME=Headline]`. */
const namedByAttribute = (pointer: string) =>
(pointer.split("/").at(-1) ?? "").includes("[@");
/** An element's text from its text nodes, or from an attribute's values, at a pointer in a view. */
const textAt = (
view: JsonValue | null,
pointer: string,
attribute?: string,
) => {
const element = resolvePointer(view, pointer);
return isXmlElement(element) ? elementText(element, attribute) : undefined;
};
/** Whether an element holding an attribute is a record rather than a run of text: it carries an identifier or a name, as Umbrello's `<ownedAttribute xmi:id="…" name="email" visibility="private"/>`, beside it. */
const isNamedRecord = (node: JsonValue, key: string) =>
isXmlElement(node) &&
Object.keys(node.attributes).some(
(other) =>
other !== key && (isIdentifyingAttribute(other) || isNameLikeKey(other)),
);
/**
* The elements below the element at a pointer that hold an attribute, as
* runs do: none holding another, none carrying an identifier or a name
* (`isNamedRecord`), and the element itself holding none; a Freeplane node
* and the nodes in it, each holding `TEXT`, are no runs.
*/
const runsOf = (view: JsonValue | null, pointer: string, key: string) => {
const element = resolvePointer(view, pointer);
const holds = (node: JsonValue) =>
isXmlElement(node) && typeof node.attributes[key] === "string";
let runs = 0;
const pending: { node: JsonValue; inside: boolean }[] = [
{ node: element ?? null, inside: false },
];
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
const { node, inside } = next;
if (!isXmlElement(node)) continue;
if (holds(node) && (inside || node === element || isNamedRecord(node, key)))
return undefined;
runs += holds(node) ? 1 : 0;
for (const child of node.children)
pending.push({ node: child, inside: inside || holds(node) });
}
return runs;
};
/** Whether an element keeps its text in runs of an attribute at both ends: no text nodes, and its holders runs (`runsOf`), two or more or one holding words with a space. */
const holdsRuns = (
{ ends }: AttributeTextContext,
pointer: string,
key: string,
) => {
const views = [ends.baseline, ends.final];
const runs = views.map((view) => runsOf(view, pointer, key));
return (
runs.every((count) => count !== undefined) &&
(runs.some((count) => (count ?? 0) > 1) ||
/\s/u.test(textAt(ends.final, pointer, key) ?? "")) &&
views.every((view) => textAt(view, pointer)?.trim() === "")
);
};
/** What an attribute-text check reads: a file's two ends, whether the final view decides a check at a pointer, and the longest text it compares. */
export interface AttributeTextContext {
readonly file: string;
readonly ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
};
readonly named: (pointer: string) => boolean;
readonly chars: number;
}
/**
* The check of text an app keeps in an attribute across runs, as Scribus a
* frame's in `<StoryText><ITEXT CH="Spring "/><ITEXT CH="Fair"/>`, for an
* element whose attribute `key` holds words that changed, or that was added
* or removed: a `text_equals` with `text_attribute` on the nearest ancestor
* an attribute names, within three levels and below the root, that holds no
* text nodes at either end and whose holders of the attribute are runs
* (`runsOf`), two or more, or one holding words with a space; with the
* ancestor, whose runs it covers. A formatting attribute such as `FONT`
* stays a field check on its own run. Undefined otherwise, as for a
* Freeplane node's own `TEXT`, which a check reads where it is.
*/
export const attributeTextCheck = (
context: AttributeTextContext,
owner: string,
key: string,
):
| { readonly element: string; readonly check: DesktopTaskCheckInput }
| undefined => {
const { ends } = context;
const element = [ends.final, ends.baseline]
.map((view) => resolvePointer(view, owner))
.find(isXmlElement);
const value = element?.attributes[key];
if (
isIdentifyingAttribute(key) ||
isFormattingAttribute(key) ||
typeof value !== "string" ||
!/\p{L}/u.test(value) ||
isStamp(value)
)
return undefined;
let at = parentOf(owner);
for (
let climbed = 1;
at !== undefined && !namedByAttribute(at) && climbed < MAX_CLIMB;
climbed += 1
)
at = parentOf(at);
if (at === undefined || parentOf(at) === undefined || !namedByAttribute(at))
return undefined;
const ancestor = at;
const after = textAt(ends.final, ancestor, key);
return holdsRuns(context, ancestor, key) &&
context.named(ancestor) &&
after !== undefined &&
after !== textAt(ends.baseline, ancestor, key) &&
after.length <= context.chars
? {
element: ancestor,
check: {
kind: "text_equals",
file: context.file,
pointer: ancestor,
value: after,
text_attribute: key,
},
}
: undefined;
};
/** The attributes an attribute-text check may read, by the element holding them: each that changed, and each of an element added or removed; none that is noise. */
export const textAttributes = (
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
ends: AttributeTextContext["ends"],
noise: (pointer: string) => NoiseReason | undefined,
) => {
const own = (view: JsonValue | null, pointer: string) => {
const element = resolvePointer(view, pointer);
return isXmlElement(element)
? Object.keys(element.attributes).map((key) => ({ owner: pointer, key }))
: [];
};
return [
...change.changed.flatMap((pointer) => {
const key = attributeKeyOf(pointer);
return key === undefined
? []
: [{ owner: pointer.split("/").slice(0, -2).join("/"), key }];
}),
...change.added.flatMap((pointer) => own(ends.final, pointer)),
...change.removed.flatMap((pointer) => own(ends.baseline, pointer)),
].filter(
({ owner, key }) =>
noise(`${owner}/attributes/${escapeToken(key)}`) === undefined,
);
};
/** Whether a change at a pointer, read in a view, is one an attribute-text check reads: its attribute in the checked element, or a run holding it there; another attribute or element is no part of it. */
export const readsText =
(checked: readonly { readonly element: string; readonly key: string }[]) =>
(pointer: string, view: JsonValue | null): boolean =>
checked.some(({ element, key }) => {
const run = resolvePointer(view, pointer);
return (
pointer.startsWith(`${element}/`) &&
(attributeKeyOf(pointer) === key ||
(isXmlElement(run) && typeof run.attributes[key] === "string"))
);
});
@@ -0,0 +1,151 @@
import { describe, expect, it } from "vitest";
import { passing, pointerOf, xml, xmlDraft } from "./appTaskDraft.fixture.js";
/** A flowchart as Dia saves it: boxes by id in one layer, each with its geometry and text, and a connector. */
const flowchart = (
checked: { text: string; corner: string; width: string },
{ reopened = false } = {},
) => {
const box = (id: string, text: string, corner: string, width: string) =>
`<dia:object type="Flowchart - Box" version="0" id="${id}"><dia:attribute name="obj_pos"><dia:point val="${corner}"/></dia:attribute><dia:attribute name="obj_bb"><dia:rectangle val="${corner};12.5,8.15"/></dia:attribute><dia:attribute name="elem_width"><dia:real val="${width}"/></dia:attribute><dia:attribute name="text"><dia:composite type="text"><dia:attribute name="string"><dia:string>${text}</dia:string></dia:attribute></dia:composite></dia:attribute></dia:object>`;
// Dia adds an empty layer of the same name each time it reopens and saves a diagram.
const empty = reopened
? '<dia:layer name="Background" visible="true" connectable="false"/>'
: "";
return `<dia:diagram xmlns:dia="http://www.lysator.liu.se/~alla/dia/">${empty}<dia:layer name="Background" visible="true" active="true">${[
box("O0", "#Receive order#", "6.695,1.7", "5.51"),
box("O1", checked.text, checked.corner, checked.width),
box("O2", "#Pack items#", "7.175,10.7", "4.55"),
].join(
"",
)}<dia:object type="Standard - Line" version="0" id="O3"><dia:attribute name="obj_pos"><dia:point val="9.45,3.6"/></dia:attribute></dia:object></dia:layer></dia:diagram>`;
};
const SEED = { text: "#Check stock#", corner: "6.96625,6.2", width: "4.9675" };
const END = {
text: "#Verify inventory#",
corner: "6.3725,6.2",
width: "6.155",
};
const LAYER = "/root/children/[name=dia:layer][>dia:object=#Receive order#]";
const box = (id: string) =>
`${LAYER}/children/[name=dia:object][@id=${id}]/children/[name=dia:attribute]`;
describe("draftTaskFiles for a box renamed in a diagram the app resizes", () => {
it("checks the new text, names the layer by a box's text so a reopened file's empty layer leaves it named, and notes the box's new geometry as layout", () => {
const file = xmlDraft(flowchart(SEED), flowchart(END));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: "Documents/doc.xml",
pointer: `${box("O1")}[@name=text]`,
value: "#Verify inventory#",
},
]);
expect(
file.values.map(({ pointer, note }) => [
pointer.slice(box("O1").length),
note,
]),
).toEqual([
[
"[@name=text]/children/[name=dia:composite]/children/[name=dia:attribute]/children/[name=dia:string]/children/0",
undefined,
],
["[@name=obj_pos]/children/[name=dia:point]/attributes/val", "layout"],
["[@name=obj_bb]/children/[name=dia:rectangle]/attributes/val", "layout"],
["[@name=elem_width]/children/[name=dia:real]/attributes/val", "layout"],
]);
const checks = [...file.suggested, ...file.guards];
expect(
passing("Documents/doc.xml", xml(flowchart(SEED)), file.suggested),
).toEqual([false]);
for (const end of [flowchart(END), flowchart(END, { reopened: true })])
expect(
passing("Documents/doc.xml", xml(end), checks).every(Boolean),
).toBe(true);
});
it("guards the other boxes' text before any geometry, and that no box of the kind was added or removed", () => {
const file = xmlDraft(flowchart(SEED), flowchart(END));
expect(file.guards.map(pointerOf)).toEqual([
`${box("O0")}[@name=text]`,
`${box("O2")}[@name=text]`,
`${LAYER}/children`,
]);
expect(file.guards.at(-1)).toEqual({
kind: "member_count",
file: "Documents/doc.xml",
pointer: `${LAYER}/children`,
matching: "[name=dia:object][@type=Flowchart - Box]",
equals: 3,
});
});
it("keeps geometry that changed with no text beside it as the suggestion, since moving a box may be the task", () => {
const moved = { ...SEED, corner: "8,6.2" };
const file = xmlDraft(flowchart(SEED), flowchart(moved));
expect(file.suggested.map(pointerOf)).toEqual([
`${box("O1")}[@name=obj_pos]/children/[name=dia:point]/attributes/val`,
`${box("O1")}[@name=obj_bb]/children/[name=dia:rectangle]/attributes/val`,
]);
expect(file.values.every(({ note }) => note === undefined)).toBe(true);
});
});
describe("draftTaskFiles counts of a list's members", () => {
const library = (...titles: string[]) =>
`<library>${titles.map((title) => `<book><title>${title}</title></book>`).join("")}</library>`;
it("counts the members of a list an edit added to, at the end's number, which fails at the seed", () => {
const file = xmlDraft(
library("Salt Roads"),
library("Salt Roads", "Quiet Rivers"),
);
const count = file.suggested.filter(({ kind }) => kind === "member_count");
expect(count).toEqual([
{
kind: "member_count",
file: "Documents/doc.xml",
pointer: "/root/children",
matching: "[name=book]",
equals: 2,
},
]);
expect(
passing("Documents/doc.xml", xml(library("Salt Roads")), count),
).toEqual([false]);
});
it("counts no lone member an edit added, as a style an app adds for a run", () => {
const file = xmlDraft(
"<doc><styles/><body><p>Plan</p></body></doc>",
'<doc><styles><style name="T1"/></styles><body><p>Plan</p></body></doc>',
);
expect(file.suggested.map(({ kind }) => kind)).not.toContain(
"member_count",
);
});
});
describe("draftTaskFiles count guards", () => {
it("guards no count of runs a text check reads, nor one the end does not hold", () => {
const before = "<doc><p><c>First</c><c>Second</c></p></doc>";
const after = "<doc><p><c>Changed</c><c>Second</c><c>Third</c></p></doc>";
const file = xmlDraft(before, after);
expect(file.suggested.map(({ kind }) => kind)).toEqual(["text_equals"]);
expect(file.guards.map(({ kind }) => kind)).not.toContain("member_count");
expect(
passing("Documents/doc.xml", xml(after), file.guards).every(Boolean),
).toBe(true);
});
});
+236
View File
@@ -0,0 +1,236 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { listSteps, recordOfField } from "./appTaskDraftSteps.js";
import { isXmlElement, resolvePointer } from "./viewPointer.js";
import { spellCondition } from "./viewSelector.js";
type Suggestion = DesktopTaskCheckInput;
/** Count checks a file's draft suggests, and count guards it offers. */
const MAX_COUNTS = 2;
const MAX_COUNT_GUARDS = 1;
/** A key naming what kind of element a member is, as Dia's `type="Flowchart - Box"`. */
const KIND_KEY = /^(?:[^:]*:)?(?:type|kind|shape)$/iu;
/** What counts read: a file's two ends, whether a list is decided by name and whole there, noise, and the pointers text checks cover. */
export interface CountContext {
readonly file: string;
readonly ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
};
readonly whole: (view: JsonValue | null, list: string) => boolean;
readonly noisy: (pointer: string) => boolean;
readonly covered: (pointer: string) => boolean;
readonly coveredRun: (pointer: string, view: JsonValue | null) => boolean;
}
/** A list of members of one tag a count reads, and of one kind when the members changed are (`kindOf`). */
interface Counted {
readonly list: string;
readonly tag: string;
readonly kind?: { readonly key: string; readonly value: string };
}
/** The list an element's `children` member sits in. */
const listOf = (pointer: string): string | undefined =>
/^(?<list>.+\/children)\/[^/]+$/u.exec(pointer)?.groups?.list;
/** The members of a tag, and kind, in a list, in a view. */
const membersOf = (view: JsonValue | null, { list, tag, kind }: Counted) => {
const items = resolvePointer(view, list);
return Array.isArray(items)
? items.filter(
(item) =>
isXmlElement(item) &&
item.name === tag &&
(kind === undefined || item.attributes[kind.key] === kind.value),
)
: [];
};
/** Whether the members of a tag in a list each hold a different value of a key, as Tiled's objects a free-form `type` (`well`, `door`, `gate`): a label of each, not a kind several share. */
const eachOwn = (items: JsonValue, tag: string, key: string) => {
const values = (Array.isArray(items) ? items : []).flatMap((item) =>
isXmlElement(item) && item.name === tag ? [item.attributes[key]] : [],
);
return values.length > 1 && new Set(values).size === values.length;
};
/** The attribute naming a member's kind, as Dia's `type="Flowchart - Box"`, which a selector can carry; none when `before`, its seed version, holds another, or when every member of its tag in `items`, its list, holds its own (`eachOwn`). */
const kindOf = (member: JsonValue, items: JsonValue, before?: JsonValue) => {
if (!isXmlElement(member)) return undefined;
const key = Object.keys(member.attributes).find((name) =>
KIND_KEY.test(name),
);
const value = key === undefined ? undefined : member.attributes[key];
return key === undefined ||
typeof value !== "string" ||
value.includes("][") ||
eachOwn(items, member.name, key) ||
(before !== undefined &&
(!isXmlElement(before) || before.attributes[key] !== value))
? undefined
: { key, value };
};
/** A counted list's key, by its list, tag and kind. */
const keyOf = ({ list, tag, kind }: Counted) =>
JSON.stringify([list, tag, kind?.key, kind?.value]);
/** Whether a list's element holds text of its own at either end, so its elements are runs of that text. */
const mixed = ({ ends }: CountContext, list: string) =>
[ends.baseline, ends.final].some((view) => {
const owner = resolvePointer(view, list.slice(0, -"/children".length));
return (
isXmlElement(owner) &&
owner.children.some(
(child) => typeof child === "string" && child.trim() !== "",
)
);
});
/** The selector a count matches: the tag, and the kind of the members that changed, as `[name=dia:object][@type=Flowchart - Box]`, so a member of another kind, as a connector, does not count. */
const matchingOf = ({ tag, kind }: Counted) =>
`[name=${tag}]${kind === undefined ? "" : spellCondition({ prefix: "@", ...kind })}`;
/** A count of a list's members of a tag at one end, as a `member_count` writes it, where both ends hold the list whole by name. */
const countAt = (
context: CountContext,
counted: Counted,
end: "baseline" | "final",
): Suggestion | undefined => {
const { ends, file } = context;
if (
!context.whole(ends.baseline, counted.list) ||
!context.whole(ends.final, counted.list) ||
mixed(context, counted.list)
)
return undefined;
return {
kind: "member_count",
file,
pointer: counted.list,
matching: matchingOf(counted),
equals: membersOf(ends[end], counted).length,
};
};
const depth = ({ list }: Counted) => list.split("/").length;
/**
* The innermost list holding the edited element that a pointer goes through
* by a member with like siblings at both ends, a record rather than a field
* of one (`recordOfField`), as Dia's boxes in their layer, not the
* attributes of the box, or Glade's buttons in their button box, not the
* dialog's children above them: what "nothing was added or removed" counts
* for an edit inside one.
*/
const editedList = (
{ ends }: CountContext,
pointer: string,
): Counted | undefined => {
const steps = listSteps(pointer, true);
for (const [index, step] of steps.entries()) {
const { list } = step;
const at = `${list}/${step.member}`;
const member = resolvePointer(ends.final, at);
const local = isXmlElement(member)
? (member.name.split(":").at(-1) ?? member.name)
: "";
// A formatting run, as Scribus's ITEXT or SVG's tspan, is not the frame the count guards.
if (/^(?:itext|tspan|span)$/iu.test(local)) continue;
if (
!isXmlElement(member) ||
recordOfField(ends.final, step, steps.slice(index + 1)) !== undefined
)
continue;
const kind = kindOf(
member,
resolvePointer(ends.final, list) ?? null,
resolvePointer(ends.baseline, at) ?? null,
);
const counted = { list, tag: member.name, ...(kind && { kind }) };
if (
[ends.baseline, ends.final].every(
(view) => membersOf(view, counted).length > 1,
)
)
return counted;
}
return undefined;
};
/**
* `member_count` checks and guards for a file's change. Where members were
* added or removed, a check that the list holds the end's number of members
* of their tag (`matchingOf`), which fails at the seed since that number
* changed, at most two, the shallowest first. Where members were only
* edited, a guard that the list holding the edited record (`editedList`)
* holds as many as it did, which the end holds too. Never
* for noise, runs of a text check, an element in mixed content, or a list a
* selector cannot name whole at both ends.
*/
export const draftCounts = (
context: CountContext,
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
): { readonly checks: Suggestion[]; readonly guards: Suggestion[] } => {
const { ends } = context;
const changed = new Map<string, Counted>();
const note = (pointer: string, view: JsonValue | null) => {
const list = listOf(pointer);
const value = resolvePointer(view, pointer);
// A member of an element a text check reads is a run of that text.
if (
list === undefined ||
!isXmlElement(value) ||
context.noisy(pointer) ||
context.coveredRun(pointer, view) ||
context.covered(list.slice(0, -"/children".length))
)
return;
const kind = kindOf(value, resolvePointer(view, list) ?? null);
const counted = { list, tag: value.name, ...(kind && { kind }) };
changed.set(keyOf(counted), counted);
};
for (const pointer of change.added) note(pointer, ends.final);
for (const pointer of change.removed) note(pointer, ends.baseline);
const checks = [...changed.values()]
.toSorted((left, right) => depth(left) - depth(right))
.filter((counted) => {
const [seed, end] = [ends.baseline, ends.final].map(
(view) => membersOf(view, counted).length,
);
// A lone member, as a style an app adds for a run, makes no list.
return seed !== end && Math.max(seed ?? 0, end ?? 0) > 1;
})
.flatMap((counted) => countAt(context, counted, "final") ?? [])
.slice(0, MAX_COUNTS);
const edited = new Map<string, Counted>();
for (const pointer of change.changed) {
const counted = context.noisy(pointer)
? undefined
: editedList(context, pointer);
if (
counted !== undefined &&
!context.covered(counted.list.slice(0, -"/children".length)) &&
![...changed.values()].some(
({ list, tag }) => list === counted.list && tag === counted.tag,
)
)
edited.set(keyOf(counted), counted);
}
// A guard holds at both ends: an edit that also added or removed such a member makes none.
const guards = [...edited.values()]
.toSorted((left, right) => depth(left) - depth(right))
.filter(
(counted) =>
membersOf(ends.baseline, counted).length ===
membersOf(ends.final, counted).length,
)
.flatMap((counted) => countAt(context, counted, "baseline") ?? [])
.slice(0, MAX_COUNT_GUARDS);
return { checks, guards };
};
@@ -6,7 +6,7 @@ import { draftOf, statePath, xml, xmlDraft } from "./appTaskDraft.fixture.js";
describe("draftTaskFiles notes on thin files", () => {
it("says which elements only position names when no check can name a change", () => {
const table = (last: string) =>
`<doc><row><cell>1</cell><cell>2</cell></row><row><cell>3</cell><cell>${last}</cell></row></doc>`;
`<doc><row><cell>1</cell><cell>2</cell></row><row><cell>1</cell><cell>${last}</cell></row></doc>`;
const file = xmlDraft(table("4"), table("5"));
@@ -1,4 +1,6 @@
import { isWellFormedXml, opensLikeXml } from "../xmlDocument.js";
import type { NamedFacts } from "./appTaskDraftNamed.js";
import { doctypeHasInternalSubset } from "./stateFormats.js";
/** Why a file in a draft has few or no suggested checks, one code per reason. */
export const FILE_NOTE_CODES = [
@@ -7,6 +9,8 @@ export const FILE_NOTE_CODES = [
"long_text",
"cut_view",
"unreadable_view",
"volatile_lines",
"read_as_text",
] as const;
/** One reason a drafted file's suggestions are thin, with the facts it rests on. */
@@ -102,3 +106,50 @@ export const fileNotes = (
...viewNotes(file, change),
...(facts === undefined ? [] : factNotes(file, facts)),
];
/** The text a check of whether a file opens like XML reads, enough for a declaration and a DOCTYPE. */
const OPENING_CHARS = 2048;
/** The bounded opening used to recognize a text view of an XML document. */
const textOpening = (lines: readonly string[]): string => {
let opening = "";
for (const line of lines) {
opening += `${line}\n`;
if (opening.length > OPENING_CHARS) break;
}
return opening.trimStart();
};
/** Text views can preserve XML that the structured reader cannot admit. */
export const textOpensXml = (lines: readonly string[]): boolean =>
opensLikeXml(textOpening(lines));
/**
* A note on a text file that opens like XML, with a declaration, a DOCTYPE
* or an element, and so reads as text only because it is not XML REA reads:
* its DOCTYPE has an internal subset, which can declare entities, or it is
* not well formed. Its checks compare lines, which hold attributes in the
* order the app wrote them.
*/
export const readAsTextNotes = (
file: string,
lines: readonly string[],
): FileNote[] => {
const opening = textOpening(lines);
if (!opensLikeXml(opening)) return [];
if (
!doctypeHasInternalSubset(opening) &&
isWellFormedXml(opening, { doctype: "external" })
)
return [];
const why = doctypeHasInternalSubset(opening)
? "its DOCTYPE has an internal subset, which can declare entities"
: "it is not well-formed XML";
return [
{
code: "read_as_text",
file,
message: `~/${file} opens like XML but reads as text, since ${why}, so its checks compare lines, each holding its attributes in the order the app wrote them.`,
},
];
};
+289 -15
View File
@@ -89,30 +89,37 @@ describe("draftTaskFiles guards", () => {
const frame = (name: string) =>
`/root/children/[name=DOCUMENT]/children/[name=PAGEOBJECT][@ANNAME=${name}]/children/[name=StoryText]/children/[name=ITEXT]/attributes/CH`;
it("offers the field a check reads on the nearest like siblings, at its seed value, outside the suggestions", () => {
it("offers the text a check reads on the nearest like siblings, at its seed value, outside the suggestions, and their count", () => {
const before = flyer("Riverside Jazz Night");
const after = flyer("Harbor Lights Jazz Festival");
const file = xmlDraft(before, after);
expect(file.suggested.map(pointerOf)).toEqual([frame("Headline")]);
// The logo has no text, so it guards nothing.
const frameText = (name: string, value: string) => ({
kind: "text_equals",
file: FILE,
pointer: `/root/children/[name=DOCUMENT]/children/[name=PAGEOBJECT][@ANNAME=${name}]`,
value,
text_attribute: "CH",
});
expect(file.suggested).toEqual([
frameText("Headline", "Harbor Lights Jazz Festival"),
]);
// The logo has no text, so it guards nothing but the frames' count.
expect(file.guards).toEqual([
frameText("Details", "Saturday at 7 PM"),
frameText("Footer", "Free entry"),
{
kind: "value_equals",
kind: "member_count",
file: FILE,
pointer: frame("Details"),
value: "Saturday at 7 PM",
},
{
kind: "value_equals",
file: FILE,
pointer: frame("Footer"),
value: "Free entry",
pointer: "/root/children/[name=DOCUMENT]/children",
matching: "[name=PAGEOBJECT]",
equals: 4,
},
]);
expect(passing(FILE, xml(before), file.guards)).toEqual([true, true]);
expect(passing(FILE, xml(after), file.guards)).toEqual([true, true]);
expect(passing(FILE, xml(before), file.guards)).toEqual([true, true, true]);
expect(passing(FILE, xml(after), file.guards)).toEqual([true, true, true]);
expect(frame("Headline")).toContain("[@ANNAME=Headline]");
});
it("guards no sibling whose field changed too, and a number by the cell's whole text", () => {
@@ -143,6 +150,28 @@ describe("draftTaskFiles guards", () => {
value: 174.9,
tolerance: 0.001,
},
{
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=Cells]/children",
matching: "[name=Cell]",
equals: 4,
},
]);
});
});
describe("draftTaskFiles guards of a spreadsheet's cells", () => {
it("guards the cells sharing the changed cell's row or column and value type, not a label in the next row", () => {
const sheet = (march: string) =>
`<Cells><Cell Row="1" Col="0" ValueType="60">Rent</Cell><Cell Row="1" Col="3" ValueType="40">1250</Cell><Cell Row="2" Col="0" ValueType="60">Groceries</Cell><Cell Row="2" Col="2" ValueType="40">402.15</Cell><Cell Row="2" Col="3" ValueType="40">${march}</Cell><Cell Row="3" Col="0" ValueType="60">Utilities</Cell><Cell Row="3" Col="1" ValueType="40">142.3</Cell></Cells>`;
const file = xmlDraft(sheet("376.9"), sheet("418.65"));
expect(file.guards.map(pointerOf)).toEqual([
"/root/children/[name=Cell][@Col=2]",
"/root/children/[name=Cell][@Col=3][@Row=1]",
"/root/children",
]);
});
});
@@ -170,10 +199,17 @@ describe("draftTaskFiles guards beyond a sibling's same field", () => {
pointer: `${task("Launch")}/work`,
value: "14400",
},
{
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=tasks]/children",
matching: "[name=task]",
equals: 3,
},
]);
});
it("guards no sibling paired by an id the app renumbers", () => {
it("keeps a sibling guard when its id has no proof of renumbering", () => {
const sheet = (march: string) =>
`<Cells><Cell Row="2" Col="3">${march}</Cell><Cell Row="5" Col="3" ExprID="1">=sum(C2:C4)</Cell><Cell Row="5" Col="4">=sum(D2:D4)</Cell></Cells>`;
@@ -183,7 +219,9 @@ describe("draftTaskFiles guards beyond a sibling's same field", () => {
"/root/children/[name=Cell][@Row=2]",
]);
expect(file.guards.map(pointerOf)).toEqual([
"/root/children/[name=Cell][@ExprID=1]",
"/root/children/[name=Cell][@Col=4]",
"/root/children",
]);
});
@@ -217,6 +255,242 @@ describe("draftTaskFiles guards beyond a sibling's same field", () => {
});
});
describe("draftTaskFiles guards of siblings named by the field they check", () => {
/** A Tiled map's objects, each with an id, a name and a free-form type of its own. */
const map = (well: string) =>
`<map><objectgroup id="2" name="Landmarks"><object id="1" name="${well}" type="well" x="95.9"/><object id="2" name="Blacksmith Door" type="door" x="320.1"/><object id="3" name="Harbor Gate" type="gate" x="191.8"/><object id="4" name="Player Spawn" type="spawn" x="48.6"/></objectgroup></map>`;
const OBJECTS = "/root/children/[name=objectgroup][@id=2]/children";
it("selects each sibling by its id, not the name the guard reads, and counts the objects though each holds a type of its own", () => {
const file = xmlDraft(map("Old Well"), map("Wishing Well"));
expect(file.suggested.map(pointerOf)).toEqual([
`${OBJECTS}/[name=object][@id=1]/attributes/name`,
`${OBJECTS}/[name=object][@name=Old Well]`,
]);
expect(file.guards).toEqual([
{
kind: "value_equals",
file: FILE,
pointer: `${OBJECTS}/[name=object][@id=2]/attributes/name`,
value: "Blacksmith Door",
},
{
kind: "value_equals",
file: FILE,
pointer: `${OBJECTS}/[name=object][@id=3]/attributes/name`,
value: "Harbor Gate",
},
{
kind: "member_count",
file: FILE,
pointer: OBJECTS,
matching: "[name=object]",
equals: 4,
},
]);
// Renaming the door fails its guard, which a guard selecting it by that name could not.
const renamed = map("Wishing Well").replace("Blacksmith Door", "Bakery");
expect(passing(FILE, xml(renamed), file.guards)).toEqual([
false,
true,
true,
]);
});
it("guards no attribute numbering the siblings in order, as MyPaint's `src`, which a layer added or moved renumbers", () => {
const stack = (top: string) =>
`<stack><layer name="${top}" src="data/layer-00.png" opacity="1.0"/><layer name="Sky" src="data/layer-01.png" opacity="0.8"/><layer name="Background" src="data/layer-02.png" opacity="0.5"/></stack>`;
const file = xmlDraft(stack("Layer"), stack("Sun"));
expect(file.guards.map(pointerOf)).toEqual([
"/root/children/[name=layer][@name=Sky]/attributes/opacity",
"/root/children/[name=layer][@name=Background]/attributes/opacity",
"/root/children",
]);
});
it("guards another field of a sibling no other attribute names alone", () => {
const list = (first: string) =>
`<list><item name="${first}" qty="3"/><item name="Lantern" qty="1"/><item name="Rope" qty="2"/></list>`;
const file = xmlDraft(list("Tent"), list("Tarp"));
expect(file.guards.map(pointerOf)).toEqual([
"/root/children/[name=item][@name=Lantern]/attributes/qty",
"/root/children/[name=item][@name=Rope]/attributes/qty",
"/root/children",
]);
});
});
describe("draftTaskFiles for components of a wiring diagram, as QElectroTech saves them", () => {
/** A component: its informations by name, and the texts it shows, one showing its label beside the name of that information. */
const component = (
uuid: string,
[label, shown, fn]: readonly [string, string, string],
user = "",
) =>
`<element uuid="{${uuid}}" prefix="X" x="470"><elementInformations><elementInformation name="function" show="1">${fn}</elementInformation><elementInformation name="label" show="1">${label}</elementInformation></elementInformations><dynamic_texts>${user}<dynamic_elmt_text uuid="{${uuid}-text}" text_from="ElementInfo" x="25"><text>${shown}</text><info_name>label</info_name></dynamic_elmt_text></dynamic_texts></element>`;
const TERMINALS =
'<dynamic_elmt_text uuid="{a1}" text_from="UserText" x="2"><text>A1</text></dynamic_elmt_text><dynamic_elmt_text uuid="{a2}" text_from="UserText" x="2"><text>A2</text></dynamic_elmt_text>';
const diagram = (coil: readonly [string, string, string]) =>
`<project><diagram><elements>${component("3524", ["H1", "H1", "Pump running"])}${component("1b6b", coil, TERMINALS)}${component("af99", ["S1", "S1", "Start pump"])}</elements></diagram></project>`;
const ELEMENTS =
"/root/children/[name=diagram]/children/[name=elements]/children";
const label = (uuid: string) =>
`${ELEMENTS}/[name=element][@uuid={${uuid}}]/children/[name=elementInformations]/children/[name=elementInformation][@name=label]`;
it("checks the coil's label, never the text that shows it, and guards the other components' labels rather than the coil's other fields", () => {
const file = xmlDraft(
diagram(["K1", "K1", "Pump contactor"]),
diagram(["KM1", "KM1", "Pump contactor"]),
);
expect(file.suggested).toEqual([
{ kind: "text_equals", file: FILE, pointer: label("1b6b"), value: "KM1" },
]);
expect(file.values.map(({ note }) => note ?? null)).toEqual([
null,
"upkeep",
]);
expect(file.guards).toEqual([
{ kind: "text_equals", file: FILE, pointer: label("3524"), value: "H1" },
{ kind: "text_equals", file: FILE, pointer: label("af99"), value: "S1" },
{
kind: "member_count",
file: FILE,
pointer: ELEMENTS,
matching: "[name=element]",
equals: 3,
},
]);
});
it("checks a field of a record of fields itself, not the record's text that joins its other fields in", () => {
const file = xmlDraft(
diagram(["K1", "K1", "Pump contactor"]),
diagram(["K1", "KM1", "Pump contactor"]),
);
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: `${ELEMENTS}/[name=element][@uuid={1b6b}]/children/[name=dynamic_texts]/children/[name=dynamic_elmt_text][@uuid={1b6b-text}]/children/[name=text]`,
value: "KM1",
},
]);
});
it("checks a component's shown text when only another component's label made the same change", () => {
const page = (
coil: readonly [string, string, string],
other: readonly [string, string, string],
) =>
`<project><diagram><elements>${component("3524", other)}${component("1b6b", coil, TERMINALS)}${component("af99", ["S1", "S1", "Start pump"])}</elements></diagram></project>`;
const file = xmlDraft(
page(["K1", "K1", "Pump contactor"], ["K1", "H1", "Pump running"]),
page(["K1", "KM1", "Pump contactor"], ["KM1", "H1", "Pump running"]),
);
expect(file.suggested.map(pointerOf)).toContain(
`${ELEMENTS}/[name=element][@uuid={1b6b}]/children/[name=dynamic_texts]/children/[name=dynamic_elmt_text][@uuid={1b6b-text}]/children/[name=text]`,
);
expect(
file.values.find((value) =>
value.pointer.endsWith("/children/[name=text]"),
)?.note,
).toBeUndefined();
});
});
describe("draftTaskFiles for a dialog's buttons, as Glade saves them", () => {
/** A button in a GtkBuilder child: its label and flags, then where it is packed. */
const button = (id: string, label: string, position: string) =>
`<child><object class="GtkButton" id="${id}"><property name="label">${label}</property><property name="visible">True</property><property name="can-focus">True</property></object><packing><property name="expand">True</property><property name="position">${position}</property></packing></child>`;
const dialog = (submit: string) =>
`<interface><object class="GtkDialog" id="feedback_dialog"><child internal-child="vbox"><object class="GtkBox"><child internal-child="action_area"><object class="GtkButtonBox">${button("cancel_button", "Cancel", "0")}${button("submit_button", submit, "1")}</object><packing><property name="position">0</property></packing></child><child><object class="GtkLabel" id="intro_label"><property name="label">Tell us what you think.</property></object><packing><property name="position">1</property></packing></child></object></child></object></interface>`;
const BUTTONS =
"/root/children/[name=object]/children/[name=child]/children/[name=object]/children/[name=child][@internal-child=action_area]/children/[name=object]/children";
it("selects the other button by where it is packed, not by the child text holding the label the guard reads, and counts the buttons, not the dialog's other children", () => {
const file = xmlDraft(dialog("Submit"), dialog("Send Feedback"));
expect(file.suggested.map(pointerOf)).toEqual([
`${BUTTONS}/[name=child][>packing=True1]/children/[name=object]/children/[name=property][@name=label]`,
]);
expect(file.guards).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: `${BUTTONS}/[name=child][>packing=True0]/children/[name=object]/children/[name=property][@name=label]`,
value: "Cancel",
},
{
kind: "member_count",
file: FILE,
pointer: BUTTONS,
matching: "[name=child]",
equals: 2,
},
]);
});
});
describe("draftTaskFiles for a plot's functions, as KmPlot saves them", () => {
/** A function: its colours, then its formula with a differential after it, laid out on lines of their own. */
const fn = (color: string, formula: string, flipped = false) => {
const attributes = [
`f0-color="${color}"`,
'type="cartesian"',
'f0-visible="1"',
];
return `<function ${(flipped ? attributes.toReversed() : attributes).join(" ")}>\n <equation-0 step="0.05">${formula}<differential x="0" y="1"/>\n </equation-0>\n <arg-min use="0">0</arg-min>\n <arg-max use="0">2π</arg-max>\n </function>`;
};
const plot = (h: string, flipped = false) =>
`<kmpdoc version="4">\n ${fn("#191970", "f(x) = x^2 − 4", flipped)}\n ${fn("#006400", "g(x) = 2sin(x)", flipped)}\n ${fn("#ff4500", h, flipped)}\n</kmpdoc>`;
const equation = (color: string) =>
`/root/children/[name=function][@f0-color=${color}]/children/[name=equation-0]`;
it("checks the formula by its element with the whitespace the app lays out collapsed, and guards the others, which a save writing attributes in another order passes", () => {
const file = xmlDraft(plot("h(x) = 0.5x + 1"), plot("h(x) = 2x + 1"));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: equation("#ff4500"),
value: "h(x) = 2x + 1",
normalize_whitespace: true,
},
]);
expect(file.guards.map(pointerOf)).toEqual([
equation("#006400"),
equation("#191970"),
"/root/children",
]);
const fresh = xml(plot("h(x) = 2x + 1", true));
expect(passing(FILE, fresh, file.suggested)).toEqual([true]);
expect(passing(FILE, fresh, file.guards)).toEqual([true, true, true]);
});
it("checks no formula the app only moved to an indented line of its own, whose collapsed text the seed holds, beside one the user changed", () => {
const seed = plot("h(x) = 2x + 1");
const end = plot("h(x) = 2x + 1")
.replace("g(x) = 2sin(x)", "g(x) = 3sin(x)")
.replace(
'<equation-0 step="0.05">h(x)',
'<equation-0 step="0.05">\n h(x)',
);
const file = xmlDraft(seed, end);
expect(file.suggested.map(pointerOf)).toEqual([equation("#006400")]);
expect(passing(FILE, xml(seed), file.suggested)).toEqual([false]);
});
});
describe("draftGuards on a long list", () => {
/** A ledger of 4,000 operations, each worded as `wording` says. */
const ledger = (wording: (index: number) => string) =>
+272 -72
View File
@@ -1,21 +1,31 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { collapseWhitespace, type DesktopTaskCheckInput } from "./appTask.js";
import { sameJson } from "./appTaskChecks.js";
import {
holdsSplitDate,
isRenumberedKey,
isStamp,
} from "./appTaskDraftNoise.js";
import { holdsSplitDate, isCoordinates, isStamp } from "./appTaskDraftNoise.js";
import { holdsNoisyText } from "./appTaskDraftText.js";
import { decimalOf, valueEqualsCheck } from "./appTaskDraftScalars.js";
import { isIdentifyingAttribute, rankAttributes } from "./attributeRank.js";
import {
isIdentifyingAttribute,
isNameLikeKey,
isPlaceholder,
isSaveNumberedId,
rankAttributes,
} from "./attributeRank.js";
import { holdsTagOnly, pairMembers } from "./memberPairing.js";
import {
listSteps,
recordOfField,
type ListStep,
} from "./appTaskDraftSteps.js";
import { numberedInOrder } from "./positionalKeys.js";
import {
elementText,
escapeToken,
isXmlElement,
pairMembers,
resolvePointer,
} from "./viewPointer.js";
import { selectorOf, spellCondition, type Condition } from "./viewSelector.js";
import { childConditions } from "./selectorCandidates.js";
type Suggestion = DesktopTaskCheckInput;
@@ -37,22 +47,6 @@ export interface GuardContext {
readonly chars: number;
}
/** Where a pointer steps into a list by selector, innermost first: the list, the member's segment and the rest of the pointer after it. */
const listSteps = (pointer: string) => {
const segments = pointer.split("/");
const steps: { list: string; member: string; rest: string[] }[] = [];
for (let index = segments.length - 1; index >= 2; index -= 1) {
const member = segments[index] ?? "";
if (segments[index - 1] === "children" && !/^\d+$/u.test(member))
steps.push({
list: segments.slice(0, index).join("/"),
member,
rest: segments.slice(index + 1),
});
}
return steps;
};
/** The guard at a sibling's pointer, when it holds the same value at both ends, by name, and is no noise. */
const guardAt = (
context: GuardContext,
@@ -93,16 +87,31 @@ const guardAt = (
}
if (check.kind === "text_equals") {
if (!isXmlElement(before) || !isXmlElement(after)) return undefined;
const value = elementText(before);
const attribute = check.text_attribute;
// A check comparing collapsed whitespace has guards that do too.
const collapsed = check.normalize_whitespace === true;
const read = (element: JsonValue) => {
const text = elementText(element, attribute);
return collapsed ? collapseWhitespace(text) : text;
};
const value = read(before);
return value.trim() !== "" &&
value === elementText(after) &&
value === read(after) &&
value.length <= context.chars &&
!holdsNoisyText(before) &&
!holdsNoisyText(after) &&
!holdsSplitDate(ends.baseline, pointer) &&
!holdsSplitDate(ends.final, pointer) &&
(attribute !== undefined ||
(!holdsNoisyText(before) &&
!holdsNoisyText(after) &&
!holdsSplitDate(ends.baseline, pointer) &&
!holdsSplitDate(ends.final, pointer))) &&
!isStamp(value)
? { kind: "text_equals", file, pointer, value }
? {
kind: "text_equals",
file,
pointer,
value,
...(attribute === undefined ? {} : { text_attribute: attribute }),
...(collapsed ? { normalize_whitespace: true } : {}),
}
: undefined;
}
return typeof before !== "object" &&
@@ -113,19 +122,46 @@ const guardAt = (
: undefined;
};
/** Whether a selector key keys a member by a value the app renumbers, as Gnumeric's `[@ExprID=2]`. */
const renumberedKey = (key: string) =>
[...key.matchAll(/\[@(?<attribute>[^=\]]+)=/gu)].some(({ groups }) =>
isRenumberedKey(groups?.attribute ?? ""),
);
/** A like sibling of a checked member: its pointer by the selector it pairs by at both ends, and its element at the seed. */
interface Sibling {
readonly member: string;
readonly element: Record<string, JsonValue>;
}
/** The like siblings of the member a step goes through, nearest first, each paired by a selector, not by position or a renumbered id, and every like member at the seed. */
/**
* How many of the attributes placing a member a sibling holds alike: those
* its selector names it by and those naming its type, among those whose
* values vary across the like members, as a spreadsheet cell shares its
* `Row` or `Col` and its `ValueType` with the cells beside it in its row or
* column, and nothing with a label in another row.
*/
const sharing = (
member: Record<string, JsonValue>,
likes: readonly JsonValue[],
key: string,
) => {
const own = attributesOf(member);
const selected = new Set(
(selectorOf(key.replaceAll("~1", "/").replaceAll("~0", "~")) ?? []).map(
({ key: name }) => name,
),
);
const varying = Object.keys(own).filter(
(key) =>
(selected.has(key) || /type$/iu.test(key)) &&
new Set(
[member, ...likes].map((item) =>
isXmlElement(item) ? item.attributes[key] : undefined,
),
).size > 1,
);
return (item: JsonValue) =>
isXmlElement(item)
? varying.filter((key) => item.attributes[key] === own[key]).length
: 0;
};
/** The like siblings of the member a step goes through, those sharing most of its attributes (`sharing`) and then the nearest first, each paired by a selector, not by position or a renumbered id, and every like member at the seed. */
const siblingsOf = (
context: GuardContext,
step: ReturnType<typeof listSteps>[number],
@@ -144,17 +180,23 @@ const siblingsOf = (
.filter(
({ item, index }) =>
index !== at && isXmlElement(item) && item.name === member.name,
)
.toSorted(
(left, right) =>
Math.abs(left.index - at) - Math.abs(right.index - at) ||
left.index - right.index,
);
const shares = sharing(
member,
likes.map(({ item }) => item),
step.member,
);
likes.sort(
(left, right) =>
shares(right.item) - shares(left.item) ||
Math.abs(left.index - at) - Math.abs(right.index - at) ||
left.index - right.index,
);
const all = older.filter(
(item) => isXmlElement(item) && item.name === member.name,
);
if (likes.length === 0) return { siblings: [], all };
const pairing = pairMembers(newer, older);
const pairing = pairMembers(newer, older, holdsTagOnly(step.list));
return {
siblings: likes.flatMap(({ index }) => {
const key = pairing.newer.keys[index];
@@ -162,7 +204,6 @@ const siblingsOf = (
const element = partner === undefined ? undefined : older[partner];
return key === undefined ||
/^\d+$/u.test(key) ||
renumberedKey(key) ||
partner === undefined ||
pairing.older.keys[partner] !== key ||
!isXmlElement(element)
@@ -180,6 +221,105 @@ const attributesOf = ({ attributes }: Record<string, JsonValue>) =>
? attributes
: {};
/** The conditions a sibling's segment selects it by, `@` attributes and `>` children's text. */
const conditionsOf = (member: string) =>
selectorOf(member.replaceAll("~1", "/").replaceAll("~0", "~")) ?? [];
/** The attribute a path into a member reads, as `name` for `attributes/name`. */
const attributeRead = (rest: readonly string[]) =>
rest.length === 2 && rest[0] === "attributes"
? (rest[1] ?? "").replaceAll("~1", "/").replaceAll("~0", "~")
: undefined;
/** What a guard at a path into a sibling reads at the seed: an attribute's value, or an element's whole text, trimmed. */
const readAt = (sibling: Sibling, rest: readonly string[]) => {
const value =
rest.length === 0
? sibling.element
: resolvePointer(sibling.element, `/${rest.join("/")}`);
return (
isXmlElement(value)
? elementText(value)
: typeof value === "string"
? value
: ""
).trim();
};
/**
* Whether a condition selects a sibling by what a guard reads, so the guard
* proves only that such a member exists: the attribute it reads, as Tiled's
* `[@name=Blacksmith Door]` for its `name`, or a value that is or holds the
* text it reads, as Glade's `[>object=CancelTrueTrueTrue]` for a button's
* `Cancel` label.
*/
const selectsByRead = (
condition: Condition,
read: string | undefined,
text: string,
) =>
condition.prefix !== "" &&
((condition.prefix === "@" && condition.key === read) ||
condition.value === text ||
(text.length >= 3 &&
/\p{L}/u.test(text) &&
condition.value.includes(text)));
/** Whether a guard at a path into a sibling reads what the sibling is selected by (`selectsByRead`). */
const readsSelector = (sibling: Sibling, rest: readonly string[]) => {
const [read, text] = [attributeRead(rest), readAt(sibling, rest)];
return conditionsOf(sibling.member).some((condition) =>
selectsByRead(condition, read, text),
);
};
/**
* The sibling selected by another condition than what a guard reads
* (`selectsByRead`), as Tiled's door by `[@id=2]` rather than the `name` the
* guard checks, or Glade's Cancel button by `[>packing=TrueTrue0]` rather
* than the child holding its label: an identifier, a name-like attribute,
* then a child's text, naming the sibling alone at both ends; undefined
* when none does.
*/
const rekeyed = (
context: GuardContext,
step: ListStep,
sibling: Sibling,
): Sibling | undefined => {
const { element } = sibling;
const tag = typeof element.name === "string" ? element.name : "";
const [read, text] = [attributeRead(step.rest), readAt(sibling, step.rest)];
const attributes = Object.entries(attributesOf(element)).flatMap(
([key, value]) =>
typeof value === "string" &&
(isIdentifyingAttribute(key) || isNameLikeKey(key)) &&
!/[=[\]]/u.test(key) &&
!value.includes("][") &&
!isStamp(value) &&
!isPlaceholder(value) &&
!isSaveNumberedId(key, value)
? [{ prefix: "@" as const, key, value }]
: [],
);
const candidates = [
...attributes.filter(({ key }) => isIdentifyingAttribute(key)),
...attributes.filter(({ key }) => !isIdentifyingAttribute(key)),
...childConditions(element).flatMap((spelled) => selectorOf(spelled) ?? []),
].filter((condition) => !selectsByRead(condition, read, text));
const at = (member: string, view: JsonValue | null) =>
resolvePointer(view, `${step.list}/${member}`);
const end = at(sibling.member, context.ends.final);
for (const condition of candidates) {
const member = escapeToken(`[name=${tag}]${spellCondition(condition)}`);
if (
at(member, context.ends.baseline) === element &&
at(member, context.ends.final) === end
)
return { member, element };
}
return undefined;
};
/** Whether like members at the seed hold more than one value at a path into them, as Planner's `work` does and its shared `type="normal"` does not; each path read once. */
const variesAmong = (all: readonly JsonValue[]) => {
const known = new Map<string, boolean>();
@@ -199,16 +339,27 @@ const variesAmong = (all: readonly JsonValue[]) => {
/**
* The path into a sibling a guard reads: the check's own field where like
* members hold different values in it; otherwise, as for a tag or a default
* every sibling shares, the sibling's best ranked attribute that varies, one
* a user sets, as Planner's `work`; the check's own field when none does.
* members hold different values in it and the sibling's selector does not
* name it; otherwise, as for a tag or a default every sibling shares, the
* sibling's best ranked attribute that varies, one a user sets, as Planner's
* `work`, and not one numbering the members in order, as MyPaint's `src`;
* the check's own field when none does, unless the selector names it,
* as a guard of the `name` it selects the sibling by proves only that such a
* member exists.
*/
const guardField = (
sibling: Sibling,
varies: (rest: readonly string[]) => boolean,
{
all,
varies,
}: {
readonly all: readonly JsonValue[];
readonly varies: (rest: readonly string[]) => boolean;
},
rest: readonly string[],
) => {
if (rest.length > 0 && varies(rest)) return rest;
const own = !readsSelector(sibling, rest);
if (rest.length > 0 && varies(rest) && own) return rest;
const selected = new Set(
[...sibling.member.matchAll(/\[@(?<key>[^=\]]+)=/gu)].map(
({ groups }) => groups?.key ?? "",
@@ -219,35 +370,81 @@ const guardField = (
typeof value === "string" &&
!selected.has(key) &&
!isIdentifyingAttribute(key) &&
!isRenumberedKey(key) &&
!isStamp(value) &&
!numberedInOrder(all, String(sibling.element.name), key) &&
varies(["attributes", escapeToken(key)])
? [{ key, value }]
: [],
),
);
return best === undefined ? rest : ["attributes", escapeToken(best.key)];
if (best !== undefined) return ["attributes", escapeToken(best.key)];
return own ? rest : undefined;
};
/** Up to two guards for one check: a field on the 16 nearest like siblings of the innermost list it goes through that has any, preferring one that varies among them. */
/** The guard a check gives on one like sibling: its field (`guardField`), with the sibling selected by another identifier where its selector names what the guard reads (`rekeyed`). */
const siblingGuard = (
context: GuardContext,
check: Suggestion,
place: {
readonly step: ReturnType<typeof listSteps>[number];
readonly all: readonly JsonValue[];
readonly varies: (rest: readonly string[]) => boolean;
},
selected: Sibling,
): Suggestion | undefined => {
const { step, all, varies } = place;
const sibling = readsSelector(selected, step.rest)
? (rekeyed(context, step, selected) ?? selected)
: selected;
const field =
check.kind === "value_equals" &&
"tolerance" in check &&
step.rest.length === 0
? []
: check.kind === "text_equals"
? step.rest
: guardField(sibling, { all, varies }, step.rest);
// A guard reading what its sibling is selected by says no more than that the member exists.
return field === undefined || readsSelector(sibling, field)
? undefined
: guardAt(context, check, [step.list, sibling.member, ...field].join("/"));
};
type Step = ListStep;
/**
* A check's list steps in the order guards try them: innermost first, but
* for a field, first the record it is a field of (`recordOfField`), so the
* other components' labels guard a component's label rather than its other
* fields.
*/
const guardSteps = (context: GuardContext, pointer: string): Step[] => {
const steps = listSteps(pointer);
return steps.flatMap((step, index) => {
const outer = recordOfField(
context.ends.final,
step,
steps.slice(index + 1),
);
return outer === undefined ? [step] : [outer, step];
});
};
/** Up to two guards for one check: a field on the `MAX_SIBLINGS_READ` nearest like siblings of the innermost list it goes through that has any, a record's before its other fields (`guardSteps`), preferring one that varies among them, stopping once it has two. */
const guardsFor = (context: GuardContext, check: Suggestion): Suggestion[] => {
if (check.kind !== "value_equals" && check.kind !== "text_equals") return [];
for (const step of listSteps(check.pointer)) {
for (const step of guardSteps(context, check.pointer)) {
const { siblings, all } = siblingsOf(context, step);
const varies = variesAmong(all);
const guards: Suggestion[] = [];
for (const sibling of siblings.slice(0, MAX_SIBLINGS_READ)) {
if (guards.length === MAX_GUARDS_PER_CHECK) break;
const field =
check.kind === "value_equals" &&
"tolerance" in check &&
step.rest.length === 0
? []
: check.kind === "value_equals"
? guardField(sibling, varies, step.rest)
: step.rest;
const pointer = [step.list, sibling.member, ...field].join("/");
const guard = guardAt(context, check, pointer);
const guard = siblingGuard(
context,
check,
{ step, all, varies },
sibling,
);
if (guard !== undefined) guards.push(guard);
}
if (guards.length > 0) return guards;
@@ -262,7 +459,7 @@ const guardsFor = (context: GuardContext, check: Suggestion): Suggestion[] => {
* seed value, which the end holds too: the
* field the check reads where it varies among them, otherwise one that does;
* never through a sibling paired by position or a renumbered id; at most
* `MAX_GUARDS` a file, none at a suggested pointer.
* `MAX_GUARDS` a file, none at a suggested pointer, coordinates last.
*/
export const draftGuards = (
context: GuardContext,
@@ -271,18 +468,21 @@ export const draftGuards = (
const taken = new Set(
suggested.flatMap((check) => ("pointer" in check ? [check.pointer] : [])),
);
// A coordinate an app may derive says less that the rest stayed than text does.
const placed = (guard: Suggestion) =>
"value" in guard && isCoordinates(guard.value) ? 1 : 0;
const guards: Suggestion[] = [];
for (const check of suggested) {
if (guards.length === MAX_GUARDS) break;
// Later checks' guards sort after these, so four that are no coordinate settle the file's.
if (guards.filter((guard) => placed(guard) === 0).length >= MAX_GUARDS)
break;
for (const guard of guardsFor(context, check))
if (
guards.length < MAX_GUARDS &&
"pointer" in guard &&
!taken.has(guard.pointer)
) {
if ("pointer" in guard && !taken.has(guard.pointer)) {
taken.add(guard.pointer);
guards.push(guard);
}
}
return guards;
return guards
.toSorted((left, right) => placed(left) - placed(right))
.slice(0, MAX_GUARDS);
};
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import { passing, pointerOf, xml, xmlDraft } from "./appTaskDraft.fixture.js";
const FILE = "Documents/doc.xml";
/** A notebook page as Xournal++ saves it: a rendered preview, and notes each placed on the layer by its own position. */
const notebook = (preview: string, ...notes: (readonly [string, string])[]) =>
`<xournal><preview>${preview}</preview><page><layer>${notes
.map(
([y, text]) =>
`<text font="Sans" size="12" x="88.28578" y="${y}" color="#000000ff">${text}</text>`,
)
.join("")}</layer></page></xournal>`;
const NOTES = [
["60.6", "Cell Biology - Week 3"],
["84.6", "Mitochondria make ATP"],
["108.5", "Ribosomes build proteins"],
] as const;
const PNG = (tail: string) =>
`iVBORw0KGgoAAAANSUhEUgAAAFsAAACACAIAAADrrYIi${tail}`;
const LAYER = "/root/children/[name=page]/children/[name=layer]";
describe("draftTaskFiles for items placed by their own position", () => {
it("checks a note added to a layer by its text and the notes' count, guards each kept note, and leaves the rendered preview out", () => {
const before = notebook(PNG("AAAA"), ...NOTES);
const after = notebook(PNG("BBBB"), ...NOTES, [
"156.5",
"Quiz on Friday: bring a calculator",
]);
const file = xmlDraft(before, after);
expect(file.suggested).toEqual([
{
kind: "text_contains",
file: FILE,
pointer: LAYER,
value: "Quiz on Friday: bring a calculator",
},
{
kind: "member_count",
file: FILE,
pointer: `${LAYER}/children`,
matching: "[name=text]",
equals: 4,
},
]);
expect(file.guards).toEqual(
NOTES.map(([, value]) => ({
kind: "text_contains",
file: FILE,
pointer: LAYER,
value,
})),
);
expect(
file.values.find(({ pointer }) => pointer.includes("[name=preview]"))
?.note,
).toBe("view_state");
// Another user places the note elsewhere, and the app renders another preview.
const elsewhere = notebook(
PNG("CCCC"),
["300.2", "Quiz on Friday: bring a calculator"],
...NOTES,
);
expect(
passing(FILE, xml(elsewhere), [...file.suggested, ...file.guards]).every(
Boolean,
),
).toBe(true);
expect(passing(FILE, xml(before), file.suggested)).toEqual([false, false]);
expect(file.suggested.map(pointerOf)).not.toContain(
"/root/children/[name=preview]",
);
});
it("checks a text whose runs carry x and y by the text, not as notes placed on the page", () => {
const poster = (headline: string) =>
`<svg><text id="title" x="10" y="20"><tspan x="10" y="20">${headline}</tspan><tspan x="10" y="40">Saturday</tspan></text></svg>`;
const file = xmlDraft(poster("Spring Fair"), poster("Summer Fair"));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer:
"/root/children/[name=text][@id=title]/children/[name=tspan][@y=20]",
value: "Summer Fair",
},
]);
expect(passing(FILE, xml(poster("Spring Fair")), file.suggested)).toEqual([
false,
]);
expect(passing(FILE, xml(poster("Summer Fair")), file.suggested)).toEqual([
true,
]);
});
});
+139
View File
@@ -0,0 +1,139 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { isStamp } from "./appTaskDraftNoise.js";
import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js";
/** The fewest characters of an item's text a check looks for, and the kept items a draft guards. */
const MIN_TEXT = 3;
const MAX_KEPT = 4;
/** The list a member sits in, and the element holding it. */
const placeOf = (pointer: string) =>
/^(?<owner>.+)\/children\/[^/]+$/u.exec(pointer)?.groups?.owner;
const NUMBER = /^-?\d+(?:\.\d+)?$/u;
/** Whether an element holds a position of its own, numeric `x` and `y`. */
const placed = (element: JsonValue | undefined) =>
isXmlElement(element) &&
["x", "y"].every((key) => NUMBER.test(String(element.attributes[key] ?? "")));
/** A run of a text element. Its `x` and `y` place that run; they do not make it a note of its own. */
const TEXT_RUN = /^(?:tspan|span)$/iu;
/**
* Whether the element at a pointer is an item placed by its own position, as
* Xournal++ places each `<text x="88.3" y="156.5">` note on a layer: it and a
* like sibling hold numeric `x` and `y`. Each is then an item of its own,
* however its tag names text, and never a run of the others' text.
*/
export const isPlacedItem = (
view: JsonValue | null,
pointer: string,
): boolean => {
const element = resolvePointer(view, pointer);
const local = isXmlElement(element)
? (element.name.split(":").at(-1) ?? element.name)
: "";
if (TEXT_RUN.test(local)) return false;
const owner = placeOf(pointer);
const list =
owner === undefined ? undefined : resolvePointer(view, `${owner}/children`);
return (
isXmlElement(element) &&
placed(element) &&
Array.isArray(list) &&
list.some(
(item) =>
item !== element &&
isXmlElement(item) &&
item.name === element.name &&
placed(item),
)
);
};
/** What an item's check reads: a file's two ends, the pointer a check names an element by, and the longest text it compares. */
export interface ItemContext {
readonly file: string;
readonly ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
};
readonly name: (pointer: string) => string | undefined;
readonly chars: number;
}
/** The texts of the other members of a tag in a list, in a view, with their places. */
const siblingTexts = (
view: JsonValue | null,
owner: string,
item: JsonValue & { readonly name: string },
) => {
const list = resolvePointer(view, `${owner}/children`);
return (Array.isArray(list) ? list : []).flatMap((sibling, index) =>
sibling !== item && isXmlElement(sibling) && sibling.name === item.name
? [{ text: elementText(sibling).trim(), index }]
: [],
);
};
/**
* The check of an item placed by its own position and added whole: a
* `text_contains` of its text on the element holding the items, which holds
* wherever the user places it, and guards of the text of up to four items
* both ends hold, nearest first; undefined when that element is no check's,
* or the text is short, a time, past the limit, or there at the seed.
*/
export const placedItemCheck = (
context: ItemContext,
pointer: string,
):
| {
readonly element: string;
readonly check: DesktopTaskCheckInput;
readonly guards: readonly DesktopTaskCheckInput[];
}
| undefined => {
const { ends, file } = context;
const owner = placeOf(pointer);
const at = owner === undefined ? undefined : context.name(owner);
const item = resolvePointer(ends.final, pointer);
const value = isXmlElement(item) ? elementText(item).trim() : "";
const seed = at === undefined ? undefined : resolvePointer(ends.baseline, at);
if (
owner === undefined ||
at === undefined ||
!isXmlElement(item) ||
!isXmlElement(seed) ||
value.length < MIN_TEXT ||
value.length > context.chars ||
isStamp(value) ||
elementText(seed).includes(value)
)
return undefined;
const kept = new Set(
siblingTexts(ends.baseline, owner, item).map(({ text }) => text),
);
const list = resolvePointer(ends.final, `${owner}/children`);
const here = Array.isArray(list) ? list.indexOf(item) : 0;
const guards = siblingTexts(ends.final, owner, item)
.filter(({ text }) => text.length >= MIN_TEXT && kept.has(text))
.toSorted(
(left, right) =>
Math.abs(left.index - here) - Math.abs(right.index - here),
)
.slice(0, MAX_KEPT)
.toSorted((left, right) => left.index - right.index)
.map(({ text }) => ({
kind: "text_contains" as const,
file,
pointer: at,
value: text,
}));
return {
element: pointer,
check: { kind: "text_contains", file, pointer: at, value },
guards,
};
};
+266
View File
@@ -0,0 +1,266 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { draftOf, pointerOf, statePath } from "./appTaskDraft.fixture.js";
import { evaluateTaskChecks, type TaskFileView } from "./appTaskChecks.js";
import { jsonCounts } from "./appTaskDraftJson.js";
import { pairRecordsById } from "./jsonRecordPairing.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
const FILE = "Documents/reading-list.trln";
/** A TreeLine outline: nodes saved sorted by their generated uid1, each with its kind (`format`), data and children's uids. */
const outline = (
books: readonly (readonly [string, string])[],
title = "The Guns of August",
) => {
const history = {
children: books.map(([uid]) => uid),
data: { NAME: "History" },
format: "CATEGORY",
uid: "7584d494d9f511f1a873edd4f1920549",
};
const nodes = [
history,
...books.map(([uid, name]) => ({
children: [],
data: { Title: name === "Guns" ? title : name, Year: "2015" },
format: "BOOK",
uid,
})),
].toSorted((left, right) => (left.uid < right.uid ? -1 : 1));
return { nodes } as unknown as JsonValue;
};
const GUNS = ["812403bed9f511f19fc4edd4f1920549", "Guns"] as const;
const SPQR = ["84f27625d9f511f188ededd4f1920549", "SPQR"] as const;
const drafted = (before: JsonValue, after: JsonValue) => {
const [file] = draftOf({
[FILE]: statePath("document", "json", before, after),
});
if (file === undefined) throw new Error("the file did not change");
return file;
};
const passing = (view: JsonValue, checks: readonly DesktopTaskCheckInput[]) =>
evaluateTaskChecks(
checks.map((check, index) => ({ ...check, id: `c${String(index)}` })),
new Map([[FILE, { format: "json" as const, view }]]),
).map(({ passed }) => passed);
describe("draftTaskFiles for records in a JSON array, as TreeLine saves its nodes", () => {
it("names a kept record by its uid, so the edit's check holds in whatever order the app saves the records, and guards their count", () => {
const file = drafted(
outline([GUNS, SPQR]),
outline([GUNS, SPQR], "The Guns of August, revised"),
);
const guns = "/nodes/[uid=812403bed9f511f19fc4edd4f1920549]";
expect(file.suggested).toEqual([
{
kind: "value_equals",
file: FILE,
pointer: `${guns}/data/Title`,
value: "The Guns of August, revised",
},
]);
expect(file.guards).toEqual([
{ kind: "member_count", file: FILE, pointer: "/nodes", equals: 3 },
]);
// Another save lists the records in another order.
const reordered = outline([SPQR, GUNS], "The Guns of August, revised");
expect(passing(reordered, file.suggested)).toEqual([true]);
});
it("counts the records a new one joins, of its kind, never suggests the uid the app generated, and notes the checks only position reaches", () => {
const book = [
"fc11808dd9f511f181b7edd4f1920549",
"The Silk Roads",
] as const;
const file = drafted(outline([GUNS, SPQR]), outline([GUNS, SPQR, book]));
expect(
file.suggested.filter(({ kind }) => kind === "member_count"),
).toEqual([
{
kind: "member_count",
file: FILE,
pointer: "/nodes",
matching: "[format=BOOK]",
equals: 3,
},
{
kind: "member_count",
file: FILE,
pointer: "/nodes/[uid=7584d494d9f511f1a873edd4f1920549]/children",
equals: 3,
},
]);
expect(
file.suggested.some(
(check) => "value" in check && check.value === book[0],
),
).toBe(false);
const positional = file.suggested
.map(pointerOf)
.filter((pointer) => pointer?.startsWith("/nodes/3"));
expect(positional).toContain("/nodes/3/data/Title");
expect(file.notes).toMatchObject([
{ code: "by_position", pointers: expect.arrayContaining(positional) },
]);
});
it("checks nothing the seed already holds, nor a removed record's place another record takes, when position alone reaches the records", () => {
const seed = outline([GUNS, SPQR]);
// A uid sorting between the others puts the new book where SPQR was.
const middle = ["830000aad9f511f19fc4edd4f1920549", "Silk"] as const;
const added = drafted(seed, outline([GUNS, middle, SPQR]));
const removed = drafted(outline([GUNS, middle, SPQR]), seed);
for (const [file, before, after] of [
[added, seed, outline([GUNS, middle, SPQR])],
[removed, outline([GUNS, middle, SPQR]), seed],
] as const) {
expect(file.suggested.length).toBeGreaterThan(0);
expect(passing(before, file.suggested).filter(Boolean)).toEqual([]);
expect(passing(after, file.suggested).every(Boolean)).toBe(true);
}
expect(added.suggested.map(pointerOf)).not.toContain("/nodes/2/format");
expect(
removed.suggested
.map(pointerOf)
.filter((pointer) => pointer?.startsWith("/nodes/2")),
).toEqual([]);
});
});
describe("draftTaskFiles for records a JSON array names by a field", () => {
const board = (lists: readonly string[]) =>
({
lists: lists.map((id) => ({
id,
title: `${id[0]?.toUpperCase() ?? ""}${id.slice(1)}`,
done: false,
})),
}) as unknown as JsonValue;
it("checks a removed record is gone by its own selector, which the end resolves to nothing, never its fields through it", () => {
const seed = board(["groceries", "chores", "work"]);
const end = board(["groceries", "work"]);
const file = drafted(seed, end);
expect(file.suggested).toEqual([
{ kind: "value_absent", file: FILE, pointer: "/lists/[id=chores]" },
{ kind: "member_count", file: FILE, pointer: "/lists", equals: 2 },
]);
expect(passing(seed, file.suggested)).toEqual([false, false]);
expect(passing(end, file.suggested)).toEqual([true, true]);
});
});
describe("jsonCounts over many edited records", () => {
it("reads the edits only until one gives the count guard, not every edited record", () => {
const rows = (bump: number) =>
({
rows: Array.from({ length: 1000 }, (_, index) => ({
name: `r${String(index)}`,
n: index + bump,
})),
}) as unknown as JsonValue;
let read = 0;
const changed = new Proxy(
Array.from(
{ length: 1000 },
(_, index) => `/rows/[name=r${String(index)}]/n`,
),
{
get: (target, key, receiver) => {
if (typeof key === "string" && /^\d+$/u.test(key)) read += 1;
return Reflect.get(target, key, receiver) as unknown;
},
},
);
const { guards } = jsonCounts(
FILE,
{ added: [], changed, removed: [] },
{ baseline: rows(0), final: rows(1) },
);
expect(guards).toEqual([
{ kind: "member_count", file: FILE, pointer: "/rows", equals: 1000 },
]);
expect(read).toBe(1);
});
it("does not count a JSON array that was removed, and counts a top-level array", () => {
const removed = drafted({ items: ["a", "b"] }, {});
expect(
removed.suggested.some(
(check) => check.kind === "member_count" && check.equals === 0,
),
).toBe(false);
const added = drafted(
[
{ uid: "a", name: "Ada" },
{ uid: "b", name: "Lin" },
],
[
{ uid: "a", name: "Ada" },
{ uid: "b", name: "Lin" },
{ uid: "c", name: "Kai" },
],
);
expect(added.suggested).toContainEqual({
kind: "member_count",
file: FILE,
pointer: "",
equals: 3,
});
const graded = (view: TaskFileView["view"]) =>
evaluateTaskChecks(
added.suggested.map((check, index) => ({
...check,
id: `c${String(index)}`,
})),
new Map([[FILE, { format: "json", view }]]),
).map(({ passed }) => passed);
expect(
graded([
{ uid: "a", name: "Ada" },
{ uid: "b", name: "Lin" },
]),
).toContain(false);
expect(
graded([
{ uid: "a", name: "Ada" },
{ uid: "b", name: "Lin" },
{ uid: "c", name: "Kai" },
]).every(Boolean),
).toBe(true);
});
it("pairs records by uid when parent_id also names each", () => {
const before = [
{ parent_id: "root", uid: "a", name: "Ada" },
{ parent_id: "root", uid: "b", name: "Lin" },
];
const after = [
{ parent_id: "moved", uid: "a", name: "Ada" },
{ parent_id: "root", uid: "b", name: "Lin" },
];
const paired = pairRecordsById(after, before);
expect(paired?.newer.keys).toEqual(["[uid=a]", "[uid=b]"]);
});
it("does not pair records through a field whose name is a selector mark", () => {
const records = (name: string) => [
{ "@record_id": "one", name },
{ "@record_id": "two", name: "Lin" },
];
expect(
pairRecordsById(records("Ada Lane"), records("Ada")),
).toBeUndefined();
});
});
+203
View File
@@ -0,0 +1,203 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import type { FileNote } from "./appTaskDraftFileNotes.js";
import { sameJson } from "./appTaskChecks.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { locatePointer, resolvePointer } from "./viewPointer.js";
import { spellCondition } from "./viewSelector.js";
type Suggestion = DesktopTaskCheckInput;
/** Count checks a JSON file's draft suggests, and count guards it offers. */
const MAX_COUNTS = 2;
const MAX_COUNT_GUARDS = 1;
/** Pointers a note lists. */
const MAX_LISTED = 5;
/** A field naming what kind of record a member is, as TreeLine's `format="BOOK"`. */
const KIND_FIELD = /^(?:type|kind|format|category)$/iu;
const isRecord = (
value: JsonValue | undefined,
): value is Record<string, JsonValue> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** The array a member pointer sits in, when its parent is one in a view. The empty pointer is the view itself, as a file whose top level is an array. */
const arrayOf = (view: JsonValue | null, pointer: string) => {
const list = pointer.replace(/\/[^/]+$/u, "");
if (list === pointer) return undefined;
const items = list === "" ? view : resolvePointer(view, list);
return Array.isArray(items) ? list : undefined;
};
/** A counted array, and the kind field and value its counted members share, when they carry one. */
interface Counted {
readonly list: string;
readonly kind?: { readonly key: string; readonly value: string };
}
/** The kind a member names, as `format="BOOK"`, when its array's records share the field with more than one value. */
const kindOf = (member: JsonValue | undefined, items: readonly JsonValue[]) => {
if (!isRecord(member)) return undefined;
const key = Object.keys(member).find((field) => KIND_FIELD.test(field));
const value = key === undefined ? undefined : member[key];
return key === undefined ||
typeof value !== "string" ||
value.includes("][") ||
!items.every((item) => isRecord(item) && typeof item[key] === "string")
? undefined
: { key, value };
};
const membersOf = (view: JsonValue | null, { list, kind }: Counted) => {
const items = list === "" ? view : resolvePointer(view, list);
return (Array.isArray(items) ? items : []).filter(
(item) =>
kind === undefined || (isRecord(item) && item[kind.key] === kind.value),
);
};
const countOf = (
file: string,
counted: Counted,
view: JsonValue | null,
): Suggestion => ({
kind: "member_count",
file,
pointer: counted.list,
...(counted.kind === undefined
? {}
: { matching: spellCondition({ prefix: "", ...counted.kind }) }),
equals: membersOf(view, counted).length,
});
/**
* `member_count` checks and guards of a JSON file's arrays, as for XML:
* where members were added or removed, a check that the array holds the
* end's number, of the members' kind where records share a kind field, as
* TreeLine's `/nodes` matching `[format=BOOK]`, at most two, the
* shallowest first; where members were only edited, a guard that the
* innermost array an edit goes through holds as many as it did, at most one.
* Never through a step by position.
*/
export const jsonCounts = (
file: string,
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
},
): { readonly checks: Suggestion[]; readonly guards: Suggestion[] } => {
const named = (list: string, view: JsonValue | null) =>
locatePointer(view, list).byPosition.length === 0;
const lists = new Map<string, Counted>();
const note = (pointer: string, view: JsonValue | null) => {
const list = arrayOf(view, pointer);
const items = list === undefined ? [] : resolvePointer(view, list);
const atEnd =
list === undefined
? undefined
: list === ""
? ends.final
: resolvePointer(ends.final, list);
if (
list === undefined ||
!Array.isArray(atEnd) ||
!named(list, ends.baseline) ||
!named(list, ends.final)
)
return;
const kind = kindOf(
resolvePointer(view, pointer),
Array.isArray(items) ? items : [],
);
const counted = { list, ...(kind && { kind }) };
lists.set(JSON.stringify(counted), counted);
};
for (const pointer of change.added) note(pointer, ends.final);
for (const pointer of change.removed) note(pointer, ends.baseline);
const depth = ({ list }: Counted) => list.split("/").length;
const checks = [...lists.values()]
.toSorted((left, right) => depth(left) - depth(right))
.filter((counted) => {
const [seed, end] = [ends.baseline, ends.final].map(
(view) => membersOf(view, counted).length,
);
// A lone member makes no list.
return seed !== end && Math.max(seed ?? 0, end ?? 0) > 1;
})
.map((counted) => countOf(file, counted, ends.final))
.slice(0, MAX_COUNTS);
// Edits stop at the first guard, and each list is read once, however many records they touch.
const guards: Suggestion[] = [];
const tried = new Set<string>();
for (const pointer of change.changed) {
const segments = pointer.split("/");
for (let index = segments.length - 1; index > 0; index -= 1) {
const list = segments.slice(0, index).join("/");
const counted = { list };
if (tried.has(list)) continue;
tried.add(list);
const items = list === "" ? ends.final : resolvePointer(ends.final, list);
if (
Array.isArray(items) &&
!lists.has(JSON.stringify(counted)) &&
named(list, ends.baseline) &&
named(list, ends.final) &&
membersOf(ends.baseline, counted).length > 1 &&
membersOf(ends.baseline, counted).length ===
membersOf(ends.final, counted).length
) {
guards.push(countOf(file, counted, ends.baseline));
break;
}
}
if (guards.length === MAX_COUNT_GUARDS) break;
}
return { checks, guards };
};
/** Pointers without a listed ancestor: a record removed whole is checked gone by its own pointer. */
export const outermost = (pointers: readonly string[]): readonly string[] =>
pointers.filter(
(pointer) => !pointers.some((other) => pointer.startsWith(`${other}/`)),
);
/** The checks that tell a file's ends apart: none the seed already passes, nor an absence the end fills, as a place by position another record took. */
export const decisive = (
suggestions: readonly Suggestion[],
ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
},
): Suggestion[] =>
suggestions.filter((check) =>
check.kind === "value_equals"
? !sameJson(resolvePointer(ends.baseline, check.pointer), check.value)
: check.kind !== "value_absent" ||
locatePointer(ends.final, check.pointer).kind === "none",
);
/** A `by_position` note on a JSON file's suggestions that reach their value only by position, as a record nothing names: another save may order the array otherwise. */
export const positionalNotes = (
file: string,
suggestions: readonly Suggestion[],
view: JsonValue | null,
): FileNote[] => {
const pointers = suggestions.flatMap((check) =>
"pointer" in check &&
locatePointer(view, check.pointer).byPosition.length > 0
? [check.pointer]
: [],
);
return pointers.length === 0
? []
: [
{
code: "by_position",
file,
message: `${String(pointers.length)} suggested check(s) of ~/${file} reach their value only by position, as nothing names the record they read: another save may order its array otherwise, so check the record by a value another way, such as a count.`,
pointers: pointers.slice(0, MAX_LISTED),
},
];
};
@@ -0,0 +1,599 @@
import { describe, expect, it } from "vitest";
import { draftOf, statePath } from "./appTaskDraft.fixture.js";
import { textView } from "./stateFormats.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
const FILE = "Documents/trip.txt";
/** A text file's lines, as a mind map exported to text keeps topics with the ids and times the app assigns. */
const lines = (...added: string[]) =>
[
"# Weekend Trip",
'topic TEXT="Packing" ID="ID_1965352635"',
'topic TEXT="Sleeping bags" ID="ID_1227863932" CREATED="1793955122470"',
...added,
"</topic>",
"</map>",
].join("\n");
const drafted = (before: string, after: string) => {
const [file] = draftOf({
[FILE]: statePath("document", "text", textView(before), textView(after)),
});
if (file === undefined) throw new Error("the file did not change");
return file;
};
describe("draftTaskFiles for lines holding values the app generates", () => {
it("keeps assignment-like text quoted in a translation", () => {
const translation = 'msgstr "Set created=2025550123 and save"';
const file = drafted(lines(), lines(translation));
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [translation] },
]);
});
it("keeps quoted ID-like text exact", () => {
const line = 'msgstr "Enter ID_329023692"';
const file = drafted('msgid "Enter"', `msgid "Enter"\n${line}`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
const checks = file.suggested.map((check, index) => ({
...check,
id: `c${index}`,
}));
const wrong = new Map([
[
FILE,
{
format: "text" as const,
view: textView('msgid "Enter"\nmsgstr "Enter WRONG"'),
},
],
]);
expect(
evaluateTaskChecks(checks, wrong).map(({ passed }) => passed),
).toEqual([false]);
});
it("keeps an escaped quote inside ordinary text", () => {
const translation = 'msgstr "Set \\\"created=2025550123 and save"';
const file = drafted('msgid "Hello"', `msgid "Hello"\n${translation}`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [translation] },
]);
});
});
describe("draftTaskFiles for XML text views", () => {
it("checks an XML text fallback without freezing a timestamp after a literal backslash", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>\n';
const node = (time: string) =>
`<node TEXT="C:\\work\\" CREATED="${time}"/>`;
const before = `${opening}</map>`;
const after = `${opening}${node("1793955250671")}\n</map>`;
const file = drafted(before, after);
const results = evaluateTaskChecks(
file.suggested.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([
[
FILE,
{
format: "text" as const,
view: textView(`${opening}${node("1793955259999")}\n</map>`),
},
],
]),
);
expect(file.suggested).toEqual([
expect.objectContaining({
kind: "line_count",
contains: '<node TEXT="C:\\work\\" CREATED="',
}),
]);
expect(results.map(({ passed }) => passed)).toEqual([true]);
});
it("keeps quoted CDATA as an exact requested line", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>\n';
const line =
'<text><![CDATA[msgstr "Set \\\"created=2025550123 and save"]]></text>';
const file = drafted(`${opening}</map>`, `${opening}${line}\n</map>`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
const altered = line.replace("2025550123", "WRONG");
const results = evaluateTaskChecks(
file.suggested.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([
[
FILE,
{
format: "text" as const,
view: textView(`${opening}${altered}\n</map>`),
},
],
]),
);
expect(results.map(({ passed }) => passed)).toEqual([false]);
});
it("keeps requested text inside a multiline XML attribute exact", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>\n';
const text = 'created=2025550123 and save"/>';
const file = drafted(
`${opening}</map>`,
`${opening}<node TEXT="Set\n${text}\n</map>`,
);
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "lines_present",
lines: expect.arrayContaining([text]),
}),
]),
);
const result = evaluateTaskChecks(
file.suggested.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([
[
FILE,
{
format: "text" as const,
view: textView(
`${opening}<node TEXT="Set\n${text.replace("2025550123", "WRONG")}\n</map>`,
),
},
],
]),
);
expect(result.some(({ passed }) => !passed)).toBe(true);
});
it("recognizes an attribute on a later line of an XML tag", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>\n<node\n';
const attribute = 'TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(`${opening}</map>`, `${opening}${attribute}\n</map>`);
expect(file.suggested).toEqual([
expect.objectContaining({
kind: "line_count",
contains: 'TEXT="C:\\work\\" CREATED="',
}),
]);
});
});
describe("draftTaskFiles for markup boundaries and incomplete XML", () => {
it("keeps quoted text after a Markdown autolink", () => {
const line =
'<https://example.test> msgstr "Set \\\"created=2025550123 and save"';
const file = drafted("# Note", `# Note\n${line}`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
});
it("recognizes attributes after a comment inside the DTD", () => {
const opening = "<!DOCTYPE map [<!-- author's note -->]>\n<map>\n";
const node = '<node TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(`${opening}</map>`, `${opening}${node}\n</map>`);
expect(file.suggested).toEqual([
expect.objectContaining({
kind: "line_count",
contains: '<node TEXT="C:\\work\\" CREATED="',
}),
]);
});
it("counts repeated new lines even when one is inside an XML comment", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>\n';
const node = '<node TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(
`${opening}</map>`,
`${opening}<!--\n${node}\n-->\n${node}\n</map>`,
);
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "line_count",
contains: '<node TEXT="C:\\work\\" CREATED="',
equals: 2,
}),
]),
);
const results = evaluateTaskChecks(
file.suggested.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([
[
FILE,
{
format: "text" as const,
view: textView(`${opening}<!--\n${node}\n-->\n</map>`),
},
],
]),
);
expect(results.some(({ passed }) => !passed)).toBe(true);
});
it("does not guess attribute boundaries when the XML syntax reader cannot finish", () => {
const opening = '<!DOCTYPE map [<!ENTITY title "Map">]>\n<map>&title;\n';
const node = '<node TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(`${opening}</map>`, `${opening}${node}\n</map>`);
expect(file.suggested).toEqual([]);
expect(file.notes).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "read_as_text",
message: expect.stringContaining("could not locate XML attributes"),
}),
]),
);
});
});
describe("draftTaskFiles for added lines", () => {
it("recognizes Unicode XML names before a malformed closing tag", () => {
const opening = "<máp>\n";
const node = '<node TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(`${opening}</máp>`, `${opening}${node}\n</wrong>`);
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "line_count",
contains: '<node TEXT="C:\\work\\" CREATED="',
}),
]),
);
});
it("requires the exact caller-supplied UUID in ordinary text", () => {
const line = "Tracking id: 123e4567-e89b-12d3-a456-426614174000";
const file = drafted("# Notes", `# Notes\n${line}`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
const results = evaluateTaskChecks(
file.suggested.map((check, index) => ({ ...check, id: `c${index}` })),
new Map([
[
FILE,
{
format: "text" as const,
view: textView("# Notes\nTracking id: WRONG"),
},
],
]),
);
expect(results.map(({ passed }) => passed)).toEqual([false]);
});
it("retains parsed attribute positions before a malformed closing tag", () => {
const opening = "<map>\n";
const node = '<node TEXT="C:\\work\\" CREATED="1793955250671"/>';
const file = drafted(`${opening}</map>`, `${opening}${node}\n</wrong>`);
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "line_count",
contains: '<node TEXT="C:\\work\\" CREATED="',
}),
]),
);
});
it.each([
"https://example.test",
"ada@example.test",
"mailto:ada@example.test",
])("keeps ordinary Markdown that begins with an autolink %s", (link) => {
const opening = `<${link}>\n`;
const line = 'msgstr "Set \\\"created=2025550123 and save"';
const file = drafted(opening, `${opening}${line}`);
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
});
it("keeps long ordinary text as a whole line", () => {
const text = `msgstr "${"ordinary words ".repeat(3000)}"`;
const file = drafted(lines(), lines(text));
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [text] },
]);
});
it("keeps phone numbers but counts a stable prefix before a named creation time", () => {
const phone = 'topic TEXT="Call 2025550123"';
const timed = 'topic TEXT="Water filter" CREATED="1793955250671"';
const file = drafted(lines(), lines(phone, timed));
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "lines_present", lines: [phone] }),
expect.objectContaining({
kind: "line_count",
contains: 'topic TEXT="Water filter" CREATED="',
}),
]),
);
});
it("counts the lines holding a new line's text up to its first generated value, rather than the line whole, which another save would not repeat", () => {
const file = drafted(
lines(),
lines(
'topic TEXT="Water filter" ID="ID_329023692" CREATED="1793955250671" MODIFIED="1793955252979"',
),
);
expect(file.suggested).toEqual([
{
kind: "line_count",
file: FILE,
contains: 'topic TEXT="Water filter" ID="',
equals: 1,
},
]);
expect(file.notes).toEqual([]);
});
it("keeps an ID-like token without a generated ID field", () => {
const line = "ID_329023692 1793955250671";
const file = drafted(lines(), lines(line));
expect(file.suggested).toEqual([
{ kind: "lines_present", file: FILE, lines: [line] },
]);
});
it("guards a kept line beside a new one, never a lone closing tag any such file holds", () => {
const file = drafted(lines(), lines("Water filter"));
expect(file.guards).toEqual([
{
kind: "lines_present",
file: FILE,
lines: [
'topic TEXT="Packing" ID="ID_1965352635"',
'topic TEXT="Sleeping bags" ID="ID_1227863932" CREATED="1793955122470"',
],
},
]);
});
});
describe("draftTaskFiles for lines added to a text file longer than its view", () => {
it("counts no lines a view cut short, since a count there is undecided", () => {
// Both views keep the first 5,000 lines of 5,001 or more, the new line among them.
const long = (...added: string[]) =>
[
...added,
...Array.from({ length: 5001 }, (_, index) => `line ${String(index)}`),
].join("\n");
const file = drafted(
long(),
long(
'topic TEXT="Water filter" ID="ID_329023692" CREATED="1793955250671"',
),
);
expect(file.change).toMatchObject({ complete: false });
expect(file.suggested.map(({ kind }) => kind)).not.toContain("line_count");
});
});
describe("draftTaskFiles guards of a document of commands and text, as LyX saves one", () => {
/** A LyX body: each heading and paragraph opened by a command and closed by `\end_layout`. */
const report = (heading: string) =>
[
"\\begin_body",
"",
"\\begin_layout Section",
"Introduction",
"\\end_layout",
"",
"\\begin_layout Standard",
"This report summarises the spring season.",
"\\end_layout",
"",
"\\begin_layout Section",
heading,
"\\end_layout",
"",
"\\begin_layout Standard",
"Volunteers spread compost in early March.",
"\\end_layout",
"",
"\\begin_layout Section",
"Harvest Results",
"\\end_layout",
"",
"\\end_body",
].join("\n");
const doc = (heading: string) => {
const view = textView(report(heading));
return { view, file: "Documents/garden-report.lyx" };
};
it("guards the other headings the same command opens, never a command line or one every section repeats", () => {
const [seed, end] = [doc("Soil Preperation"), doc("Soil Preparation")];
const [file] = draftOf({
[seed.file]: statePath("document", "text", seed.view, end.view),
});
expect(file?.suggested).toEqual([
{ kind: "lines_present", file: seed.file, lines: ["Soil Preparation"] },
{ kind: "lines_absent", file: seed.file, lines: ["Soil Preperation"] },
]);
expect(file?.guards).toEqual([
{
kind: "lines_present",
file: seed.file,
lines: ["Introduction", "Harvest Results"],
},
]);
});
});
describe("draftTaskFiles guards of lines with no text of their own", () => {
it("guards a text file's nearest lines with words, never a key alone, as a RedNotebook day's `24:`, nor a tag alone, as `<fonts>`", () => {
const journal = (twentieth: string) =>
[
"20:",
" text: Repotted the basil and the rosemary on the balcony. The rosemary roots had",
` circled the whole pot.${twentieth}`,
"24:",
" text: Cycled to the farmers market with Priya.",
"<fonts>",
"</fonts>",
].join("\n");
const file = ".rednotebook/data/2026-10.txt";
const [drafted] = draftOf({
[file]: statePath(
"application_state",
"text",
textView(journal("")),
textView(journal(" Moved the rosemary to the sunny corner.")),
),
});
expect(drafted?.guards).toEqual([
{
kind: "lines_present",
file,
lines: [
" text: Repotted the basil and the rosemary on the balcony. The rosemary roots had",
" text: Cycled to the farmers market with Priya.",
],
},
]);
});
});
describe("draftTaskFiles for the app's log beside its journal", () => {
it("drafts a changed unselected conversation history in app state", () => {
const [file] = draftOf({
".config/app/history.log": statePath(
"application_state",
"text",
textView("Ada: Hello"),
textView("Ada: Hello\nLin: Welcome"),
),
});
expect(file?.suggested).toContainEqual({
kind: "lines_present",
file: ".config/app/history.log",
lines: ["Lin: Welcome"],
});
});
it("drafts an app log and notes a text file that opens like XML but is not", () => {
const lines = (...text: string[]) => textView(text.join("\n"));
const files = draftOf({
".rednotebook/data/2026-10.txt": statePath(
"application_state",
"text",
lines("20:", " text: Repotted the basil."),
lines("20:", " text: Repotted the basil. Moved the rosemary."),
),
".rednotebook/rednotebook.log": statePath(
"application_state",
"text",
lines("2026-11-06 15:11:21,847 DEBUG Cloud updated"),
lines(
"2026-11-06 15:11:21,847 DEBUG Cloud updated",
"2026-11-06 15:11:50,559 INFO Wrote file /home/user/.rednotebook/data/2026-10.txt",
),
),
".config/app/state.xml": statePath(
"application_state",
"text",
lines("<!DOCTYPE state [<!ENTITY e 'x'>]>", "<state>&e;</state>"),
lines("<!DOCTYPE state [<!ENTITY e 'x'>]>", "<state>&e;!</state>"),
),
});
const byFile = new Map(files.map((file) => [file.file, file]));
expect(byFile.get(".rednotebook/rednotebook.log")?.suggested).not.toEqual(
[],
);
expect(byFile.get(".rednotebook/data/2026-10.txt")?.suggested).not.toEqual(
[],
);
expect(
byFile.get(".config/app/state.xml")?.notes.map(({ code }) => code),
).toEqual(["read_as_text"]);
});
it("drafts a log the caller selected, and does not call a quoted bracket an entity subset", () => {
const lines = (...text: string[]) => textView(text.join("\n"));
const selected = {
...statePath(
"application_state",
"text",
lines("opened"),
lines("opened", "saved"),
),
reasons: ["selected_path" as const],
};
const logged = draftOf({ ".config/app/notes.log": selected }, [
".config/app/notes.log",
]);
const noted = draftOf({
"Documents/state.txt": statePath(
"document",
"text",
lines('<!DOCTYPE state SYSTEM "state[1].dtd">', "<state/>"),
lines('<!DOCTYPE state SYSTEM "state[1].dtd">', "<state>saved</state>"),
),
});
expect(logged[0]?.suggested).not.toEqual([]);
expect(
noted[0]?.notes.some((note) => note.message.includes("internal subset")),
).toBe(false);
});
});
describe("draftTaskFiles guards of a line-keyed catalogue, as Poedit saves one", () => {
it("guards the other records' lines of the changed line's keyword, never its own record's source reference or msgid", () => {
const entry = (line: number, msgid: string, msgstr: string) => [
`#: argparse.py:${String(line)}`,
`msgid "${msgid}"`,
`msgstr "${msgstr}"`,
"",
];
const catalogue = (fixed: string) =>
[
...entry(1811, "positional arguments", "arguments positionnels"),
...entry(1858, "cannot have multiple subparser arguments", ""),
...entry(2249, "expected one argument", fixed),
...entry(
2250,
"expected at most one argument",
"au plus un argument attendu",
),
...entry(2312, "ambiguous option", ""),
].join("\n");
const file = "Documents/fr.po";
const [drafted] = draftOf({
[file]: statePath(
"document",
"text",
textView(catalogue("un argument inattendu")),
textView(catalogue("un argument attendu")),
),
});
expect(drafted?.guards).toEqual([
{
kind: "lines_present",
file,
lines: [
'msgstr "arguments positionnels"',
'msgstr "au plus un argument attendu"',
],
},
]);
});
});
+240 -24
View File
@@ -1,6 +1,13 @@
import { xmlAttributeQuoteRanges } from "../xmlDocument.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import {
isBookkeepingName,
isUuid,
isVolatileValue,
} from "./appTaskDraftNoise.js";
import { textOpensXml, type FileNote } from "./appTaskDraftFileNotes.js";
/** Lines a text file's guard names, and how far from the added line it looks for them. */
/** Lines a text file's guard names, and how far from the added line it looks for them when it has no like sibling. */
const MAX_GUARD_LINES = 2;
const NEIGHBOURHOOD = 6;
/** A guard line longer than this is not copied into the task. */
@@ -10,49 +17,258 @@ const MAX_GUARD_TEXT = 2000;
const markerOf = (line: string): string | undefined =>
/^\s*(?<marker>\[[ xX*>]?\]|[-*+•]|\d+[.)])\s/u.exec(line)?.groups?.marker;
/** Whether a line is a command, as LyX's `\begin_layout Section` or `\end_layout`. */
const isCommand = (line: string) => /^\s*\\[\p{L}_]+\b/u.test(line);
/** Whether a line is only markup: a command, tags with no text between them, as KmPlot's `<fonts>` or `</node>`, or a key alone, as a RedNotebook day's `24:`. */
const isMarkup = (line: string) =>
isCommand(line) ||
!/[\p{L}\d]/u.test(
line.replaceAll(/<[^>]*>/gu, "").replace(/^\s*[^\s:]+:\s*$/u, ""),
);
/** The keyword a line of a line-keyed format opens with, as a gettext catalogue's `msgstr "…"`, or its `key:` or `key =`. */
const keywordOf = (line: string): string | undefined =>
/^\s*(?<keyword>[A-Za-z_][\w.-]*)(?:\s*[:=]|\s+")/u.exec(line)?.groups
?.keyword;
/** What kind of line a line is, for its like siblings: a list item's marker, the command opening it, as `\begin_layout Section` opens a LyX heading, or its keyword (`keywordOf`), as Poedit's other `msgstr` lines. */
const kindOf = (lines: readonly string[], index: number) => {
const line = lines[index] ?? "";
const marker = markerOf(line);
const opener = lines[index - 1];
const keyword = keywordOf(line);
return marker !== undefined
? `marker\u0000${marker}`
: opener !== undefined && isCommand(opener)
? `opens\u0000${opener.trim()}`
: keyword === undefined
? undefined
: `keyword\u0000${keyword}`;
};
/** How many times each line occurs. */
const tally = (lines: readonly string[]) => {
const counts = new Map<string, number>();
for (const line of lines) counts.set(line, (counts.get(line) ?? 0) + 1);
return counts;
};
/**
* A `lines_present` guard of a text file's unchanged lines beside the first
* line an edit added, for an author to add by choice: the list items next to
* it with the same marker, as the other `[ ]` action items around a new one,
* nearest first and kept in file order; or, when it is no list item or has no
* such sibling, the nearest lines with words in them. Each is a line the
* seed and the end both hold. None when nothing was added.
* line an edit added, for an author to add by choice: the nearest lines of
* its kind (`kindOf`), as the other `[ ]` action items around a new one,
* the other headings a LyX command opens or a gettext catalogue's other
* `msgstr` lines, never its own record's `msgid`, kept in file order; or,
* when it has no such sibling, the nearest lines with words in them. Each
* is text
* the seed and the end both hold once: never a line of markup alone, as
* LyX's `\end_layout`, a tag or a key with no text, nor one that repeats.
* None when nothing was added.
*/
export const lineGuards = (
file: string,
before: readonly string[],
after: readonly string[],
): DesktopTaskCheckInput[] => {
const seed = new Set(before);
const [seed, end] = [tally(before), tally(after)];
const at = after.findIndex((line) => !seed.has(line));
const added = after[at];
if (added === undefined) return [];
const near = after
if (at < 0) return [];
const kind = kindOf(after, at);
const kept = after
.map((line, index) => ({ line, index }))
.filter(
({ line, index }) =>
index !== at &&
Math.abs(index - at) <= NEIGHBOURHOOD &&
seed.has(line) &&
seed.get(line) === 1 &&
end.get(line) === 1 &&
line.length <= MAX_GUARD_TEXT &&
/[\p{L}\d]/u.test(line),
/[\p{L}\d]/u.test(line) &&
!isMarkup(line),
)
.toSorted(
(left, right) =>
Math.abs(left.index - at) - Math.abs(right.index - at) ||
left.index - right.index,
);
const marker = markerOf(added);
const siblings = near.filter(
({ line }) => marker !== undefined && markerOf(line) === marker,
const siblings = kept.filter(
({ index }) => kind !== undefined && kindOf(after, index) === kind,
);
const lines = [
...new Set(
(siblings.length > 0 ? siblings : near)
.slice(0, MAX_GUARD_LINES)
.toSorted((left, right) => left.index - right.index)
.map(({ line }) => line),
),
];
const near = kept.filter(
({ index }) => Math.abs(index - at) <= NEIGHBOURHOOD,
);
const lines = (siblings.length > 0 ? siblings : near)
.slice(0, MAX_GUARD_LINES)
.toSorted((left, right) => left.index - right.index)
.map(({ line }) => line);
return lines.length === 0 ? [] : [{ kind: "lines_present", file, lines }];
};
/** A run of letters, digits, `_` and `-`, a token a line may hold. */
const TOKEN = /[\p{L}\d_-]+/gu;
/** Where a line's first identifiable generated time or id starts; -1 when it holds none. */
const volatileAt = (
line: string,
xmlQuotes: ReadonlySet<number>,
enclosingQuote: string | undefined,
): number => {
let end = 0;
let quote = enclosingQuote;
let xmlAttribute = enclosingQuote !== undefined;
let previous: string | undefined;
let previousOutside = false;
for (const { 0: token, index } of line.matchAll(TOKEN)) {
const gap = line.slice(end, index);
const key =
quote === undefined && previousOutside && /^\s*=\s*["']?$/u.test(gap)
? previous
: undefined;
for (let at = 0; at < gap.length; at += 1) {
const character = gap[at];
if (character === "\\" && quote !== undefined && !xmlAttribute) {
at += 1;
} else if (character === quote) {
quote = undefined;
xmlAttribute = false;
} else if (
quote === undefined &&
(character === '"' ||
(character === "'" && /[\s=]/u.test(line[end + at - 1] ?? " ")))
) {
quote = character;
xmlAttribute = xmlQuotes.has(end + at);
}
}
if (
(isVolatileValue(token, key !== undefined && isBookkeepingName(key)) &&
!isUuid(token)) ||
(key !== undefined &&
/^(?:[^:]+:)?id$/iu.test(key) &&
/^\p{L}+_\d{6,}$/u.test(token))
)
return index;
previous = token;
previousOutside = quote === undefined;
end = index + token.length;
}
return -1;
};
/**
* Checks of the lines a text file gained: a `lines_present` of those whole,
* and, for a line holding a value the app generates, as a Freeplane map's
* `ID="ID_329023692" CREATED="1793955250671"`, which a later save of the same
* edit would not repeat, a `line_count` of the lines holding its text up to
* that value, as `<node TEXT="Water filter" ID="`, at the end's number,
* where that number changed and both views hold the whole file (`counted`);
* a note on a line no such text names.
*/
export const addedLineChecks = (
file: string,
lines: {
readonly before: readonly string[];
readonly after: readonly string[];
},
{
added,
counted,
}: { readonly added: readonly string[]; readonly counted: boolean },
): { readonly checks: DesktopTaskCheckInput[]; readonly notes: FileNote[] } => {
const holding = (all: readonly string[], text: string) =>
all.filter((line) => line.includes(text)).length;
const isXml = textOpensXml(lines.after);
const source = isXml ? lines.after.join("\n") : "";
const parsed = isXml ? xmlAttributeQuoteRanges(source) : undefined;
const ranges =
parsed === undefined ? [] : parsed.ok ? parsed.value : parsed.error.ranges;
const examined = parsed?.ok === false ? parsed.error.examined : source.length;
const addedSet = new Set(added);
const classifications = new Map<string, number>();
const unexamined = new Set<string>();
let lineStart = 0;
let nextRange = 0;
for (const line of lines.after) {
const quoteStarts = new Set<number>();
const lineEnd = lineStart + line.length;
while (nextRange < ranges.length && ranges[nextRange]!.end < lineStart)
nextRange += 1;
let enclosingQuote: string | undefined;
for (let index = nextRange; index < ranges.length; index += 1) {
const range = ranges[index]!;
if (range.start >= lineEnd) break;
if (range.start < lineStart) enclosingQuote = source[range.start];
else quoteStarts.add(range.start - lineStart);
}
if (addedSet.has(line)) {
if (parsed?.ok === false && lineEnd > examined) {
unexamined.add(line);
lineStart = lineEnd + 1;
continue;
}
const at = volatileAt(line, quoteStarts, enclosingQuote);
const previous = classifications.get(line);
if (
previous === undefined ||
(at >= 0 && (previous < 0 || at < previous))
)
classifications.set(line, at);
}
lineStart = lineEnd + 1;
}
const classified = added
.filter((line) => !unexamined.has(line))
.map((line) => ({
line,
at: classifications.get(line) ?? -1,
}));
const whole = classified.filter(({ at }) => at < 0).map(({ line }) => line);
const prefixes = new Set<string>();
let unnamed = 0;
for (const { line, at } of classified.filter(
({ at }) => counted && at >= 0,
)) {
const prefix = line.slice(0, at).trimStart();
const equals = holding(lines.after, prefix);
if (
prefix.trim().length >= 3 &&
/\p{L}/u.test(prefix) &&
equals !== holding(lines.before, prefix)
)
prefixes.add(prefix);
else unnamed += 1;
}
return {
checks: [
...(whole.length > 0
? [{ kind: "lines_present" as const, file, lines: whole }]
: []),
...[...prefixes].map((contains) => ({
kind: "line_count" as const,
file,
contains,
equals: holding(lines.after, contains),
})),
],
notes: [
...(unexamined.size === 0
? []
: [
{
code: "read_as_text" as const,
file,
message: `REA could not locate XML attributes in ${String(unexamined.size)} added line(s) of ~/${file}, so no checks are suggested for them; inspect the changed text and add checks manually.`,
},
]),
...(unnamed === 0
? []
: [
{
code: "volatile_lines" as const,
file,
message: `${String(unnamed)} line(s) ~/${file} gained hold a value the app generates, an id or a time, and no text before it tells them apart, so no check of them is suggested: check what the line says with line_count and contains.`,
},
]),
],
};
};
@@ -0,0 +1,76 @@
import type { JsonValue } from "../jsonValue.js";
import { isXmlElement, resolvePointer } from "./viewPointer.js";
/** A file's views at its two ends. */
interface Ends {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
}
/**
* Whether a value is a count an app keeps of an element's members, as VYM's
* root `branchCount`, KMyMoney's `<TRANSACTIONS count="5">` or GnuCash's
* `<gnc:count-data cd:type="transaction">2</gnc:count-data>` in its book:
* an attribute whose key ends in `count`, or the text of an element whose
* tag names a count, an integer that changed, at each end equal to how many
* elements of one tag the element, or for text the element holding it,
* holds at any depth there, the counter itself left out; or, for a counter
* the change added, to how many of one tag, more than one, it holds as
* children, as FreeCAD's `<ObjectDeps Count="2">` its `Dep`s. A count a
* user enters, as an item's `<count>`, tallies no tag so.
*/
export const isMemberCount = (
ends: Ends,
pointer: string,
key: string | undefined,
) => {
const counter = pointer.replace(/\/children\/\d+$/u, "");
const holder = resolvePointer(ends.final, counter);
const scope =
key === undefined
? counter !== pointer &&
isXmlElement(holder) &&
/count/iu.test(holder.name.split(":").at(-1) ?? holder.name)
? counter.replace(/\/children\/[^/]+$/u, "")
: undefined
: /count$/iu.test(key.split(":").at(-1) ?? key)
? pointer.split("/").slice(0, -2).join("/")
: undefined;
const [before, after] = [ends.baseline, ends.final].map((view) =>
resolvePointer(view, pointer),
);
const number = (value: JsonValue | undefined) =>
typeof value === "string" && /^\d+$/u.test(value)
? Number(value)
: undefined;
const [seedCount, endCount] = [number(before), number(after)];
if (
scope === undefined ||
endCount === undefined ||
seedCount === endCount ||
(seedCount === undefined && before !== undefined)
)
return false;
const tallyAt = (view: JsonValue | null, deep: boolean) => {
const tally = new Map<string, number>();
const own = key === undefined ? resolvePointer(view, counter) : undefined;
const owner = resolvePointer(view, scope);
const pending = isXmlElement(owner) ? [...owner.children] : [];
for (let node = pending.pop(); node !== undefined; node = pending.pop())
if (isXmlElement(node) && node !== own) {
tally.set(node.name, (tally.get(node.name) ?? 0) + 1);
if (deep) pending.push(...node.children);
}
return tally;
};
if (seedCount === undefined)
return [...tallyAt(ends.final, false).values()].some(
(count) => count > 1 && count === endCount,
);
const seed = tallyAt(ends.baseline, true);
const end = tallyAt(ends.final, true);
return [...new Set([...seed.keys(), ...end.keys()])].some(
(tag) =>
(seed.get(tag) ?? 0) === seedCount && (end.get(tag) ?? 0) === endCount,
);
};
+156
View File
@@ -0,0 +1,156 @@
import type { JsonValue } from "../jsonValue.js";
import { isNameLikeKey } from "./attributeRank.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js";
import { selectorOf } from "./viewSelector.js";
/** A file's views at its two ends. */
interface Ends {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
}
/** The value of the name-like attribute a pointer's last step names its element by, as `label` for `[name=elementInformation][@name=label]`. */
const fieldKeyOf = (element: string) =>
selectorOf(
(element.split("/").at(-1) ?? "")
.replaceAll("~1", "/")
.replaceAll("~0", "~"),
)?.find(({ prefix, key }) => prefix === "@" && isNameLikeKey(key))?.value;
/**
* Text an app shows of another field it keeps, which changed alike: a text
* node whose element sits beside a field naming the key of another changed
* text with the same value at both ends, as QElectroTech's
* `<dynamic_elmt_text>` shows a component's label in its `<text>` beside
* `<info_name>label</info_name>` while `elementInformation[@name=label]`
* holds it.
*/
export const mirrorsOf = (
change: Pick<DesktopStateDifference, "changed">,
ends: Ends,
) => {
const texts = change.changed.flatMap((pointer) => {
const [before, after] = [ends.baseline, ends.final].map((view) =>
resolvePointer(view, pointer),
);
const element = pointer.replace(/\/children\/\d+$/u, "");
return element !== pointer &&
typeof before === "string" &&
typeof after === "string"
? [{ pointer, element, before, after }]
: [];
});
// The keys of the changed texts' elements, by what each was and became.
const keys = new Map<string, { pointer: string; key: string }[]>();
for (const { pointer, element, before, after } of texts) {
const key = fieldKeyOf(element);
const alike = JSON.stringify([before, after]);
if (key === undefined) continue;
const group = keys.get(alike) ?? [];
group.push({ pointer, key });
keys.set(alike, group);
}
const mirrored = new Set(
texts.flatMap((mirror) => {
const sources = keys.get(JSON.stringify([mirror.before, mirror.after]));
const record = sources?.some(({ pointer }) => pointer !== mirror.pointer)
? resolvePointer(
ends.final,
mirror.element.replace(/\/children\/[^/]+$/u, ""),
)
: undefined;
const shown = new Set(
(isXmlElement(record) ? record.children : []).map((field) =>
isXmlElement(field) ? elementText(field).trim() : "",
),
);
return (sources ?? []).some(
({ pointer, key }) =>
pointer !== mirror.pointer &&
shown.has(key) &&
sameRecord(mirror.element, pointer),
)
? [mirror.pointer]
: [];
}),
);
return (pointer: string) => mirrored.has(pointer);
};
/** An attribute that identifies a record, not a `name` two independent lists can share. */
const isRecordId = (key: string) =>
/^(?:[^:]*:)?(?:id|uid|uuid|guid|xid)$/iu.test(key);
/** The tag a selector step names, as `element` for `[name=element][@uuid={1}]`. */
const stepTag = (token: string) => /\[name=([^\][]+)/u.exec(token)?.[1];
/**
* Whether two pointers stay in one record. They may diverge into different
* parts of that record. Two different members of the same list, such as two
* components, are not one record.
*/
const sameRecord = (left: string, right: string) => {
const first = left.split("/");
const second = right.split("/");
let index = 0;
while (
index < first.length &&
index < second.length &&
first[index] === second[index]
)
index += 1;
if (index >= first.length || index >= second.length) return true;
if (first[index - 1] !== "children") return true;
const leftTag = stepTag(first[index] ?? "");
const rightTag = stepTag(second[index] ?? "");
return (
leftTag === undefined || rightTag === undefined || leftTag !== rightTag
);
};
/** Whether an element holds nothing but one identifier, as Parley's lesson membership `<entry id="6"/>`. */
export const isIdReference = (element: JsonValue | undefined): boolean => {
if (!isXmlElement(element)) return false;
const [key, ...more] = Object.keys(element.attributes);
return (
key !== undefined &&
more.length === 0 &&
isRecordId(key) &&
element.children.every(
(child) => typeof child === "string" && child.trim() === "",
)
);
};
/**
* Elements a change added that hold nothing but an identifier of a record it
* added elsewhere in the file (`isIdReference`), as Parley lists a new entry
* in its lesson by `<entry id="6"/>`: a mirror of that record, never a check
* or a count of its own.
*/
export const idReferencesOf = (
change: Pick<DesktopStateDifference, "added">,
ends: Ends,
) => {
const added = change.added.flatMap((pointer) => {
const element = resolvePointer(ends.final, pointer);
return isXmlElement(element) ? [{ pointer, element }] : [];
});
const mirrors = added.flatMap(({ pointer, element }) => {
const [key = ""] = Object.keys(element.attributes);
return isIdReference(element) &&
added.some(
(record) =>
record.element !== element &&
!isIdReference(record.element) &&
record.element.attributes[key] === element.attributes[key],
)
? [pointer]
: [];
});
return (pointer: string) =>
mirrors.some(
(mirror) => pointer === mirror || pointer.startsWith(`${mirror}/`),
);
};
@@ -0,0 +1,186 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { evaluateTaskChecks } from "./appTaskChecks.js";
import {
draftOf,
passing,
pointerOf,
statePath,
xml,
xmlDraft,
} from "./appTaskDraft.fixture.js";
const FILE = "Documents/doc.xml";
const STRING = "uMUM2QvoIZjRj";
const INT = "uC0y4gxFPBxQT";
const attribute = (id: string, name: string, type: string) =>
`<ownedAttribute xmi:type="uml:Property" xmi:id="${id}" name="${name}" visibility="private" type="${type}"/>`;
/** A model: data types, two classes of attributes, the class diagram's boxes, the id counter, and the tree view mirroring the model by id. */
const model = (added: string, height: string, counter: string) =>
`<xmi:XMI xmlns:xmi="x" xmlns:uml="u"><uml:Model xmi:id="m1" name="UML Model"><packagedElement xmi:type="uml:Model" xmi:id="Logical_View" name="Logical View"><uml:Package xmi:id="Datatypes" name="Datatypes"><packagedElement xmi:type="uml:DataType" xmi:id="${INT}" name="int"/><packagedElement xmi:type="uml:DataType" xmi:id="${STRING}" name="string"/></uml:Package><packagedElement xmi:type="uml:Class" xmi:id="u3dEaKzAZMUjj" name="Book">${attribute("unJOJYqtTrFmw", "title", STRING)}${attribute("ufuOeMM0RJQRU", "isbn", STRING)}</packagedElement><packagedElement xmi:type="uml:Class" xmi:id="u6wBR4Z5TqyET" name="Member">${attribute("u0xTeAOXDVGS9", "name", STRING)}${attribute("uJiGZsdCWAH42", "memberId", INT)}${added}</packagedElement><xmi:Extension extender="umbrello"><diagrams><diagram xmi.id="uOOLUpU1ZgvZX" name="class diagram"><widgets><classwidget xmi.id="u6wBR4Z5TqyET" localid="uiLi0eQjS7TpP" x="574" y="150" width="116" height="${height}"/><classwidget xmi.id="u3dEaKzAZMUjj" localid="uR6uLy6layctB" x="234" y="150" width="96" height="52"/></widgets></diagram></diagrams></xmi:Extension></packagedElement></uml:Model><xmi:Extension extender="umbrello"><docsettings uniqueid="${counter}"/><codegeneration lastobject="${counter}"/><listview><listitem id="Logical_View" type="801"><listitem id="${STRING}" type="829"/><listitem id="u6wBR4Z5TqyET" type="813"><listitem id="uJiGZsdCWAH42" type="814"/><listitem id="u0xTeAOXDVGS9" type="814"/>${added === "" ? "" : '<listitem id="ubcgF2AWfBmHh" type="814"/>'}</listitem></listitem></listview></xmi:Extension></xmi:XMI>`;
const SEED = model("", "52", "uAmSta7YLvI1L");
const email = (type: string) =>
model(attribute("ubcgF2AWfBmHh", "email", type), "67", "ubcgF2AWfBmHh");
const MEMBER =
"/root/children/[name=uml:Model]/children/[name=packagedElement]/children/[name=packagedElement][@name=Member]";
describe("draftTaskFiles for a UML model, as Umbrello saves one", () => {
it("checks the new attribute's type, never its class's visibility values as runs of text, so an attribute of another type fails", () => {
const file = xmlDraft(SEED, email(STRING));
expect(file.suggested).toEqual([
{
kind: "value_equals",
file: FILE,
pointer: `${MEMBER}/children/[name=ownedAttribute][@name=email]/attributes/type`,
value: STRING,
},
{
kind: "member_count",
file: FILE,
pointer: `${MEMBER}/children`,
matching: "[name=ownedAttribute][@xmi:type=uml:Property]",
equals: 3,
},
]);
expect(passing(FILE, xml(SEED), file.suggested)).toEqual([false, false]);
expect(passing(FILE, xml(email(STRING)), file.suggested)).toEqual([
true,
true,
]);
expect(passing(FILE, xml(email(INT)), file.suggested)).toEqual([
false,
true,
]);
});
it("notes the id counter and a value equal to the new attribute's id as volatile, the tree view as view state, and the class box's growth as layout", () => {
const file = xmlDraft(SEED, email(STRING));
const notes = Object.fromEntries(
file.values.map(({ pointer, note }) => [
pointer.replace(/^.*\/children\//u, ""),
note ?? null,
]),
);
expect(notes).toEqual({
"[name=ownedAttribute][@name=email]": null,
"[name=docsettings]/attributes/uniqueid": "volatile",
"[name=codegeneration]/attributes/lastobject": "volatile",
"[name=listitem][@id=ubcgF2AWfBmHh]": "view_state",
"[name=classwidget][@x=574]/attributes/height": "layout",
});
// No selector names an element by an id of random case.
expect(file.values.map(({ pointer }) => pointer).join()).not.toMatch(
/xmi\.id=/u,
);
});
it("names the data type the new attribute's type refers to by its xmi:id, though the tree view mirrors that id", () => {
const file = xmlDraft(SEED, email(STRING));
expect(file.values[0]?.refers_to).toEqual([
{
attribute: "type",
value: STRING,
element: `<packagedElement xmi:type="uml:DataType" xmi:id="${STRING}" name="string"/>`,
},
]);
expect(file.guards.map(pointerOf)).toEqual([
`${MEMBER}/children/[name=ownedAttribute][@name=name]/attributes/type`,
`${MEMBER}/children/[name=ownedAttribute][@name=memberId]/attributes/type`,
]);
});
});
describe("draftTaskFiles for a zipped UML model", () => {
it("checks the new attribute's type in a zipped model, whose data types only the archive's entries hold", () => {
const ZIP = "Documents/library.zip";
const zipped = (text: string): JsonValue => ({
entries: [
{
name: "library.xmi",
size: text.length,
sha256: "a".repeat(64),
format: "xml",
view: xml(text),
view_error: null,
},
],
entry_count: 1,
truncated: false,
});
const [file] = draftOf({
[ZIP]: statePath("document", "zip", zipped(SEED), zipped(email(STRING))),
});
const passes = (text: string) =>
evaluateTaskChecks(
(file?.suggested ?? []).map((check, index) => ({
...check,
id: `c${String(index)}`,
})),
new Map([[ZIP, { format: "zip", view: zipped(text) }]]),
).map(({ passed }) => passed);
const member = `/entries/[name=library.xmi]/view${MEMBER}`;
expect(file?.suggested).toEqual([
{
kind: "value_equals",
file: ZIP,
pointer: `${member}/children/[name=ownedAttribute][@name=email]/attributes/type`,
value: STRING,
},
{
kind: "member_count",
file: ZIP,
pointer: `${member}/children`,
matching: "[name=ownedAttribute][@xmi:type=uml:Property]",
equals: 3,
},
]);
expect(passes(SEED)).toEqual([false, false]);
expect(passes(email(STRING))).toEqual([true, true]);
expect(passes(email(INT))).toEqual([false, true]);
});
it("does not treat XML-shaped JSON in another entry as an XML type reference", () => {
const declaration = `<packagedElement xmi:type="uml:DataType" xmi:id="${STRING}" name="string"/>`;
const zipped = (text: string): JsonValue => ({
entries: [
{
name: "library.xmi",
size: text.length,
sha256: "a".repeat(64),
format: "xml",
view: xml(text.replace(declaration, "")),
view_error: null,
},
{
name: "other.json",
size: 1,
sha256: "b".repeat(64),
format: "json",
view: { name: "type", attributes: { id: STRING }, children: [] },
view_error: null,
},
],
entry_count: 2,
truncated: false,
});
const [file] = draftOf({
"Documents/library.zip": statePath(
"document",
"zip",
zipped(SEED),
zipped(email(STRING)),
),
});
expect(
file?.suggested.some(
(check) =>
"pointer" in check && check.pointer.endsWith("/attributes/type"),
),
).toBe(false);
});
});
+169 -198
View File
@@ -1,11 +1,18 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { collapseWhitespace, type DesktopTaskCheckInput } from "./appTask.js";
import {
attributeChecks,
fieldChecks,
recordChecks,
type AddedContext,
} from "./appTaskDraftAdded.js";
import {
attributeTextCheck,
readsText,
textAttributes,
} from "./appTaskDraftAttributeText.js";
import { draftCounts } from "./appTaskDraftCounts.js";
import { nestedRecordChecks } from "./appTaskDraftNested.js";
import { draftGuards } from "./appTaskDraftGuards.js";
import {
attributeKeyOf,
@@ -14,31 +21,29 @@ import {
isStamp,
type NoiseReason,
} from "./appTaskDraftNoise.js";
import { valueEqualsCheck } from "./appTaskDraftScalars.js";
import { passesOn, valueEqualsCheck } from "./appTaskDraftScalars.js";
import { isIdentifyingAttribute } from "./attributeRank.js";
import {
wholeTextSuggestions,
type WholeTextSuggestions,
} from "./appTaskDraftText.js";
import { draftValues, oneEnd, type DraftValue } from "./appTaskDraftValues.js";
import { draftValues, type DraftValue } from "./appTaskDraftValues.js";
import {
diffNamedMembers,
type DesktopStateDifference,
} from "./stateChanges.js";
import { pairMembers, pairedAtSeed } from "./memberPairing.js";
import {
escapeToken,
isXmlElement,
locatePointer,
pairMembers,
resolvePointer,
} from "./viewPointer.js";
import {
entryWithoutView,
zipArrayLeavesOut,
zipEntryAt,
zipLeavesOutAt,
zipView,
} from "./zipView.js";
referenceRoots,
valueFormat,
type CheckTree,
} from "./appTaskDraftTree.js";
type Suggestion = DesktopTaskCheckInput;
@@ -53,120 +58,6 @@ export const innermost = (pointers: readonly string[]): readonly string[] =>
(pointer) => !pointers.some((other) => other.startsWith(`${pointer}/`)),
);
/**
* The entry a pointer into a zip view goes into, when it has a view and both
* evaluators read it alike: JSON, a key file or XML. A binary or unread
* entry also holds a `null` view, which is no JSON `null`.
*/
const readableEntry = (view: JsonValue | null, pointer: string) => {
const entry = zipEntryAt(view, pointer);
return typeof entry === "object" &&
entryWithoutView(entry) === undefined &&
(entry.format === "json" ||
entry.format === "keyfile" ||
entry.format === "xml")
? entry
: undefined;
};
/**
* Where checks for a pointer the diff lists start: the view of an entry it
* names whole, or its root element for XML; the pointer itself inside that;
* undefined for an entry neither evaluator reads alike, or the entry's fields.
*/
const checkRoot = (
view: JsonValue | null,
pointer: string,
): string | undefined => {
const entry = readableEntry(view, pointer);
const [entryPointer] = /^\/entries\/[^/]+/u.exec(pointer) ?? [];
if (entry === undefined || entryPointer === undefined) return undefined;
const inner = pointer.slice(entryPointer.length).split("/").slice(1);
const root = entry.format === "xml" ? ["view", "root"] : ["view"];
const prefix = (short: readonly string[], long: readonly string[]) =>
short.length <= long.length &&
short.every((part, index) => long[index] === part);
if (prefix(inner, root)) return `${entryPointer}/${root.join("/")}`;
return prefix(root, inner) ? pointer : undefined;
};
/**
* Where checks into a view can go: an archive's entries, or an XML file's root
* element. `root` is where checks for a pointer the diff lists start, undefined
* where the evaluators do not read alike; `xml` whether a pointer goes into an
* XML view; `leavesOut` whether the view may lack part of what a pointer
* reaches, and `arrayLeavesOut` members of the array a pointer names;
* `listed` whether a pointer is a value of the document a values list shows;
* `empty` the view of a file that holds nothing.
*/
interface CheckTree {
readonly root: (
view: JsonValue | null,
pointer: string,
) => string | undefined;
readonly xml: (view: JsonValue | null, pointer: string) => boolean;
readonly leavesOut: (view: JsonValue | null, pointer: string) => boolean;
readonly arrayLeavesOut: (view: JsonValue | null, array: string) => boolean;
readonly listed: (view: JsonValue | null, pointer: string) => boolean;
readonly empty: JsonValue | null;
}
const valueFormat = (
tree: CheckTree,
view: JsonValue | null,
pointer: string,
) =>
tree === ARCHIVE && /^\/entries\/[^/]+$/u.test(pointer)
? ("archive" as const)
: tree.xml(view, pointer)
? ("xml" as const)
: ("json" as const);
const referenceRoots = (
tree: CheckTree,
view: JsonValue | null,
): JsonValue[] => {
if (tree !== ARCHIVE) return view === null ? [] : [view];
if (!isRecord(view) || !Array.isArray(view.entries)) return [];
return view.entries.flatMap((entry) =>
isRecord(entry) &&
entry.format === "xml" &&
entry.view !== undefined &&
entry.view !== null
? [entry.view]
: [],
);
};
export const ARCHIVE: CheckTree = {
root: checkRoot,
xml: (view, pointer) => readableEntry(view, pointer)?.format === "xml",
leavesOut: zipLeavesOutAt,
arrayLeavesOut: zipArrayLeavesOut,
// An entry added or removed whole, or a value inside a readable one; not an entry's size or digest.
listed: (view, pointer) =>
/^\/entries\/[^/]+$/u.test(pointer) ||
checkRoot(view, pointer) !== undefined,
// An archive with no entries, so each entry of one created or deleted is listed by its name.
empty: zipView([], 0),
};
/** An XML file's view leaves out what its `truncated` says, anywhere in the tree. */
const truncatedXml = (view: JsonValue | null) =>
isRecord(view) && view.truncated === true;
const inXmlRoot = (pointer: string) =>
pointer === "/root" || pointer.startsWith("/root/");
export const XML_FILE: CheckTree = {
root: (_view, pointer) => (inXmlRoot(pointer) ? pointer : undefined),
xml: () => true,
leavesOut: truncatedXml,
arrayLeavesOut: truncatedXml,
listed: (_view, pointer) => inXmlRoot(pointer),
empty: null,
};
/** Whether a check at a pointer is decided by name: no object or array reached by position, no array searched that the view may cut. */
const byName = (view: JsonValue | null, pointer: string, tree: CheckTree) => {
const located = locatePointer(view, pointer);
@@ -237,7 +128,7 @@ export interface NamedDraft {
/** Noise checks a document keeps when its change is nothing else, so an author still sees one. */
const MAX_FLAGGED = 3;
/** Guards a file's draft offers. */
/** Guards a file's draft offers besides its count guard. */
const MAX_GUARDS = 4;
/** The draft's options: its limits, and whether the file is a document, which keeps fewer noise checks than the app's own state. */
@@ -332,6 +223,14 @@ const equals = (
const { file, ends, tree, texts, noise } = collected.context;
const list =
noise(pointer) === undefined ? collected.values : collected.noise.values;
const before = resolvePointer(ends.baseline, pointer);
// Text whose whitespace alone changed, as a formula moved to a line of its own, holds what the seed did.
const relaid =
typeof value === "string" &&
typeof before === "string" &&
collapseWhitespace(value) === collapseWhitespace(before) &&
/\/children\/[^/]+$/u.test(pointer) &&
tree.xml(ends.final, pointer);
if (
!room(collected, list) ||
texts.covers(pointer) ||
@@ -339,24 +238,21 @@ const equals = (
(isRecord(value) && Object.keys(value).length > 0) ||
isStamp(value) ||
(tree.xml(ends.final, pointer) && inSplitDate(ends.final, pointer)) ||
isLayoutText(tree, ends.final, pointer, value)
isLayoutText(tree, ends.final, pointer, value) ||
relaid
)
return;
if (named(collected, ends.final, pointer))
take(collected, "values", [
valueEqualsCheck(
file,
pointer,
value,
resolvePointer(ends.baseline, pointer),
),
]);
else unnamed(collected, ends.final, pointer);
const check = valueEqualsCheck(file, pointer, value, before);
// A check that already passes at the seed tells nothing.
if (!named(collected, ends.final, pointer))
unnamed(collected, ends.final, pointer);
else if (!passesOn(check, before)) take(collected, "values", [check]);
};
/**
* Checks of an element added whole: a record only position names by its new
* fields, beside any whole text; a list member by its own attributes; any
* fields, beside any whole text; a list member by its own attributes and
* those of the records of attributes it nests (`nestedRecordChecks`); any
* other by its presence.
*/
const elementChecks = (
@@ -374,6 +270,8 @@ const elementChecks = (
named: (view: JsonValue | null, at: string) =>
named(collected, view, at) && !tree.leavesOut(view, at),
chars: collected.context.limit.chars,
referenceRoots: () => referenceRoots(tree, ends.baseline),
noisy: (at: string) => collected.context.noise(at) !== undefined,
long: collected.fieldLong,
};
if (!named(collected, ends.final, `${pointer}/name`)) {
@@ -390,6 +288,17 @@ const elementChecks = (
const own = [
...attributeChecks(added, pointer, value),
...(records.length > 0 ? records : fieldChecks(added, pointer, value)),
...nestedRecordChecks(
{
file,
final: ends.final,
named: (at) => added.named(ends.final, at),
chars: added.chars,
long: added.long,
},
pointer,
value,
),
];
take(
collected,
@@ -461,22 +370,25 @@ const removedCheck = (collected: Collected, pointer: string) => {
else unnamed(collected, ends.baseline, pointer);
};
/** The element a member pointer names at the seed: there, or, for one keyed by its new name as `renameKeys` keys it, the member it pairs with. */
const atSeed = (ends: AddedContext["ends"], owner: string) =>
resolvePointer(ends.baseline, owner) ?? pairedAtSeed(ends, owner);
/**
* A check that the identifier an element was renamed from names nothing at
* the end, as a layer renamed from `Untitled` that its `src` names: its tag
* the end, as a layer renamed from `Layer` that its `src` names: its tag
* and old value, where that named the element alone at the seed. An element
* its tag alone names gets none; the check of its identifier says as much.
*/
const renamedFrom = (collected: Collected, pointer: string) => {
const { file, ends, tree } = collected.context;
const key = attributeKeyOf(pointer);
const key = attributeKeyOf(pointer) ?? "";
const owner = pointer.split("/").slice(0, -2).join("/");
const list = /^(?<list>.+\/children)\/[^/]+$/u.exec(owner)?.groups?.list;
const before = resolvePointer(ends.baseline, owner);
const old = resolvePointer(ends.baseline, pointer);
const before = atSeed(ends, owner);
const old = isXmlElement(before) ? before.attributes[key] : undefined;
if (
!tree.xml(ends.baseline, owner) ||
key === undefined ||
list === undefined ||
!(owner.split("/").at(-1) ?? "").includes("][@") ||
!isIdentifyingAttribute(key) ||
@@ -503,7 +415,7 @@ const renamedFrom = (collected: Collected, pointer: string) => {
const collectChecks = (
context: CollectContext,
change: DesktopStateDifference,
): Collected => {
): Collected & { readonly runs: ReturnType<typeof readsText> } => {
const collected: Collected = {
context,
elements: [],
@@ -513,35 +425,84 @@ const collectChecks = (
fieldLong: [],
};
const { ends, tree } = context;
for (const pointer of change.added) {
const runs = attributeTexts(collected, change);
for (const pointer of change.added.filter((at) => !runs(at, ends.final))) {
const root = tree.root(ends.final, pointer);
if (root !== undefined)
addedChecks(collected, root, resolvePointer(ends.final, root));
}
for (const pointer of innermost(change.changed))
if (tree.root(ends.final, pointer) === pointer) {
if (
tree.root(ends.final, pointer) === pointer &&
!runs(pointer, ends.final)
) {
equals(collected, pointer, resolvePointer(ends.final, pointer));
// An id the app renumbered, or other noise, renamed nothing.
if (context.noise(pointer) === undefined) renamedFrom(collected, pointer);
}
for (const pointer of change.removed) removedCheck(collected, pointer);
return collected;
for (const pointer of change.removed.filter((at) => !runs(at, ends.baseline)))
removedCheck(collected, pointer);
return { ...collected, runs };
};
/**
* Take the `attributeTextCheck` of each attribute that may hold runs of
* text; whether a change at a pointer is one a check took reads: the text
* attribute of an element in it, or a run holding that attribute added or
* removed in it, not another of its attributes or elements.
*/
const attributeTexts = (
collected: Collected,
change: DesktopStateDifference,
) => {
const { file, ends, tree, limit } = collected.context;
const covered: { element: string; key: string }[] = [];
for (const { owner, key } of textAttributes(
change,
ends,
collected.context.noise,
)) {
const found =
tree.root(ends.final, owner) === owner ||
tree.root(ends.baseline, owner) === owner
? attributeTextCheck(
{
file,
ends,
named: (at) => named(collected, ends.final, at),
chars: limit.chars,
},
owner,
key,
)
: undefined;
if (
found !== undefined &&
!covered.some(({ element }) => element === found.element)
) {
covered.push({ element: found.element, key });
take(collected, "elements", [found.check]);
}
}
return readsText(covered);
};
/**
* Checks by the selectors a keyed diff names members with, in an archive's
* entries or an XML file: the whole text of each element whose text changed
* first, then elements added or removed whole, then values changed, added and
* removed. An element added to a list is checked by its own attributes, a
* record only position names by its new fields, a decimal by its number. A
* JSON value or an entry added whole is checked through its members. Nothing
* goes through an object or array by position. Noise (view state, renumbered
* ids, volatile values, times, upkeep) leaves the suggestions when anything
* first, then text kept in an attribute's runs (`attributeTextCheck`), then
* elements added or removed whole, then values changed, added and removed,
* then counts of lists whose members were added or removed (`draftCounts`).
* An element added to a list is checked by its own attributes, a record only
* position names by its new fields, a decimal by its number. A JSON value or
* an entry added whole is checked through its members. Nothing goes through
* an object or array by position. Noise (view state, renumbered ids,
* volatile values, times, upkeep, layout) leaves the suggestions when anything
* else changed, a change only position reaches included; when noise is all
* there is, it stays, flagged: up to three in a document, as many as fit in
* the app's own state, where a view setting may be the task. Beside them: the
* values the change added, changed and removed, and guards that the rest
* stays as it was.
* stays as it was, a count of the list an edit went through among them.
*/
export const namedDraft = (
file: string,
@@ -566,10 +527,23 @@ export const namedDraft = (
change,
);
const noisy = (check: Suggestion) => isNoisy(noise, check);
const counts = draftCounts(
{
file,
ends,
whole: (view, list) =>
named(view, list) && !tree.arrayLeavesOut(view, list),
noisy: (pointer) => noise(pointer) !== undefined,
covered: texts.covers,
coveredRun: checks.runs,
},
change,
);
const clean = [
...texts.suggestions.filter((check) => !noisy(check)),
...checks.elements,
...checks.values,
...counts.checks,
];
const flaggable = [
...texts.suggestions.filter(noisy),
@@ -592,57 +566,54 @@ export const namedDraft = (
format: (view, pointer) => valueFormat(tree, view, pointer),
referenceRoots: (view) => referenceRoots(tree, view),
});
// The count guard sits outside the cap, so line and sibling guards never squeeze it out.
const guards = edited
? draftGuards(
{
file,
ends,
named,
noisy: (pointer) => noise(pointer) !== undefined,
chars: options.limit.chars,
},
suggested,
).slice(0, MAX_GUARDS)
? [
...texts.guards,
...draftGuards(
{
file,
ends,
named,
noisy: (pointer) => noise(pointer) !== undefined,
chars: options.limit.chars,
},
suggested,
),
]
.slice(0, MAX_GUARDS)
.concat(counts.guards)
: [];
return {
suggested,
values,
valuesCut: cut,
guards,
facts: {
positional: checks.positional.count,
positionalTags: [...checks.positional.tags],
long: [...new Set([...texts.long, ...checks.fieldLong])],
changes: listed.length,
noise: listed.filter((pointer) => noise(pointer) !== undefined).length,
flagged: edited
? []
: suggested.flatMap((check) =>
"pointer" in check ? [check.pointer] : [],
),
},
facts: factsOf(checks, texts, {
listed,
noise,
flagged: edited ? [] : suggested,
}),
};
};
/**
* The values of an archive or XML file created or deleted: what its one end
* holds against `tree.empty`, each entry, or the root element, whole once, as
* one added to a file that changed is listed, within the same limits.
*/
export const presenceValues = (
ends: AddedContext["ends"],
tree: CheckTree,
created: boolean,
): { readonly values: DraftValue[]; readonly cut: boolean } => {
const from = created
? { baseline: tree.empty, final: ends.final }
: { baseline: ends.baseline, final: tree.empty };
const change = oneEnd(diffNamedMembers(from.baseline, from.final), created);
return draftValues(change, {
ends: from,
listed: tree.listed,
noise: changeNoise(change, from, tree.xml),
format: (view, pointer) => valueFormat(tree, view, pointer),
referenceRoots: (view) => referenceRoots(tree, view),
});
};
/** The facts a file's notes rest on: what position alone reached, text past the limit, how many changes are noise, and the noise checks kept. */
const factsOf = (
checks: Collected,
texts: WholeTextSuggestions,
change: {
readonly listed: readonly string[];
readonly noise: (pointer: string) => NoiseReason | undefined;
readonly flagged: readonly Suggestion[];
},
): NamedFacts => ({
positional: checks.positional.count,
positionalTags: [...checks.positional.tags],
long: [...new Set([...texts.long, ...checks.fieldLong])],
changes: change.listed.length,
noise: change.listed.filter((pointer) => change.noise(pointer) !== undefined)
.length,
flagged: change.flagged.flatMap((check) =>
"pointer" in check ? [check.pointer] : [],
),
});
+236
View File
@@ -0,0 +1,236 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import {
isBookkeepingName,
isStamp,
isVolatileValue,
} from "./appTaskDraftNoise.js";
import { valueEqualsCheck } from "./appTaskDraftScalars.js";
import {
isGeneratedId,
isIdentifyingAttribute,
isPlaceholder,
isViewStateName,
rankAttributes,
} from "./attributeRank.js";
import { escapeToken, isXmlElement, resolvePointer } from "./viewPointer.js";
import { spellCondition } from "./viewSelector.js";
import { checkFits, type AddedContext } from "./appTaskDraftAdded.js";
type Element = Record<string, JsonValue> & {
name: string;
attributes: Record<string, JsonValue>;
children: JsonValue[];
};
/** Checks of the records nested in one element added whole, and of one record's attributes. */
const MAX_NESTED_CHECKS = 6;
const MAX_PER_RECORD = 3;
/** Whether an element is a record of attributes alone, as KMyMoney's `<SPLIT value="-1749/20" account="A000001" …/>`: no element or text of its own. */
const attributesOnly = (item: JsonValue): item is Element =>
isXmlElement(item) &&
Object.keys(item.attributes).length > 0 &&
item.children.every(
(child) => typeof child === "string" && child.trim() === "",
);
/** The records of attributes alone among an element's children, when they are all one tag; empty otherwise. */
const recordsIn = (element: JsonValue | undefined): Element[] => {
const items = isXmlElement(element)
? element.children.filter(isXmlElement)
: [];
const records = items.filter(attributesOnly);
return records.length === items.length &&
records.every((record) => record.name === records[0]?.name)
? records
: [];
};
/** A list of records of attributes alone in an element: the steps from it to the element holding them, none for its own or a child's tag for a child's, as a transaction's `<SPLITS>`, and the records. */
interface RecordList {
readonly steps: readonly string[];
readonly records: readonly Element[];
}
/**
* The lists of records of attributes alone an element holds: its own
* children, or those of a child holding nothing else that its tag names
* alone, as a KMyMoney `<TRANSACTION>` its `<SPLITS>` of `<SPLIT>`.
*/
export const recordListsOf = (element: JsonValue): RecordList[] => {
const own = recordsIn(element);
if (own.length > 0) return [{ steps: [], records: own }];
const children = isXmlElement(element)
? element.children.filter(isXmlElement)
: [];
const tags = new Map<string, number>();
for (const { name } of children) tags.set(name, (tags.get(name) ?? 0) + 1);
return children.flatMap((child) => {
const records = recordsIn(child);
return records.length > 0 &&
tags.get(child.name) === 1 &&
!/[=[\]]/u.test(child.name)
? [{ steps: ["children", escapeToken(`[name=${child.name}]`)], records }]
: [];
});
};
/** The records at a list's steps in each like sibling of an element, as the splits of the transactions already in the book. */
const cousinsOf = (
likes: readonly JsonValue[],
steps: readonly string[],
tag: string,
): Element[] =>
likes.flatMap((like) =>
recordsIn(
steps.length === 0 ? like : resolvePointer(like, `/${steps.join("/")}`),
).filter((record) => record.name === tag),
);
/** Whether a value a selector can carry and that names something across saves. */
const selectable = (key: string, value: JsonValue | undefined) =>
typeof value === "string" &&
value !== "" &&
!/[=[\]]/u.test(key) &&
!value.includes("][") &&
!isStamp(value) &&
!isPlaceholder(value) &&
!isVolatileValue(value, isBookkeepingName(key));
/**
* The selector naming a nested record alone among its list's: an
* identifier first, unless it is one the app generates or numbers anew in
* each record holding such a list, as KMyMoney's `S0001` in every
* transaction; then the best ranked attribute short of a coordinate or an
* amount, as a split's `[@account=A000001]`.
*/
const recordKey = (
record: Element,
records: readonly Element[],
cousins: readonly Element[],
chars: number,
) => {
const values = Object.entries(record.attributes).flatMap(([key, value]) =>
selectable(key, value) && typeof value === "string" && value.length <= chars
? [{ key, value }]
: [],
);
const repeated = (key: string, value: string) =>
cousins.some((cousin) => cousin.attributes[key] === value);
const [best] = [
...values.filter(
({ key, value }) =>
isIdentifyingAttribute(key) &&
!isGeneratedId(value) &&
!repeated(key, value),
),
...rankAttributes(
values.filter(({ key }) => !isIdentifyingAttribute(key)),
).filter(({ tier }) => tier < 3),
].filter(
({ key, value }) =>
records.filter((other) => other.attributes[key] === value).length === 1,
);
return best === undefined
? undefined
: {
key: best.key,
segment: escapeToken(
`[name=${record.name}]${spellCondition({ prefix: "@", ...best })}`,
),
};
};
/**
* The keys of a record checked one by one: those whose values vary among
* the like records, its list's and those under the element's like siblings,
* as a split's `value` and `payee`, but not its `memo` or `price` that every
* split holds alike, nor one each like record holds equal to an earlier one,
* as `shares` repeats `value`; never its selector's, an identifier, a time,
* a volatile value, view state or an id the app renumbers.
*/
const checkedKeys = (
record: Element,
likes: readonly Element[],
skip: string,
) => {
const keys: string[] = [];
for (const [key, value] of Object.entries(record.attributes)) {
const all = likes.map((like) => like.attributes[key]);
if (
key === skip ||
typeof value !== "string" ||
isIdentifyingAttribute(key) ||
isPlaceholder(value) ||
isStamp(value) ||
isVolatileValue(value, isBookkeepingName(key)) ||
isViewStateName(key) ||
new Set(all).size < 2 ||
keys.some((earlier) =>
likes.every(
(like) => like.attributes[earlier] === like.attributes[key],
),
)
)
continue;
keys.push(key);
}
return keys;
};
/** What checks of nested records read: the file, the end, and whether a pointer names its value without a step by position. */
export interface NestedContext extends Pick<AddedContext, "chars" | "long"> {
readonly file: string;
readonly final: JsonValue | null;
readonly named: (pointer: string) => boolean;
}
/**
* A `value_equals` per attribute of each record of attributes alone nested
* in an element added whole to a list, as each split of a KMyMoney
* transaction holds its amount, account and payee, which the element's own
* attributes and text leave out: the record named by `recordKey`, its
* attributes by `checkedKeys`, at most six in all. Each fails at the seed,
* which lacks the element. Empty for an element with no like sibling, as no
* record then tells what varies.
*/
export const nestedRecordChecks = (
context: NestedContext,
pointer: string,
element: JsonValue,
): DesktopTaskCheckInput[] => {
if (!isXmlElement(element)) return [];
const list = resolvePointer(context.final, pointer.replace(/\/[^/]+$/u, ""));
const likes = (Array.isArray(list) ? list : []).filter(
(item) =>
item !== element && isXmlElement(item) && item.name === element.name,
);
if (likes.length === 0) return [];
return recordListsOf(element)
.flatMap(({ steps, records }) => {
const cousins = cousinsOf(likes, steps, records[0]?.name ?? "");
return records.flatMap((record) => {
const key = recordKey(record, records, cousins, context.chars);
if (key === undefined) return [];
const at = [pointer, ...steps, "children", key.segment].join("/");
return checkedKeys(record, [...records, ...cousins], key.key)
.filter((name) => {
const value = record.attributes[name];
return (
typeof value === "string" &&
checkFits(context, `${at}/attributes/${escapeToken(name)}`, value)
);
})
.slice(0, MAX_PER_RECORD)
.flatMap((name) => {
const field = `${at}/attributes/${escapeToken(name)}`;
const value = record.attributes[name];
return context.named(field) && typeof value === "string"
? [valueEqualsCheck(context.file, field, value)]
: [];
});
});
})
.slice(0, MAX_NESTED_CHECKS);
};
+342 -17
View File
@@ -3,12 +3,14 @@ import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import {
draftOf,
passing,
pointerOf,
statePath,
xml,
xmlDraft,
} from "./appTaskDraft.fixture.js";
const FILE = "Documents/doc.xml";
const CELLS =
"/root/children/[name=Sheet]/children/[name=Cells]/children/[name=Cell]";
const SELECTIONS = "/root/children/[name=Sheet]/children/[name=Selections]";
@@ -43,10 +45,15 @@ const EDITED = {
} as const;
describe("draftTaskFiles noise", () => {
it("leaves view state, renumbered ids, volatile values and times out of a document's suggestions when an edit is there, noting each in values", () => {
it("leaves view state, volatile values and times out while retaining unproven ids", () => {
const file = xmlDraft(workbook(SEED), workbook(EDITED));
expect(file.suggested.map(pointerOf)).toEqual([`${CELLS}[@Col=3][@Row=2]`]);
expect(file.suggested.map(pointerOf)).toEqual(
expect.arrayContaining([
`${CELLS}[@Col=3][@Row=2]`,
`${CELLS}[@Col=3][@Row=5]/attributes/ExprID`,
]),
);
const noted = (note: string) =>
file.values
.filter((value) => value.note === note)
@@ -60,15 +67,8 @@ describe("draftTaskFiles noise", () => {
`${SELECTIONS}/children/[name=Selection]/attributes/startCol`,
].toSorted(),
);
// The emptied formula text goes with the renumbered id of its cell.
expect(noted("renumbered")).toEqual(
[
`${CELLS}[@Col=3][@Row=5]/attributes/ExprID`,
`${CELLS}[@Col=3][@Row=5]/children/0`,
`${CELLS}[@Col=4][@Row=5]/attributes/ExprID`,
`${CELLS}[@Col=4][@Row=5]/children/0`,
].toSorted(),
);
// The attribute name alone does not prove its value is generated.
expect(noted("renumbered")).toEqual([]);
expect(noted("volatile")).toEqual([
"/root/children/[name=meta]/attributes/saved",
"/root/children/[name=meta]/attributes/session",
@@ -81,6 +81,28 @@ describe("draftTaskFiles noise", () => {
expect(file.notes).toEqual([]);
});
it("keeps a changed relationship id alongside another edit", () => {
const expense = (account: string, description: string) =>
`<doc><expense id="one" accountId="${account}" description="${description}"/></doc>`;
const file = xmlDraft(expense("A1", "old"), expense("A2", "new"));
const account = file.values.find(({ pointer }) =>
pointer.endsWith("/attributes/accountId"),
);
expect(account?.note).toBeUndefined();
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "value_equals",
pointer: expect.stringContaining("/attributes/accountId"),
value: "A2",
}),
]),
);
expect(passing(FILE, xml(expense("A1", "new")), file.suggested)).toContain(
false,
);
});
it("keeps a formula edit when the cell's ExprID changes too", () => {
const sheet = (march: string, formula: string, id: string) =>
`<Workbook><Sheet><Cells><Cell Row="2" Col="3">${march}</Cell><Cell Row="5" Col="3" ExprID="${id}">${formula}</Cell></Cells></Sheet></Workbook>`;
@@ -94,12 +116,9 @@ describe("draftTaskFiles noise", () => {
expect(shown).toContain("=sum(C2:C5)");
expect(
file.values
.filter(({ note }) => note === "renumbered")
.map(({ pointer }) => pointer),
).toEqual([
"/root/children/[name=Sheet]/children/[name=Cells]/children/[name=Cell][@Row=5]/attributes/ExprID",
]);
file.values.find(({ pointer }) => pointer.endsWith("/attributes/ExprID"))
?.note,
).toBeUndefined();
});
it("keeps an edit that follows more noise than a file has room for checks", () => {
@@ -356,6 +375,312 @@ describe("draftTaskFiles upkeep in an archive", () => {
});
});
describe("draftTaskFiles layout beside a text edit", () => {
it("keeps a number an edit changed beside text as content, unless a name on its way says it is layout", () => {
const shop = (description: string, amount: string, width: string) =>
`<shop><orders><order id="1"><description>${description}</description><amount value="${amount}"/><box width="${width}"/></order><order id="2"><description>Tape</description><amount value="1"/><box width="2"/></order></orders></shop>`;
const order = "/root/children/[name=orders]/children/[name=order][@id=1]";
const file = xmlDraft(
shop("Two boxes", "10", "4"),
shop("Twelve boxes", "12", "6"),
);
expect(
file.values.map(({ pointer, note }) => [
pointer.replace(order, "~"),
note ?? null,
]),
).toEqual([
["~/children/[name=description]/children/0", null],
["~/children/[name=amount]/attributes/value", null],
["~/children/[name=box]/attributes/width", "layout"],
]);
expect(file.suggested.map(pointerOf)).toContain(
`${order}/children/[name=amount]/attributes/value`,
);
});
});
describe("draftTaskFiles for a presentation whose save after a reload rewrote its styles", () => {
const entry = (name: string, view: string) => ({
name,
size: view.length,
sha256: view,
format: "xml",
view: xml(view),
view_error: null,
});
const NS =
'xmlns:office="o" xmlns:draw="d" xmlns:presentation="p" xmlns:text="t" xmlns:style="s"';
/** Slides as Impress keeps them: frames by class, each with an automatic style it shares and renumbers. */
const slides = (title: string) =>
`<office:document-content ${NS}><office:automatic-styles><text:list-style style:name="L2"><style:list-level-properties text:space-before="0.6cm"/></text:list-style></office:automatic-styles><office:body><office:presentation>${[
"Welcome",
"Schedule",
]
.map(
(page) =>
`<draw:page draw:name="${page}"><draw:frame presentation:style-name="pr1" presentation:class="title"><draw:text-box><text:p>${page === "Schedule" ? title : "Welcome"}</text:p></draw:text-box></draw:frame><draw:frame presentation:style-name="pr4" presentation:class="outline"><draw:text-box><text:p>Tomatoes</text:p></draw:text-box></draw:frame></draw:page>`,
)
.join("")}</office:presentation></office:body></office:document-content>`;
/** Master pages' fields, wrapped or not in an automatic text style, beside many such pages. */
const masters = (wrapped: boolean, spacing: string) =>
`<office:document-styles ${NS}><office:automatic-styles><text:list-style style:name="L2"><style:list-level-properties text:space-before="${spacing}"/></text:list-style></office:automatic-styles><office:master-styles>${Array.from(
{ length: 12 },
(_, index) =>
`<style:master-page style:name="M${String(index)}"><draw:frame presentation:class="footer"><draw:text-box><text:p>${wrapped ? '<text:span text:style-name="MT1"><presentation:footer/></text:span>' : "<presentation:footer/>"}</text:p></draw:text-box></draw:frame></style:master-page>`,
).join("")}</office:master-styles></office:document-styles>`;
const deck = (title: string, wrapped: boolean) => ({
entries: [
entry("content.xml", slides(title)),
entry("styles.xml", masters(wrapped, wrapped ? "0.9cm" : "0.6cm")),
],
entry_count: 2,
truncated: false,
});
const SCHEDULE =
"/entries/[name=content.xml]/view/root/children/[name=office:body]/children/[name=office:presentation]/children/[name=draw:page][@draw:name=Schedule]/children/[name=draw:frame]";
it("names a slide's frames by their class, not the automatic style the app renumbers, suggests the title alone, and lists it before the rewrite", () => {
const [file] = draftOf({
"Documents/garden.odp": statePath(
"document",
"zip",
deck("Planting Schedule", false),
deck("Spring Planting Calendar", true),
),
});
expect(file?.suggested).toEqual([
{
kind: "text_equals",
file: "Documents/garden.odp",
pointer: `${SCHEDULE}[@presentation:class=title]`,
value: "Spring Planting Calendar",
},
]);
const [first, ...rest] = file?.values ?? [];
expect(first).toMatchObject({
pointer: `${SCHEDULE}[@presentation:class=title]/children/[name=draw:text-box]/children/[name=text:p]/children/0`,
after: "Spring Planting Calendar",
});
expect(rest.length).toBeGreaterThan(10);
expect(rest.every(({ note }) => note === "upkeep")).toBe(true);
});
});
describe("draftTaskFiles for an animation whose app keeps what is current", () => {
/** A Pencil2D project: the frame, colour, layer and view the app has current, and its layers. */
const project = (current: string, bitmap: string) =>
`<document><projectdata><currentFrame value="1"/><currentColor r="0" b="0" g="0" a="255"/><currentLayer value="${current}"/><currentView m11="1" dx="0"/><fps value="12"/></projectdata><object><layer id="1" name="Camera Layer" type="5"/><layer id="2" name="Vector Layer" type="2"/><layer id="3" name="${bitmap}" type="1"/><layer id="4" name="Ground" type="1"/></object></document>`;
it("notes the layer the app has current as view state, never a check, beside the layer the user renamed", () => {
const file = xmlDraft(project("3", "Bitmap Layer"), project("2", "Ball"));
expect(file.suggested.map(pointerOf)).toEqual([
"/root/children/[name=object]/children/[name=layer][@id=3]/attributes/name",
"/root/children/[name=object]/children/[name=layer][@name=Bitmap Layer]",
]);
expect(
file.values.map(({ pointer, note }) => [pointer, note ?? null]),
).toEqual([
[
"/root/children/[name=object]/children/[name=layer][@id=3]/attributes/name",
null,
],
[
"/root/children/[name=projectdata]/children/[name=currentLayer]/attributes/value",
"view_state",
],
]);
});
});
describe("draftTaskFiles for a mind map, as VYM saves one", () => {
const branch = (uuid: string, heading: string) =>
`<branch hideLink="false" uuid="{${uuid}}"><heading textMode="plainText">${heading}</heading></branch>`;
/** A map: its branch count, branches each with a GUID VYM makes, a view setting, and the saved selection. */
const map = (count: string, added: string, selected: string) =>
`<vymmap version="2.6.11" branchCount="${count}"><mapcenter uuid="{4b6e7612-970d-4d72-8fae-8ebaf02511c9}"><heading>Team Offsite</heading>${branch("d1e07ab2-1ecd-4c39-aa93-e7b70576a029", "Venue")}<branch hideLink="false" uuid="{4cdcd61f-90fb-4965-91a1-849509829d26}"><heading>Agenda</heading>${branch("d47c1733-7117-42b7-b45b-9ac244bc3d67", "Kickoff talk")}${branch("8e689d15-a04a-4c60-81ad-6317a3b5874f", "Strategy workshop")}${added}</branch></mapcenter>${added === "" ? "" : '<setting key="/treeeditor/visible">false</setting>'}<select>${selected}</select></vymmap>`;
const SEED = map("4", "", "mc:0,bo:2");
const END = map(
"5",
branch("18eadb5d-04fc-4448-a0f9-1f9a3dedaff7", "Sunset boat tour"),
"mc:0,bo:1",
);
const AGENDA =
"/root/children/[name=mapcenter]/children/[name=branch][@uuid={4cdcd61f-90fb-4965-91a1-849509829d26}]/children";
it("names the new branch by its heading, not the GUID VYM made for it, and checks that heading and the branches' count", () => {
const file = xmlDraft(SEED, END);
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: "Documents/doc.xml",
pointer: `${AGENDA}/[name=branch][>heading=Sunset boat tour]/children/[name=heading]`,
value: "Sunset boat tour",
},
{
kind: "member_count",
file: "Documents/doc.xml",
pointer: AGENDA,
matching: "[name=branch]",
equals: 3,
},
]);
});
it("notes the saved selection and a tree editor setting as view state and the branch count as upkeep, the new heading first", () => {
const file = xmlDraft(SEED, END);
expect(
file.values.map(({ pointer, note }) => [
pointer.replace(AGENDA, "~"),
note ?? null,
]),
).toEqual([
[
"~/[name=branch][>heading=Sunset boat tour]/children/[name=heading]",
null,
],
["/root/children/[name=setting]", "view_state"],
["/root/attributes/branchCount", "upkeep"],
["/root/children/[name=select]/children/0", "view_state"],
]);
});
});
describe("draftTaskFiles counts an app keeps of its records", () => {
it("notes a count in an element's text that equals its records, as GnuCash's count-data, as upkeep, never a check or a guard", () => {
const book = (count: string, added: string) =>
`<gnc:book xmlns:gnc="g" xmlns:cd="c"><gnc:count-data cd:type="account">2</gnc:count-data><gnc:count-data cd:type="transaction">${count}</gnc:count-data><gnc:account name="Groceries"/><gnc:account name="Checking"/><gnc:transaction description="Corner Grocer"/>${added}</gnc:book>`;
const file = xmlDraft(
book("1", ""),
book("2", '<gnc:transaction description="Greenleaf Market"/>'),
);
const count =
"/root/children/[name=gnc:count-data][@cd:type=transaction]/children/0";
expect(file.values.find(({ pointer }) => pointer === count)).toMatchObject({
note: "upkeep",
});
expect(file.suggested.map(pointerOf)).not.toContain(count);
expect(
file.guards.map(pointerOf).filter((at) => at?.includes("count-data")),
).toEqual([]);
});
it("checks a count the user entered, which tallies no tag at both ends, though it equals how many of a tag its record holds", () => {
const stock = (widgets: string) =>
`<inventory><item><name>Widget</name><count>${widgets}</count></item><item><name>Gadget</name><count>5</count></item></inventory>`;
const file = xmlDraft(stock("3"), stock("1"));
const count = file.values.find(({ after }) => after === "1");
expect(count).toBeDefined();
expect(count?.note).toBeUndefined();
expect(passing(FILE, xml(stock("3")), file.suggested)).toEqual([false]);
expect(passing(FILE, xml(stock("1")), file.suggested)).toEqual([true]);
});
it("suggests no check of the count a new element keeps of its members, as FreeCAD's ObjectDeps of its Deps", () => {
/** Objects as FreeCAD saves them: each one's dependencies, by name, then the objects. */
const model = (count: string, deps: string, objects: string) =>
`<Document><Objects Count="${count}" Dependencies="1"><ObjectDeps Name="Plate" Count="0"/>${deps}<Object type="Part::Box" name="Plate" id="1324"/>${objects}</Objects></Document>`;
const file = xmlDraft(
model("1", "", ""),
model(
"3",
'<ObjectDeps Name="Hole" Count="0"/><ObjectDeps Name="PlateWithHole" Count="2"><Dep Name="Plate"/><Dep Name="Hole"/></ObjectDeps>',
'<Object type="Part::Cylinder" name="Hole" id="1325"/><Object type="Part::Cut" name="PlateWithHole" id="1326"/>',
),
);
// Count="2" counts the two Deps it holds; Count="0" another object's none, which no tag tallies.
expect(file.suggested.map(pointerOf)).not.toContain(
"/root/children/[name=Objects]/children/[name=ObjectDeps][@Name=PlateWithHole]/attributes/Count",
);
});
});
describe("draftTaskFiles styles a user applies", () => {
const NS = 'xmlns:office="o" xmlns:text="t" xmlns:style="s"';
/** A Writer document: its automatic styles, and named sections each holding a paragraph in a named style. */
const minutes = (quote: string, next: string) =>
`<office:document-content ${NS}><office:automatic-styles><style:style style:name="P1" style:family="paragraph"/></office:automatic-styles><office:body><office:text><text:h text:style-name="Heading_20_1">Minutes</text:h><text:section text:name="Quote"><text:p text:style-name="${quote}">Ship it, said Ana.</text:p></text:section><text:section text:name="Next"><text:p text:style-name="Standard">${next}</text:p></text:section></office:text></office:body></office:document-content>`;
it("checks a named style the user gave a paragraph beside another edit, never upkeep, as it would an automatic one the app renumbers", () => {
const seed = minutes("Standard", "Next meeting Friday.");
const end = minutes("Quotations", "Next meeting Monday.");
const file = xmlDraft(seed, end);
const style = file.values.find(({ after }) => after === "Quotations");
expect(style).toBeDefined();
expect(style?.note).toBeUndefined();
expect(
file.suggested.some(
(check) => "value" in check && check.value === "Quotations",
),
).toBe(true);
// A solve that edits the date alone fails.
expect(
passing(
FILE,
xml(minutes("Standard", "Next meeting Monday.")),
file.suggested,
),
).toContain(false);
});
});
describe("draftTaskFiles for a name shared by two lists", () => {
it("checks a category added beside a template of the same name", () => {
const file = xmlDraft(
'<doc><template name="Travel"><item>bag</item></template></doc>',
'<doc><template name="Travel"><item>bag</item></template><category name="Travel"/></doc>',
);
expect(
file.values.some(
(value) =>
value.pointer.includes("category") && value.note === "upkeep",
),
).toBe(false);
expect(file.suggested.map(pointerOf).join(" ")).toContain("category");
});
});
describe("draftTaskFiles for a drawing resized beside a rename", () => {
const model = (name: string, width: string) =>
`<model><name>${name}</name><diagram><widget width="${width}"/><widget width="4"/></diagram></model>`;
it("checks the width the user changed when the only other edit is a name outside the drawing", () => {
const file = xmlDraft(model("Shop", "10"), model("Store", "20"));
const width = file.suggested.find(
(check) => "pointer" in check && check.pointer.endsWith("width"),
);
expect(file.suggested.map(pointerOf)).toContain(
"/root/children/[name=diagram]/children/[name=widget][@width=20]/name",
);
expect(
file.values.some(
(value) => value.pointer.includes("width") && value.note === "layout",
),
).toBe(false);
expect(passing(FILE, xml(model("Store", "10")), file.suggested)).toContain(
false,
);
expect(
passing(FILE, xml(model("Store", "20")), file.suggested).every(Boolean),
).toBe(true);
});
});
describe("draftTaskFiles when a sibling lock changed", () => {
const text = (line: string) => ({
lines: [line],
+401 -60
View File
@@ -1,11 +1,14 @@
import type { JsonValue } from "../jsonValue.js";
import { isTimestamp } from "./appTask.js";
import {
isAutomaticStyle,
isIdentifyingAttribute,
isNameLikeKey,
isViewStateName,
VIEW_STATE,
} from "./attributeRank.js";
import { isMemberCount } from "./appTaskDraftMemberCount.js";
import { idReferencesOf, mirrorsOf } from "./appTaskDraftMirrors.js";
import { isPositionalKey, positionalKeys } from "./positionalKeys.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { elementText, isXmlElement, resolvePointer } from "./viewPointer.js";
@@ -17,6 +20,7 @@ export const NOISE_REASONS = [
"volatile",
"timestamp",
"upkeep",
"layout",
] as const;
export type NoiseReason = (typeof NOISE_REASONS)[number];
@@ -34,25 +38,24 @@ const isViewStateValue = (value: string): boolean =>
const namesElement = (key: string) =>
isNameLikeKey(key) || /^(?:[^:]*:)?key$/iu.test(key);
/** An attribute an app renumbers as it saves: a generated id such as Gnumeric's `ExprID` or Scribus's `ItemID`, or LibreOffice's `rsid`. */
export const isRenumberedKey = (key: string): boolean => {
const local = key.split(":").at(-1) ?? key;
return (
!isIdentifyingAttribute(key) &&
/(?:[a-z]I[dD]|(?:^|[-_])[rR][sS][iI][dD])$/u.test(local)
);
};
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
export const isUuid = (value: string): boolean => UUID.test(value);
/** Seconds since 1970 of 2000-01-01 and 2100-01-01: an epoch time a save stamps falls between. */
const EPOCH_RANGE = [946_684_800, 4_102_444_800] as const;
/** UUIDs and epoch-shaped values in named save metadata are likely generated. */
/** Base64 of binary data an app encodes as it saves, as Xournal++'s page preview, a PNG (`iVBORw0KGgo`), or any run of 256 or more base64 characters mixing cases and digits, line breaks aside: no prose runs that long without a space. */
const ENCODED =
/^(?:iVBORw0KGgo[A-Za-z0-9+/=\r\n]*|(?=[^]*[a-z])(?=[^]*[A-Z])(?=[^]*\d)[A-Za-z0-9+/\r\n]{256,}={0,2})$/u;
/**
* UUIDs, encoded binary, and epoch-shaped values in named save metadata are
* likely generated. Numeric shape alone does not identify a timestamp.
*/
export const isVolatileValue = (
value: string,
bookkeeping = false,
): boolean => {
if (UUID.test(value)) return true;
if (isUuid(value) || ENCODED.test(value.trim())) return true;
if (!bookkeeping) return false;
if (!/^\d{10}(?:\d{3})?$/u.test(value)) return false;
const seconds = Number(value.slice(0, 10));
@@ -81,7 +84,7 @@ const DATE_PART = /^(?:year|month|day|hour|minute|second)$/u;
* `cdate` and `mdate`, or `created`, `modified`, `saved` or `updated`.
*/
const BOOKKEEPING =
/^[cm]date$|creat(?:ed|ion)|modif(?:ied|ication)|updated|saved|changed|accessed|timestamp/u;
/^[cm]date$|creat(?:ed|ion)|modif(?:ied|ication)|updated|saved|changed|accessed|entered|timestamp/u;
export const isBookkeepingName = (name: string) =>
BOOKKEEPING.test((name.split(":").at(-1) ?? name).toLowerCase());
@@ -167,6 +170,97 @@ const stampedAlong = (elements: readonly Element[]) => {
});
};
/** A date written whole, as GnuCash's `2026-11-06 08:50:12 +0000`, which `isTimestamp` reads only in ISO 8601's own spelling. */
const DATE_TEXT = /^\s*\d{4}-\d{2}-\d{2}\b/u;
/** Whether a value is a date under an element bookkeeping names, as GnuCash's `<trn:date-entered><ts:date>…`, or such an element holding one. */
const stampedWhole = (
elements: readonly Element[],
value: JsonValue | undefined,
) =>
elements.some(isBookkeeping) &&
DATE_TEXT.test(
typeof value === "string"
? value
: isXmlElement(value)
? elementText(value)
: "",
);
/** Whether an element holds an id the app assigns, as GnuCash's `<trn:id type="guid">`. */
const assignedId = (element: Element) =>
/^(?:[^:]*:)?id$/iu.test(element.name) &&
isRecord(element.attributes) &&
element.attributes.type === "guid";
/** Whether text holds a control character other than a tab or line break, or the replacement character, which no user types, as GnuCash's options hold before it fills them. */
const isGarbled = (value: string) =>
[...value].some((character) => {
const code = character.codePointAt(0) ?? 0;
return (
(code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) ||
code === 0x7f ||
code === 0xfffd
);
});
/** An attribute counting the ids an app hands out, as Umbrello's `uniqueid` or Tiled's `nextobjectid`. */
const ID_COUNTER = /^(?:next|unique|last)[-_]?(?:[\p{L}_-]*)id$/iu;
/** A key keeping the last or next id an app hands out, as Umbrello's `lastobject`, which holds the id its new element took. */
const COUNTER_KEY = /^(?:next|unique|last)[-_]?[\p{L}_-]*$/iu;
/** Whether a value is one a program makes: a UUID, an epoch time or garbled text, a count under the metadata, an id counter, an id the change gave a new element where a counter or that element holds it (`fresh`), or in or at an id the app assigns. */
const volatileAt = (
elements: readonly Element[],
key: string | undefined,
value: JsonValue | undefined,
fresh: boolean,
xml: boolean,
) =>
(typeof value === "string" &&
(isVolatileValue(
value,
elements.some(isBookkeeping) ||
(key !== undefined && isBookkeepingName(key)),
) ||
isGarbled(value) ||
fresh)) ||
(key !== undefined && ID_COUNTER.test(key.split(":").at(-1) ?? key)) ||
metadataCount(elements, key, value) ||
elements.some(assignedId) ||
(xml && isXmlElement(value) && assignedId(value));
/**
* The ids of the elements a change added (`id`, `xid`, `uuid`, `guid`, as
* Umbrello's new attribute's `xmi:id="ubcgF2AWfBmHh"`), which another save
* of the same edit would not repeat, so a value equal to one in an id
* counter or in that element is the app's: those of four or more
* characters, not a plain number.
*/
const freshIds = (
change: Pick<DesktopStateDifference, "added">,
ends: Ends,
): ReadonlySet<string> =>
new Set(
change.added.flatMap((pointer) => {
const element = resolvePointer(ends.final, pointer);
return isXmlElement(element)
? Object.entries(element.attributes).flatMap(([key, value]) =>
/^(?:[^:]*:)?(?:x|uu|g)?id$/iu.test(key) &&
typeof value === "string" &&
value.length >= 4 &&
!/^\d+$/u.test(value)
? [value]
: [],
)
: [];
}),
);
/** A container of an app's own bookkeeping slots, as GnuCash's `book:slots`, which it adds to and fills on reopening a book. */
const isSlots = (element: Element) => /^(?:[^:]*:)?slots$/u.test(element.name);
/** Whether a pointer is a date the app stamps in parts, or inside one. */
export const inSplitDate = (view: JsonValue | null, pointer: string): boolean =>
stampedAlong(elementsAlong(view, pointer));
@@ -198,9 +292,15 @@ const showsView = (element: Element) =>
isViewStateName(element.name) ||
Object.entries(isRecord(element.attributes) ? element.attributes : {}).some(
([key, value]) =>
typeof value === "string" && namesElement(key) && isViewStateValue(value),
typeof value === "string" &&
namesElement(key) &&
(isViewStateValue(value) || VIEW_SETTING.test(value)),
);
/** A settings path whose last part says how a panel shows, as VYM's `<setting key="/treeeditor/visible">`. */
const VIEW_SETTING =
/^\/(?:[\w-]+\/)+(?:visible|hidden|shown?|expanded|collapsed|geometry|state|size|zoom)$/iu;
/** A file's views at its two ends. */
interface Ends {
readonly baseline: JsonValue | null;
@@ -246,13 +346,21 @@ const positionalRenumbering = (ends: Ends) => {
};
};
/** A pointer to an archive entry's own size or digest, which change with any edit to it. */
const ENTRY_META = /^\/entries\/[^/]+\/(?!view(?:\/|$))/u;
/** A pointer into an archive entry's view: the entry's part of it, as `/entries/[name=styles.xml]/view/`. */
const ENTRY_VIEW = /^\/entries\/[^/]+\/view\//u;
/**
* Attributes an archive entry's elements only gained, as LibreOffice fills in
* `loext:tab-stop-distance` across `styles.xml` on save, while another entry
* holds the edit: whether each pointer is one.
* What an app keeps up as it saves, while the edit is elsewhere: attributes an
* known style defaults an archive entry's elements gained, as LibreOffice fills in
* `loext:tab-stop-distance` across `styles.xml`, while another entry holds
* the edit; and, while a change outside them is the edit, any change to a
* document's styles, `styles.xml` or its style containers and master,
* handout and notes pages, or to an attribute naming an automatic style
* at both ends (`isAutomaticStyle`), as Impress wraps its master pages'
* fields in a new `MT1` style after a reload.
*/
const upkeepOf = (
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
@@ -288,6 +396,41 @@ const upkeepOf = (
filled.set(entry, counts);
counts.set(key, (counts.get(key) ?? 0) + 1);
}
// A style a user names, as "Quotations" given to a paragraph, is an edit; one the app numbers, as `P1`, its upkeep.
const automatic = (pointer: string, key: string) =>
[ends.baseline, ends.final].every((view) => {
const value = resolvePointer(view, pointer);
return (
value === undefined ||
(typeof value === "string" && isAutomaticStyle(key, value))
);
});
const styled = (pointer: string) => {
const key = attributeKeyOf(pointer);
const view =
resolvePointer(ends.final, pointer) === undefined
? ends.baseline
: ends.final;
return (
xml(view, pointer) &&
(ENTRY_VIEW.exec(pointer)?.[0] === "/entries/[name=styles.xml]/view/" ||
(key !== undefined &&
/style-name$/iu.test(key) &&
automatic(pointer, key)) ||
elementsAlong(view, pointer).some(({ name }) => STYLE_AREA.test(name)))
);
};
// The user's edit is elsewhere when a change no other rule calls noise lies outside the styles.
const elsewhere = [
...change.added,
...change.changed,
...change.removed,
].some(
(pointer) =>
noise(pointer) === undefined &&
!styled(pointer) &&
!ENTRY_META.test(pointer),
);
return (pointer: string) => {
const [entry] = ENTRY_VIEW.exec(pointer) ?? [];
const key = attributeKeyOf(pointer);
@@ -295,39 +438,235 @@ const upkeepOf = (
entry === undefined || key === undefined
? 0
: (filled.get(entry)?.get(key) ?? 0);
const view =
resolvePointer(ends.final, pointer) === undefined
? ends.baseline
: ends.final;
const inStyleArea = elementsAlong(view, pointer).some(({ name }) =>
STYLE_AREA.test(name),
);
const automaticName =
key !== undefined && /style-name$/iu.test(key) && automatic(pointer, key);
// One attribute gained in styles.xml is the edit. A repeated fill-in, an automatic style name, or a style area the app rewrites is upkeep.
return (
edited.size > 0 &&
entry !== undefined &&
!edited.has(entry) &&
gained(pointer) &&
count >= 2
(elsewhere &&
(automaticName || inStyleArea || (styled(pointer) && count >= 2))) ||
(edited.size > 0 &&
entry !== undefined &&
!edited.has(entry) &&
gained(pointer) &&
count >= 2)
);
};
};
/** An element holding an ODF document's styles, or its master, handout and notes pages, which an app rewrites as it saves after a reload. */
const STYLE_AREA =
/^(?:office:(?:styles|automatic-styles|master-styles|font-face-decls)|style:(?:master-page|handout-master))$/u;
/** A number, or a list of numbers split by commas or semicolons, as Dia's `6.3225,6.15;12.5775,8.15`. */
const COORDINATES =
/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?(?:[,;] ?-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)*$/u;
/** Whether a value is a coordinate or a list of them, which an app may derive rather than its user enter. */
export const isCoordinates = (value: JsonValue | undefined): boolean =>
typeof value === "string" && COORDINATES.test(value.trim());
/** How far above an attribute's element the element whose text changed may sit for the attribute to be its layout. */
const MAX_LAYOUT_CLIMB = 3;
/**
* Attributes holding coordinates that changed inside an element whose text
* changed while their own element's did not, as Dia moves and resizes a box
* (`obj_pos`, `obj_bb`, `elem_width`) around its new text: layout the app
* derives from the edit. A list of numbers is layout; a lone number only
* where a name on its way says it is (`namesLayout`). The element whose text changed is at most three
* levels up and below the root's own children; an attribute of an element
* whose own text changed, as a spreadsheet cell's `office:value` beside its
* text, is none.
*/
const derivedLayout = (
change: Pick<DesktopStateDifference, "changed">,
ends: Ends,
) => {
const textAt = (view: JsonValue | null, pointer: string) => {
const element = resolvePointer(view, pointer);
return isXmlElement(element) ? elementText(element) : undefined;
};
const known = new Map<string, boolean>();
const retexted = (pointer: string) => {
const before = textAt(ends.baseline, pointer);
const found =
known.get(pointer) ??
(before !== undefined && before !== textAt(ends.final, pointer));
known.set(pointer, found);
return found;
};
const layout = new Set(
change.changed.filter((pointer) => {
const value = resolvePointer(ends.final, pointer);
const owner = ownerOfAttribute(pointer);
if (
attributeKeyOf(pointer) === undefined ||
!isCoordinates(value) ||
retexted(owner)
)
return false;
const segments = owner.split("/");
const above = Array.from({ length: MAX_LAYOUT_CLIMB }, (_, index) =>
segments.slice(0, -2 * (index + 1)).join("/"),
);
const at = above.findIndex(
(element) =>
/\/children\/[^/]+$/u.test(element) &&
element.split("/").at(-3) !== "root" &&
retexted(element),
);
// A lone number is layout only where a name on its way says so; a list of them always is.
return (
at >= 0 &&
(/[,;]/u.test(String(value)) ||
namesLayout(ends.final, pointer, [owner, ...above.slice(0, at)]))
);
}),
);
return (pointer: string) => layout.has(pointer);
};
/** A tag naming a drawing of a model rather than the model, as Umbrello's `diagrams`, `diagram`, `widgets` and `classwidget`. */
const DRAWING = /(?:diagram|widget|canvas|scene)s?$/iu;
/**
* Coordinates in a drawing of the model, while the model change is
* elsewhere, as Umbrello grows a class's box (`classwidget` `height` 52 to
* 67) in its diagram when an attribute is added to the class: an attribute
* holding a list of numbers, or a number a name on its way calls layout,
* below an element whose tag names a diagram, widget, canvas or scene, while
* a change no other rule calls noise lies outside every such element.
*/
const drawingLayout = (
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
ends: Ends,
noise: (pointer: string) => NoiseReason | undefined,
) => {
const viewOf = (pointer: string) =>
resolvePointer(ends.final, pointer) === undefined
? ends.baseline
: ends.final;
const drawn = (pointer: string) =>
elementsAlong(viewOf(pointer), pointer).some(({ name }) =>
DRAWING.test(name.split(":").at(-1) ?? name),
);
// A model element added or removed can resize the drawing. A rename or
// other edit outside it does not make a deliberate resize into layout.
const elsewhere = [...change.added, ...change.removed].some(
(pointer) =>
noise(pointer) === undefined &&
!ENTRY_META.test(pointer) &&
!drawn(pointer),
);
return (pointer: string) => {
const value = resolvePointer(viewOf(pointer), pointer);
return (
elsewhere &&
attributeKeyOf(pointer) !== undefined &&
isCoordinates(value) &&
drawn(pointer) &&
(/[,;]/u.test(String(value)) ||
namesLayout(viewOf(pointer), pointer, [ownerOfAttribute(pointer)]))
);
};
};
/** A word in a name for where or how large something is drawn: a position, a point, a box, a corner, a width or height, an offset or a side. */
const LAYOUT_WORD =
/^(?:pos|position|x|y|z|point|bb|bbox|bounds|rect|rectangle|corner|width|height|w|h|left|top|right|bottom|offset|origin|coords?)$/u;
/** Whether a name holds a layout word, its parts split at punctuation and case, as Dia's `obj_pos`, `elem_width` or `dia:point`. */
const isLayoutName = (name: string) =>
name
.replaceAll(/(?<lower>\p{Ll})(?<upper>\p{Lu})/gu, "$<lower> $<upper>")
.toLowerCase()
.split(/[^\p{L}\d]+/u)
.some((word) => LAYOUT_WORD.test(word));
/**
* Whether the attribute at a pointer, its element's tag, or the tag or a
* name-like attribute's value of an element between it and the element
* whose text changed, names layout, as Dia keeps `elem_width` in
* `<dia:attribute name="elem_width"><dia:real val="6.155"/>`; an order's
* `<amount value="12"/>` is no layout.
*/
const namesLayout = (
view: JsonValue | null,
pointer: string,
elements: readonly string[],
) =>
[
attributeKeyOf(pointer) ?? "",
...elements.flatMap((at) => {
const element = resolvePointer(view, at);
return isXmlElement(element)
? [
element.name,
...Object.entries(element.attributes).flatMap(([key, value]) =>
isNameLikeKey(key) && typeof value === "string" ? [value] : [],
),
]
: [];
}),
].some(isLayoutName);
/**
* Why each pointer into a file is noise, or undefined when it is not: a tag,
* attribute or name-like attribute value on its way naming view state, as
* `[@config:name=CursorPositionX]`; an attribute an app renumbers, an
* identifier it numbers by position, or anything inside an element both ends
* hold whose renumbered attribute changed, as Gnumeric empties a formula cell
* whose shared expression it renumbers; a UUID or epoch time, or a duration or
* `[@config:name=CursorPositionX]`; an identifier numbered by position;
* a UUID or epoch time, an id
* counter, an id the change gave a new element (`freshIds`), or a duration or
* count under the document's metadata; a time the app stamps, whole or in
* parts (`inSplitDate`); the known style default an archive entry gained
* while another entry holds the edit.
* parts (`inSplitDate`), or a date under a tag naming bookkeeping; an id
* the app assigns (`type="guid"`), or text of control characters; upkeep, a
* change inside an app's `slots`, a known style default an archive entry
* gained while another entry holds the edit, a text showing another field
* that changed alike (`mirrorsOf`), or an element holding nothing but the id
* of a record the change added (`idReferencesOf`); layout an edit's text
* derived (`derivedLayout`), or a drawing of the model holds while the
* model change is elsewhere (`drawingLayout`).
*/
export const changeNoise = (
change: Pick<DesktopStateDifference, "added" | "changed" | "removed">,
ends: Ends,
xml: (view: JsonValue | null, pointer: string) => boolean,
): ((pointer: string) => NoiseReason | undefined) => {
const renumbered = change.changed.flatMap((pointer) => {
const key = attributeKeyOf(pointer);
return xml(ends.final, pointer) && key !== undefined && isRenumberedKey(key)
? [ownerOfAttribute(pointer)]
: [];
});
const isXmlPointer = (pointer: string) =>
xml(
resolvePointer(ends.final, pointer) === undefined
? ends.baseline
: ends.final,
pointer,
);
const xmlChange = {
added: change.added.filter((pointer) => xml(ends.final, pointer)),
changed: change.changed.filter(isXmlPointer),
removed: change.removed.filter((pointer) => xml(ends.baseline, pointer)),
};
const byPosition = positionalRenumbering(ends);
const fresh = freshIds(xmlChange, ends);
const added = new Set(change.added);
// A reference on an element both ends hold, as a split moved to the new account, is the user's.
const freshAt = (
pointer: string,
key: string | undefined,
value: JsonValue | undefined,
) =>
typeof value === "string" &&
fresh.has(value) &&
((key !== undefined && COUNTER_KEY.test(key.split(":").at(-1) ?? key)) ||
pointer
.split("/")
.some((_, index, segments) =>
added.has(segments.slice(0, index + 1).join("/")),
));
const known = new Map<string, NoiseReason | undefined>();
const base = (pointer: string): NoiseReason | undefined => {
if (known.has(pointer)) return known.get(pointer);
@@ -342,38 +681,40 @@ export const changeNoise = (
const reason: NoiseReason | undefined =
elements.some(showsView) || (key !== undefined && isViewStateName(key))
? "view_state"
: (key !== undefined &&
(isRenumberedKey(key) ||
(isIdentifyingAttribute(key) && byPosition(pointer, key)))) ||
renumbered.some((element) => {
if (pointer !== element && !pointer.startsWith(`${element}/`))
return false;
if (pointer === element) return false;
const next = resolvePointer(ends.final, pointer);
const text =
typeof next === "string"
? next.trim()
: isXmlElement(next)
? elementText(next).trim()
: undefined;
// Gnumeric clears a shared formula when it renumbers the cell. A formula that still has text was edited.
return text === undefined || text === "";
})
: key !== undefined &&
isIdentifyingAttribute(key) &&
byPosition(pointer, key)
? "renumbered"
: (typeof value === "string" &&
isVolatileValue(
value,
elements.some(isBookkeeping) ||
(key !== undefined && isBookkeepingName(key)),
)) ||
metadataCount(elements, key, value)
: volatileAt(
elements,
key,
value,
freshAt(pointer, key, value),
isXml,
)
? "volatile"
: isStamp(value ?? null) || stampedAlong(elements)
: isStamp(value ?? null) ||
stampedAlong(elements) ||
stampedWhole(elements, value)
? "timestamp"
: undefined;
: elements.some(isSlots) ||
(isXml && isMemberCount(ends, pointer, key))
? "upkeep"
: undefined;
known.set(pointer, reason);
return reason;
};
const upkeep = upkeepOf(change, ends, base, xml);
return (pointer) => base(pointer) ?? (upkeep(pointer) ? "upkeep" : undefined);
const layout = derivedLayout(change, ends);
const drawing = drawingLayout(change, ends, base);
const mirror = mirrorsOf(xmlChange, ends);
const reference = idReferencesOf(xmlChange, ends);
return (pointer) =>
base(pointer) ??
(isXmlPointer(pointer) &&
(upkeep(pointer) || mirror(pointer) || reference(pointer))
? "upkeep"
: isXmlPointer(pointer) && (layout(pointer) || drawing(pointer))
? "layout"
: undefined);
};
+1 -1
View File
@@ -34,7 +34,7 @@ export const draftNoteSchema = z.strictObject({
.string()
.optional()
.describe(
"by_position, view_state_only, long_text, cut_view, unreadable_view: the drafted file the note is about.",
"by_position, view_state_only, long_text, cut_view, unreadable_view, volatile_lines: the drafted file the note is about.",
),
files: z
.array(z.strictObject({ file: z.string(), role: z.string() }))
+330 -22
View File
@@ -1,8 +1,9 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { passing, xml, xmlDraft } from "./appTaskDraft.fixture.js";
import { pairMembers, resolvePointer } from "./viewPointer.js";
import { passing, pointerOf, xml, xmlDraft } from "./appTaskDraft.fixture.js";
import { pairMembers } from "./memberPairing.js";
import { resolvePointer } from "./viewPointer.js";
const FILE = "Documents/doc.xml";
@@ -14,9 +15,17 @@ const membersAt = (text: string, pointer: string): JsonValue[] => {
};
describe("draftTaskFiles for a change only position reaches", () => {
/** A sheet as an ODS spreadsheet keeps it: rows no attribute names, each cell's text in a paragraph, and a save counter. */
const sheet = (february: string, total: string, cycles: string) =>
`<spreadsheet><meta><editing-cycles>${cycles}</editing-cycles></meta><table name="Q1 Sales" style="ta1"><row><cell type="string"><p>Month</p></cell><cell type="string"><p>Sales</p></cell></row><row><cell type="string"><p>February</p></cell><cell type="float" value="${february}"><p>${february}</p></cell></row><row><cell type="string"><p>Total</p></cell><cell type="float" formula="sum" value="${total}"><p>${total}</p></cell></row></table></spreadsheet>`;
/** A sheet as an ODS spreadsheet keeps it: rows no attribute names, each cell's text in a paragraph, labelled apart or alike, and a save counter. */
const sheet = (
february: string,
total: string,
cycles: string,
labelled = false,
) => {
const label = (text: string) =>
`<cell type="string"><p>${labelled ? text : "Q1"}</p></cell>`;
return `<spreadsheet><meta><editing-cycles>${cycles}</editing-cycles></meta><table name="Q1 Sales" style="ta1"><row><cell type="string"><p>Month</p></cell><cell type="string"><p>Sales</p></cell></row><row>${label("February")}<cell type="float" value="${february}"><p>${february}</p></cell></row><row>${label("Total")}<cell type="float" formula="sum" value="${total}"><p>${total}</p></cell></row></table></spreadsheet>`;
};
it("checks the whole text of the ancestor above the step by position, by its name, and demotes the noise beside it rather than suggesting it", () => {
const before = sheet("21300", "59625", "1");
@@ -29,7 +38,7 @@ describe("draftTaskFiles for a change only position reaches", () => {
kind: "text_equals",
file: FILE,
pointer: "/root/children/[name=table][@name=Q1 Sales]",
value: "MonthSalesFebruary23100Total61425",
value: "MonthSalesQ123100Q161425",
},
]);
expect(passing(FILE, xml(before), file.suggested)).toEqual([false]);
@@ -37,6 +46,34 @@ describe("draftTaskFiles for a change only position reaches", () => {
expect(file.notes.map(({ code }) => code)).not.toContain("view_state_only");
});
it("names a row by its label cell, so the edited cell is checked by name, not the table's whole text", () => {
const before = sheet("21300", "59625", "1", true);
const after = sheet("23100", "61425", "2", true);
const file = xmlDraft(before, after);
const row = (label: string) =>
`/root/children/[name=table][>row=MonthSales]/children/[name=row][>cell=${label}]/children/[name=cell][@type=float]`;
expect(file.suggested.slice(0, 2)).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: row("February"),
value: "23100",
},
{
kind: "text_equals",
file: FILE,
pointer: row("Total"),
value: "61425",
},
]);
expect(passing(FILE, xml(before), file.suggested).some(Boolean)).toBe(
false,
);
expect(passing(FILE, xml(after), file.suggested).every(Boolean)).toBe(true);
});
it("suggests no noise when position alone reaches the edit and no ancestor's text can take a check", () => {
// The table's text is past the limit a text check compares.
const long = "x".repeat(2100);
@@ -100,6 +137,13 @@ describe("identifiers an app numbers by position", () => {
pointer: `${tasks}[@name=User testing]/name`,
value: "task",
},
{
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=tasks]/children",
matching: "[name=task][@type=normal]",
equals: 4,
},
]);
expect(file.values.map(({ pointer, note }) => [pointer, note])).toEqual([
[`${tasks}[@name=User testing]`, undefined],
@@ -116,6 +160,13 @@ describe("identifiers an app numbers by position", () => {
const tasks = "/root/children/[name=tasks]/children/[name=task]";
expect(file.suggested).toEqual([
{ kind: "value_absent", file: FILE, pointer: `${tasks}[@name=Design]` },
{
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=tasks]/children",
matching: "[name=task][@type=normal]",
equals: 2,
},
]);
});
@@ -166,28 +217,41 @@ describe("identifiers an app numbers by position", () => {
});
describe("an element renamed", () => {
/** A painting's layer stack as MyPaint saves it: each layer by name, its pixels in `src`, the one selected flagged. */
const stack = (top: string) =>
`<image w="800" h="600"><stack>${[
[top, "00", "576", "true"],
["Sky", "01", "0", "false"],
["Background", "02", "0", "false"],
]
/**
* A painting's layer stack as MyPaint saves it: each layer by name, its
* pixels in `src`, numbered along the stack as MyPaint 2 writes it or named
* by the layer, the one selected flagged; the top layer first, or second.
*/
const stack = (
top: string,
{
numbered = true,
moved = false,
}: { numbered?: boolean; moved?: boolean } = {},
) => {
const layers = [
[top, "sun", "576", "true"],
["Sky", "sky", "0", "false"],
["Background", "ground", "0", "false"],
];
const order = moved ? [1, 0, 2].map((at) => layers[at] ?? []) : layers;
return `<image w="800" h="600"><stack>${order
.map(
([name, layer, x, selected]) =>
`<layer composite-op="svg:src-over" name="${name ?? ""}" opacity="1.0" selected="${selected ?? ""}" src="data/layer-${layer ?? ""}.png" visibility="visible" x="${x ?? ""}" y="0"/>`,
([name, own, x, selected], index) =>
`<layer composite-op="svg:src-over" name="${name ?? ""}" opacity="1.0" selected="${selected ?? ""}" src="data/${numbered ? `layer-0${String(index)}` : (own ?? "")}.png" visibility="visible" x="${x ?? ""}" y="0"/>`,
)
.join("")}</stack></image>`;
};
const LAYER = "/root/children/[name=stack]/children/[name=layer]";
it("pairs a layer whose name alone changed, at its place among the layers, by another attribute naming it alone rather than the one selected", () => {
const layers = (top: string) =>
membersAt(stack(top), "/root/children/0/children");
membersAt(stack(top, { numbered: false }), "/root/children/0/children");
const pairing = pairMembers(layers("Sun"), layers("Untitled"));
const keys = [
"[name=layer][@src=data/layer-00.png]",
"[name=layer][@src=data/sun.png]",
"[name=layer][@name=Sky]",
"[name=layer][@name=Background]",
];
@@ -197,14 +261,25 @@ describe("an element renamed", () => {
});
});
it("checks the renamed layer's new name by the attribute that names it, and that the old name names nothing", () => {
it("keys a renamed layer by each version's own name where the attribute pairing it numbers the layers in order, as MyPaint's src", () => {
const layers = (top: string) =>
membersAt(stack(top), "/root/children/0/children");
const pairing = pairMembers(layers("Sun"), layers("Untitled"));
expect(pairing.newer.keys[0]).toBe("[name=layer][@name=Sun]");
expect(pairing.older.keys[0]).toBe("[name=layer][@name=Untitled]");
expect(pairing.newer.partners).toEqual([0, 1, 2]);
});
it("checks the renamed layer's new name by the attribute that names it, and that the old name names nothing, though a later save moves it", () => {
const file = xmlDraft(stack("Untitled"), stack("Sun"));
expect(file.suggested).toEqual([
{
kind: "value_equals",
file: FILE,
pointer: `${LAYER}[@src=data~1layer-00.png]/attributes/name`,
pointer: `${LAYER}[@name=Sun]/attributes/name`,
value: "Sun",
},
{
@@ -213,14 +288,247 @@ describe("an element renamed", () => {
pointer: `${LAYER}[@name=Untitled]`,
},
]);
expect(file.values).toMatchObject([
{ kind: "changed", before: "Untitled", after: "Sun" },
]);
// The move renumbers every src, which a check by src would have failed.
expect(
[stack("Untitled"), stack("Sun"), stack("Moon")].map((text) =>
passing(FILE, xml(text), file.suggested),
),
[
stack("Untitled"),
stack("Sun"),
stack("Moon"),
stack("Sun", { moved: true }),
].map((text) => passing(FILE, xml(text), file.suggested)),
).toEqual([
[false, false],
[true, true],
[false, true],
[true, true],
]);
// No layer added or removed is a guard at the unchanged count.
expect(file.guards.at(-1)).toEqual({
kind: "member_count",
file: FILE,
pointer: "/root/children/[name=stack]/children",
matching: "[name=layer]",
equals: 3,
});
});
});
describe("members named by a child's text or a generated id", () => {
it("counts a child's text on every sibling, one an identifier names included, so a selector both match names neither", () => {
const records = (note: string) =>
`<records><record id="fixed"><title>Shared</title><note>kept</note></record><record><title>Shared</title><note>${note}</note></record></records>`;
const file = xmlDraft(records("before"), records("after"));
const pointers = [
...file.suggested.flatMap((check) =>
"pointer" in check ? [check.pointer] : [],
),
...file.values.map(({ pointer }) => pointer),
];
expect(
pointers.some((pointer) => pointer.includes("[>title=Shared]")),
).toBe(false);
expect(file.values.map(({ after }) => after)).toEqual(["after"]);
expect(
passing(FILE, xml(records("after")), file.suggested).every(Boolean),
).toBe(true);
});
it("names a new node by its text rather than the id the app generated, wherever the id sits among its attributes, and pairs a kept one by that id", () => {
const map = (...nodes: string[]) =>
`<map><node TEXT="Packing" ID="ID_1965352635">${nodes.join("")}</node></map>`;
const node = (id: string, text: string) =>
`<node ID="${id}" TEXT="${text}" CREATED="1793955120032"/>`;
const pairing = pairMembers(
membersAt(
map(
node("ID_1749680464", "Tent"),
node("ID_329023692", "Water filter"),
),
"/root/children/0/children",
),
membersAt(
map(node("ID_1749680464", "Tent")),
"/root/children/0/children",
),
);
expect(pairing.newer.keys).toEqual([
"[name=node][@ID=ID_1749680464]",
"[name=node][@TEXT=Water filter]",
]);
});
});
describe("a container in a list named for its tag", () => {
/** A workbook as Gnumeric saves one: sheets in `Sheets`, each named by its `Name` child. */
const book = (march: string, more = "") =>
`<Workbook><Sheets><Sheet><Name>Budget</Name><Cells><Cell Row="2" Col="2">402.15</Cell><Cell Row="2" Col="3">${march}</Cell></Cells></Sheet>${more}</Sheets></Workbook>`;
it("names a sheet its tag alone names by its name child, so a sheet added later leaves the check its own", () => {
const file = xmlDraft(book("376.9"), book("418.65"));
expect(file.suggested.map(pointerOf)).toEqual([
"/root/children/[name=Sheets]/children/[name=Sheet][>Name=Budget]/children/[name=Cells]/children/[name=Cell][@Col=3]",
]);
const another = book("418.65", "<Sheet><Name>Notes</Name><Cells/></Sheet>");
expect(passing(FILE, xml(another), file.suggested)).toEqual([true]);
});
it("holds no step of a list not named for its member's tag, nor a member with no name", () => {
const plain = (text: string) =>
`<doc><body><section><title>Plan</title><p>${text}</p></section></body></doc>`;
const file = xmlDraft(plain("Monday"), plain("Tuesday"));
expect(file.suggested.map(pointerOf)).toEqual([
"/root/children/[name=body]/children/[name=section]/children/[name=p]",
]);
});
});
describe("records an app gave generated ids", () => {
const records = (first: string, second: string) =>
`<records><record id="0b5c1f0e-3c1d-4f7a-9a3e-2d7f5b8c9e10"><title>${first}</title></record><record id="7d1e2a90-5b4c-4e8f-8a21-6c3b9f0d4e57"><title>${second}</title></record></records>`;
it("pairs kept records by their ids, so titles they swapped read as two title edits, not two id changes", () => {
const file = xmlDraft(records("Alpha", "Beta"), records("Beta", "Alpha"));
expect(
file.values.map(({ pointer, kind, note }) => [
pointer,
kind,
note ?? null,
]),
).toEqual(
[
"0b5c1f0e-3c1d-4f7a-9a3e-2d7f5b8c9e10",
"7d1e2a90-5b4c-4e8f-8a21-6c3b9f0d4e57",
].map((id) => [
`/root/children/[name=record][@id=${id}]/children/[name=title]/children/0`,
"changed",
null,
]),
);
expect(
passing(FILE, xml(records("Alpha", "Beta")), file.suggested),
).not.toContain(true);
expect(
passing(FILE, xml(records("Beta", "Alpha")), file.suggested).every(
Boolean,
),
).toBe(true);
});
});
describe("shapes an ODF app numbers on every save", () => {
/** A Draw page's boxes, each named by the user, and numbered `id1`… by LibreOffice from `first` as it saves. */
const page = (second: string, first = 1) =>
`<draw:page xmlns:draw="d" xmlns:text="t" draw:name="page1">${[
"Order Received",
second,
"Pack Items",
"Ship Order",
]
.map(
(text, index) =>
`<draw:custom-shape draw:name="Step ${String(index + 1)}" draw:style-name="gr1" xml:id="id${String(index + first)}" draw:id="id${String(index + first)}"><text:p>${text}</text:p></draw:custom-shape>`,
)
.join("")}</draw:page>`;
const shape = (step: number) =>
`/root/children/[name=draw:custom-shape][@draw:name=Step ${String(step)}]`;
it("names each box by the name the user gave it, not the id the save numbered, so a save numbering them anew keeps the checks and guards", () => {
const file = xmlDraft(page("Pick Items"), page("Pick and Scan"));
expect(file.suggested).toEqual([
{
kind: "text_equals",
file: FILE,
pointer: shape(2),
value: "Pick and Scan",
},
]);
expect(file.guards.map(pointerOf)).toEqual([
shape(1),
shape(3),
"/root/children",
]);
// Another save numbers the shapes from 5.
const renumbered = xml(page("Pick and Scan", 5));
expect(passing(FILE, renumbered, file.suggested)).toEqual([true]);
expect(passing(FILE, renumbered, file.guards)).toEqual([true, true, true]);
// The value lists no other pointer by an id the save numbered.
expect(file.values[0]).toMatchObject({
pointer: `${shape(2)}/children/[name=text:p]/children/0`,
});
expect(file.values[0]?.alternatives).toBeUndefined();
});
});
describe("entries an app numbers by where it saves them", () => {
/** A Parley collection: entries numbered 0.. by save position, each two translations by language, and a lesson listing them by id. */
const entry = (id: number, english: string, spanish: string) =>
`<entry id="${String(id)}"><translation id="0"><text>${english}</text></translation><translation id="1"><text>${spanish}</text></translation></entry>`;
const collection = (pairs: readonly (readonly [string, string])[]) =>
`<kvtml><entries>${pairs.map(([english, spanish], id) => entry(id, english, spanish)).join("")}</entries><lessons><container><name>Lesson 1</name>${pairs.map((_, id) => `<entry id="${String(id)}"/>`).join("")}</container></lessons></kvtml>`;
const DOG = ["dog", "perro"] as const;
const BOOK = ["book", "libro"] as const;
const APPLE = ["apple", "manzana"] as const;
const LIBRARY = ["library", "biblioteca"] as const;
const SEED = [DOG, BOOK, APPLE];
const ENTRIES = "/root/children/[name=entries]/children";
it("names the new entry and the kept ones by their translations, not the id that numbers them by save position, so a save inserting the entry elsewhere keeps the checks", () => {
const file = xmlDraft(collection(SEED), collection([...SEED, LIBRARY]));
expect(file.suggested.map(pointerOf)).toEqual([
`${ENTRIES}/[name=entry][>translation=library]/children/[name=translation][@id=1]`,
ENTRIES,
]);
expect(file.guards.map(pointerOf)).toEqual([
`${ENTRIES}/[name=entry][>translation=apple]/children/[name=translation][@id=1]`,
`${ENTRIES}/[name=entry][>translation=book]/children/[name=translation][@id=1]`,
]);
const inserted = xml(collection([DOG, BOOK, LIBRARY, APPLE]));
expect(passing(FILE, inserted, file.suggested)).toEqual([true, true]);
expect(passing(FILE, inserted, file.guards)).toEqual([true, true]);
});
it("notes the lesson's entry holding nothing but the new entry's id as upkeep naming that entry, never a check or a count", () => {
const file = xmlDraft(collection(SEED), collection([...SEED, LIBRARY]));
const lesson =
"/root/children/[name=lessons]/children/[name=container]/children";
expect(
file.values.find(({ pointer }) => pointer.startsWith(lesson)),
).toMatchObject({
pointer: `${lesson}/[name=entry][@id=3]`,
note: "upkeep",
refers_to: [{ attribute: "id", value: "3" }],
});
expect(
[...file.suggested, ...file.guards].some((check) =>
pointerOf(check)?.startsWith(lesson),
),
).toBe(false);
});
});
describe("elements keyed only by an id a save numbered with six digits", () => {
const notes = (hello: string) =>
`<notes><p xml:id="id123456">${hello}</p><p xml:id="id654321">There</p></notes>`;
it("checks the edited paragraph by that id, counted once", () => {
const file = xmlDraft(notes("Hello"), notes("Hi"));
expect(file.suggested.map(pointerOf)).toEqual([
"/root/children/[name=p][@xml:id=id123456]",
]);
});
});
+14 -2
View File
@@ -1,6 +1,6 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { numberOf } from "./appTaskChecks.js";
import { numberOf, sameJson } from "./appTaskChecks.js";
/** How far a decimal the app writes as text may drift, such as `437.80000000000001` for 437.8, and still match. */
export const DECIMAL_TOLERANCE = 0.001;
@@ -13,12 +13,24 @@ export const decimalOf = (value: JsonValue | undefined): number | undefined => {
return Number.isFinite(number) ? number : undefined;
};
/** Whether a decimal's number is within the tolerance of a baseline value, read as the evaluators read a number, so a check by number would pass there too. */
/** Whether a decimal's number is within the tolerance of a baseline value, read as the evaluators read a number, `"10"` and `"1e1"` included, so a check by number would pass there too. */
const nearBaseline = (number: number, before: JsonValue | undefined) => {
const old = before === undefined ? undefined : numberOf(before);
return old !== undefined && Math.abs(old - number) <= DECIMAL_TOLERANCE;
};
/** Whether a `value_equals` passes on a value, as the evaluator decides it: by number within its tolerance, or as JSON. */
export const passesOn = (
check: DesktopTaskCheckInput,
value: JsonValue | undefined,
): boolean => {
if (check.kind !== "value_equals" || value === undefined) return false;
const number = numberOf(value);
return check.tolerance !== undefined && typeof check.value === "number"
? number !== undefined && Math.abs(number - check.value) <= check.tolerance
: sameJson(value, check.value);
};
/**
* A `value_equals` check of a value: a decimal string as its number within
* `DECIMAL_TOLERANCE`, unless `before`, the value the check must fail on, is
+81
View File
@@ -0,0 +1,81 @@
import type { JsonValue } from "../jsonValue.js";
import { isNameLikeKey } from "./attributeRank.js";
import { isXmlElement, resolvePointer } from "./viewPointer.js";
import { selectorOf } from "./viewSelector.js";
/** Where a pointer steps into a list: the list, the member's segment and the rest of the pointer after it. */
export interface ListStep {
readonly list: string;
readonly member: string;
readonly rest: readonly string[];
}
/** Where a pointer steps into a list, innermost first; by selector only, unless `positional` keeps steps by position too. */
export const listSteps = (pointer: string, positional = false): ListStep[] => {
const segments = pointer.split("/");
const steps: ListStep[] = [];
for (let index = segments.length - 1; index >= 2; index -= 1) {
const member = segments[index] ?? "";
if (
segments[index - 1] === "children" &&
(positional || !/^\d+$/u.test(member))
)
steps.push({
list: segments.slice(0, index).join("/"),
member,
rest: segments.slice(index + 1),
});
}
return steps;
};
/** Whether a step's member is named as a field is, by a name-like attribute alone, as QElectroTech's `elementInformation[@name=label]`. */
const namedAsField = ({ member }: ListStep) => {
const [only, ...more] = (
selectorOf(member.replaceAll("~1", "/").replaceAll("~0", "~")) ?? []
).filter(({ prefix }) => prefix !== "");
return (
only !== undefined &&
more.length === 0 &&
only.prefix === "@" &&
isNameLikeKey(only.key)
);
};
/** Whether a like sibling of an outer step's member holds the field a step goes through, at the same path, as every component holds its `label`. */
const sharedField = (
view: JsonValue | null,
step: ListStep,
outer: ListStep,
) => {
const records = resolvePointer(view, outer.list);
const record = resolvePointer(view, `${outer.list}/${outer.member}`);
const inner = outer.rest.slice(0, outer.rest.length - step.rest.length);
return (
Array.isArray(records) &&
isXmlElement(record) &&
records.some(
(item) =>
item !== record &&
isXmlElement(item) &&
item.name === record.name &&
resolvePointer(item, `/${inner.join("/")}`) !== undefined,
)
);
};
/**
* The record a step's member is a field of: the nearest step out whose like
* siblings hold the same field at the same path, for a member named as a
* field (`namedAsField`), as every QElectroTech component holds its
* `elementInformation[@name=label]`, or a Glade button its `label` property;
* undefined for a member that is a record of its own.
*/
export const recordOfField = (
view: JsonValue | null,
step: ListStep,
outer: readonly ListStep[],
): ListStep | undefined =>
namedAsField(step)
? outer.find((candidate) => sharedField(view, step, candidate))
: undefined;
+134 -24
View File
@@ -1,11 +1,12 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopTaskCheckInput } from "./appTask.js";
import { collapseWhitespace, type DesktopTaskCheckInput } from "./appTask.js";
import {
holdsSplitDate,
isBookkeeping,
isStamp,
isVolatileValue,
} from "./appTaskDraftNoise.js";
import { isPlacedItem, placedItemCheck } from "./appTaskDraftItems.js";
import { valueEqualsCheck } from "./appTaskDraftScalars.js";
import { rankAttributes } from "./attributeRank.js";
import type { DesktopStateDifference } from "./stateChanges.js";
@@ -34,6 +35,8 @@ export interface TextPlacement {
/** Text checks for the elements whose text changed, and the pointers those checks make redundant: text and whole runs holding text in them, or an element added whole checked itself, not an attribute or name of an element both ends hold, nor an element holding no text, as an image or a break. */
export interface WholeTextSuggestions {
readonly suggestions: readonly DesktopTaskCheckInput[];
/** Kept positioned items associated with the selected text checks. */
readonly guards: readonly DesktopTaskCheckInput[];
/** Elements whose text changed that no check took, because every place for one held more text than the limit. */
readonly long: readonly string[];
readonly covers: (pointer: string) => boolean;
@@ -168,6 +171,34 @@ const byOwnAttribute = (element: string, ends: Ends): Candidate | undefined => {
return undefined;
};
/**
* Whether the element at a pointer is a field its tag names in a record of
* two or more fields holding text, at both ends, as QElectroTech's `<text>`
* beside `<info_name>` in a `<dynamic_elmt_text>`: a check reads it, not the
* record's text, which would join its fields; a Draw shape's one paragraph
* beside its geometry is the shape's text.
*/
const isField = (pointer: string, ends: Ends) => {
const parent = parentOf(pointer);
const tag = /^\[name=(?<tag>[^\]]+)\]$/u.exec(pointer.split("/").at(-1) ?? "")
?.groups?.tag;
return (
parent !== undefined &&
tag !== undefined &&
[ends.baseline, ends.final].every((view) => {
const record = resolvePointer(view, parent);
const fields = isXmlElement(record)
? record.children.filter(isXmlElement)
: [];
return (
holdsFields(record) &&
fields.filter((field) => elementText(field).trim() !== "").length > 1 &&
fields.filter(({ name }) => name === tag).length === 1
);
})
);
};
/** How far a text check climbs from an element no attribute names to an ancestor its tag names. */
const MAX_TAG_CLIMB = 3;
/** A formatting run a later save may split, merge, or drop while keeping the paragraph. */
@@ -219,7 +250,8 @@ export const holdsNoisyText = (
* Where a text check goes for an element whose text changed, best first, so
* the check names the paragraph, which a later save keeps, rather than a run
* it may split or merge: up from an element in mixed content (its parent
* holds text beside it, at either end) to the nearest that is not, then, from
* holds text beside it, at either end) to the nearest that is not, which a
* field its tag names in a record of fields (`isField`) stays; then, from
* one named by tag or position alone, to the nearest ancestor named by an
* attribute, as AbiWord's `p` by its `xid`, where one is below the document's
* root. An element passed on the way that an identifier of its own names, the
@@ -238,6 +270,8 @@ const outsideRuns = (pointer: string, ends: Ends): readonly Candidate[] => {
parent = parentOf(current)
)
current = parent;
if (isField(current, ends))
return [{ element: current, pointer: current, identifier: false }];
const passed: string[] = [];
let named = current;
while (!namedByAttribute(named)) {
@@ -342,46 +376,83 @@ const recordLike = (value: JsonValue | undefined): boolean =>
const TEXT_TAG = /^(?:p|h|h[1-6]|para|simpara|li|text|tspan|span|a)$/u;
/**
* A tag of a formatting run inside a piece of text, compared without its
* namespace and without case. `link` and `code` stay out: some records name a
* field that, and a field is not a run.
* A tag of inline formatting, by its local name: bold, italic and the like,
* a span, link or code run, or Gnote's `size:` and `link:` runs. A record
* whose fields are only such, as `<list-item><bold>olive oil</bold>`, is text.
*/
const FORMAT_TAG =
/^(?:span|a|s|c|tspan|tab|line-break|soft-page-break|br|b|i|u|em|strong|bold|italic|underline|emphasis|sub|sup|small|font|mark|q|r|t|run|hyperlink)$/u;
const INLINE_TAG =
/^(?:b|i|u|s|em|strong|bold|italic|underline|strikethrough|emphasis|span|a|code|sub|sup|small|big|mark|font|tt|monospace|highlight|link)$/u;
const INLINE_PREFIX = /^(?:size|link):/u;
const isFormatTag = (tag: string) =>
FORMAT_TAG.test((tag.split(":").at(-1) ?? tag).toLowerCase());
const isInline = (name: string) =>
INLINE_PREFIX.test(name) ||
INLINE_TAG.test((name.split(":").at(-1) ?? name).toLowerCase());
/**
* Whether an element holds fields: only elements, layout whitespace aside, as
* Tellico's `<entry>` holds `<title>` and `<publisher>`, or a record holds
* repeated `<field>` elements, whatever they are called; unless it is text
* made of runs: its tag names a paragraph or other text (`TEXT_TAG`), every
* element child is a formatting run (`FORMAT_TAG`), as a list item
* `<bold>olive oil</bold>`, or a child's text opens or closes with
* whitespace, as a sentence splits into runs, `Meet ` and a linked `Monday`,
* where a field holds a value whole.
* made of runs: its tag names a paragraph or other text (`TEXT_TAG`), its
* elements are all inline formatting (`INLINE_TAG`), or a child's text opens
* or closes with a space, as a sentence splits into runs, `Meet ` and a
* linked `Monday`, where a field holds a value whole; a line break and
* indentation the app lays out after a field's text, as KmPlot's, is none.
*/
export const holdsFields = (value: JsonValue | undefined): boolean =>
recordLike(value) &&
isXmlElement(value) &&
!TEXT_TAG.test(value.name.split(":").at(-1) ?? value.name) &&
!value.children.every(
(child) => !isXmlElement(child) || isFormatTag(child.name),
(child) => !isXmlElement(child) || isInline(child.name),
) &&
!value.children.some((child) => {
const text = isXmlElement(child) ? elementText(child) : "";
return text.trim() !== "" && text.trim() !== text;
// A space, not a line break the app lays out, at either edge splits a sentence.
return /^[ \t]+\S|\S[ \t]+$/u.test(text);
});
/** Whether an element at a pointer sits in a paragraph or other text, an ancestor's tag naming one (`TEXT_TAG`), as Word's `<w:r>` run in its `<w:p>`. */
const inText = (view: JsonValue | null, pointer: string): boolean => {
for (
let parent = parentOf(pointer);
parent !== undefined;
parent = parentOf(parent)
) {
const element = resolvePointer(view, parent);
if (
isXmlElement(element) &&
TEXT_TAG.test(element.name.split(":").at(-1) ?? element.name)
)
return true;
}
return false;
};
/** Whether an element at a pointer is a record: it `holdsFields`, and sits in no paragraph, where it is a run of its text. */
export const isRecordAt = (
view: JsonValue | null,
pointer: string,
value: JsonValue | undefined,
): boolean => holdsFields(value) && !inText(view, pointer);
/**
* Whether the kept ancestor of a record added or removed whole is a list of
* its kind, whose whole text would fold in records the edit left alone: it
* holds no text of its own, and another element of that tag with text that
* both ends hold alike, as Tellico's `<collection>` holds the other entries.
*/
const listOf = (holder: string, element: JsonValue, ends: Ends) => {
if (!isXmlElement(element) || !holdsFields(element) || mixedAt(holder, ends))
const listOf = (
holder: string,
pointer: string,
element: JsonValue,
ends: Ends,
) => {
if (
!isXmlElement(element) ||
!isRecordAt(ends.final, pointer, element) ||
!isRecordAt(ends.baseline, pointer, element) ||
mixedAt(holder, ends)
)
return false;
const like = (view: JsonValue | null) => {
const list = resolvePointer(view, holder);
@@ -431,7 +502,8 @@ const textHolder = (
) => {
const kept = keptAncestor(pointer, ends);
const unnamed = removed && /^\d+$/u.test(pointer.split("/").at(-1) ?? "");
const listed = kept !== undefined && !unnamed && listOf(kept, element, ends);
const listed =
kept !== undefined && !unnamed && listOf(kept, pointer, element, ends);
return { holder: listed ? undefined : kept, listed };
};
@@ -439,6 +511,8 @@ const textHolder = (
interface Placed {
readonly element: string;
readonly check: DesktopTaskCheckInput;
/** Positioned items can supply checks of their kept siblings. */
readonly guards?: readonly DesktopTaskCheckInput[];
}
/** What text checks read: the file, its two ends, and where checks go. */
@@ -448,6 +522,10 @@ interface TextContext {
readonly place: TextPlacement;
}
/** Whether text is one line the app lays out between line breaks. */
const isLaidOutLine = (value: string) =>
/[\r\n]/u.test(value) && !/[\r\n]/u.test(value.trim());
/**
* The check of an element's whole text: a decimal held as the element's one
* text node, as a spreadsheet keeps a cell's number, by its value within a
@@ -460,9 +538,18 @@ export const wholeTextCheck = (
value: string,
before: string | undefined,
): DesktopTaskCheckInput => {
const numeric = valueEqualsCheck(file, pointer, value, before);
// A line between breaks is still that line. Trim it before the decimal test so `\\n437.8\\n` stays a number within tolerance.
const comparable = isLaidOutLine(value) ? value.trim() : value;
const earlier =
before !== undefined && isLaidOutLine(before) ? before.trim() : before;
// The element's joined text, not its first text node. A later save may split `437.8` into `437.` and a run holding `8`. When that text is a decimal, compare the number within the usual tolerance, so `437.80` and a long float still match.
const numeric = valueEqualsCheck(file, pointer, comparable, earlier);
if ("tolerance" in numeric) return numeric;
return { kind: "text_equals", file, pointer, value };
// One line the app lays out between line breaks, as KmPlot's formula before its next element, compares with its whitespace collapsed.
const laidOut = isLaidOutLine(value)
? { value: collapseWhitespace(value), normalize_whitespace: true }
: { value };
return { kind: "text_equals", file, pointer, ...laidOut };
};
/** The element a candidate names in the final view, whole, at the pointer `name` gives it. */
@@ -482,7 +569,8 @@ const candidateAt = (
* The text check a candidate takes: an element the final view holds whole at
* the pointer `name` gives it, its text at most the limit, no timestamp and
* holding no date stamped in parts, and changed from the baseline's or, for
* an element `added` whole, absent there.
* an element `added` whole, absent there; never a line the app only laid
* out anew, which a check comparing collapsed whitespace finds at the seed.
*/
const textCheck = (
context: TextContext,
@@ -494,9 +582,16 @@ const textCheck = (
const { pointer, now } = found;
const before = resolvePointer(context.ends.baseline, pointer);
if (!added && !isXmlElement(before)) return undefined;
// A timestamp between other text is not part of the check. Joining across it asks for text the file never contains.
if (holdsNoisyText(now)) return undefined;
const value = elementText(now);
const old = isXmlElement(before) ? elementText(before) : undefined;
const relaidOut =
old !== undefined &&
isLaidOutLine(value) &&
collapseWhitespace(old) === collapseWhitespace(value);
return value !== old &&
!relaidOut &&
value.length <= context.place.limit.chars &&
!isStamp(value) &&
!holdsNoisyText(now) &&
@@ -527,6 +622,8 @@ const textHolders = (change: Listed, ends: Ends, place: TextPlacement) => {
const holders = new Set<string>();
/** Elements added whole holding text, each with the ancestor checked for it, if any. */
const added = new Map<string, string | undefined>();
/** Items placed by their own position, added whole. */
const items: string[] = [];
const note = (
pointer: string,
view: JsonValue | null,
@@ -549,6 +646,11 @@ const textHolders = (change: Listed, ends: Ends, place: TextPlacement) => {
!isWhitespace(elementText(value)) &&
place.inTree(pointer)
) {
// An item placed by its own position is no run of its list's text.
if (isPlacedItem(view, pointer)) {
if (how === "added") items.push(pointer);
return;
}
const { holder, listed } = textHolder(
pointer,
value,
@@ -567,7 +669,7 @@ const textHolders = (change: Listed, ends: Ends, place: TextPlacement) => {
}
for (const pointer of change.added) note(pointer, ends.final, "added");
for (const pointer of change.removed) note(pointer, ends.baseline, "removed");
return { holders, added };
return { holders, added, items };
};
/**
@@ -588,7 +690,7 @@ export const wholeTextSuggestions = (
ends: Ends,
place: TextPlacement,
): WholeTextSuggestions => {
const { holders, added } = textHolders(change, ends, place);
const { holders, added, items } = textHolders(change, ends, place);
const context = { file, ends, place };
const checks = new Map<string, Placed | undefined>();
const check = (candidate: Candidate) => {
@@ -622,6 +724,13 @@ export const wholeTextSuggestions = (
if (found !== undefined && !placed.includes(found)) placed.push(found);
};
for (const holder of holders) keep(climb(holder));
for (const item of items)
keep(
placedItemCheck(
{ file, ends, name: place.name, chars: place.limit.chars },
item,
),
);
for (const [element, holder] of added)
if (holder === undefined || climb(holder) === undefined)
keep(
@@ -639,6 +748,7 @@ export const wholeTextSuggestions = (
.slice(0, place.limit.suggestions);
return {
suggestions: suggested.map(({ check }) => check),
guards: suggested.flatMap(({ guards }) => guards ?? []),
long: [...long],
covers: (pointer) => {
if (
@@ -27,7 +27,7 @@ describe("draftTaskFiles for lines added to free text", () => {
expect(
passing(FILE, xml(note(`${LIST}\nolive oil`)), checks).every(Boolean),
).toBe(true);
// Free text has no item boundary the current checks can select.
// Whole free text has no item boundary the current checks can select.
expect(
passing(
FILE,
@@ -67,3 +67,24 @@ describe("draftTaskFiles for lines added to free text", () => {
expect(file.guards).toEqual([]);
});
});
describe("draftTaskFiles for a line added to a note among others, as CherryTree saves them", () => {
const notebook = (chores: string) =>
`<cherrytree><node unique_id="1" name="Weekend chores"><rich_text>${chores}</rich_text></node><node unique_id="2" name="Groceries"><rich_text>Oat milk</rich_text></node><node unique_id="3" name="Gift ideas"><rich_text>Puzzle book</rich_text></node></cherrytree>`;
const CHORES =
"Water the tomato plants\nSweep the back porch\nReplace the hallway bulb\nReturn the library books";
it("keeps the sibling count guard beside a whole-text check", () => {
const file = xmlDraft(
notebook(CHORES),
notebook(`${CHORES}\nClean the gutters`),
);
expect(file.guards).toContainEqual({
kind: "member_count",
file: "Documents/doc.xml",
pointer: "/root/children",
matching: "[name=node]",
equals: 3,
});
});
});
+154
View File
@@ -0,0 +1,154 @@
import type { JsonValue } from "../jsonValue.js";
import type { AddedContext } from "./appTaskDraftAdded.js";
import { changeNoise } from "./appTaskDraftNoise.js";
import { draftValues, oneEnd, type DraftValue } from "./appTaskDraftValues.js";
import { diffNamedMembers } from "./stateChanges.js";
import {
entryWithoutView,
zipArrayLeavesOut,
zipEntryAt,
zipLeavesOutAt,
zipView,
} from "./zipView.js";
const isRecord = (
value: JsonValue | null | undefined,
): value is Record<string, JsonValue> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/**
* The entry a pointer into a zip view goes into, when it has a view and both
* evaluators read it alike: JSON, a key file or XML. A binary or unread
* entry also holds a `null` view, which is no JSON `null`.
*/
const readableEntry = (view: JsonValue | null, pointer: string) => {
const entry = zipEntryAt(view, pointer);
return typeof entry === "object" &&
entryWithoutView(entry) === undefined &&
(entry.format === "json" ||
entry.format === "keyfile" ||
entry.format === "xml")
? entry
: undefined;
};
/**
* Where checks for a pointer the diff lists start: the view of an entry it
* names whole, or its root element for XML; the pointer itself inside that;
* undefined for an entry neither evaluator reads alike, or the entry's fields.
*/
const checkRoot = (
view: JsonValue | null,
pointer: string,
): string | undefined => {
const entry = readableEntry(view, pointer);
const [entryPointer] = /^\/entries\/[^/]+/u.exec(pointer) ?? [];
if (entry === undefined || entryPointer === undefined) return undefined;
const inner = pointer.slice(entryPointer.length).split("/").slice(1);
const root = entry.format === "xml" ? ["view", "root"] : ["view"];
const prefix = (short: readonly string[], long: readonly string[]) =>
short.length <= long.length &&
short.every((part, index) => long[index] === part);
if (prefix(inner, root)) return `${entryPointer}/${root.join("/")}`;
return prefix(root, inner) ? pointer : undefined;
};
/**
* Where checks into a view can go: an archive's entries, or an XML file's root
* element. `root` is where checks for a pointer the diff lists start, undefined
* where the evaluators do not read alike; `xml` whether a pointer goes into an
* XML view; `leavesOut` whether the view may lack part of what a pointer
* reaches, and `arrayLeavesOut` members of the array a pointer names;
* `listed` whether a pointer is a value of the document a values list shows;
* `empty` the view of a file that holds nothing.
*/
export interface CheckTree {
readonly root: (
view: JsonValue | null,
pointer: string,
) => string | undefined;
readonly xml: (view: JsonValue | null, pointer: string) => boolean;
readonly leavesOut: (view: JsonValue | null, pointer: string) => boolean;
readonly arrayLeavesOut: (view: JsonValue | null, array: string) => boolean;
readonly listed: (view: JsonValue | null, pointer: string) => boolean;
readonly empty: JsonValue | null;
}
export const ARCHIVE: CheckTree = {
root: checkRoot,
xml: (view, pointer) => readableEntry(view, pointer)?.format === "xml",
leavesOut: zipLeavesOutAt,
arrayLeavesOut: zipArrayLeavesOut,
// An entry added or removed whole, or a value inside a readable one; not an entry's size or digest.
listed: (view, pointer) =>
/^\/entries\/[^/]+$/u.test(pointer) ||
checkRoot(view, pointer) !== undefined,
// An archive with no entries, so each entry of one created or deleted is listed by its name.
empty: zipView([], 0),
};
/** An XML file's view leaves out what its `truncated` says, anywhere in the tree. */
const truncatedXml = (view: JsonValue | null) =>
isRecord(view) && view.truncated === true;
const inXmlRoot = (pointer: string) =>
pointer === "/root" || pointer.startsWith("/root/");
export const XML_FILE: CheckTree = {
root: (_view, pointer) => (inXmlRoot(pointer) ? pointer : undefined),
xml: () => true,
leavesOut: truncatedXml,
arrayLeavesOut: truncatedXml,
listed: (_view, pointer) => inXmlRoot(pointer),
empty: null,
};
export const valueFormat = (
tree: CheckTree,
view: JsonValue | null,
pointer: string,
) =>
tree === ARCHIVE && /^\/entries\/[^/]+$/u.test(pointer)
? ("archive" as const)
: tree.xml(view, pointer)
? ("xml" as const)
: ("json" as const);
export const referenceRoots = (
tree: CheckTree,
view: JsonValue | null,
): JsonValue[] => {
if (tree !== ARCHIVE) return view === null ? [] : [view];
if (!isRecord(view) || !Array.isArray(view.entries)) return [];
return view.entries.flatMap((entry) =>
isRecord(entry) &&
entry.format === "xml" &&
entry.view !== undefined &&
entry.view !== null
? [entry.view]
: [],
);
};
/**
* The values of an archive or XML file created or deleted: what its one end
* holds against `tree.empty`, each entry, or the root element, whole once, as
* one added to a file that changed is listed, within the same limits.
*/
export const presenceValues = (
ends: AddedContext["ends"],
tree: CheckTree,
created: boolean,
): { readonly values: DraftValue[]; readonly cut: boolean } => {
const from = created
? { baseline: tree.empty, final: ends.final }
: { baseline: ends.baseline, final: tree.empty };
const change = oneEnd(diffNamedMembers(from.baseline, from.final), created);
return draftValues(change, {
ends: from,
listed: tree.listed,
noise: changeNoise(change, from, tree.xml),
format: (view, pointer) => valueFormat(tree, view, pointer),
referenceRoots: (view) => referenceRoots(tree, view),
});
};
+373 -6
View File
@@ -1,8 +1,16 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { draftOf, statePath, xml, xmlDraft } from "./appTaskDraft.fixture.js";
import { compactValue, draftValues } from "./appTaskDraftValues.js";
import {
draftOf,
passing,
pointerOf,
statePath,
xml,
xmlDraft,
} from "./appTaskDraft.fixture.js";
import { draftValues } from "./appTaskDraftValues.js";
import { compactValue } from "./compactValue.js";
import { resolvePointer } from "./viewPointer.js";
import { zipEntry, zipView } from "./zipView.js";
@@ -24,12 +32,13 @@ it("cuts XML previews after escaping, including entity and surrogate boundaries"
complete.length,
complete.length + 1,
])
expect(compactValue(element, "xml", limit)).toBe(
expect(compactValue(element, limit, "xml")).toBe(
complete.length > limit ? `${complete.slice(0, limit)}…` : complete,
);
expect(
compactValue(
{ name: "n", attributes: { value: "&".repeat(1_000_000) }, children: [] },
600,
"xml",
),
).toBe(`${('<n value="' + "&amp;".repeat(120)).slice(0, 600)}…`);
@@ -39,7 +48,7 @@ it("cuts JSON previews after escaping keys and values", () => {
const value = { '😀"\n': ["a\n😀\\\ud800"] };
const complete = JSON.stringify(value);
for (let limit = 0; limit <= complete.length + 1; limit += 1)
expect(compactValue(value, "json", limit)).toBe(
expect(compactValue(value, limit, "json")).toBe(
complete.length > limit ? `${complete.slice(0, limit)}…` : complete,
);
});
@@ -58,12 +67,13 @@ describe("draftTaskFiles values", () => {
const file = xmlDraft(before, after);
expect(file.values_cut).toBe(false);
// Text first, so no cut ever drops it.
expect(file.values.map(({ pointer, kind }) => [kind, pointer])).toEqual([
["added", "/root/children/[name=ope][@wording=Weekly groceries]"],
["changed", "/root/children/[name=note]/children/0"],
["added", "/root/children/[name=ope][@wording=Weekly groceries]"],
["removed", "/root/children/[name=tag]"],
]);
const [added, changed, removed] = file.values;
const [changed, added, removed] = file.values;
expect(added).toMatchObject({ before: null, after: GROCERIES });
expect(removed).toMatchObject({ before: '<tag name="old"/>', after: null });
// A scalar's before and after are what its pointer reads at each end.
@@ -570,3 +580,360 @@ describe("draftTaskFiles values of a file created or deleted", () => {
).toBeLessThanOrEqual(8 * 1024);
});
});
describe("draftTaskFiles for a transaction added to a book, as GnuCash saves one", () => {
const GROCERIES = "98f0ee4c216a43e290133637df088843";
const CHECKING = "63fd8736eb444c57803945f330e68a28";
const account = (name: string, id: string) =>
`<gnc:account version="2.0.0"><act:name>${name}</act:name><act:id type="guid">${id}</act:id></gnc:account>`;
const split = (id: string, value: string, to: string) =>
`<trn:split><split:id type="guid">${id}</split:id><split:reconciled-state>n</split:reconciled-state><split:value>${value}</split:value><split:account type="guid">${to}</split:account></trn:split>`;
/** A transaction: its id, currency, dates, description, a slot the app keeps and its splits. */
const transaction = (
[id, description, posted, entered]: readonly string[],
splits: string,
) =>
`<gnc:transaction version="2.0.0"><trn:id type="guid">${id ?? ""}</trn:id><trn:currency><cmdty:id>USD</cmdty:id></trn:currency><trn:date-posted><ts:date>${posted ?? ""}</ts:date></trn:date-posted><trn:date-entered><ts:date>${entered ?? ""}</ts:date></trn:date-entered><trn:description>${description ?? ""}</trn:description><trn:slots><slot><slot:key>date-posted</slot:key></slot></trn:slots><trn:splits>${splits}</trn:splits></gnc:transaction>`;
const CORNER = transaction(
[
"1b4e2dae15ea45c5889105a7ae939e04",
"Corner Grocer",
"2026-10-16 10:59:00 +0000",
"2026-11-06 08:49:09 +0000",
],
split("0aa0a2a505ac40dd9c74f0abfe7e0ca1", "5275/100", GROCERIES) +
split("954a27fff0ad4d54a9a6f26436a60c54", "-5275/100", CHECKING),
);
const greenleaf = (ids: readonly string[], entered: string) =>
transaction(
[ids[0] ?? "", "Greenleaf Market", "2026-11-03 10:59:00 +0000", entered],
split(ids[1] ?? "", "6348/100", GROCERIES) +
split(ids[2] ?? "", "-6348/100", CHECKING),
);
/** A book: options GnuCash fills on reopening, from control bytes to an id, its accounts and transactions. */
const gnucash = (option: string, added: string, slots = "") =>
`<gnc-v2 xmlns:gnc="g" xmlns:act="a" xmlns:trn="t" xmlns:split="s" xmlns:ts="ts" xmlns:cmdty="c" xmlns:slot="sl" xmlns:book="b"><gnc:book version="2.0.0"><book:slots><slot><slot:key>Default Customer TaxTable</slot:key><slot:value type="guid">${option}</slot:value></slot>${slots}</book:slots>${account("Groceries", GROCERIES)}${account("Checking Account", CHECKING)}${CORNER}${added}</gnc:book></gnc-v2>`;
const SEED = gnucash("??\u007f", "");
const END = gnucash(
"99471669fefd47b7b6eb2131be4e6d00",
greenleaf(
[
"a893ecc337254562a3b167b4534dc020",
"c05c3906b2634257883cbf894462acc1",
"d15c3906b2634257883cbf894462acc2",
],
"2026-11-06 08:53:08 +0000",
),
"<slot><slot:key>remove-color-not-set-slots</slot:key></slot>",
);
const TRANSACTION =
"/root/children/[name=gnc:book]/children/[name=gnc:transaction][>trn:description=Greenleaf Market]";
it("names the transaction by its description, checks what the user entered under it, counts the transactions, and suggests none of what the app stamps or keeps", () => {
const file = xmlDraft(SEED, END);
expect(
file.suggested.map((check) => [
check.kind,
pointerOf(check)?.replace(TRANSACTION, "~"),
]),
).toEqual([
["text_equals", "~/children/[name=trn:date-posted]"],
[
"text_equals",
"~/children/[name=trn:splits]/children/[name=trn:split][>split:value=6348~1100]/children/[name=split:account]",
],
[
"text_equals",
"~/children/[name=trn:splits]/children/[name=trn:split][>split:value=-6348~1100]/children/[name=split:account]",
],
["member_count", "/root/children/[name=gnc:book]/children"],
]);
// Another save of the same entry: new ids, another time entered.
const later = gnucash(
"11471669fefd47b7b6eb2131be4e6d01",
greenleaf(
[
"b893ecc337254562a3b167b4534dc021",
"e05c3906b2634257883cbf894462acc3",
"f15c3906b2634257883cbf894462acc4",
],
"2026-11-09 14:02:41 +0000",
),
);
expect(passing("Documents/doc.xml", xml(SEED), file.suggested)).toEqual([
false,
false,
false,
false,
]);
expect(
passing("Documents/doc.xml", xml(later), file.suggested).every(Boolean),
).toBe(true);
});
it("lists the transaction field by field and each split whole, naming the account a split's text refers to, and notes the app's ids, entry time and slots", () => {
const file = xmlDraft(SEED, END);
const listed = file.values.map(({ pointer, note, refers_to }) => [
pointer.replace(TRANSACTION, "~"),
note ?? null,
refers_to?.map(({ element }) => element) ?? null,
]);
expect(listed).toEqual(
expect.arrayContaining([
["~/children/[name=trn:description]", null, null],
[
"~/children/[name=trn:splits]/children/[name=trn:split][>split:value=6348~1100]",
null,
['<gnc:account version="2.0.0"><act:name>Groceries</act:name>…'],
],
[
"~/children/[name=trn:splits]/children/[name=trn:split][>split:value=-6348~1100]",
null,
[
'<gnc:account version="2.0.0"><act:name>Checking Account</act:name>…',
],
],
["~/children/[name=trn:id]", "volatile", null],
["~/children/[name=trn:date-entered]", "timestamp", null],
["~/children/[name=trn:slots]/children/[name=slot]", "upkeep", null],
]),
);
const slots = file.values.filter(({ pointer }) =>
pointer.includes("[name=book:slots]"),
);
expect(slots.map(({ note }) => note)).toEqual(["upkeep", "upkeep"]);
});
});
/** A split of a transaction: its id, which KMyMoney numbers anew in every transaction, amount, account and payee. */
const split = (id: string, value: string, account: string, payee: string) =>
`<SPLIT value="${value}" shares="${value}" memo="" account="${account}" price="1/1" id="${id}" payee="${payee}" reconcileflag="0"/>`;
const transaction = (id: string, date: string, splits: string) =>
`<TRANSACTION memo="" entrydate="2026-11-06" postdate="${date}" id="${id}" commodity="USD"><SPLITS>${splits}</SPLITS></TRANSACTION>`;
const WATER = transaction(
"T000000000000000001",
"2026-10-12",
split("S0001", "-209/5", "A000001", "P000002") +
split("S0002", "209/5", "A000011", "P000002"),
);
const ELECTRIC = transaction(
"T000000000000000002",
"2026-10-20",
split("S0001", "-921/10", "A000001", "P000003") +
split("S0002", "921/10", "A000011", "P000003"),
);
const PAYMENT = transaction(
"T000000000000000003",
"2026-11-03",
split("S0001", "-1749/20", "A000001", "P000003") +
split("S0002", "1749/20", "A000011", "P000003"),
);
/** A book: a file version whose id is a small number, payees, accounts the institution and parent list by id, and transactions. */
const kmy = (count: string, added: string) =>
`<KMYMONEY-FILE><FILEINFO><FIXVERSION id="3"/></FILEINFO><INSTITUTION id="I000001" name="Maple Grove Credit Union"><ACCOUNTIDS><ACCOUNTID id="A000001"/></ACCOUNTIDS></INSTITUTION><PAYEES><PAYEE id="P000002" name="Northside Water Co."/><PAYEE id="P000003" name="Riverside Electric"/></PAYEES><ACCOUNTS><ACCOUNT id="AStd::Expense" name="Expense"><SUBACCOUNTS><SUBACCOUNT id="A000011"/></SUBACCOUNTS></ACCOUNT><ACCOUNT id="A000001" name="Household Checking"/><ACCOUNT id="A000011" name="Utilities"/></ACCOUNTS><TRANSACTIONS count="${count}">${WATER}${ELECTRIC}${added}</TRANSACTIONS></KMYMONEY-FILE>`;
const SEED = kmy("2", "");
const END = kmy("3", PAYMENT);
const SPLITS =
"/root/children/[name=TRANSACTIONS]/children/[name=TRANSACTION][@postdate=2026-11-03]/children/[name=SPLITS]/children";
describe("draftTaskFiles for a transaction added to a book, as KMyMoney saves one", () => {
it("omits an oversized nested split field while retaining short checks and its note", () => {
const large = "x".repeat(100_000);
const end = kmy(
"3",
PAYMENT.replace(
'memo="" account="A000001"',
`memo="${large}" account="A000001"`,
),
);
const file = xmlDraft(SEED, end);
expect(
file.suggested
.filter((check) => JSON.stringify(check).length >= 10_000)
.map((check) => ({
kind: check.kind,
pointer: "pointer" in check ? check.pointer.slice(0, 220) : "",
})),
).toEqual([]);
expect(file.suggested).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "value_equals", value: "-1749/20" }),
]),
);
expect(file.notes).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "long_text",
pointers: expect.arrayContaining([
`${SPLITS}/[name=SPLIT][@account=A000001]/attributes/memo`,
]),
}),
]),
);
});
it("checks each split of the new transaction by the account it names, its amount and payee, not by the split id every transaction repeats", () => {
const file = xmlDraft(SEED, END);
const field = (account: string, key: string, value: string) => ({
kind: "value_equals",
file: "Documents/doc.xml",
pointer: `${SPLITS}/[name=SPLIT][@account=${account}]/attributes/${key}`,
value,
});
// `shares` repeats `value` in every split, and `memo`, `price` and `reconcileflag` are alike in all.
expect(file.suggested.slice(0, 4)).toEqual([
field("A000001", "value", "-1749/20"),
field("A000001", "payee", "P000003"),
field("A000011", "value", "1749/20"),
field("A000011", "payee", "P000003"),
]);
const checks = file.suggested.slice(0, 4);
expect(passing("Documents/doc.xml", xml(SEED), checks)).toEqual([
false,
false,
false,
false,
]);
expect(passing("Documents/doc.xml", xml(END), checks)).toEqual([
true,
true,
true,
true,
]);
// A wrong amount fails.
const wrong = END.replace('value="1749/20"', 'value="1700/20"');
expect(passing("Documents/doc.xml", xml(wrong), checks)).toEqual([
true,
true,
false,
true,
]);
});
});
describe("draftTaskFiles for references in KMyMoney transactions", () => {
it("names the account and payee each split refers to, the account over an id list naming it too, and no element a plain count equals", () => {
const file = xmlDraft(SEED, END);
const added = file.values.find(({ kind }) => kind === "added");
expect(
added?.refers_to?.map(({ attribute, value, element }) => [
attribute,
value,
element,
]),
).toEqual([
[
"account",
"A000001",
'<ACCOUNT id="A000001" name="Household Checking"/>',
],
["payee", "P000003", '<PAYEE id="P000003" name="Riverside Electric"/>'],
["account", "A000011", '<ACCOUNT id="A000011" name="Utilities"/>'],
]);
// count="3" equals FIXVERSION's id, but `count` names no element.
const count = file.values.find(({ pointer }) =>
pointer.endsWith("/attributes/count"),
);
expect(count).toMatchObject({ before: "2", after: "3" });
expect(count?.refers_to).toBeUndefined();
});
it("checks a split moved to a new account, though its value equals the id the new account took, so a solve that never moves it fails", () => {
const opened = (seed: string) =>
seed
.replace(
'<SUBACCOUNT id="A000011"/>',
'<SUBACCOUNT id="A000011"/><SUBACCOUNT id="A000012"/>',
)
.replace(
'<ACCOUNT id="A000011" name="Utilities"/>',
'<ACCOUNT id="A000011" name="Utilities"/><ACCOUNT id="A000012" name="Water"/>',
);
const moved = opened(SEED).replace(
'account="A000011" price="1/1" id="S0002" payee="P000002"',
'account="A000012" price="1/1" id="S0002" payee="P000002"',
);
const file = xmlDraft(SEED, moved);
const account = file.values.find(
({ pointer, after }) =>
pointer.endsWith("/attributes/account") && after === "A000012",
);
expect(account).toBeDefined();
expect(account?.note).toBeUndefined();
expect(
passing("Documents/doc.xml", xml(moved), file.suggested),
).not.toContain(false);
// Opening the account alone leaves the water bill where it was.
expect(
passing("Documents/doc.xml", xml(opened(SEED)), file.suggested),
).toContain(false);
});
});
describe("draftTaskFiles values' other pointers", () => {
it("lists a changed value's pointer by each other name its element holds alone, as an Inkscape text's label beside its id", () => {
const poster = (headline: string) =>
`<svg xmlns:inkscape="i"><text id="text12" inkscape:label="Headline" x="10"><tspan>${headline}</tspan></text><text id="text14" inkscape:label="Venue" x="10"><tspan>Pier 4</tspan></text></svg>`;
const file = xmlDraft(poster("Jazz Night"), poster("Jazz Festival"));
const [changed] = file.values;
expect(changed).toMatchObject({
pointer:
"/root/children/[name=text][@id=text12]/children/[name=tspan]/children/0",
after: "Jazz Festival",
alternatives: [
"/root/children/[name=text][@inkscape:label=Headline]/children/[name=tspan]/children/0",
],
});
// Each reads the same value at the end.
expect(
resolvePointer(
xml(poster("Jazz Festival")),
changed?.alternatives?.[0] ?? "",
),
).toBe("Jazz Festival");
});
});
describe("draftTaskFiles values in an archive's entries", () => {
it("lists a chapter title's pointer by the id its h1 holds, though its tag alone names it", () => {
const chapter = (title: string) =>
`<html><body><h1 id="chapter-two">${title}</h1><p>The supply boat brought one letter.</p></body></html>`;
const epub = (title: string) => {
const entry = zipEntry(
{
name: "OEBPS/Text/Section0002.xhtml",
size: 1,
compressedSize: 1,
method: 8,
encrypted: false,
},
new TextEncoder().encode(chapter(title)),
);
return zipView([entry], 1);
};
const [file] = draftOf({
"Documents/book.epub": statePath(
"document",
"zip",
epub("A Letter from the Mainlnad"),
epub("A Letter from the Mainland"),
),
});
const h1 =
"/entries/[name=OEBPS~1Text~1Section0002.xhtml]/view/root/children/[name=body]/children/[name=h1]";
expect(file?.values[0]).toMatchObject({
pointer: `${h1}/children/0`,
alternatives: [
"/entries/[name=OEBPS~1Text~1Section0002.xhtml]/view/root/children/[name=body]/children/[name=h1][@id=chapter-two]/children/0",
],
});
});
});
+234 -183
View File
@@ -6,9 +6,20 @@ import {
NOISE_REASONS,
type NoiseReason,
} from "./appTaskDraftNoise.js";
import { isIdentifyingAttribute } from "./attributeRank.js";
import { isIdentifyingAttribute, isViewStateName } from "./attributeRank.js";
import type { DesktopStateDifference } from "./stateChanges.js";
import { isXmlElement, locatePointer, resolvePointer } from "./viewPointer.js";
import { alternativePointers } from "./appTaskDraftAlternatives.js";
import { isIdReference } from "./appTaskDraftMirrors.js";
import { recordListsOf } from "./appTaskDraftNested.js";
import { holdsFields, isRecordAt } from "./appTaskDraftText.js";
import { attributesOf, compactValue, previewWriter } from "./compactValue.js";
import { pairMembers, pairedAtSeed } from "./memberPairing.js";
import {
escapeToken,
isXmlElement,
locatePointer,
resolvePointer,
} from "./viewPointer.js";
/** Why a value's pointer cannot go into a check as it is, or why the value is noise. */
export const VALUE_NOTES = ["by_position", ...NOISE_REASONS] as const;
@@ -31,6 +42,7 @@ export interface DraftValue {
readonly after: JsonValue;
readonly note?: ValueNote;
readonly refers_to?: readonly ValueReference[];
readonly alternatives?: readonly string[];
}
/** One entry of a drafted file's `values`, as the draft writes it. */
@@ -52,7 +64,7 @@ export const draftValueSchema = z.strictObject({
.enum(VALUE_NOTES)
.optional()
.describe(
"by_position: no selector names it, so no check can use the pointer; view_state, renumbered, volatile, timestamp or upkeep: noise the app writes, left out of the suggested checks.",
"by_position: no selector names it, so no check can use the pointer; view_state, renumbered, volatile, timestamp, upkeep or layout: noise the app writes, left out of the suggested checks.",
),
refers_to: z
.array(
@@ -66,6 +78,12 @@ export const draftValueSchema = z.strictObject({
.describe(
'Other elements a value names by their key or id, such as category 44 naming <cat key="44" name="Groceries"/>.',
),
alternatives: z
.array(z.string())
.optional()
.describe(
"A changed value's pointer naming its element by another identifier or name it holds alone, such as a shape's draw:name, for a check to use instead; at most three.",
),
});
/** Bounds on the values a draft lists, so a large change cannot crowd out the rest of it. */
@@ -74,7 +92,7 @@ export const VALUE_LIMITS = {
fileBytes: 8 * 1024,
draftBytes: 24 * 1024,
chars: 600,
references: 3,
references: 5,
} as const;
const isRecord = (
@@ -82,154 +100,6 @@ const isRecord = (
): value is Record<string, JsonValue> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const cut = (text: string, max: number) =>
text.length > max ? `${text.slice(0, max)}…` : text;
/** An element's attributes; none for a value that holds none. */
const attributesOf = (element: Record<string, JsonValue>) => {
const { attributes } = element;
return isRecord(attributes) ? attributes : {};
};
/** Keep one character past the limit to distinguish an exact fit from a cut. */
const previewWriter = (max: number) => {
const parts: string[] = [];
let length = 0;
const push = (text: string): boolean => {
const kept = text.slice(0, Math.max(0, max + 1 - length));
parts.push(kept);
length += kept.length;
return length <= max;
};
const escaped = (text: string, attribute = false): boolean => {
for (let index = 0; index < text.length; index += 1) {
const char = text[index] ?? "";
if (
!push(
char === "&"
? "&amp;"
: char === "<"
? "&lt;"
: attribute && char === '"'
? "&quot;"
: char,
)
)
return false;
}
return true;
};
const jsonString = (text: string): boolean => {
if (!push('"')) return false;
for (let index = 0; index < text.length; index += 1) {
const code = text.codePointAt(index);
const width = code !== undefined && code > 0xffff ? 2 : 1;
const encoded = JSON.stringify(text.slice(index, index + width));
if (!push(encoded.slice(1, -1))) return false;
index += width - 1;
}
return push('"');
};
const startTag = (
element: Record<string, JsonValue> & { name: string },
): boolean => {
if (!push("<") || !push(element.name)) return false;
const attributes = attributesOf(element);
for (const key in attributes) {
if (!Object.hasOwn(attributes, key)) continue;
if (
!push(" ") ||
!push(key) ||
!push('="') ||
!escaped(String(attributes[key]), true) ||
!push('"')
)
return false;
}
return true;
};
return {
push,
escaped,
jsonString,
startTag,
result: () => cut(parts.join(""), max),
};
};
/** An archive entry's own fields, without its view. */
const isArchiveEntry = (value: JsonValue): value is Record<string, JsonValue> =>
isRecord(value) && "sha256" in value && "view" in value && "name" in value;
/**
* A value as an author reads it: a scalar as it is, cut past `max`
* characters; an element as compact XML, with every text node the XML reader
* kept, which already leaves out the whitespace an app lays out between
* elements; an archive entry as its name, format and size; anything else as
* JSON. Writing stops once past `max`, so a large subtree costs no more than
* the cut.
*/
export const compactValue = (
value: JsonValue | undefined,
format: "json" | "xml" | "archive",
max: number = VALUE_LIMITS.chars,
): JsonValue => {
if (value === undefined) return null;
if (typeof value === "string") return cut(value, max);
if (value === null || typeof value !== "object") return value;
const { push, escaped, jsonString, startTag, result } = previewWriter(max);
const write = (node: JsonValue): boolean => {
if (format === "xml" && isXmlElement(node)) {
if (!startTag(node)) return false;
if (node.children.length === 0) return push("/>");
return (
push(">") &&
node.children.every((child) =>
typeof child === "string" ? escaped(child) : write(child),
) &&
push("</") &&
push(node.name) &&
push(">")
);
}
if (format === "archive" && isArchiveEntry(node))
return write({
...(node.name === undefined ? {} : { name: node.name }),
format: node.format ?? null,
size: node.size ?? null,
});
if (Array.isArray(node))
return (
push("[") &&
node.every(
(item, index) => (index === 0 || push(",")) && write(item),
) &&
push("]")
);
if (isRecord(node)) {
if (!push("{")) return false;
let first = true;
for (const key in node) {
if (!Object.hasOwn(node, key)) continue;
if (
(!first && !push(",")) ||
!jsonString(key) ||
!push(":") ||
!write(node[key] ?? null)
)
return false;
first = false;
}
return push("}");
}
return typeof node === "string"
? jsonString(node)
: push(JSON.stringify(node));
};
write(value);
return result();
};
/** The longest value a reference is resolved from. */
const MAX_REFERENCE_CHARS = 64;
@@ -257,22 +127,37 @@ const indexUnder = (
};
/**
* XML elements by the value of their `key` or `id` attribute, across a view,
* and by tag: at most `PER_TAG` of a tag in document order, so a key that
* records or archive entries repeat costs no more than that.
* XML elements by the value of their `key` or `id` attribute, `xmi:id`
* among them, across a view, and by tag: at most `PER_TAG` of a tag in
* document order, so a key that records or archive entries repeat costs no
* more than that. A view the app keeps of the document, as Umbrello's
* `listview` mirroring its model by id, names nothing.
*/
const referenceIndex = (roots: readonly JsonValue[]) => {
const index = new Map<string, Map<string, JsonValue[]>>();
const pending: JsonValue[] = [...roots];
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
if (isXmlElement(node))
if (isXmlElement(node) && isViewStateName(node.name)) continue;
if (isXmlElement(node)) {
for (const [key, value] of Object.entries(attributesOf(node)))
if (
typeof value === "string" &&
referable(value) &&
/^(?:key|id)$/iu.test(key.split(":").at(-1) ?? key)
/^(?:key|id)$/iu.test(localOf(key))
)
indexUnder(index, value, node);
// An id an app keeps as a child's text, as GnuCash's `<act:id type="guid">`, names the element it sits in.
for (const child of node.children) {
const id = leafText(child);
if (
isXmlElement(child) &&
/^id$/iu.test(localOf(child.name)) &&
id !== undefined &&
referable(id)
)
indexUnder(index, id, node);
}
}
const children = isXmlElement(node)
? node.children
: Array.isArray(node)
@@ -285,6 +170,53 @@ const referenceIndex = (roots: readonly JsonValue[]) => {
return index;
};
/** A name without its namespace prefix. */
const localOf = (name: string) => name.split(":").at(-1) ?? name;
/** An element's text when it holds only one text node, as `<act:name>Groceries</act:name>`. */
const leafText = (node: JsonValue): string | undefined => {
const [only] = isXmlElement(node) ? node.children : [];
return isXmlElement(node) &&
node.children.length === 1 &&
typeof only === "string"
? only
: undefined;
};
/** An element as a reference shows it: its start tag, and its name where a child holds one, as `<gnc:account version="2.0.0"><act:name>Groceries</act:name>…`. */
const referenceTag = (
element: Record<string, JsonValue> & { name: string },
) => {
const writer = previewWriter(VALUE_LIMITS.chars);
if (!writer.startTag(element)) return writer.result();
const children = isXmlElement(element) ? element.children : [];
if (children.length === 0) {
writer.push("/>");
return writer.result();
}
if (!writer.push(">")) return writer.result();
const named = children.find(
(child) =>
isXmlElement(child) &&
/^(?:name|title|label)$/iu.test(localOf(child.name)) &&
leafText(child) !== undefined,
);
if (isXmlElement(named)) {
if (
!writer.push("<") ||
!writer.push(named.name) ||
!writer.push(">") ||
!writer.escaped(leafText(named) ?? "") ||
!writer.push("</") ||
!writer.push(named.name) ||
!writer.push(">")
)
return writer.result();
}
writer.push("…");
return writer.result();
};
/** Whether an attribute's name and an element's tag share a stem, as HomeBank's `payee` and `<pay>`. */
const stemOf = (attribute: string, tag: string) => {
const [left, right] = [attribute, tag].map((name) =>
@@ -298,7 +230,7 @@ const stemOf = (attribute: string, tag: string) => {
);
};
/** What a value a pointer reads names: the one other element whose `key` or `id` it equals, or, among several, the one whose tag shares the attribute's stem. */
/** What a value a pointer reads names: the one other element whose `key` or `id` it equals, or, among several, the one whose tag shares the attribute's stem, the one named for it first; a plain number only through an attribute so named, or one ending in `id`, `ref` or `key`. */
const referencesFrom = (
index: ReadonlyMap<string, ReadonlyMap<string, readonly JsonValue[]>>,
) => {
@@ -308,15 +240,33 @@ const referencesFrom = (
self: JsonValue | undefined,
): ValueReference | undefined => {
if (!referable(value)) return undefined;
// A plain number, as a list's `count="5"`, names an element only through an attribute named for one.
const plain = /^-?\d+(?:\.\d+)?$/u.test(value);
const found = [...(index.get(value)?.values() ?? [])]
.flat()
.filter((node) => node !== self);
const hinted =
.filter(
(node) =>
node !== self &&
(!plain ||
(attribute !== undefined &&
isXmlElement(node) &&
(stemOf(attribute, node.name) ||
/(?:id|ref|key)$/iu.test(localOf(attribute))))),
);
const stemmed =
found.length === 1 || attribute === undefined
? found
: found.filter(
(node) => isXmlElement(node) && stemOf(attribute, node.name),
);
// Among several, the tag the attribute is named for, as `account` an `<ACCOUNT>` before an `<ACCOUNTID>`.
const named = stemmed.filter(
(node) =>
isXmlElement(node) &&
localOf(node.name).toLowerCase() ===
localOf(attribute ?? "").toLowerCase(),
);
const hinted = stemmed.length > 1 && named.length === 1 ? named : stemmed;
const [element] = hinted;
return hinted.length === 1 && isXmlElement(element)
? {
@@ -329,17 +279,15 @@ const referencesFrom = (
return resolve;
};
const referenceTag = (
element: Record<string, JsonValue> & { name: string },
): string => {
const writer = previewWriter(VALUE_LIMITS.chars);
if (writer.startTag(element))
writer.push(
element.children instanceof Array && element.children.length === 0
? "/>"
: ">…",
);
return writer.result();
/** References without repeats, the first of each attribute and value. */
const uniqueReferences = (references: readonly ValueReference[]) => {
const seen = new Set<string>();
return references.filter(({ attribute, value }) => {
const key = JSON.stringify([attribute, value]);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
/** What a values list reads: a file's two ends and how it treats each pointer. */
@@ -362,10 +310,28 @@ export interface ValueContext {
const byteLength = (value: unknown) =>
new TextEncoder().encode(JSON.stringify(value)).length;
/** Records of attributes an element nests whose references a value lists, as the splits of a transaction. */
const MAX_NESTED_RECORDS = 10;
/** The references in an element's attributes other than its own identifiers; of one holding nothing but an identifier, as Parley's `<entry id="6"/>`, that identifier's. */
const attributeReferences = (
resolve: ReturnType<typeof referencesFrom>,
element: JsonValue,
) =>
Object.entries(isXmlElement(element) ? element.attributes : {}).flatMap(
([key, item]) =>
typeof item === "string" &&
((!isIdentifyingAttribute(key) && !/^key$/iu.test(key)) ||
isIdReference(element))
? (resolve(item, key, element) ?? [])
: [],
);
/**
* The elements a value names: each attribute of an element by its own value,
* other than the element's own identifiers, or a scalar, with the attribute
* that holds it.
* other than the element's own identifiers, and of the records of
* attributes it nests, as a KMyMoney split's `account` and `payee`; or a
* scalar, with the attribute that holds it. Each once.
*/
const referencesOf = (
resolve: ReturnType<typeof referencesFrom>,
@@ -374,13 +340,22 @@ const referencesOf = (
): ValueReference[] => {
const value = resolvePointer(view, pointer);
if (isXmlElement(value))
return Object.entries(attributesOf(value)).flatMap(([key, item]) =>
typeof item === "string" &&
!isIdentifyingAttribute(key) &&
!/^key$/iu.test(key)
? (resolve(item, key, value) ?? [])
: [],
);
return uniqueReferences([
...attributeReferences(resolve, value),
...recordListsOf(value)
.flatMap(({ records }) => records)
.slice(0, MAX_NESTED_RECORDS)
.flatMap((record) => attributeReferences(resolve, record)),
// A field holding another element's id as its text, as a split's `<split:account>`.
...[value, ...value.children].flatMap((field) => {
const text = leafText(field);
return isXmlElement(field) &&
text !== undefined &&
!/^id$/iu.test(localOf(field.name))
? (resolve(text, field.name, value) ?? [])
: [];
}),
]);
if (typeof value !== "string") return [];
const segments = pointer.split("/");
const attribute =
@@ -389,6 +364,15 @@ const referencesOf = (
return [resolve(value, attribute, owner) ?? []].flat();
};
/** What a pointer names at the seed; an attribute of a member keyed by its new name, as a renamed layer, read from the member it pairs with there. */
const seedValue = ({ ends }: ValueContext, pointer: string) => {
const key = attributeKeyOf(pointer);
const seen = resolvePointer(ends.baseline, pointer);
if (seen !== undefined || key === undefined) return seen;
const member = pairedAtSeed(ends, pointer.split("/").slice(0, -2).join("/"));
return isXmlElement(member) ? member.attributes[key] : undefined;
};
/** A value's entry, with the references it holds, before any limit. */
const entryOf = (
context: ValueContext,
@@ -420,6 +404,12 @@ const entryOf = (
VALUE_LIMITS.references,
)
: [];
const alternatives =
kind === "changed" &&
note === undefined &&
context.format(view, pointer) === "xml"
? alternativePointers(view, pointer)
: [];
return {
pointer,
kind,
@@ -427,7 +417,8 @@ const entryOf = (
kind === "added"
? null
: compactValue(
resolvePointer(baseline, pointer),
seedValue(context, pointer),
VALUE_LIMITS.chars,
context.format(baseline, pointer),
),
after:
@@ -435,16 +426,71 @@ const entryOf = (
? null
: compactValue(
resolvePointer(final, pointer),
VALUE_LIMITS.chars,
context.format(final, pointer),
),
...(note === undefined ? {} : { note }),
...(refers.length === 0 ? {} : { refers_to: refers }),
...(alternatives.length === 0 ? {} : { alternatives }),
};
};
/** How an entry sorts: what a check can name first, then what only position reaches, then noise. */
/**
* The pointers a value added whole is listed by: a record of text fields in
* a list of its kind, as GnuCash's `<gnc:transaction>`, by each of its
* fields, and a field that lists such records, as its `<trn:splits>`, by
* each record, so the cut on one value never hides a field; anything else
* whole, as a document's root or a FreeCAD object of property lists.
*/
const fieldsOf = (view: JsonValue | null, pointer: string): string[] => {
const value = resolvePointer(view, pointer);
const list = resolvePointer(view, pointer.replace(/\/[^/]+$/u, ""));
if (
!isXmlElement(value) ||
!/\/children\/[^/]+$/u.test(pointer) ||
!Array.isArray(list) ||
list.filter((item) => isXmlElement(item) && item.name === value.name)
.length < 2 ||
!isRecordAt(view, pointer, value) ||
!value.children.some((child) => leafText(child) !== undefined)
)
return [pointer];
const members = (element: JsonValue) => {
const { keys } = pairMembers(
isXmlElement(element) ? element.children : [],
[],
).newer;
return (isXmlElement(element) ? element.children : []).flatMap(
(child, index) =>
isXmlElement(child)
? [{ child, key: escapeToken(keys[index] ?? String(index)) }]
: [],
);
};
return members(value).flatMap(({ child, key }) => {
const at = `${pointer}/children/${key}`;
const records = members(child);
return records.length > 0 &&
records.every(
({ child: record }) =>
record.name === records[0]?.child.name && holdsFields(record),
)
? records.map((record) => `${at}/children/${record.key}`)
: [at];
});
};
/** How an entry sorts: what a check can name first, text before attributes and whole elements, so a cut never drops the edit; then what only position reaches; then noise. */
const rank = (entry: DraftValue) =>
entry.note === undefined ? 0 : entry.note === "by_position" ? 1 : 2;
entry.note === undefined
? typeof entry.after === "string" &&
!entry.after.startsWith("<") &&
/\/children\/\d+$/u.test(entry.pointer)
? 0
: 1
: entry.note === "by_position"
? 2
: 3;
/**
* The values a file's net change added, changed and removed, at the pointers
@@ -481,6 +527,11 @@ export const draftValues = (
const entries = [
...change.added
.filter((pointer) => context.listed(final, pointer))
.flatMap((pointer) =>
context.format(final, pointer) === "xml"
? fieldsOf(final, pointer)
: [pointer],
)
.map((pointer) => entryOf(context, references, pointer, "added")),
...change.changed
.filter((pointer) => context.listed(final, pointer))
+4 -1
View File
@@ -175,7 +175,8 @@ def _xml_text(entry, view, pointer: str, found) -> bool:
def _near(at: str, found, expected, tolerance, join: bool):
"""A value compared within a tolerance: numbers, and numeral strings, by their difference. An element's text is
joined only when join says the view is XML."""
number = _number(_element_text(found) if join else found)
read = _element_text(found) if join else found
number = _number(read.strip() if isinstance(read, str) else read)
within = f"within {_shown(tolerance)} of {_shown(expected)}"
if number is None:
return False, f"{at} is {_shown(found)}, not a number"
@@ -327,6 +328,8 @@ def _members(check, entry):
if kind == "unresolved":
return False, f"{at}: {found}"
if kind == "none":
if _array_leaves_out(form, view, pointer):
return _undecided(check)
return False, f"{at} has no value" if found is None else f"{at}: {found}"
if not isinstance(found, list):
return False, f"{at} is {_shown(found)}, not an array"
+34 -4
View File
@@ -41,11 +41,41 @@ def _selector(token: str):
return conditions
_ISO_STAMP = re.compile(
r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:[.,]\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$", re.ASCII
)
_ASCTIME_STAMP = re.compile(
r"^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 0-3]?\d \d{2}:\d{2}:\d{2} \d{4}$", re.ASCII
)
def _is_saved_time(text: str) -> bool:
stripped = text.strip()
return _ISO_STAMP.fullmatch(stripped) is not None or _ASCTIME_STAMP.fullmatch(stripped) is not None
def _text_without_stamps(node) -> str:
"""An element's text with save-time leaves removed, matching the selector that named it."""
if isinstance(node, str):
return "" if _is_saved_time(node) else node
if not _is_element(node):
return ""
return "".join(_text_without_stamps(child) for child in node["children"])
def _has_child_text(member, key: str, value: str) -> bool:
"""Whether an element has a child element named key whose text, its whitespace collapsed, is value."""
return _is_element(member) and any(
_is_element(child) and child["name"] == key and _collapse_whitespace(_element_text(child)) == value
for child in member["children"])
"""Whether an element has a child element named key whose text, its whitespace collapsed, is value. A nested
save time is not part of the name. A child that is only a time still matches that time."""
if not _is_element(member):
return False
for child in member["children"]:
if not _is_element(child) or child["name"] != key:
continue
plain = _collapse_whitespace(_text_without_stamps(child))
text = plain if plain else _collapse_whitespace(_element_text(child))
if text == value:
return True
return False
def _selects(member, conditions) -> bool:
+57 -10
View File
@@ -4,12 +4,14 @@ export const isIdentifyingAttribute = (key: string): boolean =>
/**
* Words in a name for how the app showed, printed or kept the document rather
* than what it holds: its cursor, selection, scroll, zoom, windows, view and
* configuration settings, printer, and a save's history, edit time and count,
* generator and statistics.
* than what it holds: its cursor, selection (VYM's `<select>`), the layer,
* frame, view or colour it has current, scroll, zoom, windows, view and
* configuration settings, a list or tree view mirroring the document,
* printer, a save's history, edit time and count, generator and statistics,
* and the preview or thumbnail it renders.
*/
export const VIEW_STATE =
/cursor|selection|selected|scroll|zoom|viewport|window|splitter|toplevel|topleft|uidata|namedview|view-?settings|config(?:uration)?-?settings|printer|history|edit(?:ing)?-?(?:time|duration|cycles?)|last-?saved|generator|document-?statistic/iu;
/cursor|^select$|selection|selected|current[-_]?(?:layer|frame|view|colou?r|page|tab|tool|index|item|row|column|cell|sheet|slide|object|scene|track)|scroll|zoom|viewport|window|splitter|toplevel|topleft|uidata|namedview|view-?settings|(?:list|tree)-?view|config(?:uration)?-?settings|printer|history|edit(?:ing)?-?(?:time|duration|cycles?)|last-?saved|generator|document-?statistic|preview|thumbnail/iu;
/** Whether a tag or attribute name is about how the app showed the document rather than what it holds. */
export const isViewStateName = (name: string): boolean => VIEW_STATE.test(name);
@@ -24,24 +26,69 @@ const STYLE_NAME = /(?:style|font|family|class|type)-?name$/u;
const HEX_TOKEN = /^[0-9a-f-]{8,}$/iu;
const LONG_TOKEN = /^(?=.*\d)[A-Za-z0-9+/=_-]{16,}$/u;
/** Whether a value stands for no value, as Grisbi writes `Id="(null)"` on every transaction: it names nothing. */
export const isPlaceholder = (value: string): boolean =>
/^\(?(?:null|nil|none|undefined)\)?$/iu.test(value.trim());
/** Umbrello's ids: `u` and twelve letters and digits mixing cases at random, as `ubcgF2AWfBmHh`, with a digit or four or more changes of case. */
const isRandomCaseId = (value: string): boolean =>
/^u(?=[^]*[A-Z])(?=[^]*[a-z])[A-Za-z\d]{12}$/u.test(value) &&
(/\d/u.test(value) ||
(value.match(/\p{Ll}(?=\p{Lu})|\p{Lu}(?=\p{Ll})/gu)?.length ?? 0) >= 4);
/** Whether a value is a GUID, braced or not, as VYM's `uuid="{18eadb5d-04fc-4448-a0f9-1f9a3dedaff7}"` on each branch. */
export const isGuid = (value: string): boolean =>
/^\{?[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}?$/iu.test(value);
/** Whether a value is a uid an app generates: a GUID, or 32 hex digits without dashes, as TreeLine's uuid1 `fc11808dd9f511f181b7edd4f1920549`. */
export const isGeneratedUid = (value: string): boolean =>
isGuid(value) || /^(?=[^]*[a-f])[0-9a-f]{32}$/iu.test(value);
/** Whether a value is a word a program makes, a hex run, GUID, long token or an id of random case, rather than one a user typed. */
export const isGeneratedToken = (value: string): boolean =>
HEX_TOKEN.test(value) ||
isGuid(value) ||
LONG_TOKEN.test(value) ||
isRandomCaseId(value);
/** Whether an identifier's value is one an app generates for a new element, as Freeplane's `ID_329023692` or a GUID, which another save of the same edit would not repeat. */
export const isGeneratedId = (value: string): boolean =>
/^[A-Za-z]*[_-]?\d{6,}$/u.test(value) || isGeneratedToken(value);
/** Whether an identifier is one an ODF app numbers anew as it saves, as LibreOffice's `xml:id="id2"` and `draw:id="id2"` on a shape: where the shape came in that save, not which shape it is. */
export const isSaveNumberedId = (key: string, value: string): boolean =>
/^(?:xml|draw):id$/iu.test(key) && /^id\d+$/u.test(value);
/** Whether a key names what its element is called rather than a style or font it uses. */
export const isNameLikeKey = (key: string): boolean => {
const local = localName(key);
return NAME_LIKE.test(local) && !STYLE_NAME.test(local);
};
/** A length with its unit, as ODF's `svg:height="2.629cm"`: a coordinate, however it is spelled. */
const MEASURE = /^-?\d+(?:\.\d+)?(?:cm|mm|in|pt|pc|px|em|%)$/u;
/** Whether an attribute names an automatic style an app numbers as it saves, as LibreOffice's `presentation:style-name="pr1"` or `text:style-name="MT1"`, which it shares and renumbers on reload. */
export const isAutomaticStyle = (key: string, value: string): boolean =>
/style-name$/iu.test(key) && /^[A-Za-z]{1,4}\d+$/u.test(value);
/**
* How well an attribute names its element across saves, best first: 0 a
* name-like key, 1 a worded value that is no generated token, 2 an integer of
* up to five digits, 3 anything else, such as a coordinate, a long number or a
* token, which a later save may change, as it may view state such as which
* layer is `selected`.
* up to five digits, 3 anything else, such as a coordinate or a length with
* its unit, a long number, a token or an automatic style name (`pr1`), which
* a later save may change, as it may view state such as which layer is
* `selected`.
*/
export const attributeTier = (key: string, value: string): 0 | 1 | 2 | 3 => {
if (isViewStateName(key)) return 3;
if (
isViewStateName(key) ||
isAutomaticStyle(key, value) ||
MEASURE.test(value)
)
return 3;
if (isNameLikeKey(key)) return 0;
if (/\p{L}/u.test(value) && !HEX_TOKEN.test(value) && !LONG_TOKEN.test(value))
return 1;
if (/\p{L}/u.test(value) && !isGeneratedToken(value)) return 1;
return /^-?\d{1,5}$/u.test(value) ? 2 : 3;
};
+155
View File
@@ -0,0 +1,155 @@
import type { JsonValue } from "../jsonValue.js";
import { isXmlElement } from "./viewPointer.js";
const isRecord = (
value: JsonValue | undefined,
): value is Record<string, JsonValue> =>
typeof value === "object" && value !== null && !Array.isArray(value);
export const cut = (text: string, max: number) =>
text.length > max ? `${text.slice(0, max)}…` : text;
/** An element's attributes; none for a value that holds none. */
export const attributesOf = (element: Record<string, JsonValue>) => {
const { attributes } = element;
return isRecord(attributes) ? attributes : {};
};
/** Keep one character past the limit to distinguish an exact fit from a cut. */
export const previewWriter = (max: number) => {
const parts: string[] = [];
let length = 0;
const push = (text: string): boolean => {
const kept = text.slice(0, Math.max(0, max + 1 - length));
parts.push(kept);
length += kept.length;
return length <= max;
};
const escaped = (text: string, attribute = false): boolean => {
for (let index = 0; index < text.length; index += 1) {
const char = text[index] ?? "";
if (
!push(
char === "&"
? "&amp;"
: char === "<"
? "&lt;"
: attribute && char === '"'
? "&quot;"
: char,
)
)
return false;
}
return true;
};
const jsonString = (text: string): boolean => {
if (!push('"')) return false;
for (let index = 0; index < text.length; index += 1) {
const code = text.codePointAt(index);
const width = code !== undefined && code > 0xffff ? 2 : 1;
const encoded = JSON.stringify(text.slice(index, index + width));
if (!push(encoded.slice(1, -1))) return false;
index += width - 1;
}
return push('"');
};
const startTag = (
element: Record<string, JsonValue> & { name: string },
): boolean => {
if (!push("<") || !push(element.name)) return false;
const attributes = attributesOf(element);
for (const key in attributes) {
if (!Object.hasOwn(attributes, key)) continue;
if (
!push(" ") ||
!push(key) ||
!push('="') ||
!escaped(String(attributes[key]), true) ||
!push('"')
)
return false;
}
return true;
};
return {
push,
escaped,
jsonString,
startTag,
result: () => cut(parts.join(""), max),
};
};
/** An archive entry's own fields, without its view. */
const isArchiveEntry = (value: JsonValue): value is Record<string, JsonValue> =>
isRecord(value) && "sha256" in value && "view" in value && "name" in value;
/**
* A value as an author reads it: a scalar as it is, cut past `max`
* characters; an element as compact XML, with every text node the XML reader
* kept, which already leaves out the whitespace an app lays out between
* elements; an archive entry as its name, format and size; anything else as
* JSON. Writing stops once past `max`, so a large subtree costs no more than
* the cut.
*/
export const compactValue = (
value: JsonValue | undefined,
max: number,
format: "json" | "xml" | "archive",
): JsonValue => {
if (value === undefined) return null;
if (typeof value === "string") return cut(value, max);
if (value === null || typeof value !== "object") return value;
const { push, escaped, jsonString, startTag, result } = previewWriter(max);
const write = (node: JsonValue): boolean => {
if (format === "xml" && isXmlElement(node)) {
if (!startTag(node)) return false;
if (node.children.length === 0) return push("/>");
return (
push(">") &&
node.children.every((child) =>
typeof child === "string" ? escaped(child) : write(child),
) &&
push("</") &&
push(node.name) &&
push(">")
);
}
if (format === "archive" && isArchiveEntry(node))
return write({
...(node.name === undefined ? {} : { name: node.name }),
format: node.format ?? null,
size: node.size ?? null,
});
if (Array.isArray(node))
return (
push("[") &&
node.every(
(item, index) => (index === 0 || push(",")) && write(item),
) &&
push("]")
);
if (isRecord(node)) {
if (!push("{")) return false;
let first = true;
for (const key in node) {
if (!Object.hasOwn(node, key)) continue;
if (
(!first && !push(",")) ||
!jsonString(key) ||
!push(":") ||
!write(node[key] ?? null)
)
return false;
first = false;
}
return push("}");
}
return typeof node === "string"
? jsonString(node)
: push(JSON.stringify(node));
};
write(value);
return result();
};
+86
View File
@@ -0,0 +1,86 @@
import type { JsonValue } from "../jsonValue.js";
import { isGeneratedId } from "./attributeRank.js";
import { isXmlElement } from "./viewPointer.js";
/** A field naming a JSON record, as TreeLine's `uid`: `id`, `uid`, `uuid`, `guid`, `key`, or a name ending in `_id`, `-id` or `Id`. */
const ID_FIELD = /^(?:_?id|uid|uuid|guid|key)$|[_-]id$|[a-z]Id$/u;
/** The record's own id, ahead of a relationship such as `parent_id`, which also matches `ID_FIELD`. */
const OWN_ID = ["uid", "uuid", "guid", "id", "key"];
const isJsonRecord = (value: JsonValue): value is Record<string, JsonValue> =>
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
!isXmlElement(value);
/** Whether every member holds a string at a key a selector can carry, each its own. */
const namesEach = (members: readonly JsonValue[], key: string) => {
const values = members.map((member) =>
isJsonRecord(member) ? member[key] : undefined,
);
return (
values.every(
(value) =>
typeof value === "string" && value !== "" && !value.includes("]["),
) && new Set(values).size === values.length
);
};
/** One version's side of a pairing: each member's key, and the other version's member it pairs with. */
interface Side {
readonly keys: readonly string[];
readonly partners: readonly (number | undefined)[];
}
/**
* Pair the JSON records of two versions of an array by an id field each
* holds alone at both ends (`ID_FIELD`), as TreeLine's nodes by
* `[uid=7584d494d9f511f1a873edd4f1920549]`, whatever order the app saves
* them in; a member only one version holds is named by its id too, unless
* the app generated it (`isGeneratedId`), when another save would not
* repeat it and only position names the member. Undefined when the members
* are not all JSON records or no such field names each.
*/
export const pairRecordsById = (
newer: readonly JsonValue[],
older: readonly JsonValue[],
): { readonly newer: Side; readonly older: Side } | undefined => {
const [first] = [...newer, ...older];
if (!isJsonRecord(first ?? null) || ![...newer, ...older].every(isJsonRecord))
return undefined;
const key = Object.keys(first ?? {})
.filter(
(field) =>
ID_FIELD.test(field) &&
// `[@attr]` and `[>child]` are selector marks, not a JSON field's name.
!/^[@>]|[=[\]]/u.test(field) &&
namesEach(newer, field) &&
namesEach(older, field),
)
.toSorted((left, right) => {
const rank = (field: string) => {
const own = OWN_ID.indexOf(field.toLowerCase());
return own < 0 ? OWN_ID.length : own;
};
return rank(left) - rank(right);
})[0];
if (key === undefined) return undefined;
const idOf = (member: JsonValue) =>
isJsonRecord(member) ? String(member[key]) : "";
const side = (
members: readonly JsonValue[],
others: readonly JsonValue[],
): Side => {
const where = new Map(others.map((other, index) => [idOf(other), index]));
const partners = members.map((member) => where.get(idOf(member)));
return {
keys: members.map((member, index) =>
partners[index] === undefined && isGeneratedId(idOf(member))
? String(index)
: `[${key}=${idOf(member)}]`,
),
partners,
};
};
return { newer: side(newer, older), older: side(older, newer) };
};
+565
View File
@@ -0,0 +1,565 @@
import type { JsonValue } from "../jsonValue.js";
import { isTimestamp } from "./appTask.js";
import {
isGeneratedId,
isGuid,
isIdentifyingAttribute,
isPlaceholder,
isSaveNumberedId,
rankAttributes,
} from "./attributeRank.js";
import {
isPositionalKey,
numberedInOrder,
positionalKeys,
savePositionKeys,
} from "./positionalKeys.js";
import {
childConditions,
condition,
countUnspelledPairs,
holdingCondition,
MAX_PAIRED,
pairSuffix,
type Attribute,
type Candidates,
} from "./selectorCandidates.js";
import { pairRecordsById } from "./jsonRecordPairing.js";
import { resolvePointer } from "./viewPointer.js";
import { selectorOf } from "./viewSelector.js";
const isRecord = (
value: JsonValue | null | undefined,
): value is Record<string, JsonValue> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const own = (record: Record<string, JsonValue>, key: string) =>
Object.hasOwn(record, key) ? record[key] : undefined;
/** A value a selector can carry and that stays the same between saves. */
const selectable = (value: string) =>
!value.includes("][") && !isTimestamp(value) && !isPlaceholder(value);
/** An attribute name a selector can carry. */
const attributeName = (key: string) => key !== "" && !/[=[\]]/u.test(key);
/** Two-attribute selectors from the attributes `paired`, the best ranked pairs first. */
const pairsOf = (paired: readonly (Attribute & { tier: number })[]) =>
paired
.flatMap((first, index) =>
paired.slice(index + 1).map((second) => ({
tier: first.tier + second.tier,
suffix: pairSuffix(first, second),
})),
)
.toSorted((left, right) => left.tier - right.tier)
.map(({ suffix }) => suffix);
/**
* The selectors that could name a member, most general first: `[name=N]`;
* then its identifiers, a `name` attribute first; then each other attribute
* by itself, a name-like key, a worded value or a small integer first; then
* two of the best `MAX_PAIRED` of those together; then a coordinate, a long
* number or a token by itself, and an id an ODF app numbers anew on each save
* (`isSaveNumberedId`); then a child element's text, as Osmo's record
* by `[>first_name=Delphine]` (`childConditions`), for an element no
* identifier names; last, an id the app generates (`isGeneratedId`), as
* Freeplane's `ID_329023692`, or a GUID in any attribute, as VYM's `uuid`,
* after an identifier numbering the members by save position
* (`savePositionKeys`), as Parley's `<entry id="6">`, where a child's text
* names the member.
* All are counted over every sibling, so a selector several siblings match
* is never taken for one naming a member alone; but an element with
* identifying attributes is keyed by those alone,
* so one whose identifiers are new is another element, whatever else it
* shares. An identifier the app numbers by position (`positional`) names no
* member. The ids number the name among those seen, so a name is spelled
* into a selector only once one is chosen, not per attribute.
*/
const candidatesOf = (
member: JsonValue,
names: Map<string, number>,
positional: ReadonlySet<string>,
saved: ReadonlySet<string>,
): Candidates | undefined => {
if (!isRecord(member)) return undefined;
const name = own(member, "name");
if (typeof name !== "string" || !selectable(name)) return undefined;
const attributes = own(member, "attributes");
const usable = (
isRecord(attributes) ? Object.entries(attributes) : []
).flatMap(([key, value]) =>
typeof value === "string" &&
attributeName(key) &&
selectable(value) &&
!isPositionalKey(positional, name, key)
? [{ key, value }]
: [],
);
// An id the app generates names a kept member, but no new one another save would key alike, so it ranks last.
const children = childConditions(member);
// An id numbering the members by save position names one after a child's text does.
const placed =
children.length === 0
? []
: usable.filter(
({ key }) =>
isIdentifyingAttribute(key) && isPositionalKey(saved, name, key),
);
// An id the app numbers anew on each save names no member past it: it ranks with the tokens.
const numbered = usable.filter(({ key, value }) =>
isSaveNumberedId(key, value),
);
const generated = usable.filter(
(field) =>
!placed.includes(field) &&
!numbered.includes(field) &&
((isIdentifyingAttribute(field.key) && isGeneratedId(field.value)) ||
isGuid(field.value)),
);
const identities = usable.filter(
(field) =>
isIdentifyingAttribute(field.key) &&
!generated.includes(field) &&
!numbered.includes(field) &&
!placed.includes(field),
);
const named = (key: string) => key.toLowerCase() === "name";
const ranked = [
...rankAttributes(
usable.filter(
(field) =>
!isIdentifyingAttribute(field.key) && !generated.includes(field),
),
),
...numbered.map((field) => ({ ...field, tier: 3 as const })),
];
const pairable = ranked.filter(({ tier }) => tier < 3);
const suffixes = [
"",
...[
...identities.filter(({ key }) => named(key)),
...identities.filter(({ key }) => !named(key)),
...pairable,
].map(condition),
...pairsOf(pairable.slice(0, MAX_PAIRED)),
...ranked.filter(({ tier }) => tier === 3).map(condition),
];
// Counted on every member, one its identifiers key included, since the evaluator matches any member holding the child.
suffixes.push(
...children,
...placed.map(condition),
...generated.map(condition),
);
const number = names.get(name) ?? names.size;
names.set(name, number);
// A suffix is empty or opens with `[`, so the number before it cannot run into it.
const ids = suffixes.map((suffix) => `${String(number)}${suffix}`);
const choosable =
identities.length > 0 ? identities.length + 1 : suffixes.length;
return {
name,
number,
ids,
choosable,
byChild:
suffixes.length - children.length - placed.length - generated.length,
identified: identities.length + 1,
generated: generated.length,
pairable: pairable.map(({ key }) => key),
};
};
/**
* The candidates a member present in both versions pairs by, in order: its
* tag and stable identifiers, then an id the app generated, which a kept
* member keeps, as a record's UUID however its title changes, then the rest
* it may be keyed by. A new member is keyed with that id last (`unmatched`).
*/
const pairingOrder = ({
ids,
choosable,
identified,
generated,
}: Candidates): number[] => {
const last = ids.length - generated;
const ranks = Array.from({ length: ids.length }, (_, at) => at);
return [
...ranks.slice(0, Math.min(identified, choosable)),
...ranks.slice(last),
...ranks.slice(Math.min(identified, choosable), Math.min(choosable, last)),
];
};
/** The selector a member's candidate at `index` spells: its name, then its id past the name's number. */
const selectorAt = ({ name, number, ids }: Candidates, index: number) =>
`[name=${name}]${(ids[index] ?? "").slice(String(number).length)}`;
const countIds = (members: readonly (Candidates | undefined)[]) => {
const counts = new Map<string, number>();
for (const candidates of members)
for (const id of candidates?.ids ?? [])
counts.set(id, (counts.get(id) ?? 0) + 1);
return counts;
};
/** Each member's place among the members of its tag, as the tag and how many come before it; none for a member with no tag. */
const placesOf = (members: readonly JsonValue[]) => {
const seen = new Map<string, number>();
return members.map((member) => {
const name = isRecord(member) ? own(member, "name") : undefined;
if (typeof name !== "string") return undefined;
const before = seen.get(name) ?? 0;
seen.set(name, before + 1);
return `${String(before)}\u0000${name}`;
});
};
/**
* Whether two members are one element renamed: the same tag and attribute
* keys, one identifier's value changed and every other attribute and the
* children alike, as MyPaint renames a layer.
*/
const renamed = (newer: JsonValue, older: JsonValue) => {
if (!isRecord(newer) || !isRecord(older)) return false;
const [after, before] = [own(newer, "attributes"), own(older, "attributes")];
if (
own(newer, "name") !== own(older, "name") ||
!isRecord(after) ||
!isRecord(before)
)
return false;
const keys = Object.keys(after);
const changed = keys.filter((key) => own(before, key) !== after[key]);
const [key] = changed;
return (
keys.length === Object.keys(before).length &&
changed.length === 1 &&
key !== undefined &&
Object.hasOwn(before, key) &&
isIdentifyingAttribute(key) &&
JSON.stringify(own(newer, "children")) ===
JSON.stringify(own(older, "children"))
);
};
/** An element's attributes; none for any other value. */
const attributesOf = (member: JsonValue) => {
const attributes = isRecord(member) ? own(member, "attributes") : undefined;
return isRecord(attributes) ? attributes : {};
};
/** One version's members as a pairing reads and fills them. */
interface Pairing {
readonly members: readonly JsonValue[];
readonly candidates: readonly (Candidates | undefined)[];
readonly counts: ReadonlyMap<string, number>;
readonly keys: (string | undefined)[];
readonly partners: (number | undefined)[];
}
/**
* The keys of a member `renamed` where the attribute it pairs by numbers the
* members in order, as MyPaint's `src`, which a move renumbers: each
* version's own value of the renamed identifier, as `[@name=Crescent Moon]`
* and `[@name=Sketch]`, where each names its member alone; undefined
* otherwise, and the pairing keeps the attribute.
*/
const renameKeys = (
sides: { readonly newer: Pairing; readonly older: Pairing },
at: { readonly index: number; readonly match: number; readonly id: string },
) => {
const { newer, older } = sides;
const candidates = newer.candidates[at.index];
const [after, before] = [
attributesOf(newer.members[at.index] ?? null),
attributesOf(older.members[at.match] ?? null),
];
const paired =
candidates === undefined
? undefined
: selectorOf(at.id.slice(String(candidates.number).length))?.[0]?.key;
const key = Object.keys(after).find((name) => after[name] !== before[name]);
if (
candidates === undefined ||
paired === undefined ||
key === undefined ||
!numberedInOrder(newer.members, candidates.name, paired) ||
!numberedInOrder(older.members, candidates.name, paired)
)
return undefined;
const spelled = (side: Pairing, value: JsonValue | undefined) => {
const suffix = typeof value === "string" ? condition({ key, value }) : "";
return suffix !== "" &&
side.counts.get(`${String(candidates.number)}${suffix}`) === 1
? `[name=${candidates.name}]${suffix}`
: undefined;
};
const [mine, theirs] = [
spelled(newer, after[key]),
spelled(older, before[key]),
];
return mine === undefined || theirs === undefined
? undefined
: { newer: mine, older: theirs };
};
/**
* Pair, as one element `renamed`, a member of each version left unpaired at
* the same place among the members of its tag, by its first selector past
* its identifiers that names it alone in both versions with the same value,
* as a layer by its `src`; left unpaired when none does. Where that selector
* numbers the members in order, each version keys it by its own name
* (`renameKeys`).
*/
const pairRenamed = (newer: Pairing, older: Pairing) => {
const unpaired = new Map<string, number>();
placesOf(older.members).forEach((place, index) => {
if (place !== undefined && older.partners[index] === undefined)
unpaired.set(place, index);
});
placesOf(newer.members).forEach((place, index) => {
const match = place === undefined ? undefined : unpaired.get(place);
const candidates = newer.candidates[index];
const theirs = match === undefined ? undefined : older.candidates[match];
if (
match === undefined ||
candidates === undefined ||
theirs === undefined ||
newer.partners[index] !== undefined ||
!renamed(newer.members[index] ?? null, older.members[match] ?? null)
)
return;
const at = candidates.ids.findIndex(
(id, position) =>
position >= candidates.choosable &&
newer.counts.get(id) === 1 &&
older.counts.get(id) === 1 &&
theirs.ids.includes(id),
);
if (at < 0) return;
const keys = renameKeys(
{ newer, older },
{ index, match, id: candidates.ids[at] ?? "" },
);
newer.keys[index] = keys?.newer ?? selectorAt(candidates, at);
older.keys[match] = keys?.older ?? selectorAt(candidates, at);
newer.partners[index] = match;
older.partners[match] = index;
});
};
/** Whether pairing a list holds its members' tag-only keys: the children of a document's root element, where an app may add a container of the tag, as Dia a layer. */
/** Where a list sits, for its members' `holdingCondition`: whether it is the document root's children, and the tag the step to its element names, when one does. */
export interface ListPlace {
readonly root: boolean;
readonly owner?: string;
}
/** A list's place, read from its pointer, as `/root/children/[name=gnm:Sheets]/children` sits in `gnm:Sheets`. */
export const holdsTagOnly = (list: string): ListPlace => {
const owner = selectorOf(
(list.split("/").at(-2) ?? "").replaceAll("~1", "/").replaceAll("~0", "~"),
)?.find(({ prefix, key }) => prefix === "" && key === "name")?.value;
return {
root: /(?:^|\/)root\/children$/u.test(list),
...(owner === undefined ? {} : { owner }),
};
};
/** Whether a tag is the singular of a list's, as `gnm:Sheet` of `gnm:Sheets`, so the list holds or could hold several. */
const pluralOf = (owner: string | undefined, tag: string) => {
const [list, one] = [owner?.toLowerCase() ?? "", tag.toLowerCase()];
return (
list === `${one}s` ||
list === `${one}es` ||
(one.endsWith("y") && list === `${one.slice(0, -1)}ies`)
);
};
/**
* Give each member of a pair its tag alone names a `holdingCondition`, so it
* stays named if a sibling of its tag appears: in the root's children, and
* in a list named for its tag, as `gnm:Sheets` holds a `gnm:Sheet`.
*/
const holdTagOnly = (newer: Pairing, older: Pairing, place: ListPlace) => {
newer.partners.forEach((match, index) => {
const candidates = newer.candidates[index];
const deep =
candidates !== undefined && pluralOf(place.owner, candidates.name);
if (
match === undefined ||
candidates === undefined ||
newer.keys[index] !== `[name=${candidates.name}]` ||
(!place.root && !deep)
)
return;
const held = holdingCondition(
newer.members[index] ?? null,
older.members[match] ?? null,
!place.root,
);
if (held !== undefined)
newer.keys[index] = older.keys[match] =
`[name=${candidates.name}]${held}`;
});
};
/** One version's side of a pairing: each member's key, and the other version's member it pairs with. */
interface PairedSide {
readonly keys: readonly string[];
readonly partners: readonly (number | undefined)[];
}
/**
* Pair the members of two versions of an array one to one. A member pairs by
* its first candidate selector naming it alone in its version and one unpaired
* member of the other, whichever before it name nothing there; then one
* element renamed by another selector (`pairRenamed`). One with no partner
* keeps its first selector naming it alone and nothing in the other version.
* Members left without a selector are keyed and paired by position; so is an
* identifier the app numbers by position, as `positionalKeys` finds. Given
* the list's `place`, a pair its tag alone names also gets a
* `holdingCondition` (`holdTagOnly`).
*/
const pairElements = (
newer: readonly JsonValue[],
older: readonly JsonValue[],
place?: ListPlace,
): { readonly newer: PairedSide; readonly older: PairedSide } => {
const names = new Map<string, number>();
const positional = positionalKeys(newer, older);
const saved = savePositionKeys(newer, older);
const newCandidates = newer.map((member) =>
candidatesOf(member, names, positional, saved),
);
const oldCandidates = older.map((member) =>
candidatesOf(member, names, positional, saved),
);
const newCounts = countIds(newCandidates);
const oldCounts = countIds(oldCandidates);
countUnspelledPairs([
{ members: newer, candidates: newCandidates, counts: newCounts },
{ members: older, candidates: oldCandidates, counts: oldCounts },
]);
const count = (counts: ReadonlyMap<string, number>, id: string) =>
counts.get(id) ?? 0;
const oldById = new Map<string, number>();
oldCandidates.forEach((candidates, index) => {
for (const at of candidates === undefined ? [] : pairingOrder(candidates)) {
const id = candidates?.ids[at] ?? "";
if (count(oldCounts, id) === 1) oldById.set(id, index);
}
});
const newKeys: (string | undefined)[] = newer.map(() => undefined);
const oldKeys: (string | undefined)[] = older.map(() => undefined);
const newPartners: (number | undefined)[] = newer.map(() => undefined);
const oldPartners: (number | undefined)[] = older.map(() => undefined);
newCandidates.forEach((candidates, index) => {
if (candidates === undefined) return;
for (const at of pairingOrder(candidates)) {
const id: string = candidates.ids[at] ?? "";
const match = count(newCounts, id) === 1 ? oldById.get(id) : undefined;
if (match === undefined || oldPartners[match] !== undefined) continue;
newKeys[index] = oldKeys[match] = selectorAt(candidates, at);
newPartners[index] = match;
oldPartners[match] = index;
return;
}
});
const sides = [
{
members: newer,
candidates: newCandidates,
counts: newCounts,
keys: newKeys,
partners: newPartners,
},
{
members: older,
candidates: oldCandidates,
counts: oldCounts,
keys: oldKeys,
partners: oldPartners,
},
] as const;
pairRenamed(...sides);
if (place !== undefined) holdTagOnly(...sides, place);
/**
* The first selector naming a member alone in its version and nothing in
* the other; by a child's text only where the list's length changed, since
* otherwise a member whose naming child an edit changed is that member.
*/
const unmatched = (
candidates: Candidates | undefined,
here: ReadonlyMap<string, number>,
there: ReadonlyMap<string, number>,
) => {
if (candidates === undefined) return undefined;
const last =
newer.length === older.length ? candidates.byChild : candidates.choosable;
const at = candidates.ids
.slice(0, Math.min(candidates.choosable, last))
.findIndex((id) => count(here, id) === 1 && count(there, id) === 0);
return at < 0 ? undefined : selectorAt(candidates, at);
};
newCandidates.forEach((candidates, index) => {
newKeys[index] ??= unmatched(candidates, newCounts, oldCounts);
});
oldCandidates.forEach((candidates, index) => {
oldKeys[index] ??= unmatched(candidates, oldCounts, newCounts);
});
for (let index = 0; index < Math.min(newer.length, older.length); index += 1)
if (newKeys[index] === undefined && oldKeys[index] === undefined) {
newPartners[index] = index;
oldPartners[index] = index;
}
const side = (
keys: readonly (string | undefined)[],
partners: readonly (number | undefined)[],
): PairedSide => ({
keys: keys.map((key, index) => key ?? String(index)),
partners,
});
return {
newer: side(newKeys, newPartners),
older: side(oldKeys, oldPartners),
};
};
/** Pair the members of two versions of an array one to one: JSON records by an id field each holds (`pairRecordsById`), others by selector (`pairElements`). */
export const pairMembers = (
newer: readonly JsonValue[],
older: readonly JsonValue[],
place?: ListPlace,
): { readonly newer: PairedSide; readonly older: PairedSide } =>
pairRecordsById(newer, older) ?? pairElements(newer, older, place);
/**
* The member a pointer names at the end, as its seed version: the other
* version's member it pairs with in the same list, as a layer `renameKeys`
* keys by its new name pairs with the layer of its old one; undefined when
* the pointer names no member of a list.
*/
export const pairedAtSeed = (
ends: {
readonly baseline: JsonValue | null;
readonly final: JsonValue | null;
},
member: string,
): JsonValue | undefined => {
const list = /^(?<list>.*\/children)\/[^/]+$/u.exec(member)?.groups?.list;
const newer =
list === undefined ? undefined : resolvePointer(ends.final, list);
const older =
list === undefined ? undefined : resolvePointer(ends.baseline, list);
const element = resolvePointer(ends.final, member);
if (list === undefined || !Array.isArray(newer) || !Array.isArray(older))
return undefined;
const index = newer.indexOf(element ?? null);
const partner =
index < 0
? undefined
: pairMembers(newer, older, holdsTagOnly(list)).newer.partners[index];
return partner === undefined ? undefined : older[partner];
};
+53
View File
@@ -122,9 +122,62 @@ export const positionalKeys = (
return keys;
};
/**
* Identifiers numbering a list's members of a tag 0..N-1 in document order at
* both ends, where members came or went, as Parley numbers its entries by
* where they are saved: a place among the members as much as a name, which a
* member with a child's text to name it by ranks after that text.
*/
export const savePositionKeys = (
newer: readonly JsonValue[],
older: readonly JsonValue[],
): ReadonlySet<string> => {
const before = attributesByTag(older);
const fromZero = (members: readonly Record<string, string>[]) =>
Object.keys(members[0] ?? {}).filter(
(key) =>
isIdentifyingAttribute(key) &&
members.every((member, index) => member[key] === String(index)),
);
const keys = new Set<string>();
for (const [tag, members] of attributesByTag(newer)) {
const old = before.get(tag) ?? [];
if (old.length === members.length) continue;
const numbered = new Set(fromZero(old));
for (const key of fromZero(members))
if (numbered.has(key)) keys.add(tagKey(tag, key));
}
return keys;
};
/** Whether `positionalKeys` holds an identifier of members with a tag. */
export const isPositionalKey = (
keys: ReadonlySet<string>,
tag: string,
key: string,
) => keys.has(tagKey(tag, key));
/**
* Whether an attribute's values on the members with a tag end in numbers that
* count up or down by one in document order, as MyPaint names each layer's
* `src` `data/layer-00.png`, `data/layer-01.png` and on along the stack on
* every save: they say where a member sits, not which it is.
*/
export const numberedInOrder = (
members: readonly JsonValue[],
tag: string,
key: string,
): boolean => {
const numbers = (attributesByTag(members).get(tag) ?? []).map((attributes) =>
Number(
/(?<n>\d+)\D*$/u.exec(attributes[key] ?? "")?.groups?.n ?? Number.NaN,
),
);
const [first, second] = numbers;
if (first === undefined || second === undefined) return false;
const step = second - first;
return (
Math.abs(step) === 1 &&
numbers.every((number, index) => number === first + step * index)
);
};
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { childConditions } from "./selectorCandidates.js";
describe("childConditions", () => {
it("stops reading a child's text once it is past what a selector names a member by, however long the text", () => {
const element = (text: string) => ({
name: "record",
attributes: {},
children: [
{ name: "title", attributes: {}, children: ["Budget"] },
{ name: "body", attributes: {}, children: [text] },
],
});
const huge = element(`a b ${"x".repeat(4 * 1024 * 1024)}`);
const started = performance.now();
const conditions = childConditions(huge);
const elapsed = performance.now() - started;
expect(conditions).toEqual(["[>title=Budget]"]);
// Building the whole collapsed text took about half a second.
expect(elapsed).toBeLessThan(100);
});
});
+164 -4
View File
@@ -1,5 +1,13 @@
import type { JsonValue } from "../jsonValue.js";
import { spellCondition, type Condition } from "./viewSelector.js";
import { isTimestamp } from "./appTask.js";
import {
isGeneratedId,
isIdentifyingAttribute,
isNameLikeKey,
isPlaceholder,
rankAttributes,
} from "./attributeRank.js";
import { selectorOf, spellCondition, type Condition } from "./viewSelector.js";
const isRecord = (
value: JsonValue | null | undefined,
@@ -12,15 +20,19 @@ const own = (record: Record<string, JsonValue>, key: string) =>
/**
* A member's selectors as its name and the ids they are counted by, the
* number its name is counted by and then the conditions after the name; how
* many of them, from the first, may key it; and the keys of its attributes
* that pair, best ranked first, its pairs spelled from the first
* `MAX_PAIRED`.
* many of them, from the first, may key it, where those by a child's text
* start, and those by its stable identifiers end; how many ids the app
* generated close the list; and the keys of its attributes that pair, best
* ranked first, its pairs spelled from the first `MAX_PAIRED`.
*/
export interface Candidates {
readonly name: string;
readonly number: number;
readonly ids: readonly string[];
readonly choosable: number;
readonly byChild: number;
readonly identified: number;
readonly generated: number;
readonly pairable: readonly string[];
}
@@ -39,6 +51,74 @@ export const pairSuffix = (first: Attribute, second: Attribute) =>
? `${condition(first)}${condition(second)}`
: `${condition(second)}${condition(first)}`;
/** The longest child text a selector names a member by. */
const MAX_CHILD_TEXT = 64;
/**
* An element's text with its whitespace collapsed as `collapseWhitespace`
* does, as `[>CHILD=VALUE]` reads it, whatever elements hold it, so every
* member a selector matches counts; collapsed as it is read, and undefined
* once longer than a selector names a member by.
*/
const shortText = (element: JsonValue): string | undefined => {
let text = "";
let space = false;
/** Add a text node's characters, collapsed; false once the text is past the limit, read no further. */
const append = (node: string) => {
for (const character of node)
if (" \t\r\n".includes(character)) space = text !== "";
else {
text += `${space ? " " : ""}${character}`;
space = false;
if (text.length > MAX_CHILD_TEXT) return false;
}
return true;
};
const pending: JsonValue[] = [element];
for (let node = pending.pop(); node !== undefined; node = pending.pop())
if (typeof node === "string") {
if (isTimestamp(node)) continue;
if (!append(node)) return undefined;
} else if (isRecord(node) && Array.isArray(node.children))
for (let index = node.children.length - 1; index >= 0; index -= 1)
pending.push(node.children[index] ?? null);
return text;
};
/**
* The `[>CHILD=VALUE]` conditions that could name an element by a child's
* text, best first by `attributeTier`: a name-like tag, as Osmo's
* `first_name`, then worded text, then a small integer, then other numbers.
* A child whose text is long, blank, a time, or a token or id a program
* generates names nothing a later save keeps.
*/
export const childConditions = (member: JsonValue): string[] => {
const children = isRecord(member) ? own(member, "children") : undefined;
const found = (Array.isArray(children) ? children : []).flatMap((child) => {
const key = isRecord(child) ? own(child, "name") : undefined;
const value = typeof key === "string" ? shortText(child) : undefined;
return typeof key === "string" &&
value !== undefined &&
key !== "" &&
!/[=[\]]/u.test(key) &&
/[\p{L}\d]/u.test(value) &&
!value.includes("][") &&
!isTimestamp(value) &&
!isGeneratedId(value) &&
!isPlaceholder(value) &&
!/\d{10}/u.test(value)
? [{ key, value }]
: [];
});
return [
...new Set(
rankAttributes(found).map(({ key, value }) =>
spellCondition({ prefix: ">", key, value }),
),
),
];
};
/** One version's members, their candidates, and how many members each id names. */
interface CountedVersion {
readonly members: readonly JsonValue[];
@@ -128,3 +208,83 @@ export const countUnspelledPairs = (versions: readonly CountedVersion[]) => {
if (spelled(id)) counts.set(id, (counts.get(id) ?? 0) + 1);
});
};
/** An identifier that holds its value at both versions and a selector can carry. */
const keptIdentifier = (
after: Record<string, JsonValue>,
before: Record<string, JsonValue>,
name: string,
) => {
const value = after[name];
return typeof value === "string" &&
value === before[name] &&
!/[=[\]]/u.test(name) &&
!value.includes("][") &&
!isTimestamp(value)
? condition({ key: name, value })
: undefined;
};
/** Whether an element holds elements and no text of its own, as Gnumeric's `gnm:Sheet` its name and cells. */
const holdsElements = (member: JsonValue) => {
const children = isRecord(member) ? own(member, "children") : undefined;
const all = Array.isArray(children) ? children : [];
return (
all.some((child) => isRecord(child)) &&
all.every((child) => typeof child !== "string" || child.trim() === "")
);
};
/** Whether an element holds a list, two or more elements of one tag and no text of its own, as Dia's layer its boxes. */
const isContainer = (member: JsonValue) => {
const children = isRecord(member) ? own(member, "children") : undefined;
const all = Array.isArray(children) ? children : [];
const tags = all.flatMap((child) => {
const tag = isRecord(child) ? own(child, "name") : undefined;
return typeof tag === "string" ? [tag] : [];
});
return (
new Set(tags).size < tags.length &&
all.every((child) => typeof child !== "string" || child.trim() === "")
);
};
/**
* A condition that keeps a member its tag alone names its own once the app
* adds a sibling of that tag, as Dia adds an empty `Background` layer each
* time it reopens a diagram, for a list's container with an identifier, a
* kind a document can hold several of: an id both versions hold, which a new
* sibling would not share; else a child's text both hold, which an empty one
* lacks; else its `name`, which a new one may repeat, as Dia's do. `nested`,
* for a member of a list named for its tag, as a `gnm:Sheet` in
* `gnm:Sheets`, takes any element holding elements, and only a name-like
* child, as `[>gnm:Name=Budget]`. Undefined when none is there.
*/
export const holdingCondition = (
newer: JsonValue,
older: JsonValue,
nested = false,
): string | undefined => {
const attributesOf = (member: JsonValue) => {
const attributes = isRecord(member) ? own(member, "attributes") : undefined;
return isRecord(attributes) ? attributes : {};
};
const [after, before] = [attributesOf(newer), attributesOf(older)];
const identifiers = (nested ? holdsElements : isContainer)(newer)
? Object.keys(after).filter(isIdentifyingAttribute)
: [];
const named = (key: string) => key.toLowerCase() === "name";
const theirs = new Set(childConditions(older));
const children = childConditions(newer).filter(
(spelled) =>
theirs.has(spelled) &&
(!nested || isNameLikeKey(selectorOf(spelled)?.[0]?.key ?? "")),
);
const kept = (keys: readonly string[]) =>
keys.flatMap((key) => keptIdentifier(after, before, key) ?? [])[0];
return identifiers.length === 0 && !(nested && holdsElements(newer))
? undefined
: (kept(identifiers.filter((key) => !named(key))) ??
children[0] ??
kept(identifiers.filter(named)));
};
+13 -5
View File
@@ -1,6 +1,7 @@
import type { JsonValue } from "../jsonValue.js";
import type { DesktopStateFormat } from "./stateFormats.js";
import { memberLookup, pairMembers } from "./viewPointer.js";
import { holdsTagOnly, pairMembers } from "./memberPairing.js";
import { memberLookup } from "./viewPointer.js";
import { zipLeavesOut } from "./zipView.js";
const MAX_LISTED = 100;
@@ -76,10 +77,14 @@ interface Noting extends WalkOptions {
const keyedMembers = (
from: readonly JsonValue[],
other: JsonValue | undefined,
older: boolean,
at: { readonly older: boolean; readonly list: string },
) => {
const others = Array.isArray(other) ? other : [];
const pairing = older ? pairMembers(others, from) : pairMembers(from, others);
const hold = holdsTagOnly(at.list);
const pairing = at.older
? pairMembers(others, from, hold)
: pairMembers(from, others, hold);
const older = at.older;
const side = older ? pairing.older : pairing.newer;
const lookup = memberLookup(other);
return side.keys.map((key, index) => {
@@ -119,7 +124,10 @@ const walk = (
path.length -= segment.length + 1;
};
if (Array.isArray(from) && into.keyed === true) {
const members = keyedMembers(from, other, into.older === true);
const members = keyedMembers(from, other, {
older: into.older === true,
list: path.segments.map((segment) => `/${segment}`).join(""),
});
from.forEach((item, index) => {
const member = members[index];
if (member !== undefined) visit(member.key, item, member.counterpart);
@@ -320,7 +328,7 @@ export const diffStateViews = (
options: { readonly named?: boolean } = {},
): DesktopStateDifference => {
const difference =
format === "xml" && options.named === true
(format === "xml" || format === "json") && options.named === true
? namedOrPositional(before, after)
: compareViews(format, before, after);
// Only REA's own readers write coverage flags; JSON and key files are data.
+49
View File
@@ -41,6 +41,18 @@ describe("detectStateFormat", () => {
).toBe("binary");
});
it("reads Unicode XML names in unnamed formats and rejects malformed XML", () => {
for (const [text, format] of [
['<地图 名称="甲"><节点/></地图>', "xml"],
['<!DOCTYPE 地图 SYSTEM "map.dtd"><地图/>', "xml"],
["<地图><节点></地图>", "text"],
["<ada@example.test>\nBuy milk", "text"],
] as const) {
expect(detectStateFormat("map.dat", bytes(text))).toBe(format);
expect(textSyntaxFormat("map.dat", text)).toBe(format);
}
});
it("tells JSON, XML, key files and plain text apart", () => {
expect(detectStateFormat("/h/a.json", bytes('{"a":1}'))).toBe("json");
expect(detectStateFormat("/h/notes", bytes("{not json"))).toBe("text");
@@ -164,6 +176,43 @@ describe("detectStateFormat with a DOCTYPE", () => {
).toBe("text");
});
it("reads a file that opens with a DOCTYPE naming no internal subset and then an element as XML, as KmPlot's plot, whatever it is called", () => {
const plot = (doctype: string, body = '<function type="cartesian"/>') =>
bytes(`${doctype}\n<kmpdoc version="4">\n ${body}\n</kmpdoc>\n`);
expect(
detectStateFormat(
"/h/Documents/lesson_plots.fkt",
plot("<!DOCTYPE kmpdoc>"),
),
).toBe("xml");
expect(
textSyntaxFormat(
"/h/Documents/lesson_plots.fkt",
'<!DOCTYPE kmpdoc>\n<kmpdoc version="4"/>\n',
),
).toBe("xml");
expect(
textSyntaxFormat(
"/h/Documents/state.txt",
'<!DOCTYPE state SYSTEM "state[1].dtd"><state/>',
),
).toBe("xml");
// A DOCTYPE that can declare entities, or text that is not well formed, stays text.
expect(
detectStateFormat(
"/h/Documents/lesson_plots.fkt",
plot('<!DOCTYPE kmpdoc [<!ENTITY e "x">]>', "<f>&e;</f>"),
),
).toBe("text");
expect(
detectStateFormat(
"/h/Documents/lesson_plots.fkt",
plot("<!DOCTYPE kmpdoc>", "<function>"),
),
).toBe("text");
});
it.each([
'<!DOCTYPE abiword PUBLIC "-//ABISOURCE//DTD AWML 1.0 Strict//EN" "http://www.abisource.com/awml.dtd"><abiword/>',
'<!DOCTYPE abiword [<!ENTITY lol "lol">]><abiword>&lol;</abiword>',
+60 -2
View File
@@ -7,6 +7,7 @@ import { safeParseJson } from "../safeJson.js";
import {
declaredDocumentType,
isWellFormedXml,
opensLikeXml,
parseXmlDocument,
} from "../xmlDocument.js";
@@ -222,6 +223,59 @@ const namedJson = (path: string, trimmed: string): boolean =>
const namedXml = (path: string, trimmed: string): boolean =>
XML_EXTENSIONS.test(path) || trimmed.startsWith("<?xml");
/**
* Whether text opens with an element, as a Freeplane map's `<map version=…>`
* without a declaration, or with a DOCTYPE that has no internal subset and
* then an element, as KmPlot's `<!DOCTYPE kmpdoc><kmpdoc …>`, so it is XML
* if it is well formed, whatever the file is called. A DOCTYPE with an
* internal subset, which may declare entities, never opens one.
*/
/**
* Whether a DOCTYPE before `>` opens an internal subset. A `[` inside a
* quoted system or public id, as `state[1].dtd`, does not.
*/
const doctypeOpensSubset = (text: string, from: number): boolean => {
let quote = "";
for (let index = from; index < text.length; index += 1) {
const character = text[index] ?? "";
if (quote !== "") {
if (character === quote) quote = "";
continue;
}
if (character === '"' || character === "'") quote = character;
else if (character === "[") return true;
else if (character === ">") return false;
}
return false;
};
const opensElement = (trimmed: string): boolean => {
if (!trimmed.startsWith("<!DOCTYPE") && opensLikeXml(trimmed)) return true;
const declared = /^(?:<\?xml[^>]*>\s*)?<!DOCTYPE\b/u.exec(trimmed);
if (declared === null) return false;
let quote = "";
for (let index = declared[0].length; index < trimmed.length; index += 1) {
const character = trimmed[index] ?? "";
if (quote !== "") {
if (character === quote) quote = "";
continue;
}
if (character === '"' || character === "'") quote = character;
else if (character === "[") return false;
else if (character === ">") {
const rest = trimmed.slice(index + 1).trimStart();
return opensLikeXml(rest);
}
}
return false;
};
/** Whether `opening` has a DOCTYPE whose internal subset starts outside quotes. */
export const doctypeHasInternalSubset = (opening: string): boolean => {
const declared = /^(?:<\?xml[^>]*>\s*)?<!DOCTYPE\b/u.exec(opening);
return declared !== null && doctypeOpensSubset(opening, declared[0].length);
};
/**
* Whether decoded text is JSON or XML as `detectStateFormat` reads it, told
* by syntax alone so no value or document is built: JSON a token at a time
@@ -233,7 +287,10 @@ export const textSyntaxFormat = (
): "json" | "xml" | "text" => {
const trimmed = text.trimStart();
if (namedJson(path, trimmed) && isJsonText(text)) return "json";
if (namedXml(path, trimmed) && isWellFormedXml(text, XML_POLICY))
if (
(namedXml(path, trimmed) || opensElement(trimmed)) &&
isWellFormedXml(text, XML_POLICY)
)
return "xml";
return "text";
};
@@ -258,7 +315,8 @@ export const detectStateFormat = (
: safeParseJson(text).ok)
)
return "json";
if (namedXml(path, trimmed))
// Check syntax without constructing a document for format detection.
if (namedXml(path, trimmed) || opensElement(trimmed))
return isWellFormedXml(text, XML_POLICY) ? "xml" : "text";
return isKeyfile(text) ? "keyfile" : "text";
};
+24
View File
@@ -317,3 +317,27 @@ describe("isApplicationDconfGroup", () => {
expect(isApplicationDconfGroup("org/mousepadx", names)).toBe(false);
});
});
describe("stateReasons for a state directory the app names with its version", () => {
it("counts TreeLine's ~/.treeline-3.1 beside ~/.treeline, and a numbered folder alike, never another app's longer name", () => {
const facts: DesktopRoleFacts = {
home: "/home/ada",
stateDirectories: ["/home/ada/.treeline"],
stateTails: [".treeline"],
selectedRoots: [],
selections: [],
titles: [],
openedFiles: new Set(),
};
const reasons = (path: string) => stateReasons(facts, path, [], false);
expect(reasons("/home/ada/.treeline-3.1/settings.ini")).toEqual([
"state_directory",
]);
expect(reasons("/home/ada/.treeline3/settings.ini")).toEqual([
"state_directory",
]);
expect(reasons("/home/ada/.treelines/settings.ini")).toEqual([]);
expect(reasons("/home/ada/.treeline-beta/settings.ini")).toEqual([]);
});
});
+11 -2
View File
@@ -90,7 +90,12 @@ const hiddenTail = (path: string): string | null => {
return index < 0 ? null : path.slice(index + 1);
};
/** The state directory a path lies in, or the folder beside one whose name differs only in letter case that the application may create during the capture, as the path spells it. */
/**
* The state directory a path lies in, or the folder beside one that the
* application may create during the capture, as the path spells it: one
* whose name differs only in letter case, or that adds a version, as
* TreeLine's `~/.treeline-3.1` beside `~/.treeline`.
*/
export const stateDirectoryOf = (
path: string,
directories: readonly string[],
@@ -99,9 +104,13 @@ export const stateDirectoryOf = (
const parent = directory.slice(0, directory.lastIndexOf("/") + 1);
if (!path.startsWith(parent)) continue;
const folder = path.slice(parent.length).split("/")[0] ?? "";
const name = directory.slice(parent.length).toLowerCase();
const own = folder.toLowerCase();
if (
folder.length > 0 &&
folder.toLowerCase() === directory.slice(parent.length).toLowerCase()
(own === name ||
(own.startsWith(name) &&
/^-?\d+(?:\.\d+)*$/u.test(own.slice(name.length))))
)
return `${parent}${folder}`;
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
import type { JsonValue } from "../jsonValue.js";
import { locatePointer, memberLookup, pairMembers } from "./viewPointer.js";
import { pairMembers } from "./memberPairing.js";
import { locatePointer, memberLookup } from "./viewPointer.js";
const element = (
name: string,
+16 -306
View File
@@ -1,15 +1,5 @@
import type { JsonValue } from "../jsonValue.js";
import { collapseWhitespace, isTimestamp } from "./appTask.js";
import { isIdentifyingAttribute, rankAttributes } from "./attributeRank.js";
import { isPositionalKey, positionalKeys } from "./positionalKeys.js";
import {
condition,
countUnspelledPairs,
MAX_PAIRED,
pairSuffix,
type Attribute,
type Candidates,
} from "./selectorCandidates.js";
import { bracketed, selectorOf, type Condition } from "./viewSelector.js";
/** The arrays a pointer stepped into, each as the pointer to it. */
@@ -92,15 +82,23 @@ const fieldOf = (member: JsonValue, { prefix, key }: Condition) => {
return typeof value === "string" ? value : undefined;
};
/** An element's text with save-time leaves removed, so a name around a timestamp still matches after the time changes. */
const textWithoutStamps = (node: JsonValue): string => {
if (typeof node === "string") return isTimestamp(node) ? "" : node;
if (!isRecord(node) || !Array.isArray(node.children)) return "";
return node.children.map((child) => textWithoutStamps(child)).join("");
};
/** Whether an element has a child element named `key` whose text, its whitespace collapsed, is `value`. */
const hasChildText = (member: JsonValue, { key, value }: Condition) =>
isXmlElement(member) &&
member.children.some(
(child) =>
isXmlElement(child) &&
child.name === key &&
collapseWhitespace(elementText(child)) === value,
);
member.children.some((child) => {
if (!isXmlElement(child) || child.name !== key) return false;
// A nested save time is not part of the name. A child that is only a time still matches that time.
const plain = collapseWhitespace(textWithoutStamps(child));
const text = plain === "" ? collapseWhitespace(elementText(child)) : plain;
return text === value;
});
/** Whether an array member meets every condition; selectors compare strings only. */
const selects = (member: JsonValue, conditions: readonly Condition[]) =>
@@ -166,6 +164,8 @@ export const locatePointer = (
view: JsonValue | null,
pointer: string,
): Located => {
if (pointer === "")
return { kind: "value", value: view, searched: [], byPosition: [] };
let current: JsonValue = view;
const segments = pointer.slice(1).split("/");
const steps = { searched: [] as string[], byPosition: [] as string[] };
@@ -298,293 +298,3 @@ export const resolvePointer = (
const located = locatePointer(view, pointer);
return located.kind === "value" ? located.value : undefined;
};
/** A value a selector can carry and that stays the same between saves. */
const selectable = (value: string) =>
!value.includes("][") && !isTimestamp(value);
/** An attribute name a selector can carry. */
const attributeName = (key: string) => key !== "" && !/[=[\]]/u.test(key);
/** Two-attribute selectors from the attributes `paired`, the best ranked pairs first. */
const pairsOf = (paired: readonly (Attribute & { tier: number })[]) =>
paired
.flatMap((first, index) =>
paired.slice(index + 1).map((second) => ({
tier: first.tier + second.tier,
suffix: pairSuffix(first, second),
})),
)
.toSorted((left, right) => left.tier - right.tier)
.map(({ suffix }) => suffix);
/**
* The selectors that could name a member, most general first: `[name=N]`;
* then its identifiers, a `name` attribute first; then each other attribute
* by itself, a name-like key, a worded value or a small integer first; then
* two of the best `MAX_PAIRED` of those together; then a coordinate, a long
* number or a token by itself. All are counted over every sibling, so a
* selector several siblings match is never taken for one naming a member
* alone; but an element with identifying attributes is keyed by those alone,
* so one whose identifiers are new is another element, whatever else it
* shares. An identifier the app numbers by position (`positional`) names no
* member. The ids number the name among those seen, so a name is spelled into
* a selector only once one is chosen, not per attribute.
*/
const candidatesOf = (
member: JsonValue,
names: Map<string, number>,
positional: ReadonlySet<string>,
): Candidates | undefined => {
if (!isRecord(member)) return undefined;
const name = own(member, "name");
if (typeof name !== "string" || !selectable(name)) return undefined;
const attributes = own(member, "attributes");
const usable = (
isRecord(attributes) ? Object.entries(attributes) : []
).flatMap(([key, value]) =>
typeof value === "string" &&
attributeName(key) &&
selectable(value) &&
!isPositionalKey(positional, name, key)
? [{ key, value }]
: [],
);
const identities = usable.filter(({ key }) => isIdentifyingAttribute(key));
const named = (key: string) => key.toLowerCase() === "name";
const ranked = rankAttributes(
usable.filter(({ key }) => !isIdentifyingAttribute(key)),
);
const pairable = ranked.filter(({ tier }) => tier < 3);
const suffixes = [
"",
...[
...identities.filter(({ key }) => named(key)),
...identities.filter(({ key }) => !named(key)),
...pairable,
].map(condition),
...pairsOf(pairable.slice(0, MAX_PAIRED)),
...ranked.filter(({ tier }) => tier === 3).map(condition),
];
const number = names.get(name) ?? names.size;
names.set(name, number);
// A suffix is empty or opens with `[`, so the number before it cannot run into it.
const ids = suffixes.map((suffix) => `${String(number)}${suffix}`);
const choosable =
identities.length > 0 ? identities.length + 1 : suffixes.length;
return {
name,
number,
ids,
choosable,
pairable: pairable.map(({ key }) => key),
};
};
/** The selector a member's candidate at `index` spells: its name, then its id past the name's number. */
const selectorAt = ({ name, number, ids }: Candidates, index: number) =>
`[name=${name}]${(ids[index] ?? "").slice(String(number).length)}`;
const countIds = (members: readonly (Candidates | undefined)[]) => {
const counts = new Map<string, number>();
for (const candidates of members)
for (const id of candidates?.ids ?? [])
counts.set(id, (counts.get(id) ?? 0) + 1);
return counts;
};
/** Each member's place among the members of its tag, as the tag and how many come before it; none for a member with no tag. */
const placesOf = (members: readonly JsonValue[]) => {
const seen = new Map<string, number>();
return members.map((member) => {
const name = isRecord(member) ? own(member, "name") : undefined;
if (typeof name !== "string") return undefined;
const before = seen.get(name) ?? 0;
seen.set(name, before + 1);
return `${String(before)}\u0000${name}`;
});
};
/**
* Whether two members are one element renamed: the same tag and attribute
* keys, one identifier's value changed and every other attribute and the
* children alike, as MyPaint renames a layer.
*/
const renamed = (newer: JsonValue, older: JsonValue) => {
if (!isRecord(newer) || !isRecord(older)) return false;
const [after, before] = [own(newer, "attributes"), own(older, "attributes")];
if (
own(newer, "name") !== own(older, "name") ||
!isRecord(after) ||
!isRecord(before)
)
return false;
const keys = Object.keys(after);
const changed = keys.filter((key) => own(before, key) !== after[key]);
const [key] = changed;
return (
keys.length === Object.keys(before).length &&
changed.length === 1 &&
key !== undefined &&
Object.hasOwn(before, key) &&
isIdentifyingAttribute(key) &&
JSON.stringify(own(newer, "children")) ===
JSON.stringify(own(older, "children"))
);
};
/** One version's members as a pairing reads and fills them. */
interface Pairing {
readonly members: readonly JsonValue[];
readonly candidates: readonly (Candidates | undefined)[];
readonly counts: ReadonlyMap<string, number>;
readonly keys: (string | undefined)[];
readonly partners: (number | undefined)[];
}
/**
* Pair, as one element `renamed`, a member of each version left unpaired at
* the same place among the members of its tag, by its first selector past
* its identifiers that names it alone in both versions with the same value,
* as a layer by its `src`; left unpaired when none does.
*/
const pairRenamed = (newer: Pairing, older: Pairing) => {
const unpaired = new Map<string, number>();
placesOf(older.members).forEach((place, index) => {
if (place !== undefined && older.partners[index] === undefined)
unpaired.set(place, index);
});
placesOf(newer.members).forEach((place, index) => {
const match = place === undefined ? undefined : unpaired.get(place);
const candidates = newer.candidates[index];
const theirs = match === undefined ? undefined : older.candidates[match];
if (
match === undefined ||
candidates === undefined ||
theirs === undefined ||
newer.partners[index] !== undefined ||
!renamed(newer.members[index] ?? null, older.members[match] ?? null)
)
return;
const at = candidates.ids.findIndex(
(id, position) =>
position >= candidates.choosable &&
newer.counts.get(id) === 1 &&
older.counts.get(id) === 1 &&
theirs.ids.includes(id),
);
if (at < 0) return;
newer.keys[index] = older.keys[match] = selectorAt(candidates, at);
newer.partners[index] = match;
older.partners[match] = index;
});
};
/** One version's side of a pairing: each member's key, and the other version's member it pairs with. */
interface PairedSide {
readonly keys: readonly string[];
readonly partners: readonly (number | undefined)[];
}
/**
* Pair the members of two versions of an array one to one. A member pairs by
* its first candidate selector naming it alone in its version and one unpaired
* member of the other, whichever before it name nothing there; then one
* element renamed by another selector (`pairRenamed`). One with no partner
* keeps its first selector naming it alone and nothing in the other version.
* Members left without a selector are keyed and paired by position; so is an
* identifier the app numbers by position, as `positionalKeys` finds.
*/
export const pairMembers = (
newer: readonly JsonValue[],
older: readonly JsonValue[],
): { readonly newer: PairedSide; readonly older: PairedSide } => {
const names = new Map<string, number>();
const positional = positionalKeys(newer, older);
const newCandidates = newer.map((member) =>
candidatesOf(member, names, positional),
);
const oldCandidates = older.map((member) =>
candidatesOf(member, names, positional),
);
const newCounts = countIds(newCandidates);
const oldCounts = countIds(oldCandidates);
countUnspelledPairs([
{ members: newer, candidates: newCandidates, counts: newCounts },
{ members: older, candidates: oldCandidates, counts: oldCounts },
]);
const count = (counts: ReadonlyMap<string, number>, id: string) =>
counts.get(id) ?? 0;
const oldById = new Map<string, number>();
oldCandidates.forEach((candidates, index) => {
for (const id of candidates?.ids.slice(0, candidates.choosable) ?? [])
if (count(oldCounts, id) === 1) oldById.set(id, index);
});
const newKeys: (string | undefined)[] = newer.map(() => undefined);
const oldKeys: (string | undefined)[] = older.map(() => undefined);
const newPartners: (number | undefined)[] = newer.map(() => undefined);
const oldPartners: (number | undefined)[] = older.map(() => undefined);
newCandidates.forEach((candidates, index) => {
if (candidates === undefined) return;
for (const [at, id] of candidates.ids
.slice(0, candidates.choosable)
.entries()) {
const match = count(newCounts, id) === 1 ? oldById.get(id) : undefined;
if (match === undefined || oldPartners[match] !== undefined) continue;
newKeys[index] = oldKeys[match] = selectorAt(candidates, at);
newPartners[index] = match;
oldPartners[match] = index;
return;
}
});
pairRenamed(
{
members: newer,
candidates: newCandidates,
counts: newCounts,
keys: newKeys,
partners: newPartners,
},
{
members: older,
candidates: oldCandidates,
counts: oldCounts,
keys: oldKeys,
partners: oldPartners,
},
);
/** The first selector naming a member alone in its version and nothing in the other. */
const unmatched = (
candidates: Candidates | undefined,
here: ReadonlyMap<string, number>,
there: ReadonlyMap<string, number>,
) => {
if (candidates === undefined) return undefined;
const at = candidates.ids
.slice(0, candidates.choosable)
.findIndex((id) => count(here, id) === 1 && count(there, id) === 0);
return at < 0 ? undefined : selectorAt(candidates, at);
};
newCandidates.forEach((candidates, index) => {
newKeys[index] ??= unmatched(candidates, newCounts, oldCounts);
});
oldCandidates.forEach((candidates, index) => {
oldKeys[index] ??= unmatched(candidates, oldCounts, newCounts);
});
for (let index = 0; index < Math.min(newer.length, older.length); index += 1)
if (newKeys[index] === undefined && oldKeys[index] === undefined) {
newPartners[index] = index;
oldPartners[index] = index;
}
const side = (
keys: readonly (string | undefined)[],
partners: readonly (number | undefined)[],
): PairedSide => ({
keys: keys.map((key, index) => key ?? String(index)),
partners,
});
return {
newer: side(newKeys, newPartners),
older: side(oldKeys, oldPartners),
};
};
+53
View File
@@ -29,6 +29,17 @@ const declaresInternalSubset = (declaration: string): boolean =>
/** XML 1.0's `NameStartChar`, and the further characters `NameChar` allows. */
const NAME_START = String.raw`:A-Z_a-z\u{C0}-\u{D6}\u{D8}-\u{F6}\u{F8}-\u{2FF}\u{370}-\u{37D}\u{37F}-\u{1FFF}\u{200C}\u{200D}\u{2070}-\u{218F}\u{2C00}-\u{2FEF}\u{3001}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFFD}\u{10000}-\u{EFFFF}`;
const NAME_MORE = String.raw`\-.0-9\u{B7}\u{300}-\u{36F}\u{203F}\u{2040}`;
/** XML element opening grammar shared by the desktop format readers. */
export const XML_ELEMENT_OPENING = String.raw`<[${NAME_START}][${NAME_START}${NAME_MORE}]*(?=[ \t\r\n]|/?>)`;
const XML_OPENING = new RegExp(
`^(?:<\\?xml\\b|<!DOCTYPE\\b|${XML_ELEMENT_OPENING})`,
"u",
);
/** Whether text begins with a possible XML declaration, DOCTYPE or start tag. */
export const opensLikeXml = (source: string): boolean =>
XML_OPENING.test(source);
/** XML 1.0's `PubidChar` but the apostrophe, which only a double-quoted literal may hold. */
const PUBID = String.raw`\n\r a-zA-Z0-9\-()+,./:=?;!*#@$_%`;
const SPACE = String.raw`[ \t\r\n]`;
@@ -161,6 +172,48 @@ export const xmlElementRanges = (
}
};
/** Inclusive source ranges of attribute quotes, parsed without reading a DTD. */
export const xmlAttributeQuoteRanges = (
source: string,
): Result<
readonly { readonly start: number; readonly end: number }[],
{
readonly error: XmlDocumentParseError;
readonly ranges: readonly {
readonly start: number;
readonly end: number;
}[];
readonly examined: number;
}
> => {
const ranges: { start: number; end: number }[] = [];
let reader: SaxesParser<{ xmlns: true }> | undefined;
try {
checkXmlSyntax(source, "allow", (syntax) => {
reader = syntax;
syntax.on("attribute", () => {
const end = syntax.position - 1;
const quote = source[end];
if (quote !== '"' && quote !== "'")
throw new XmlDocumentParseError("malformed");
const start = source.lastIndexOf(quote, end - 1);
if (start < 0) throw new XmlDocumentParseError("malformed");
ranges.push({ start, end });
});
});
return ok(ranges);
} catch (cause: unknown) {
return err({
error:
cause instanceof XmlDocumentParseError
? cause
: new XmlDocumentParseError("malformed", cause),
ranges,
examined: Math.max(0, (reader?.position ?? 0) - 1),
});
}
};
/** One boundary owns strict XML syntax, under a DOCTYPE policy, and the source-located DOM projection. */
export const parseXmlDocument = (
source: string,
@@ -110,6 +110,15 @@ it("returns each changed file's values, with what a value names, and guards outs
check("check-1", `${item("eggs")}/attributes/cat`, "1"),
check("check-2", `${item("eggs")}/attributes/qty`, "12"),
check("check-3", `${item("bread")}/attributes/qty`, "3"),
// An item was added, so the list's count is a check too.
{
id: "check-4",
kind: "member_count",
file: LIST,
pointer: "/root/children",
matching: "[name=item]",
equals: 3,
},
]);
// The same fields on the nearest other items, which the user left alone.
expect(draft?.guards).toEqual([
@@ -0,0 +1,58 @@
import { execFileSync } from "node:child_process";
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("agentenv capture launch", () => {
it("records an exit when the capture process never starts, so stop does not wait", async () => {
const root = await createTestTempDirectory("agentenv-capture-");
const bin = join(root, "bin");
const work = join(root, "work");
const capture = join(root, "capture");
await mkdir(bin);
await mkdir(work);
await writeFile(join(bin, "rea"), "#!/bin/sh\nexit 0\n");
await chmod(join(bin, "rea"), 0o755);
const script = `
import importlib.util, json, os, sys
spec = importlib.util.spec_from_file_location("capture", sys.argv[1])
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def boom(*_args, **_kwargs):
raise OSError("cannot start")
module.subprocess.Popen = boom
module.start({"work": sys.argv[2], "capture": sys.argv[3], "desktop_entry": "notes.desktop"})
print(json.dumps({"exit": module._exit_code(sys.argv[3]), "control": os.path.exists(os.path.join(sys.argv[3], "control"))}))
`;
const output = execFileSync(
"python3",
[
"-I",
"-B",
"-c",
script,
fileURLToPath(
new URL("../../../bridge/agentenv/capture.py", import.meta.url),
),
work,
capture,
],
{
env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}` },
encoding: "utf8",
},
);
const lines = output.trim().split("\n");
const recorded = JSON.parse(lines.at(-1) ?? "{}") as {
exit: number | null;
control: boolean;
};
expect(recorded.exit).toBe(1);
expect(recorded.control).toBe(false);
});
});
@@ -67,6 +67,23 @@ for name, text in json.load(sys.stdin):
.split(/\r?\n/u);
};
it("detects Unicode XML names in both state readers while rejecting non-XML text", () => {
const files = [
["map.dat", '<地图 名称="甲"><节点/></地图>'],
["map.dat", '<!DOCTYPE 地图 SYSTEM "map.dtd"><地图/>'],
["map.dat", "<máp/>"],
["map.dat", "<地图><节点></地图>"],
["note.dat", "<ada@example.test>\nBuy milk"],
] as const;
const expected = ["xml", "xml", "xml", "text", "text"];
expect(pythonFormats(files)).toEqual(expected);
expect(
files.map(([name, text]) =>
detectStateFormat(name, new TextEncoder().encode(text)),
),
).toEqual(expected);
});
it("detects key files by the state view's rule rather than a name or any group header", () => {
const files = [
["list.txt", "Groceries\n[x]\nmilk\n"],
@@ -50,7 +50,7 @@ console.log(JSON.stringify({ wide: deeperThan(wide, 500), edge: deeperThan(neste
it("pairs elements with a long tag and many attributes in a small heap, spelling a selector only once chosen", async () => {
// Spelling the tag into a selector per attribute needed more than 140 MiB here.
const pairing = await inSmallHeap(
"viewPointer.ts",
"memberPairing.ts",
"pairMembers",
`const tag = "t".repeat(40_000);
const element = (id) => {
@@ -146,6 +146,48 @@ describe("XML with a DOCTYPE in the exported module", () => {
});
});
it("reads text that opens with an element as XML when it is well formed, whatever the file is called, alike in both", async () => {
const saved = (name: string, text: string) => ({
name,
bytes: new TextEncoder().encode(text),
});
const files = [
saved(
"weekend-trip.mm",
'<map version="freeplane 1.7.0">\n<node TEXT="Weekend Trip" ID="ID_1"><node TEXT="Packing" ID="ID_2"/></node>\n</map>\n',
),
saved("notes.txt", "<b>bold</b> and <i>italic</b>\n"),
saved("plain.txt", " <todo><item>milk</item></todo>\n"),
];
await expectSameFileViews(files);
const formats = await Promise.all(
files.map(async (file) => (await typescriptFileView(file)).format),
);
expect(formats).toEqual(["xml", "text", "xml"]);
});
it("reads text that opens with a DOCTYPE naming no internal subset and then an element as XML, as KmPlot's plots, alike in both", async () => {
const saved = (name: string, text: string) => ({
name,
bytes: new TextEncoder().encode(text),
});
const files = [
saved(
"lesson_plots.fkt",
'<!DOCTYPE kmpdoc>\n<kmpdoc version="4">\n <function type="cartesian"><equation-0 step="0.05">h(x) = 2x + 1</equation-0></function>\n</kmpdoc>\n',
),
saved("entities.fkt", '<!DOCTYPE a [<!ENTITY e "boom">]>\n<a>&e;</a>\n'),
saved("broken.fkt", "<!DOCTYPE a>\n<a><b></a>\n"),
];
await expectSameFileViews(files);
const formats = await Promise.all(
files.map(async (file) => (await typescriptFileView(file)).format),
);
expect(formats).toEqual(["xml", "text", "text"]);
});
it("never reads the DTD a DOCTYPE names: neither its entities nor its default attributes apply", async () => {
const folder = await createTestTempDirectory("desktop-xml-dtd-");
const dtd = join(folder, "a.dtd");