mosaic-headless 1.40.0 → 1.40.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <img src="https://img.shields.io/badge/node_properties-120-success?style=flat-square" alt="120 個の node プロパティ">
19
19
  <img src="https://img.shields.io/badge/style_properties-101-success?style=flat-square" alt="101 個のスタイルプロパティ">
20
20
  <img src="https://img.shields.io/badge/responsive_checks-733-blueviolet?style=flat-square" alt="733 件のレスポンシブ検査">
21
- <img src="https://img.shields.io/badge/self--tests-48-blueviolet?style=flat-square" alt="48 項目のセルフテスト">
21
+ <img src="https://img.shields.io/badge/self--tests-55-blueviolet?style=flat-square" alt="55 項目のセルフテスト">
22
22
  </p>
23
23
 
24
24
  <p align="center">
@@ -183,7 +183,7 @@ node type、node プロパティ、スタイルプロパティ、スタイル状
183
183
  | `data/theme-zip-verification.csv` | 22 | Mosaic 自身のテーマ ZIP を往復させて比較 |
184
184
  | `data/conversion-batch.csv` | 19 | あるサイトのすべての Elementor ページを変換・構築・検査 |
185
185
 
186
- - セルフテスト:`python tools/test_mosaic.py`、オフラインの 48 項目(検索、中国語の用語、構築結果の形と拒否ルール、公開されている構築インターフェース、このリポジトリの数値とプライバシー)。
186
+ - セルフテスト:`python tools/test_mosaic.py`、オフラインの 55 項目(検索、中国語の用語、構築結果の形と拒否ルール、公開されている構築インターフェース、このリポジトリの数値とプライバシー)。
187
187
  - evals:Mosaic 1.0.10〜1.0.12 の挙動に関する 16 問。skill ありで 16/16、なしで 0/16。結果:[evals/RESULTS.md](evals/RESULTS.md)。
188
188
  - `SKILL.md`、これらの README、バッジの数値は、`tools/check_numbers.py` がデータと照合しています。詳細:[verification-record.md](references/verification-record.md)。
189
189
 
package/README.ko.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <img src="https://img.shields.io/badge/node_properties-120-success?style=flat-square" alt="120개 node 속성">
19
19
  <img src="https://img.shields.io/badge/style_properties-101-success?style=flat-square" alt="101개 스타일 속성">
20
20
  <img src="https://img.shields.io/badge/responsive_checks-733-blueviolet?style=flat-square" alt="733개 반응형 검사">
21
- <img src="https://img.shields.io/badge/self--tests-48-blueviolet?style=flat-square" alt="48개 자체 테스트">
21
+ <img src="https://img.shields.io/badge/self--tests-55-blueviolet?style=flat-square" alt="55개 자체 테스트">
22
22
  </p>
23
23
 
24
24
  <p align="center">
@@ -183,7 +183,7 @@ node type, node 속성, 스타일 속성, 스타일 상태는 플러그인 소
183
183
  | `data/theme-zip-verification.csv` | 22 | Mosaic 자체 테마 ZIP을 왕복시켜 비교 |
184
184
  | `data/conversion-batch.csv` | 19 | 한 사이트의 모든 Elementor 페이지를 변환, 구축, 검사 |
185
185
 
186
- - 자체 테스트: `python tools/test_mosaic.py`, 오프라인 테스트 48개(조회, 중국어 용어, 구축 결과의 형태와 거부 규칙, 공개된 구축 인터페이스, 이 저장소의 숫자와 개인정보).
186
+ - 자체 테스트: `python tools/test_mosaic.py`, 오프라인 테스트 55개(조회, 중국어 용어, 구축 결과의 형태와 거부 규칙, 공개된 구축 인터페이스, 이 저장소의 숫자와 개인정보).
187
187
  - evals: Mosaic 1.0.10~1.0.12 동작에 관한 16문항. skill 사용 시 16/16, 미사용 시 0/16. 결과: [evals/RESULTS.md](evals/RESULTS.md).
188
188
  - `SKILL.md`, 이 README들, 배지의 숫자는 `tools/check_numbers.py`가 데이터와 대조합니다. 자세한 내용: [verification-record.md](references/verification-record.md).
189
189
 
package/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <img src="https://img.shields.io/badge/node_properties-120-success?style=flat-square" alt="120 node properties">
19
19
  <img src="https://img.shields.io/badge/style_properties-101-success?style=flat-square" alt="101 style properties">
20
20
  <img src="https://img.shields.io/badge/responsive_checks-733-blueviolet?style=flat-square" alt="733 responsive checks">
21
- <img src="https://img.shields.io/badge/self--tests-48-blueviolet?style=flat-square" alt="48 self-tests">
21
+ <img src="https://img.shields.io/badge/self--tests-55-blueviolet?style=flat-square" alt="55 self-tests">
22
22
  </p>
23
23
 
24
24
  <p align="center">
@@ -183,7 +183,7 @@ Node types, node properties, style properties and style states are extracted fro
183
183
  | `data/theme-zip-verification.csv` | 22 | Mosaic's own theme ZIP round-tripped and compared |
184
184
  | `data/conversion-batch.csv` | 19 | every Elementor page of a site converted, built and checked |
185
185
 
186
- - Self-test: `python tools/test_mosaic.py`, 48 offline tests (lookups, Chinese terms, the build output's shape and refusals, the public build interface, this repository's numbers and privacy).
186
+ - Self-test: `python tools/test_mosaic.py`, 55 offline tests (lookups, Chinese terms, the build output's shape and refusals, the public build interface, this repository's numbers and privacy).
187
187
  - Evals: 16 questions about Mosaic 1.0.10 to 1.0.12 behaviour; with the skill 16/16, without it 0/16. Results: [evals/RESULTS.md](evals/RESULTS.md).
188
188
  - Every number in `SKILL.md`, these READMEs and their badges is checked against the data by `tools/check_numbers.py`. Detail: [verification-record.md](references/verification-record.md).
189
189
 
package/README.zh-TW.md CHANGED
@@ -18,7 +18,7 @@
18
18
  <img src="https://img.shields.io/badge/node_properties-120-success?style=flat-square" alt="120 個 node 屬性">
