@sorb/seed 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sorb/seed",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Storybook → Figma capture for Sorb: headless capture + the resolved bindable token map. Heavy deps (esbuild, later Playwright) live here so the bridge stays lean.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -1,5 +1,15 @@
1
1
  import { TIER_RANK } from '@sorb/core'
2
2
 
3
+ // Dev-gated warn(): no-op in production / unless SORB_DEBUG is set, so serve-time
4
+ // isn't noisy but local capture/dev surfaces drops loudly. (Diagnostics contract §4.)
5
+ const warn = (...args) => {
6
+ const env = (typeof process !== 'undefined' && process.env) || {}
7
+ if (env.SORB_DEBUG || env.NODE_ENV !== 'production') {
8
+ // eslint-disable-next-line no-console
9
+ console.warn('[sorb-seed]', ...args)
10
+ }
11
+ }
12
+
3
13
  // Token annotation for captured layer values.
4
14
  //
5
15
  // Exact, normalized matching against the resolved bindable token map
@@ -20,23 +30,87 @@ const toHex2 = (n) =>
20
30
  Math.round(Math.max(0, Math.min(255, n))).toString(16).padStart(2, '0')
21
31
  const alphaHex = (a) => toHex2(Math.max(0, Math.min(1, a)) * 255)
22
32
 