19
19
  <img src="https://img.shields.io/badge/style_properties-101-success?style=flat-square" alt="101 個樣式屬性">
20
20
  <img src="https://img.shields.io/badge/responsive_checks-733-blueviolet?style=flat-square" alt="733 條 RWD 檢查">
21
- <img src="https://img.shields.io/badge/self--tests-48-blueviolet?style=flat-square" alt="48 項自我測試">
21
+ <img src="https://img.shields.io/badge/self--tests-55-blueviolet?style=flat-square" alt="55 項自我測試">
22
22
  </p>
23
23
 
24
24
  <p align="center">
@@ -183,7 +183,7 @@ node type、node 屬性、樣式屬性、樣式狀態從外掛原始碼抽出(
183
183
  | `data/theme-zip-verification.csv` | 22 | Mosaic 自己的佈景 ZIP 匯出再匯入並比對 |
184
184
  | `data/conversion-batch.csv` | 19 | 一個網站的每個 Elementor 頁面都轉換、建置並檢查 |
185
185
 
186
- - 自我測試:`python tools/test_mosaic.py`,48 項離線測試(查詢、中文用語、建頁產出的結構與拒收規則、對外的建頁介面、本 repo 的數字與隱私)。
186
+ - 自我測試:`python tools/test_mosaic.py`,55 項離線測試(查詢、中文用語、建頁產出的結構與拒收規則、對外的建頁介面、本 repo 的數字與隱私)。
187
187
  - evals:16 題 Mosaic 1.0.10 到 1.0.12 的行為題;有 skill 16/16,沒有 skill 0/16。結果見 [evals/RESULTS.md](evals/RESULTS.md)。
188
188
  - `SKILL.md`、這幾份 README 和徽章上的數字,都由 `tools/check_numbers.py` 對照資料核對。細節見 [verification-record.md](references/verification-record.md)。
189
189
 
package/SKILL.md CHANGED
@@ -6,7 +6,7 @@ license: "MIT"
6
6
  user-invocable: true
7
7
  metadata:
8
8
  author: "moksa (https://moksaweb.com)"
9
- version: "1.40.0"
9
+ version: "1.40.2"
10
10
  homepage: "https://github.com/Moksa1123/mosaic-headless"
11
11
  ---
12
12
 
@@ -133,7 +133,7 @@ fits, and say in the spec which native path was checked.
133
133
  |---|---|---|
134
134
  | **Build a page** | `mo.py skeleton`; `mo.py check <every type>`; `mo.py params` / `css` for every key; `build_page.py --spec page.json` | build exits 0, then the Verify rows for a page pass |
135
135
  | **Build a whole site** | `build_site.py --site site.json`; rebuild pages that share components **in the same run** | every page `OK`, no `STALE CACHE` line; `verify_navigation.py` exit 0 |
136
- | **Change a built site** (a header line, a page's text or structure) | `wp eval-file tools/list_bindings.php <themeID>` → `sync_nodes.py --site --bindings` (dry run) → `--apply`. Not `build_site.py`: it makes a new master, and building some pages splits the site | sync prints `verified` per document, exit 0; a rerun shows nothing to do |
136
+ | **Change a built site** (a header line, a page's text or structure) | `wp eval-file tools/list_bindings.php <themeID>` → `sync_nodes.py --site --bindings` (dry run; it must list only what you changed - narrow it with `--attr <attrID>`) → `--apply`. Not `build_site.py`: it makes a new master, and building some pages splits the site | sync prints `verified` per document, exit 0; a rerun shows nothing to do |
137
137
  | **Change a style** | `mo.py css <property>` → style key; `mo.py states` for a state; tokens via `{"token": "--x"}` in a `theme` block, not per-node values | `verify_rwd.py` and `verify_browser.py` exit 0 |
138
138
  | **Responsive** | `_t` / `_m` keys only ([responsive.md](references/responsive.md)); a width copied from Elementor needs `maxWidth: "100%"` | `verify_rwd.py`, `audit_mobile.py --widths 390,768` exit 0 |
139
139
  | **Popup / drawer / tour** | `modal` (blocking) or `popover` (non-blocking); shorthand triggers only `pageLoad` / `exitIntent` / `scrollDepth`; a tour advances on `afterClose` | `verify_dialog.py` / `verify_popovers.py` exit 0 |
@@ -21,7 +21,7 @@
21
21
  "license": "MIT",
22
22
  "metadata": {
23
23
  "author": "moksa (https://moksaweb.com)",
24
- "version": "1.40.0",
24
+ "version": "1.40.2",
25
25
  "homepage": "https://github.com/Moksa1123/mosaic-headless"
26
26
  }
27
27
  },
@@ -24,7 +24,7 @@
24
24
  "user-invocable": true,
25
25
  "metadata": {
26
26
  "author": "moksa (https://moksaweb.com)",
27
- "version": "1.40.0",
27
+ "version": "1.40.2",
28
28
  "homepage": "https://github.com/Moksa1123/mosaic-headless"
29
29
  }
30
30
  },
@@ -21,7 +21,7 @@
21
21
  "license": "MIT",
22
22
  "metadata": {
23
23
  "author": "moksa (https://moksaweb.com)",
24
- "version": "1.40.0",
24
+ "version": "1.40.2",
25
25
  "homepage": "https://github.com/Moksa1123/mosaic-headless"
26
26
  }
27
27
  },
@@ -21,7 +21,7 @@
21
21
  "license": "MIT",
22
22
  "metadata": {
23
23
  "author": "moksa (https://moksaweb.com)",
24
- "version": "1.40.0",
24
+ "version": "1.40.2",
25
25
  "homepage": "https://github.com/Moksa1123/mosaic-headless"
26
26
  }
27
27
  },
@@ -21,7 +21,7 @@
21
21
  "license": "MIT",
22
22
  "metadata": {
23
23
  "author": "moksa (https://moksaweb.com)",
24
- "version": "1.40.0",
24
+ "version": "1.40.2",
25
25
  "homepage": "https://github.com/Moksa1123/mosaic-headless"
26
26
  }
27
27
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mosaic-headless",
3
- "version": "1.40.0",
3
+ "version": "1.40.2",
4
4
  "description": "AI-agent skill: build Mosaic Pro (Nextend) WordPress sites by writing the underlying data model directly - 23 custom tables, no visual editor, no DOM. Every node type, style property and node property swept against a live install and asserted on the delivered HTML and compiled CSS. Installs into Claude Code, Cursor, Codex CLI, Gemini CLI, Copilot, Continue, Windsurf and Claude.ai.",
5
5
  "keywords": [
6
6
  "wordpress",
@@ -409,6 +409,31 @@ against the 1.0.13 source or this skill's tables; the rest is that site's measur
409
409
  From another site's test install, handed to this skill; each line says what was
410
410
  also checked here against the 1.0.13 source.
411
411
 
412
+ - **What Mosaic stores is not byte-equal to what was sent, even when nothing
413
+ changed** - which is why comparing a spec to a live site needs normalising
414
+ (`tools/sync_nodes.py` does it). After a fresh rebuild with an unchanged spec, a
415
+ live 1.0.13 site showed 1,588 node "differences" in 21 documents. That site's own
416
+ breakdown (2026-11-21; one node can have several):
417
+ - `customDeclarations` re-spaced AND re-lined - a space after `:` and `,`, a newline
418
+ between declarations: 1,560 nodes, 1,107 with nothing else;
419
+ - `rgb()` / `rgba()` values re-spaced (`rgba(0, 0, 0, 0)` for `rgba(0,0,0,0)`):
420
+ 259 nodes (`color`, `backgroundColor`);
421
+ - an icon's `svg` rewritten: attributes reordered (`xmlns` first) and `width` /
422
+ `height` added to the root `<svg>` (from its viewBox): 281 nodes;
423
+ - keys the type does not keep, stored as null: `attributes` on button / menu-link
424
+ (11), a form label's `forInput` (5), tabs-menu's `accessibleLabel` (1);
425
+ - interactions stored without each interaction's `uuid` and without
426
+ `clickOptions.ID` (5), and a `settings.target.uuid` that names the node id the
427
+ build minted;
428
+ - and, not on that site because its spec used none, `build_page.py` itself: every
429
+ `boxShadow`, `transition` and `transform` list item gets a new random `uuid` on
430
+ every run - compare with those renamed, never by value;
431
+ - children heal() inserts. **Auto-inserted or really extra:** a live node the spec
432
+ does not have is Mosaic's own when it has no `attrID` and its type is a default
433
+ child of its parent's type (`data/default-children.csv`, "default" or "heal" -
434
+ e.g. an empty `accordion-content` gets `text > wysiwyg-text`); anything else -
435
+ a node with an `attrID`, or a type the parent does not insert - is really
436
+ extra, and means the site was edited outside the spec.
412
437
  - **Every `srcset` and `sizes` entry needs its own `uuid`, or the whole set is dropped
413
438
  in silence.** The commit succeeds and the image renders without them. Shapes:
414
439
  `srcset: [{"image": "wp-attachment://image/<id>/<size>/<path>", "widthOrDpr": "300w", "uuid": "<uuid>"}]`,
@@ -40,7 +40,7 @@ Every tool in `tools/`, and where the REST session comes from. Moved out of SKIL
40
40
  | `verify_dialog.py` | the modal in a real browser (1.0.9 and 1.0.10 alike: open is read as `:popover-open` or `dialog.open`): does it open, close, answer Esc, remember, cap - and does an OpenStreetMap carry the coordinates it was given |
41
41
  | `verify_popovers.py` | 1.0.10's popover in a real browser: opens, lands where its positioning says, blocks nothing, closes the way closedby says, flips, chains, and ends - every check reads `:popover-open`, never an attribute |
42
42
  | `verify_dialog_lab.py` | the question after "does the modal work": can three nodes be made into a bottom sheet, a side drawer, a corner notice, a full takeover and a gate with no way out - and does each one still fit at phone width, which the page's own width check cannot see |
43
- | `sync_nodes.py` | update a built site IN PLACE: matches the spec to the live master and each page's template by `attrID`, commits only the nodes whose data changed, rebuilds a page's template when its structure changed (one commit, or new tree first and old removed after in batches of 150), refuses a site split across masters or a document with two roots, saves every document's JSON before writing, re-reads and verifies after. Dry run unless `--apply`. `build_site.py` makes a new master every run, so use this for any change to a site that is already built |
43
+ | `sync_nodes.py` | update a built site IN PLACE: matches the spec to the live master and each page's template by `attrID`, commits only the nodes whose data changed, rebuilds a page's template when its structure changed (one commit, or new tree first and old removed after in batches of 150), refuses a site split across masters or a document with two roots, saves every document's JSON before writing, re-reads and verifies after. Dry run unless `--apply`; `--attr a,b` limits the comparison and the writes to those subtrees. Before comparing it normalises what Mosaic rewrites on save (re-spaced CSS and colours, rewritten svg, keys a type does not keep, interaction ids, build_page's random list-item uuids) and leaves alone the children heal inserts (references/facts.md, third site). Read the dry run before `--apply`: it should list only what you changed. `build_site.py` makes a new master every run, so use this for any change to a site that is already built |
44
44
  | `list_bindings.php` | read only, `wp eval-file tools/list_bindings.php <themeID> > bindings.json`: which template and master serve each post (`wp_mosaic_template_assigns`, which the REST API does not list) - the input `sync_nodes.py` needs |
45
45
  | `verify_lightbox.py` | the WooCommerce product-image lightbox (PhotoSwipe) at 390 / 820 / 1024 / 1440px: close button flush with the toolbar's top-right corner, counter top-left, spinner out of the flow - WooCommerce's own skin breaks the first at 1024px and below (references/standard-fixes.md) |
46
46
  | `verify_sticky.py` | a sticky element while the page scrolls: rectangle intersection with every `--avoid` element at each step, never past its `--bound` container, actually stuck at `--top` - a computed `position: sticky` passes a column that rides over the whole page |