23
- /** Normalize any CSS color to canonical `#rrggbbaa`, or null if not a color. */
24
- export const normalizeColor = (value) => {
25
- if (value == null) return null
26
- const s = String(value).trim().toLowerCase()
27
- if (s === 'transparent') return '#00000000'
28
- let m = s.match(/^#([0-9a-f]{3,8})$/)
29
- if (m) return expandHex(m[1])
30
- m = s.match(/^rgba?\(\s*([^)]+)\)$/)
33
+ // A minimal CSS named-color table (the common names). Keeps `normalizeColor`
34
+ // dependency-free while covering values that show up in captured design tokens.
35
+ // (REC-6 class-5 exotic/unicode-color improvement.)
36
+ export const CSS_NAMED_COLORS = {
37
+ black: '#000000ff',
38
+ white: '#ffffffff',
39
+ red: '#ff0000ff',
40
+ green: '#008000ff',
41
+ blue: '#0000ffff',
42
+ yellow: '#ffff00ff',
43
+ cyan: '#00ffffff',
44
+ aqua: '#00ffffff',
45
+ magenta: '#ff00ffff',
46
+ fuchsia: '#ff00ffff',
47
+ gray: '#808080ff',
48
+ grey: '#808080ff',
49
+ silver: '#c0c0c0ff',
50
+ maroon: '#800000ff',
51
+ olive: '#808000ff',
52
+ lime: '#00ff00ff',
53
+ teal: '#008080ff',
54
+ navy: '#000080ff',
55
+ purple: '#800080ff',
56
+ orange: '#ffa500ff',
57
+ pink: '#ffc0cbff',
58
+ brown: '#a52a2aff',
59
+ gold: '#ffd700ff',
60
+ indigo: '#4b0082ff',
61
+ violet: '#ee82eeff',
62
+ coral: '#ff7f50ff',
63
+ salmon: '#fa8072ff',
64
+ khaki: '#f0e68cff',
65
+ crimson: '#dc143cff',
66
+ turquoise: '#40e0d0ff',
67
+ }
68
+
69
+ // Sentinel marker (REC-6): distinguishes a value we *recognized as a color* but
70
+ // couldn't parse ('unparseable') from a value that simply isn't a color
71
+ // ('no-match'). `normalizeColor` still returns a hex string or null for callers;
72
+ // `classifyColor` exposes the richer outcome so REC-1's `dropped[]` can record
73
+ // *why* a value vanished.
74
+ const NBSP = /[   ]/g
75
+
76
+ /**
77
+ * Classify a value as a color.
78
+ * @returns {{ hex: string|null, status: 'ok'|'no-match'|'unparseable' }}
79
+ * - ok: parsed → canonical hex
80
+ * - no-match: a clean value that just isn't a color (e.g. '4px', a dimension)
81
+ * - unparseable: looks color-ish (a `#…` / `rgb(…)` / named shape) but is malformed
82
+ */
83
+ export const classifyColor = (value) => {
84
+ if (value == null) return { hex: null, status: 'no-match' }
85
+ // Normalize exotic whitespace (NBSP etc.) that silently breaks matches.
86
+ const s = String(value).replace(NBSP, ' ').trim().toLowerCase()
87
+ if (s === '') return { hex: null, status: 'no-match' }
88
+ if (s === 'transparent') return { hex: '#00000000', status: 'ok' }
89
+ if (Object.prototype.hasOwnProperty.call(CSS_NAMED_COLORS, s)) {
90
+ return { hex: CSS_NAMED_COLORS[s], status: 'ok' }
91
+ }
92
+ // `#…` shape: a clean hex parses; a `#`-prefixed-but-bad value is unparseable.
93
+ if (s[0] === '#') {
94
+ const m = s.match(/^#([0-9a-f]{3,8})$/)
95
+ if (m && [3, 4, 6, 8].includes(m[1].length)) return { hex: expandHex(m[1]), status: 'ok' }
96
+ return { hex: null, status: 'unparseable' }
97
+ }
98
+ // `rgb(…)` / `rgba(…)` shape.
99
+ const m = s.match(/^rgba?\(\s*([^)]+)\)$/)
31
100
  if (m) {
32
101
  const p = m[1].split(',').map((x) => x.trim())
33
- if (p.length < 3) return null
102
+ if (p.length < 3) return { hex: null, status: 'unparseable' }
103
+ const nums = p.map((x) => parseFloat(x))
104
+ if (nums.slice(0, 3).some((n) => Number.isNaN(n))) return { hex: null, status: 'unparseable' }
34
105
  const a = p[3] !== undefined ? parseFloat(p[3]) : 1
35
- return '#' + toHex2(+p[0]) + toHex2(+p[1]) + toHex2(+p[2]) + alphaHex(a)
106
+ return { hex: '#' + toHex2(nums[0]) + toHex2(nums[1]) + toHex2(nums[2]) + alphaHex(a), status: 'ok' }
36
107
  }
37
- return null
108
+ return { hex: null, status: 'no-match' }
38
109
  }
39
110
 
111
+ /** Normalize any CSS color to canonical `#rrggbbaa`, or null if not a color. */
112
+ export const normalizeColor = (value) => classifyColor(value).hex
113
+
40
114
  /** Normalize a CSS length to a px number, or null. */
41
115
  export const normalizeDimension = (value) => {
42
116
  if (value == null) return null
@@ -44,21 +118,70 @@ export const normalizeDimension = (value) => {
44
118
  return m ? parseFloat(m[1]) : null
45
119
  }
46
120
 
47
- /** Build value→[token] indexes (colors, dims) from the resolved bindable map. */
121
+ // REC-2: a value that's still wrapped in `{…}` is an unresolved alias — Style
122
+ // Dictionary didn't follow the ref (a typo, a missing target, or a reference
123
+ // cycle). Observable, not fatal.
124
+ const ALIAS_RE = /^\{.+\}$/
125
+ const isAlias = (value) => typeof value === 'string' && ALIAS_RE.test(value.trim())
126
+ /** The bare ref path inside `{…}` (e.g. `{color.a}` → `color.a`), or null. */
127
+ const aliasTarget = (value) =>
128
+ isAlias(value) ? String(value).trim().slice(1, -1).trim() : null
129
+
130
+ // Walk the alias graph from `id` and return the set of ids on an A↔B (or longer)
131
+ // cycle reachable from it, using the resolved map's own alias edges.
132
+ const findAliasCycles = (resolved) => {
133
+ const byId = new Map(resolved.map((t) => [t.id, t]))
134
+ const onCycle = new Set()
135
+ for (const start of resolved) {
136
+ if (!isAlias(start.value)) continue
137
+ const seen = new Set()
138
+ let cur = start
139
+ while (cur && isAlias(cur.value)) {
140
+ if (seen.has(cur.id)) { for (const id of seen) onCycle.add(id); break }
141
+ seen.add(cur.id)
142
+ cur = byId.get(aliasTarget(cur.value))
143
+ }
144
+ }
145
+ return onCycle
146
+ }
147
+
148
+ /**
149
+ * Build value→[token] indexes (colors, dims) from the resolved bindable map.
150
+ * @returns {{ colors: Map, dims: Map, dropped: {id, value, reason}[] }}
151
+ * `dropped` (REC-1/2/6) records every token whose value normalized to null —
152
+ * unresolved-alias / cycle / unparseable-color / no-match — so a silent vanish
153
+ * becomes observable. Backward-compatible: `{colors, dims}` destructure still works.
154
+ */
48
155
  export const buildTokenIndex = (resolved) => {
49
156
  const colors = new Map()
50
157
  const dims = new Map()
158
+ const dropped = []
159
+ const cycles = findAliasCycles(resolved)
51
160
  const add = (map, key, t) => {
52
161
  if (key == null) return
53
162
  if (!map.has(key)) map.set(key, [])
54
163
  map.get(key).push(t)
55
164
  }
165
+ const drop = (t, reason) => dropped.push({ id: t.id, value: t.value, reason })
56
166
  for (const t of resolved) {
57
- const c = normalizeColor(t.value)
58
- if (c) add(colors, c, t)
59
- else add(dims, normalizeDimension(t.value), t)
167
+ // REC-2: unresolved aliases / cycles never index — surface them.
168
+ if (isAlias(t.value)) {
169
+ drop(t, cycles.has(t.id) ? 'alias-cycle' : 'unresolved-alias')
170
+ continue
171
+ }
172
+ const col = classifyColor(t.value)
173
+ if (col.hex) { add(colors, col.hex, t); continue }
174
+ const d = normalizeDimension(t.value)
175
+ if (d != null) { add(dims, d, t); continue }
176
+ // Neither a color nor a dimension → record *why* (REC-6 marker distinguishes
177
+ // a malformed color from a value that's simply no color).
178
+ drop(t, col.status === 'unparseable' ? 'unparseable-color' : 'no-match')
179
+ }
180
+ if (dropped.length) {
181
+ warn(`buildTokenIndex dropped ${dropped.length} token(s):`,
182
+ dropped.map((d) => `${d.id} (${d.reason})`).join(', '))
60
183
  }
61
- return { colors, dims }
184
+ return { colors, dims, dropped }
62
185
  }
63
186
 
64
187
  // Binding = property affinity first, then tier precedence.
@@ -81,7 +204,11 @@ const pick = (cands, role) => {
81
204
  const roled = role ? cands.filter((c) => c.id.includes('.' + role)) : []
82
205
  const pool = roled.length ? roled : cands
83
206
  const best = [...pool].sort(byTier)[0]
84
- return { token: best.id, candidates: cands.map((c) => c.id) }
207
+ // REC-1/REC-3 fold-in: a role-miss that fell back to the tier-only pool can bind
208
+ // the WRONG token silently. Flag it as a low-confidence pick so the bind is
209
+ // observable. `offRole` is additive; existing callers ignore it.
210
+ const offRole = !!(role && !roled.length)
211
+ return { token: best.id, candidates: cands.map((c) => c.id), offRole, role }
85
212
  }
86
213
 
87
214
  export const matchColor = (index, value, role) => {
@@ -100,8 +227,16 @@ export const matchDimension = (index, value, role) => {
100
227
  export const annotateTree = (node, index) => {
101
228
  const tokens = {}
102
229
  const candidates = {}
230
+ const diagnostics = []
103
231
  const set = (key, res) => {
104
- if (res.token) { tokens[key] = res.token; candidates[key] = res.candidates }
232
+ if (res.token) {
233
+ tokens[key] = res.token
234
+ candidates[key] = res.candidates
235
+ // REC-1 fold-in: a token bound off-role is low-confidence — surface it.
236
+ if (res.offRole) {
237
+ diagnostics.push({ kind: 'off-role-bind', detail: { key, role: res.role, token: res.token } })
238
+ }
239
+ }
105
240
  }
106
241
  // A fill on a TEXT node is foreground (`text`); on a frame it's `bg`.
107
242
  const fillRole = node.type === 'TEXT' ? 'text' : 'bg'
@@ -112,7 +247,14 @@ export const annotateTree = (node, index) => {
112
247
  // No shadow tokens yet → no role, falls back to tier-only.
113
248
  node.effects.forEach((e, i) => { if (e.color) set(`effect${i}`, matchColor(index, e.color.raw)) })
114
249
  }
115
- if (Object.keys(tokens).length) node.sorb = { tokens, candidates }
250
+ if (Object.keys(tokens).length) {
251
+ node.sorb = { tokens, candidates }
252
+ // `diagnostics` is additive — only attached when there's something to report.
253
+ if (diagnostics.length) node.sorb.diagnostics = diagnostics
254
+ }
255
+ if (diagnostics.length) {
256
+ warn(`annotateTree: ${diagnostics.length} low-confidence bind(s) on ${node.name || node.type}`)
257
+ }
116
258
  if (Array.isArray(node.children)) node.children.forEach((c) => annotateTree(c, index))
117
259
  return node
118
260
  }
@@ -0,0 +1,208 @@
1
+ // Tests for the capture token-annotator (auto-bind: property affinity + tier
2
+ // precedence). Run: node --test (zero-dep; resolves @sorb/core via the workspace link).
3
+ import { test } from 'node:test'
4
+ import assert from 'node:assert/strict'
5
+ import {
6
+ normalizeColor,
7
+ classifyColor,
8
+ normalizeDimension,
9
+ buildTokenIndex,
10
+ matchColor,
11
+ matchDimension,
12
+ annotateTree,
13
+ } from './annotateTokens.js'
14
+
15
+ // A resolved map where one color value (#0f65ef) is shared across a component
16
+ // bg, a component border, a semantic bg, and a semantic border — so the tests
17
+ // exercise BOTH role affinity (which property) and tier precedence (the tiebreak).
18
+ const RESOLVED = [
19
+ { id: 'button.primary.bg.default', cssVar: '--button-primary-bg-default', value: '#0f65ef', tier: 'component', type: 'color' },
20
+ { id: 'button.primary.border.default', cssVar: '--button-primary-border-default', value: '#0F65EF', tier: 'component', type: 'color' },
21
+ { id: 'color.action.primary', cssVar: '--color-action-primary', value: '#0f65ef', tier: 'semantic', type: 'color' },
22
+ { id: 'color.border.default', cssVar: '--color-border-default', value: '#0f65ef', tier: 'semantic', type: 'color' },
23
+ { id: 'button.primary.text.default', cssVar: '--button-primary-text-default', value: '#ffffff', tier: 'component', type: 'color' },
24
+ { id: 'button.radius', cssVar: '--button-radius', value: '4px', tier: 'component', type: 'dimension' },
25
+ ]
26
+
27
+ test('normalizeColor handles hex (3/4/6/8), rgb(a), transparent, and rejects junk', () => {
28
+ assert.equal(normalizeColor('#fff'), '#ffffffff')
29
+ assert.equal(normalizeColor('#FFFF'), '#ffffffff')
30
+ assert.equal(normalizeColor('#0f65ef'), '#0f65efff')
31
+ assert.equal(normalizeColor('#0F65EF80'), '#0f65ef80')
32
+ assert.equal(normalizeColor('rgb(15, 101, 239)'), '#0f65efff')
33
+ assert.equal(normalizeColor('rgba(0,0,0,0)'), '#00000000')
34
+ assert.equal(normalizeColor('transparent'), '#00000000')
35
+ assert.equal(normalizeColor('not-a-color'), null)
36
+ assert.equal(normalizeColor(null), null)
37
+ })
38
+
39
+ test('normalizeDimension parses px / unitless / decimals, rejects non-lengths', () => {
40
+ assert.equal(normalizeDimension('4px'), 4)
41
+ assert.equal(normalizeDimension('4'), 4)
42
+ assert.equal(normalizeDimension(8), 8)
43
+ assert.equal(normalizeDimension('2.5px'), 2.5)
44
+ assert.equal(normalizeDimension('-1px'), -1)
45
+ assert.equal(normalizeDimension('1rem'), null)
46
+ assert.equal(normalizeDimension(null), null)
47
+ })
48
+
49
+ test('buildTokenIndex groups tokens by normalized value into colors/dims', () => {
50
+ const idx = buildTokenIndex(RESOLVED)
51
+ assert.equal(idx.colors.get('#0f65efff').length, 4) // four tokens share this color
52
+ assert.equal(idx.colors.get('#ffffffff').length, 1)
53
+ assert.equal(idx.dims.get(4).length, 1)
54
+ })
55
+
56
+ test('matchColor: role affinity picks the right property family', () => {
57
+ const idx = buildTokenIndex(RESOLVED)
58
+ // bg role → only the component bg carries `.bg`
59
+ assert.equal(matchColor(idx, '#0f65ef', 'bg').token, 'button.primary.bg.default')
60
+ // border role → two `.border` cands; tier tiebreak picks component over semantic
61
+ assert.equal(matchColor(idx, '#0f65ef', 'border').token, 'button.primary.border.default')
62
+ })
63
+
64
+ test('matchColor: all matches are kept as candidates regardless of the pick', () => {
65
+ const idx = buildTokenIndex(RESOLVED)
66
+ const res = matchColor(idx, '#0f65ef', 'bg')
67
+ assert.equal(res.candidates.length, 4)
68
+ assert.ok(res.candidates.includes('color.action.primary'))
69
+ })
70
+
71
+ test('matchColor: with no role, tier precedence wins (component beats semantic)', () => {
72
+ const idx = buildTokenIndex(RESOLVED)
73
+ const res = matchColor(idx, '#0f65ef')
74
+ assert.ok(['button.primary.bg.default', 'button.primary.border.default'].includes(res.token))
75
+ })
76
+
77
+ test('matchColor / matchDimension return null token for a value with no match', () => {
78
+ const idx = buildTokenIndex(RESOLVED)
79
+ assert.equal(matchColor(idx, '#123456', 'bg').token, null)
80
+ assert.equal(matchDimension(idx, 99, 'radius').token, null)
81
+ })
82
+
83
+ test('matchDimension binds a radius value to the component radius token', () => {
84
+ const idx = buildTokenIndex(RESOLVED)
85
+ assert.equal(matchDimension(idx, 4, 'radius').token, 'button.radius')
86
+ })
87
+
88
+ test('annotateTree binds a button: fill→bg, stroke→border, radius, TEXT child→text', () => {
89
+ const idx = buildTokenIndex(RESOLVED)
90
+ const node = {
91
+ type: 'FRAME',
92
+ fills: [{ raw: '#0f65ef' }],
93
+ strokes: [{ raw: '#0f65ef' }],
94
+ cornerRadius: 4,
95
+ children: [{ type: 'TEXT', fills: [{ raw: '#ffffff' }] }],
96
+ }
97
+ const out = annotateTree(node, idx)
98
+ assert.equal(out.sorb.tokens.fill, 'button.primary.bg.default')
99
+ assert.equal(out.sorb.tokens.stroke, 'button.primary.border.default')
100
+ assert.equal(out.sorb.tokens.cornerRadius, 'button.radius')
101
+ // a fill on a TEXT node is foreground → the `text` role
102
+ assert.equal(out.children[0].sorb.tokens.fill, 'button.primary.text.default')
103
+ })
104
+
105
+ test('annotateTree leaves unmatched nodes without a `sorb` key', () => {
106
+ const idx = buildTokenIndex(RESOLVED)
107
+ const node = { type: 'FRAME', fills: [{ raw: '#abcdef' }] }
108
+ const out = annotateTree(node, idx)
109
+ assert.equal(out.sorb, undefined)
110
+ })
111
+
112
+ // ── REC-6: CSS named-color support + unparseable/no-match marker ──────────────
113
+
114
+ test('REC-6: normalizeColor resolves common CSS named colors', () => {
115
+ assert.equal(normalizeColor('red'), '#ff0000ff')
116
+ assert.equal(normalizeColor('WHITE'), '#ffffffff') // case-insensitive
117
+ assert.equal(normalizeColor('rebeccapurple'), null) // not in the minimal table → no-match
118
+ assert.equal(normalizeColor('purple'), '#800080ff')
119
+ })
120
+
121
+ test('REC-6: classifyColor distinguishes ok / no-match / unparseable', () => {
122
+ assert.deepEqual(classifyColor('#0f65ef'), { hex: '#0f65efff', status: 'ok' })
123
+ assert.deepEqual(classifyColor('blue'), { hex: '#0000ffff', status: 'ok' })
124
+ // a `#`-prefixed but malformed value is recognized-but-unparseable, not just no-match
125
+ assert.equal(classifyColor('#ggg').status, 'unparseable')
126
+ assert.equal(classifyColor('#12').status, 'unparseable')
127
+ assert.equal(classifyColor('rgb(1,2)').status, 'unparseable')
128
+ assert.equal(classifyColor('rgb(x,y,z)').status, 'unparseable')
129
+ // a clean non-color (e.g. a dimension) is no-match, not unparseable
130
+ assert.equal(classifyColor('4px').status, 'no-match')
131
+ assert.equal(classifyColor('not-a-color').status, 'no-match')
132
+ assert.equal(classifyColor(null).status, 'no-match')
133
+ })
134
+
135
+ test('REC-6: normalizeColor tolerates exotic whitespace (NBSP) around a hex', () => {
136
+ assert.equal(normalizeColor(' #0f65ef '), '#0f65efff')
137
+ })
138
+
139
+ // ── REC-1: buildTokenIndex.dropped[] for vanished tokens ─────────────────────
140
+
141
+ test('REC-1: buildTokenIndex still destructures to {colors, dims} (backward-compat)', () => {
142
+ const { colors, dims, dropped } = buildTokenIndex(RESOLVED)
143
+ assert.ok(colors.get('#0f65efff'))
144
+ assert.ok(dims.get(4))
145
+ assert.deepEqual(dropped, []) // a clean map drops nothing
146
+ })
147
+
148
+ test('REC-1: an unparseable-color token is dropped with a marker reason', () => {
149
+ const { dropped } = buildTokenIndex([
150
+ { id: 'color.bad', cssVar: '--bad', value: '#ggg', tier: 'semantic', type: 'color' },
151
+ ])
152
+ assert.equal(dropped.length, 1)
153
+ assert.equal(dropped[0].id, 'color.bad')
154
+ assert.equal(dropped[0].reason, 'unparseable-color')
155
+ })
156
+
157
+ test('REC-1: a no-match token (NBSP-only / junk) is dropped as no-match', () => {
158
+ const { dropped } = buildTokenIndex([
159
+ { id: 'space.weird', cssVar: '--w', value: ' ', tier: 'primitive', type: 'dimension' },
160
+ ])
161
+ assert.equal(dropped.length, 1)
162
+ assert.equal(dropped[0].reason, 'no-match')
163
+ })
164
+
165
+ // ── REC-2: unresolved-alias / cycle detection ────────────────────────────────
166
+
167
+ test('REC-2: a still-wrapped {…} value is dropped as unresolved-alias (not thrown)', () => {
168
+ const { dropped, colors } = buildTokenIndex([
169
+ { id: 'color.action', cssVar: '--a', value: '{color.brand.primary}', tier: 'semantic', type: 'color' },
170
+ { id: 'color.brand.primary', cssVar: '--p', value: '#0f65ef', tier: 'primitive', type: 'color' },
171
+ ])
172
+ const alias = dropped.find((d) => d.id === 'color.action')
173
+ assert.ok(alias)
174
+ assert.equal(alias.reason, 'unresolved-alias')
175
+ // the real token still indexed normally
176
+ assert.ok(colors.get('#0f65efff'))
177
+ })
178
+
179
+ test('REC-2: an A↔B alias cycle is detected and dropped as alias-cycle', () => {
180
+ const { dropped } = buildTokenIndex([
181
+ { id: 'a', cssVar: '--a', value: '{b}', tier: 'semantic', type: 'color' },
182
+ { id: 'b', cssVar: '--b', value: '{a}', tier: 'semantic', type: 'color' },
183
+ ])
184
+ const reasons = dropped.map((d) => d.reason)
185
+ assert.equal(dropped.length, 2)
186
+ assert.ok(reasons.every((r) => r === 'alias-cycle'))
187
+ })
188
+
189
+ // ── pick() off-role fallback → low-confidence diagnostic ─────────────────────
190
+
191
+ test('off-role fallback bind is surfaced as a low-confidence diagnostic', () => {
192
+ // #ffffff only carries a `.text` token; binding it as a frame `bg` fill is off-role.
193
+ const idx = buildTokenIndex(RESOLVED)
194
+ const node = { type: 'FRAME', fills: [{ raw: '#ffffff' }] }
195
+ const out = annotateTree(node, idx)
196
+ assert.equal(out.sorb.tokens.fill, 'button.primary.text.default') // still binds
197
+ assert.ok(Array.isArray(out.sorb.diagnostics))
198
+ assert.equal(out.sorb.diagnostics[0].kind, 'off-role-bind')
199
+ assert.equal(out.sorb.diagnostics[0].detail.role, 'bg')
200
+ })
201
+
202
+ test('an on-role bind attaches no diagnostics (additive, only when needed)', () => {
203
+ const idx = buildTokenIndex(RESOLVED)
204
+ const node = { type: 'FRAME', fills: [{ raw: '#0f65ef' }] }
205
+ const out = annotateTree(node, idx)
206
+ assert.equal(out.sorb.tokens.fill, 'button.primary.bg.default')
207
+ assert.equal(out.sorb.diagnostics, undefined)
208
+ })
package/src/capture.js CHANGED
@@ -201,6 +201,106 @@ export const captureNode = (el, parentRect) => {
201
201
  /** Entry point: capture a root element with itself at the origin (0,0). */
202
202
  export const captureRoot = (el) => captureNode(el, el.getBoundingClientRect())
203
203
 
204
+ // ─── Capture root trim (sorb-capture-trim-spec.md) ──────────────────────────
205
+ // Storybook wraps each story in full-width padded divs, so a raw captured root
206
+ // is the story container (e.g. 1248×86) with the real component (button 82×38)
207
+ // nested at an offset inside empty wrappers. `tightenRoot` trims the tree to the
208
+ // meaningful component AT CAPTURE TIME so every consumer (insert, preview, label
209
+ // wrapper) gets a tight, token-bound node. Pure + annotation-safe: it runs in
210
+ // captureCli BEFORE annotateTree, and only drops un-annotated, non-visual
211
+ // wrappers, so token bindings on the kept subtree are untouched.
212
+
213
+ /**
214
+ * "Content-bearing" = the node, or any descendant, paints (a non-transparent
215
+ * fill or a stroke) or is TEXT. Same notion as the preview SVG walker.
216
+ * @param {object} node LayerNode
217
+ * @returns {boolean}
218
+ */
219
+ export const hasContent = (node) => {
220
+ if (!node) return false
221
+ if (node.type === 'TEXT') return true
222
+ if ((node.fills && node.fills[0]) || (node.strokes && node.strokes[0])) return true
223
+ return (node.children || []).some(hasContent)
224
+ }
225
+
226
+ /** A node that ITSELF paints (own fill/stroke) or is TEXT — vs a transparent wrapper. */
227
+ const selfPaints = (node) =>
228
+ node.type === 'TEXT' || !!(node.fills && node.fills[0]) || !!(node.strokes && node.strokes[0])
229
+
230
+ /**
231
+ * Union of the rects of all self-painting (or TEXT) nodes in `node`'s subtree,
232
+ * expressed in `node`'s LOCAL coordinate space (node's own origin = 0,0).
233
+ * Returns null when nothing in the subtree paints. Children carry offsets
234
+ * relative to their parent, so the walk accumulates them; negative/overflow
235
+ * offsets are included (the union never clips content).
236
+ * @param {object} node
237
+ * @returns {{minX:number,minY:number,maxX:number,maxY:number}|null}
238
+ */
239
+ export const contentBBox = (node) => {
240
+ let box = null
241
+ const acc = (n, ox, oy) => {
242
+ if (!n) return
243
+ if (selfPaints(n)) {
244
+ const x1 = ox + (n.width || 0)
245
+ const y1 = oy + (n.height || 0)
246
+ if (box === null) box = { minX: ox, minY: oy, maxX: x1, maxY: y1 }
247
+ else {
248
+ if (ox < box.minX) box.minX = ox
249
+ if (oy < box.minY) box.minY = oy
250
+ if (x1 > box.maxX) box.maxX = x1
251
+ if (y1 > box.maxY) box.maxY = y1
252
+ }
253
+ }
254
+ for (const c of n.children || []) acc(c, ox + (c.x || 0), oy + (c.y || 0))
255
+ }
256
+ acc(node, 0, 0)
257
+ return box
258
+ }
259
+
260
+ /**
261
+ * Trim a captured root to its meaningful component:
262
+ * 1) descend through pure pass-through wrappers (a single content-bearing,
263
+ * non-TEXT child, and no paint of their own),
264
+ * 2) crop the kept node to its content bounding box and normalize direct-child
265
+ * offsets so content sits at the origin.
266
+ * Mutates the kept node's geometry in step 2 and returns it. See
267
+ * sorb-capture-trim-spec.md §3.
268
+ * @param {object} root LayerNode
269
+ * @returns {object} the tightened node
270
+ */
271
+ export const tightenRoot = (root) => {
272
+ if (!root) return root
273
+ let node = root
274
+ // 1) descend through pure pass-through wrappers
275
+ while (true) {
276
+ const selfVisual = (node.fills && node.fills[0]) || (node.strokes && node.strokes[0])
277
+ if (selfVisual) break // node paints something → keep it
278
+ const kids = (node.children || []).filter(hasContent)
279
+ // unwrap a sole content-bearing child UNLESS it is TEXT (the wrapper carries
280
+ // the component's frame; don't descend into raw text). Multiple content kids
281
+ // (e.g. a variant row) → stop here.
282
+ if (kids.length === 1 && kids[0].type !== 'TEXT') {
283
+ node = kids[0]
284
+ continue
285
+ }
286
+ break
287
+ }
288
+ // 2) crop node to the bbox of its content (local coords)
289
+ const bbox = contentBBox(node)
290
+ if (bbox === null) return node // nothing drawn → leave as-is
291
+ const dx = bbox.minX
292
+ const dy = bbox.minY
293
+ for (const child of node.children || []) {
294
+ child.x = (child.x || 0) - dx
295
+ child.y = (child.y || 0) - dy
296
+ }
297
+ node.x = 0
298
+ node.y = 0
299
+ node.width = bbox.maxX - bbox.minX
300
+ node.height = bbox.maxY - bbox.minY
301
+ return node
302
+ }
303
+
204
304
  // Install the walker on `window` so it can be called from a Playwright
205
305
  // page.evaluate(() => window.__sorbCapture(...)) after this module is
206
306
  // bundled and injected via addInitScript. No-op in Node tests.
@@ -0,0 +1,142 @@
1
+ // Unit tests for the capture root-trim helpers (sorb-capture-trim-spec.md §6).
2
+ // Pure geometry — no Playwright/DOM needed. Run: `node --test src/capture.test.js`.
3
+
4
+ import { test } from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import { hasContent, contentBBox, tightenRoot } from './capture.js'
7
+
8
+ // ─── tiny LayerNode factories ───────────────────────────────────────────────
9
+ const SOLID = [{ type: 'SOLID', r: 0.1, g: 0.3, b: 0.9 }]
10
+
11
+ /** A FRAME. Pass `{ fill: true }` to make it self-painting. */
12
+ const frame = (x, y, w, h, opts = {}, children = []) => ({
13
+ type: 'FRAME',
14
+ name: opts.name || 'div',
15
+ x, y, width: w, height: h,
16
+ fills: opts.fill ? SOLID : [],
17
+ strokes: opts.stroke ? SOLID : [],
18
+ children,
19
+ })
20
+
21
+ const text = (x, y, w, h, value = 'Primary') => ({
22
+ type: 'TEXT', name: value, x, y, width: w, height: h, fills: SOLID, children: [],
23
+ })
24
+
25
+ // ─── hasContent ─────────────────────────────────────────────────────────────
26
+ test('hasContent: TEXT, painted frame, and nested content are content-bearing', () => {
27
+ assert.equal(hasContent(text(0, 0, 10, 10)), true)
28
+ assert.equal(hasContent(frame(0, 0, 10, 10, { fill: true })), true)
29
+ assert.equal(hasContent(frame(0, 0, 10, 10, { stroke: true })), true)
30
+ // transparent wrapper around a painted child → content-bearing via descendant
31
+ assert.equal(hasContent(frame(0, 0, 10, 10, {}, [frame(0, 0, 5, 5, { fill: true })])), true)
32
+ // empty transparent wrapper → not content-bearing
33
+ assert.equal(hasContent(frame(0, 0, 10, 10, {}, [frame(0, 0, 5, 5)])), false)
34
+ assert.equal(hasContent(null), false)
35
+ })
36
+
37
+ // ─── contentBBox ────────────────────────────────────────────────────────────
38
+ test('contentBBox: union of painted/text rects in local coords; null when nothing paints', () => {
39
+ // a painted button with an inset text label
40
+ const button = frame(0, 0, 82, 38, { fill: true }, [text(16, 10, 50, 18)])
41
+ assert.deepEqual(contentBBox(button), { minX: 0, minY: 0, maxX: 82, maxY: 38 })
42
+
43
+ // transparent wrapper: bbox bounds only the painted descendants (accumulated offset)
44
+ const wrapped = frame(0, 0, 200, 100, {}, [frame(20, 30, 40, 20, { fill: true })])
45
+ assert.deepEqual(contentBBox(wrapped), { minX: 20, minY: 30, maxX: 60, maxY: 50 })
46
+
47
+ // nothing drawn → null
48
+ assert.equal(contentBBox(frame(0, 0, 100, 100, {}, [frame(0, 0, 10, 10)])), null)
49
+ })
50
+
51
+ test('contentBBox: negative/overflow offsets are included (never clips content)', () => {
52
+ const n = frame(0, 0, 100, 100, {}, [
53
+ frame(-5, -8, 10, 10, { fill: true }),
54
+ frame(90, 95, 20, 20, { fill: true }),
55
+ ])
56
+ assert.deepEqual(contentBBox(n), { minX: -5, minY: -8, maxX: 110, maxY: 115 })
57
+ })
58
+
59
+ // ─── tightenRoot: the three canonical shapes (spec §6) ──────────────────────
60
+ test('tightenRoot: single component — descends wrappers, crops to the button (82×38 at origin)', () => {
61
+ // story 1248×86 → wrapper → wrapper → button 82×38 @(24,24) → text
62
+ const tree = frame(0, 0, 1248, 86, {}, [
63
+ frame(0, 0, 1248, 86, {}, [
64
+ frame(0, 0, 1248, 86, {}, [
65
+ frame(24, 24, 82, 38, { fill: true, name: 'button' }, [text(16, 10, 50, 18)]),
66
+ ]),
67
+ ]),
68
+ ])
69
+ const out = tightenRoot(tree)
70
+ assert.equal(out.name, 'button')
71
+ assert.equal(out.x, 0)
72
+ assert.equal(out.y, 0)
73
+ assert.equal(out.width, 82)
74
+ assert.equal(out.height, 38)
75
+ // the text child is preserved (annotation-safe) and unshifted (dx=dy=0)
76
+ assert.equal(out.children.length, 1)
77
+ assert.equal(out.children[0].type, 'TEXT')
78
+ })
79
+
80
+ test('tightenRoot: multi-child row — stops at the row, crops to the variant group (tight, not 1248)', () => {
81
+ // a row of three buttons, left-padded by 10
82
+ const row = frame(0, 0, 1248, 40, { name: 'row' }, [
83
+ frame(10, 0, 80, 40, { fill: true }, [text(8, 10, 40, 18)]),
84
+ frame(110, 0, 90, 40, { fill: true }, [text(8, 10, 50, 18)]),
85
+ frame(210, 0, 70, 40, { fill: true }, [text(8, 10, 40, 18)]),
86
+ ])
87
+ const tree = frame(0, 0, 1248, 40, {}, [row])
88
+ const out = tightenRoot(tree)
89
+ assert.equal(out.name, 'row')
90
+ assert.equal(out.x, 0)
91
+ assert.equal(out.width, 270) // (210+70) - 10 → tight row, not 1248
92
+ assert.equal(out.height, 40)
93
+ assert.equal(out.children.length, 3)
94
+ assert.equal(out.children[0].x, 0) // first button shifted left by dx=10
95
+ assert.equal(out.children[1].x, 100)
96
+ assert.equal(out.children[2].x, 200)
97
+ })
98
+
99
+ test('tightenRoot: visual card — descent stops at the painted surface (kept, not skipped)', () => {
100
+ const card = frame(20, 10, 320, 180, { fill: true, name: 'card' }, [
101
+ frame(16, 16, 200, 24, {}, [text(0, 0, 180, 20, 'Title')]),
102
+ ])
103
+ const tree = frame(0, 0, 1248, 220, {}, [card])
104
+ const out = tightenRoot(tree)
105
+ assert.equal(out.name, 'card')
106
+ assert.equal(out.width, 320) // card surface preserved
107
+ assert.equal(out.height, 180)
108
+ assert.equal(out.x, 0)
109
+ })
110
+
111
+ // ─── tightenRoot: edge cases (spec §5) ──────────────────────────────────────
112
+ test('tightenRoot: sole child is TEXT — does not descend into raw text; crops the wrapper to it', () => {
113
+ const tree = frame(0, 0, 200, 50, { name: 'label-wrap' }, [text(5, 5, 40, 16, 'Hi')])
114
+ const out = tightenRoot(tree)
115
+ assert.equal(out.name, 'label-wrap') // kept the wrapper, not the TEXT
116
+ assert.equal(out.width, 40)
117
+ assert.equal(out.height, 16)
118
+ assert.equal(out.children[0].x, 0) // text normalized to origin
119
+ assert.equal(out.children[0].y, 0)
120
+ })
121
+
122
+ test('tightenRoot: nothing drawn — returns the tree untouched, no crash', () => {
123
+ const tree = frame(0, 0, 100, 100, {}, [frame(0, 0, 50, 50)])
124
+ const out = tightenRoot(tree)
125
+ assert.equal(out, tree) // unchanged reference
126
+ assert.equal(out.width, 100)
127
+ })
128
+
129
+ test('tightenRoot: wrapper with its OWN bound fill stops descent (no lost token surface)', () => {
130
+ // an Alert/Card whose background is token-bound: selfVisual → keep it
131
+ const alert = frame(0, 0, 600, 60, { fill: true, name: 'alert' }, [
132
+ frame(0, 0, 600, 60, {}, [text(12, 20, 200, 18, 'Heads up')]),
133
+ ])
134
+ const tree = frame(0, 0, 1248, 60, {}, [alert])
135
+ const out = tightenRoot(tree)
136
+ assert.equal(out.name, 'alert')
137
+ assert.equal(out.width, 600)
138
+ })
139
+
140
+ test('tightenRoot: null/empty input is safe', () => {
141
+ assert.equal(tightenRoot(null), null)
142
+ })
package/src/captureCli.js CHANGED
@@ -7,6 +7,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs'
7
7
  import { createHash } from 'crypto'
8
8
  import { dirname, resolve, basename, extname } from 'path'
9
9
  import { build } from 'esbuild'
10
+ import { tightenRoot } from './capture.js'
10
11
  import { buildTokenIndex, annotateTree } from './annotateTokens.js'
11
12
 
12
13
  // Playwright is an OPTIONAL peer dep — only `capture` needs it, and it pulls a
@@ -159,7 +160,12 @@ export const runCapture = async (opts) => {
159
160
  await page.close()
160
161
  continue
161
162
  }
162
- const tree = annotateTree(rawTree, index)
163
+ // Trim the story container down to the meaningful component BEFORE
164
+ // annotation/storage so insert + preview get a tight, token-bound node
165
+ // (sorb-capture-trim-spec.md). Annotation runs on the kept subtree, so
166
+ // token bindings are unaffected.
167
+ const tightened = tightenRoot(rawTree)
168
+ const tree = annotateTree(tightened, index)
163
169
  const hash = 'sha256:' + sha256(JSON.stringify(tree))
164
170
 
165
171
  // --changed: reuse the previous artifact if hash matches