@@ -39,8 +39,10 @@ from __future__ import annotations
39
39
 
40
40
  import argparse
41
41
  import copy
42
+ import csv
42
43
  import json
43
44
  import os
45
+ import re
44
46
  import sys
45
47
  import time
46
48
  import uuid
@@ -57,55 +59,238 @@ SHELL_REGIONS = ("header", "footer")
57
59
 
58
60
 
59
61
  # ── matching ──────────────────────────────────────────────────────────────────
62
+ #
63
+ # A node Mosaic stored is not byte-equal to the record build_page sent, even when
64
+ # nothing changed. Measured on a live 1.0.13 site (2026-11-21), a fresh rebuild and an
65
+ # unchanged spec gave 1,588 "differences" before these rules:
66
+ # - build_page gives every boxShadow / transition / transform list item a NEW random
67
+ # uuid on every run, and interactions carry run-random uuids too;
68
+ # - Mosaic re-spaces customDeclarations (a space after ':' and ',');
69
+ # - Mosaic rewrites an icon's svg (attribute order, xmlns first, width/height added);
70
+ # - heal() inserts children a composite type needs (data/default-children.csv).
71
+ # So both sides are normalised before they are compared, and children Mosaic adds by
72
+ # itself are recognised and left alone.
73
+
74
+ DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
75
+ UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)
76
+ TAG_RE = re.compile(r"<([A-Za-z][\w:.-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^\s>]+))?)*)\s*(/?)>")
77
+ ATTR_RE = re.compile(r"([^\s=>/]+)(?:\s*=\s*(\"[^\"]*\"|'[^']*'|[^\s>]+))?")
78
+ COLOR_FN_RE = re.compile(r"^\s*(?:rgba?|hsla?)\(", re.I)
79
+ # Data keys a node type does not keep: sent, accepted, and stored as null (button and
80
+ # menu-link `attributes`, a form label's `forInput`, tabs-menu `accessibleLabel`;
81
+ # measured 2026-11-21). Compared only when the site does hold a value for them.
82
+ DROPPED_ON_SAVE = {"attributes", "forInput", "accessibleLabel"}
83
+
84
+
85
+ def _csv(name):
86
+ with open(os.path.join(DATA_DIR, name), encoding="utf-8", newline="") as fh:
87
+ return list(csv.DictReader(fh))
88
+
89
+
90
+ _DEFAULTS = None
91
+ _STABLE = None
92
+
93
+
94
+ def default_children() -> dict[str, set]:
95
+ """parent type -> the child types Mosaic inserts into it by itself."""
96
+ global _DEFAULTS
97
+ if _DEFAULTS is None:
98
+ _DEFAULTS = {r["type"]: set(filter(None, r["default_children"].split("|")))
99
+ for r in _csv("default-children.csv")}
100
+ return _DEFAULTS
101
+
102
+
103
+ def stable_uuids() -> set:
104
+ """uuids that mean something by value: variant ids from the catalog."""
105
+ global _STABLE
106
+ if _STABLE is None:
107
+ _STABLE = {r["id"].lower() for r in _csv("variants.csv") if r.get("id")}
108
+ return _STABLE
109
+
110
+
111
+ def css_norm(text: str) -> str:
112
+ # Mosaic stores 'palt' as "palt", re-spaces (aspect-ratio 1/1 as 1 / 1, a space after
113
+ # ':' and ','), and puts each declaration on its own line. Not + or -: inside calc()
114
+ # the spaces around them are significant.
115
+ text = (text or "").replace("'", '"')
116
+ text = re.sub(r"\s+", " ", text).strip()
117
+ text = re.sub(r"\s*([:;,{}()/])\s*", r"\1", text)
118
+ return text.rstrip(";")
119
+
120
+
121
+ def svg_norm(text: str) -> str:
122
+ """Attribute order and the root svg's width/height do not count."""
123
+ first = [True]
124
+
125
+ def tag(m):
126
+ name, attrs, close = m.group(1), m.group(2) or "", m.group(3)
127
+ pairs = []
128
+ for a in ATTR_RE.finditer(attrs):
129
+ k, v = a.group(1), a.group(2)
130
+ v = (v or "").strip("\"'")
131
+ if first[0] and name.lower() == "svg" and k.lower() in ("width", "height"):
132
+ continue
133
+ pairs.append((k.lower(), v))
134
+ if name.lower() == "svg":
135
+ first[0] = False
136
+ return "<%s%s%s>" % (name.lower(), "".join(' %s="%s"' % p for p in sorted(pairs)), "/" if close else "")
137
+ text = TAG_RE.sub(tag, text or "")
138
+ return re.sub(r">\s+<", "><", re.sub(r"\s+", " ", text)).strip()
139
+
140
+
141
+ def normalise(value, id_map: dict, stable: set, key=None):
142
+ """A comparable copy of one data value: spec node ids mapped to live ones, run-random
143
+ uuids renamed in order of appearance, CSS and SVG text normalised."""
144
+ seen: dict[str, str] = {}
145
+
146
+ def u(s: str) -> str:
147
+ low = s.lower()
148
+ if low in id_map:
149
+ return id_map[low]
150
+ if low in stable:
151
+ return low
152
+ if UUID_RE.match(s):
153
+ seen.setdefault(low, "~u%d" % (len(seen) + 1))
154
+ return seen[low]
155
+ return s
156
+
157
+ top = key
158
+
159
+ def walk(v, key=None, depth=0):
160
+ if isinstance(v, dict):
161
+ out = {}
162
+ for k in sorted(v, key=str):
163
+ # Mosaic drops these from a stored interaction: every "ID" (clickOptions.ID)
164
+ # and the uuid of each interaction in the list (measured, 2026-11-21)
165
+ if top == "interactions" and (k == "ID" or (k == "uuid" and depth == 1)):
166
+ continue
167
+ out[u(k) if isinstance(k, str) else k] = walk(v[k], k, depth + 1)
168
+ return out
169
+ if isinstance(v, list):
170
+ return [walk(x, key, depth + 1) for x in v]
171
+ if isinstance(v, str):
172
+ if key == "customDeclarations":
173
+ return css_norm(v)
174
+ if key == "svg":
175
+ return svg_norm(v)
176
+ if COLOR_FN_RE.match(v): # rgba(0, 0, 0, 0) is stored for rgba(0,0,0,0)
177
+ return re.sub(r"\s+", "", v)
178
+ return u(v)
179
+ return v
180
+ return walk(value, key)
181
+
182
+
183
+ def match_trees(spec_nodes, spec_top, live_nodes, live_top):
184
+ """Walk both trees together. Children are aligned in order: by attrID where the spec
185
+ node has one, else by type. A live child the spec does not have is AUTO (Mosaic
186
+ inserted it: no attrID, and its type is a default child of its parent's type) or
187
+ EXTRA. Returns (pairs, spec_only, auto, extra); pairs carry the ancestor attrIDs."""
188
+ def kids_of(nodes):
189
+ out: dict[str, list[dict]] = {}
190
+ for n in nodes:
191
+ out.setdefault(n["parentID"], []).append(n)
192
+ for v in out.values():
193
+ v.sort(key=lambda n: n.get("ordering", ""))
194
+ return out
195
+ sk, lk = kids_of(spec_nodes), kids_of(live_nodes)
196
+ live_by_id = {n["ID"]: n for n in live_nodes}
197
+ defaults = default_children()
198
+ pairs, spec_only, auto, extra = [], [], [], []
199
+
200
+ def attr(n):
201
+ return (n.get("data") or {}).get("attrID")
202
+
203
+ def classify(l, parent_type, pkey, ancestors):
204
+ if not attr(l) and l["type"] in defaults.get(parent_type, set()):
205
+ stack = [l]
206
+ while stack: # the whole inserted subtree is Mosaic's
207
+ n = stack.pop()
208
+ auto.append(n)
209
+ stack += lk.get(n["ID"], [])
210
+ else:
211
+ extra.append((l, "%s/+%s" % (pkey, l["type"]), ancestors))
212
+
213
+ def align(s_parent, l_parent, pkey, l_parent_type, ancestors):
214
+ S, L = sk.get(s_parent, []), lk.get(l_parent, [])
215
+ pos, counts = 0, {}
216
+ for s in S:
217
+ a = attr(s)
218
+ j = next((i for i in range(pos, len(L))
219
+ if (a and attr(L[i]) == a) or (not a and not attr(L[i]) and L[i]["type"] == s["type"])), None)
220
+ if j is None:
221
+ k = "@" + a if a else "%s/%s" % (pkey, s["type"])
222
+ spec_only.append((s, k, ancestors))
223
+ continue
224
+ for skipped in L[pos:j]:
225
+ classify(skipped, l_parent_type, pkey, ancestors)
226
+ l, pos = L[j], j + 1
227
+ if a:
228
+ key = "@" + a
229
+ else:
230
+ counts[s["type"]] = counts.get(s["type"], 0) + 1
231
+ key = "%s/%s#%d" % (pkey, s["type"], counts[s["type"]])
232
+ pairs.append((s, l, key, ancestors))
233
+ align(s["ID"], l["ID"], key, l["type"], ancestors + ([a] if a else []))
234
+ for rest in L[pos:]:
235
+ classify(rest, l_parent_type, pkey, ancestors)
236
+
237
+ top_type = live_by_id.get(live_top, {}).get("type", "")
238
+ align(spec_top, live_top, "ROOT", top_type, [])
239
+ return pairs, spec_only, auto, extra
240
+
241
+
242
+ def plan(spec_records: list[dict], spec_top: str, live_nodes: list[dict], live_top: str, only_attrs=None):
243
+ """(same_structure, structural differences, [(live node, merged data, changed keys)], notes).
244
+ only_attrs limits everything to the subtrees rooted at those attrIDs."""
245
+ live = [n for n in live_nodes if n.get("status") != "delete" and n.get("parentType") != "override"]
246
+ pairs, spec_only, auto, extra = match_trees(spec_records, spec_top, live, live_top)
60
247
 
61
- def keyed(nodes: list[dict], top_parent: str) -> dict[str, dict]:
62
- """Key every node under top_parent: '@attrID' when it has one, else
63
- '<parent key>/<index among siblings>:<type>'. Nodes outside the subtree are left out."""
64
- children: dict[str, list[dict]] = {}
65
- for n in nodes:
66
- children.setdefault(n["parentID"], []).append(n)
67
- out: dict[str, dict] = {}
68
-
69
- def walk(parent_id: str, parent_key: str):
70
- kids = sorted(children.get(parent_id, []), key=lambda n: n.get("ordering", ""))
71
- for i, n in enumerate(kids):
72
- attr = (n.get("data") or {}).get("attrID")
73
- k = "@" + attr if attr else "%s/%d:%s" % (parent_key, i, n["type"])
74
- out[k] = dict(n, _key=k, _parent=parent_key, _index=i)
75
- walk(n["ID"], k)
76
-
77
- walk(top_parent, "ROOT")
78
- return out
79
-
80
-
81
- def structure(index: dict[str, dict]) -> dict[str, tuple]:
82
- return {k: (n["type"], n["_parent"], n["_index"]) for k, n in index.items()}
83
-
248
+ def inside(key, ancestors):
249
+ if not only_attrs:
250
+ return True
251
+ return any(a in only_attrs for a in ancestors) or (key.startswith("@") and key[1:] in only_attrs)
84
252
 
85
- def plan(spec_records: list[dict], spec_top: str, live_nodes: list[dict], live_top: str):
86
- """(same_structure, structural differences, [(live node, merged data, changed keys)], warnings)."""
87
- live = [n for n in live_nodes if n.get("status") != "delete" and n.get("parentType") != "override"]
88
- s_idx, l_idx = keyed(spec_records, spec_top), keyed(live, live_top)
89
- s_st, l_st = structure(s_idx), structure(l_idx)
90
253
  struct = []
91
- for k in sorted(set(s_st) | set(l_st)):
92
- if s_st.get(k) != l_st.get(k):
93
- struct.append("%s: spec %s / live %s" % (k, s_st.get(k), l_st.get(k)))
94
- updates, warnings = [], []
95
- if not struct:
96
- for k, s in s_idx.items():
97
- ln = l_idx[k]
98
- sd, ld = s.get("data") or {}, ln.get("data") or {}
99
- changed = [key for key in sd if json.dumps(sd[key], sort_keys=True) != json.dumps(ld.get(key), sort_keys=True)]
100
- extra = [key for key in ld if key not in sd]
101
- if extra:
102
- warnings.append("%s keeps live-only keys %s (the spec cannot remove a key; rebuild to drop it)"
103
- % (k, ", ".join(extra)))
104
- if changed:
105
- merged = dict(ld)
106
- merged.update({key: sd[key] for key in changed})
107
- updates.append((ln, merged, changed))
108
- return not struct, struct, updates, warnings
254
+ for s, l, key, anc in pairs:
255
+ if s["type"] != l["type"] and inside(key, anc):
256
+ struct.append("%s: type spec %s / live %s" % (key, s["type"], l["type"]))
257
+ struct += ["%s: only in the spec (%s)" % (k, s["type"]) for s, k, anc in spec_only if inside(k, anc)]
258
+ struct += ["%s: only on the site (%s)" % (k, l["type"]) for l, k, anc in extra if inside(k, anc)]
259
+
260
+ notes = []
261
+ if auto:
262
+ notes.append("%d node(s) Mosaic inserted itself (default children) - kept, not counted" % len(auto))
263
+ if only_attrs:
264
+ # An --attr id that neither side of THIS document has is simply not here: the
265
+ # document is skipped, not refused (a site-wide run touches every document and the
266
+ # id lives in one of them). One-sided cases are already in struct above, as
267
+ # "only in the spec" / "only on the site", from the alignment.
268
+ def attrs_of(nodes):
269
+ return {(n.get("data") or {}).get("attrID") for n in nodes} - {None}
270
+ here = set(only_attrs) & (attrs_of(spec_records) | attrs_of(live))
271
+ if not here:
272
+ return True, [], [], ["no --attr node in this document - skipped"]
273
+ updates = []
274
+ if struct:
275
+ return False, struct, updates, notes
276
+ id_map = {s["ID"].lower(): l["ID"].lower() for s, l, _, _ in pairs}
277
+ stable = stable_uuids() | {v.lower() for v in VAR_IDS.values()} | {l["ID"].lower() for _, l, _, _ in pairs}
278
+ for s, l, key, anc in pairs:
279
+ if not inside(key, anc):
280
+ continue
281
+ sd, ld = s.get("data") or {}, l.get("data") or {}
282
+ changed = [k for k in sd
283
+ if not (k in DROPPED_ON_SAVE and ld.get(k) in (None, [], ""))
284
+ and json.dumps(normalise(sd[k], id_map, stable, k), sort_keys=True)
285
+ != json.dumps(normalise(ld.get(k), id_map, stable, k), sort_keys=True)]
286
+ extra_keys = [k for k in ld if k not in sd]
287
+ if extra_keys and changed:
288
+ notes.append("%s keeps live-only keys %s" % (key, ", ".join(extra_keys)))
289
+ if changed:
290
+ merged = dict(ld)
291
+ merged.update({k: sd[k] for k in changed})
292
+ updates.append((dict(l, _key=key), merged, changed))
293
+ return True, struct, updates, notes
109
294
 
110
295
 
111
296
  # ── documents ─────────────────────────────────────────────────────────────────
@@ -157,8 +342,9 @@ def depth_order(nodes: list[dict]) -> list[dict]:
157
342
 
158
343
 
159
344
  class Run:
160
- def __init__(self, client, apply: bool, backup: str, batch: int = 150, pause: float = 3.0):
345
+ def __init__(self, client, apply: bool, backup: str, batch: int = 150, pause: float = 3.0, attrs=None):
161
346
  self.client, self.apply, self.backup = client, apply, backup
347
+ self.attrs = set(attrs or [])
162
348
  self.batch, self.pause = max(1, batch), max(0.0, pause)
163
349
  self.failed = False
164
350
  self.wrote = 0
@@ -245,7 +431,7 @@ def sync_shell(run: Run, site: dict, master_id: str, surface, comps) -> None:
245
431
  updates, struct_all = [], []
246
432
  for region, tree in shell.items():
247
433
  recs, _ = spec_flat(tree, master_id, "master", "div", surface, comps)
248
- same, struct, ups, warns = plan(recs, "SPEC-TOP", nodes, region_parent[region])
434
+ same, struct, ups, warns = plan(recs, "SPEC-TOP", nodes, region_parent[region], run.attrs)
249
435
  struct_all += ["%s %s" % (region, s) for s in struct]
250
436
  updates += ups
251
437
  for w in warns:
@@ -271,7 +457,7 @@ def sync_shell(run: Run, site: dict, master_id: str, surface, comps) -> None:
271
457
  left = []
272
458
  for region, tree in shell.items():
273
459
  recs, _ = spec_flat(tree, master_id, "master", "div", surface, comps)
274
- same, struct, ups, _ = plan(recs, "SPEC-TOP", new_nodes, region_parent[region])
460
+ same, struct, ups, _ = plan(recs, "SPEC-TOP", new_nodes, region_parent[region], run.attrs)
275
461
  left += struct + ["%s differs" % u[0]["_key"] for u in ups]
276
462
  return left
277
463
  run.verify(instance, "masterDocumentInstance", key, before, recheck)
@@ -293,7 +479,7 @@ def sync_page(run: Run, page: dict, binding: dict, surface, comps) -> None:
293
479
  run.failed = True
294
480
  return
295
481
  recs, uses_components = spec_flat(page["tree"], template_id, "template", "template-internal", surface, comps)
296
- same, struct, updates, warns = plan(recs, "SPEC-TOP", nodes, root["ID"])
482
+ same, struct, updates, warns = plan(recs, "SPEC-TOP", nodes, root["ID"], run.attrs)
297
483
  for w in warns:
298
484
  print(" note %s %s" % (label, w))
299
485
  before = all_shell_instances(nodes)
@@ -314,6 +500,10 @@ def sync_page(run: Run, page: dict, binding: dict, surface, comps) -> None:
314
500
  % (label, len(struct), template_id[:8], master_id[:8]))
315
501
  for s in struct[:6]:
316
502
  print(" %s" % s)
503
+ if run.attrs:
504
+ print("REFUSE %s: a structural change inside --attr; rebuild the page (run without --attr)" % label)
505
+ run.failed = True
506
+ return
317
507
  if uses_components:
318
508
  print("REFUSE %s: the page uses components; rebuild it with build_site.py (override pass)" % label)
319
509
  run.failed = True
@@ -344,7 +534,7 @@ def sync_page(run: Run, page: dict, binding: dict, surface, comps) -> None:
344
534
  def recheck(new_nodes):
345
535
  r2, _ = spec_flat(page["tree"], template_id, "template", "template-internal", surface, comps)
346
536
  new_root = next((n for n in new_nodes if n["type"] == "template-internal" and n.get("status") != "delete"), None)
347
- s2, st2, ups2, _ = plan(r2, "SPEC-TOP", new_nodes, new_root["ID"] if new_root else "")
537
+ s2, st2, ups2, _ = plan(r2, "SPEC-TOP", new_nodes, new_root["ID"] if new_root else "", run.attrs)
348
538
  return st2 + ["%s differs" % u[0]["_key"] for u in ups2]
349
539
  run.verify(instance, "templateDocumentInstance", key, before, recheck)
350
540
  body = run.client.page(page["slug"])
@@ -362,6 +552,7 @@ def main() -> int:
362
552
  ap.add_argument("--site", required=True, help="the site spec build_site.py built from")
363
553
  ap.add_argument("--bindings", required=True, help="output of: wp eval-file tools/list_bindings.php <themeID>")
364
554
  ap.add_argument("--only", help="comma list of: shell, and/or page slugs (default: everything in the spec)")
555
+ ap.add_argument("--attr", help="comma list of attrIDs: compare and write only those subtrees")
365
556
  ap.add_argument("--apply", action="store_true", help="write; without it nothing is written")
366
557
  ap.add_argument("--backup", default="sync-backup-%s" % time.strftime("%Y%m%d-%H%M%S"),
367
558
  help="folder for the JSON of every document before it is written")
@@ -400,7 +591,8 @@ def main() -> int:
400
591
  if bindings.get("themeID") and cfg.get("themeID") and bindings["themeID"] != cfg["themeID"]:
401
592
  print("REFUSE: bindings are for theme %s, the config for %s" % (bindings["themeID"][:8], cfg["themeID"][:8]))
402
593
  return 1
403
- run = Run(Client(cfg), a.apply, a.backup, a.batch, a.pause)
594
+ run = Run(Client(cfg), a.apply, a.backup, a.batch, a.pause,
595
+ [x.strip() for x in (a.attr or "").split(",") if x.strip()])
404
596
  surface = Surface()
405
597
  VAR_IDS.clear()
406
598
  for name in ((site.get("theme") or {}).get("variables") or {}):
@@ -448,6 +448,131 @@ class SyncNodesPlan(unittest.TestCase):
448
448
  self.assertFalse(same)
449
449
  self.assertTrue(any("@t-new" in s for s in struct))
450
450
 
451
+ # what a live 1.0.13 site did to an unchanged spec (2026-11-21): random list-item
452
+ # uuids on every build, re-spaced CSS, a rewritten svg, a heal-inserted child
453
+ SVG = '<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z"/></svg>'
454
+
455
+ def rich_tree(self, title="Hello", body="Body"):
456
+ return {"type": "div", "data": {"attrID": "r-root"},
457
+ "style": {"&": {"_": {"shadow": {"x": "0px", "y": "4px", "color": "rgba(0,0,0,.2)"},
458
+ "transitionAll": "200ms ease", "move": {"translateY": "-8px"},
459
+ "customDeclarations": "outline:0;font-feature-settings:'palt' 1,'kern' 1"}}},
460
+ "children": [
461
+ {"type": "icon", "data": {"attrID": "r-icon", "svg": self.SVG}},
462
+ {"type": "text", "data": {"tagName": "h2", "attrID": "r-title"}, "text": title},
463
+ {"type": "accordion", "data": {"attrID": "r-acc"}, "children": [
464
+ {"type": "accordion-item", "data": {"attrID": "r-item"}, "children": [
465
+ {"type": "accordion-title", "data": {"attrID": "r-q"}, "text": "Q"},
466
+ {"type": "accordion-content", "data": {"attrID": "r-a"}}]}]},
467
+ {"type": "text", "data": {"attrID": "r-body"}, "text": body},
468
+ {"type": "button", "nodeID": "pin-target", "data": {"attrID": "r-btn", "url": {"v": "/x/"},
469
+ "attributes": [{"name": "aria-label", "value": "Open"}]},
470
+ "style": {"&": {"_": {"backgroundColor": "rgba(0,0,0,0)", "color": "rgb(255,255,255)"}}},
471
+ "text": "Open"},
472
+ {"type": "div", "data": {"attrID": "r-opener", "interactions": [
473
+ {"uuid": "11111111-2222-4333-8444-555555555555", "type": "click",
474
+ "clickOptions": {"ID": "66666666-7777-4888-9999-000000000000"},
475
+ "settings": {"target": {"type": "element", "uuid": "pin-target"}}}]}}]}
476
+
477
+ def as_stored(self, records):
478
+ """What Mosaic hands back: CSS re-spaced, svg rewritten, default children added."""
479
+ import uuid as _uuid
480
+ out = []
481
+ for r in records:
482
+ r = json.loads(json.dumps(r))
483
+ st = ((r.get("data") or {}).get("style") or {}).get("states") or {}
484
+ for bps in st.values():
485
+ for props in bps.values():
486
+ if "customDeclarations" in props:
487
+ props["customDeclarations"] = (props["customDeclarations"]
488
+ .replace(":", ": ").replace(",", ", ")
489
+ .replace(";", ";\n"))
490
+ for ck in ("backgroundColor", "color"):
491
+ if isinstance(props.get(ck), str):
492
+ props[ck] = props[ck].replace(",", ", ")
493
+ d = r.get("data") or {}
494
+ if "attributes" in d: # button / menu-link keep none
495
+ d["attributes"] = None
496
+ for it in d.get("interactions") or []: # stored without these
497
+ it.pop("uuid", None)
498
+ (it.get("clickOptions") or {}).pop("ID", None)
499
+ if r["type"] == "icon":
500
+ r["data"]["svg"] = ('<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" '
501
+ 'fill="none" viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>')
502
+ out.append(r)
503
+ if r["type"] == "accordion-content": # heal fills an empty panel
504
+ t = {"ID": str(_uuid.uuid4()), "parentID": r["ID"], "parentType": "node", "type": "text",
505
+ "ordering": "a0", "status": "publish", "data": {}}
506
+ out += [t, {"ID": str(_uuid.uuid4()), "parentID": t["ID"], "parentType": "node",
507
+ "type": "wysiwyg-text", "ordering": "a0", "status": "publish", "data": {"text": ""}}]
508
+ return out
509
+
510
+ def test_rebuild_of_unchanged_rich_spec_is_zero(self):
511
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
512
+ same, struct, updates, notes = self.sn.plan(self.flat(self.rich_tree(), "S"), "S", live, "L")
513
+ self.assertTrue(same, struct)
514
+ self.assertEqual(updates, [], [(u[0]["_key"], u[2]) for u in updates])
515
+ self.assertTrue(any("inserted itself" in n for n in notes), notes)
516
+
517
+ def test_one_real_edit_in_rich_spec_is_one_update(self):
518
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
519
+ same, struct, updates, _ = self.sn.plan(self.flat(self.rich_tree(title="Changed"), "S"), "S", live, "L")
520
+ self.assertTrue(same, struct)
521
+ self.assertEqual([(u[0]["type"], u[2]) for u in updates], [("wysiwyg-text", ["text"])])
522
+
523
+ def test_extra_node_with_attr_is_structural(self):
524
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
525
+ root = next(n for n in live if (n.get("data") or {}).get("attrID") == "r-root")
526
+ live.append({"ID": "extra-1", "parentID": root["ID"], "parentType": "node", "type": "div",
527
+ "ordering": "z9", "status": "publish", "data": {"attrID": "someone-elses"}})
528
+ same, struct, _, _ = self.sn.plan(self.flat(self.rich_tree(), "S"), "S", live, "L")
529
+ self.assertFalse(same)
530
+ self.assertTrue(any("only on the site" in s for s in struct), struct)
531
+
532
+ def test_attr_filter_limits_scope(self):
533
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
534
+ spec = self.flat(self.rich_tree(title="T2", body="B2"), "S")
535
+ _, _, all_updates, _ = self.sn.plan(spec, "S", live, "L")
536
+ _, _, only, _ = self.sn.plan(spec, "S", live, "L", {"r-body"})
537
+ self.assertEqual((len(all_updates), len(only)), (2, 1))
538
+
539
+ def test_attr_absent_from_a_document_skips_it(self):
540
+ # a site-wide --attr run: the id lives in one page; every other document has
541
+ # it on neither side and must be skipped, not refused (live site, 2026-11-21)
542
+ other = {"type": "div", "data": {"attrID": "o-root"},
543
+ "children": [{"type": "text", "data": {"attrID": "o-title"}, "text": "Other page"}]}
544
+ same, struct, updates, notes = self.sn.plan(self.flat(other, "S"), "S",
545
+ self.as_stored(self.flat(other, "L")), "L", {"r-body"})
546
+ self.assertTrue(same, struct)
547
+ self.assertEqual((struct, updates), ([], []))
548
+ self.assertTrue(any("skipped" in n for n in notes), notes)
549
+ # the document that has it still finds its one edit
550
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
551
+ same, struct, updates, _ = self.sn.plan(self.flat(self.rich_tree(body="B2"), "S"), "S", live, "L", {"r-body"})
552
+ self.assertTrue(same, struct)
553
+ self.assertEqual(len(updates), 1)
554
+
555
+ def test_attr_on_one_side_only_is_structural(self):
556
+ live = self.as_stored(self.flat(self.rich_tree(), "L"))
557
+ spec = self.rich_tree()
558
+ spec["children"].append({"type": "text", "data": {"attrID": "r-new"}, "text": "New"})
559
+ same, struct, _, _ = self.sn.plan(self.flat(spec, "S"), "S", live, "L", {"r-new"})
560
+ self.assertFalse(same)
561
+ self.assertTrue(any("@r-new" in s for s in struct), struct)
562
+
563
+ def test_normalisers(self):
564
+ self.assertEqual(self.sn.css_norm("a: 1px , 2px;b:c ;"), self.sn.css_norm("a:1px,2px;b:c"))
565
+ # measured on a live site: aspect-ratio 1/1 stored as 1 / 1, one declaration per line
566
+ self.assertEqual(self.sn.css_norm("aspect-ratio:1/1;object-fit:cover;display:block;"),
567
+ self.sn.css_norm("aspect-ratio: 1 / 1;\nobject-fit: cover;\ndisplay: block;"))
568
+ self.assertEqual(self.sn.css_norm("grid-column:1/-1"), self.sn.css_norm("grid-column: 1 / -1"))
569
+ # but calc() keeps its operator spacing
570
+ self.assertNotEqual(self.sn.css_norm("width:calc(100% - 10px)"), self.sn.css_norm("width:calc(100%-10px)"))
571
+ self.assertEqual(self.sn.svg_norm('<svg width="9" b="2" a="1"><g/></svg>'),
572
+ self.sn.svg_norm('<svg a="1" b="2" height="9"><g/></svg>'))
573
+ self.assertNotEqual(self.sn.svg_norm('<svg a="1"><path d="M0"/></svg>'),
574
+ self.sn.svg_norm('<svg a="1"><path d="M1"/></svg>'))
575
+
451
576
  def test_override_shell_counter(self):
452
577
  shell = {"parentType": "override", "parentID": "I", "status": "publish",
453
578
  "data": {"override": {"originalID": "X"}}}