@capagents/forgeqe 2.7.0 → 2.7.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.
Files changed (95) hide show
  1. package/HOW_TO_USE.md +92 -19
  2. package/THIRD_PARTY_NOTICES.md +39 -0
  3. package/dist/docs-site/docs/index.html +79 -2
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1564 -1506
  6. package/dist/web/THIRD_PARTY_NOTICES.md +18 -51
  7. package/dist/web/assets/Agent-CxCmYQU5.js +4 -0
  8. package/dist/web/assets/ApiTests-BYx-CDHt.js +10 -0
  9. package/dist/web/assets/Chat-C6tALAzM.js +3 -0
  10. package/dist/web/assets/Data-IpXp3YB-.js +3 -0
  11. package/dist/web/assets/Evidence-B9rcXYHM.js +1 -0
  12. package/dist/web/assets/Features-EGps6J7t.js +1 -0
  13. package/dist/web/assets/Jobs-DutW6w6P.js +5 -0
  14. package/dist/web/assets/KindPage-DOYNwJDp.js +6 -0
  15. package/dist/web/assets/Migration-5kPbd43c.js +2 -0
  16. package/dist/web/assets/Product-DSxgpqDA.js +1 -0
  17. package/dist/web/assets/Quality-Bo0GxWoZ.js +1 -0
  18. package/dist/web/assets/Record-gGESInMV.js +2 -0
  19. package/dist/web/assets/Regression-b5ykN8hf.js +5 -0
  20. package/dist/web/assets/Reports-BcIDq-yP.js +2 -0
  21. package/dist/web/assets/Response-DLbH7Zyc.js +4 -0
  22. package/dist/web/assets/Runs-C9YExlBk.js +2 -0
  23. package/dist/web/assets/Shell-DGv_Zqjs.js +3 -0
  24. package/dist/web/assets/TestCases-CynVHtUB.js +1 -0
  25. package/dist/web/assets/TestData-5ynuvxFS.js +2 -0
  26. package/dist/web/assets/Tosca-BMePLsZA.js +2 -0
  27. package/dist/web/assets/WhatsNew-gMY090GS.js +1 -0
  28. package/dist/web/assets/dataParts-PzO8u_dt.js +3 -0
  29. package/dist/web/assets/index-CrZYPHPP.css +2 -0
  30. package/dist/web/assets/index-DI1ST-gI.js +43 -0
  31. package/dist/web/assets/parts-BD8kP4IN.js +1 -0
  32. package/dist/web/assets/productParts-Q9GA6BML.js +1 -0
  33. package/dist/web/assets/qualityParts-Df8rJX4J.js +1 -0
  34. package/dist/web/assets/segmented-1nc3D7ML.js +1 -0
  35. package/dist/web/assets/{thread-Jysn_9Ki.js → thread-CE28Yblm.js} +2 -2
  36. package/dist/web/assets/{usePageChat-DOel8PVW.js → usePageChat-3HvaQpPP.js} +1 -1
  37. package/dist/web/index.html +3 -3
  38. package/docs/prompts/graphify-evidence.md +164 -0
  39. package/docs/user-guide.html +79 -2
  40. package/forgeqe.example.yaml +17 -1
  41. package/package.json +3 -1
  42. package/prompts/README.md +1 -0
  43. package/prompts/tosca.md +64 -0
  44. package/py/forgeqe_tosca/__init__.py +85 -0
  45. package/py/forgeqe_tosca/__main__.py +50 -0
  46. package/py/forgeqe_tosca/ntir.py +484 -0
  47. package/py/forgeqe_tosca/render.py +128 -0
  48. package/py/forgeqe_tosca/tsu.py +187 -0
  49. package/py/forgeqe_tosca/vendor/toscatsu/LICENSE +26 -0
  50. package/py/forgeqe_tosca/vendor/toscatsu/UPSTREAM +7 -0
  51. package/py/forgeqe_tosca/vendor/toscatsu/gen_tsu.py +735 -0
  52. package/py/forgeqe_tosca/vendor/toscatsu/parse_tsu.py +1979 -0
  53. package/py/forgeqe_tosca/vendor/toscatsu/spec_to_manifest.py +878 -0
  54. package/py/forgeqe_tosca/vendored.py +50 -0
  55. package/skills/tosca-knowledge/SKILL.md +56 -0
  56. package/skills/tosca-knowledge/references/actions-and-values.md +63 -0
  57. package/skills/tosca-knowledge/references/locators.md +29 -0
  58. package/skills/tosca-knowledge/references/mapping-cypress.md +21 -0
  59. package/skills/tosca-knowledge/references/mapping-playwright.md +31 -0
  60. package/skills/tosca-knowledge/references/mapping-selenium-webdriverio.md +26 -0
  61. package/skills/tosca-knowledge/references/ntir.md +46 -0
  62. package/dist/web/assets/Agent-CTf8KPLI.js +0 -4
  63. package/dist/web/assets/ApiTests-8frnNIDb.js +0 -10
  64. package/dist/web/assets/Chat-Dj_ewn_H.js +0 -3
  65. package/dist/web/assets/Data-rQIV2OfV.js +0 -3
  66. package/dist/web/assets/Evidence-Dn4Uyakw.js +0 -1
  67. package/dist/web/assets/Features-BHbDkY6d.js +0 -1
  68. package/dist/web/assets/Jobs-1kD96CNp.js +0 -5
  69. package/dist/web/assets/KindPage-zoTK8F69.js +0 -6
  70. package/dist/web/assets/Migration-BZcHKmJc.js +0 -2
  71. package/dist/web/assets/Product-DDFGmWxZ.js +0 -1
  72. package/dist/web/assets/Quality-CopMddhf.js +0 -1
  73. package/dist/web/assets/Record-DrgYte-f.js +0 -2
  74. package/dist/web/assets/Regression-Cvj1amuO.js +0 -5
  75. package/dist/web/assets/Reports-BCZeHlgo.js +0 -2
  76. package/dist/web/assets/Response-wbe7YDRm.js +0 -4
  77. package/dist/web/assets/Runs-C-U8Zto_.js +0 -2
  78. package/dist/web/assets/Shell-CUmMbYAE.js +0 -3
  79. package/dist/web/assets/TestCases-D_WpgWxA.js +0 -1
  80. package/dist/web/assets/TestData-B5gzaqO3.js +0 -2
  81. package/dist/web/assets/WhatsNew-BD1_wOmf.js +0 -1
  82. package/dist/web/assets/arrow-down-I4TbiZy1.js +0 -1
  83. package/dist/web/assets/arrow-right-vf1aUPQ0.js +0 -1
  84. package/dist/web/assets/circle-DdyoI0MW.js +0 -1
  85. package/dist/web/assets/circle-dashed-D-xCti8W.js +0 -1
  86. package/dist/web/assets/circle-dot-__mRW42w.js +0 -1
  87. package/dist/web/assets/dataParts-Pr6w8WFl.js +0 -3
  88. package/dist/web/assets/index-BiJ_Nvm1.css +0 -2
  89. package/dist/web/assets/index-mdr9iNZb.js +0 -43
  90. package/dist/web/assets/keyboard-yInSyaVv.js +0 -1
  91. package/dist/web/assets/pencil-wafYzIpD.js +0 -1
  92. package/dist/web/assets/productParts-96V-QyCQ.js +0 -1
  93. package/dist/web/assets/qualityParts-CQ_0RsYl.js +0 -1
  94. package/dist/web/assets/segmented-OwL-zu4L.js +0 -1
  95. package/dist/web/assets/upload-CXgoFfF6.js +0 -1
@@ -0,0 +1,1979 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ parse_tsu.py — Tosca .tsu → HTML report + JSON step manifest + Playwright scaffold.
4
+
5
+ Usage:
6
+ python3 parse_tsu.py file.tsu # HTML only
7
+ python3 parse_tsu.py file.tsu --steps-json # + JSON manifest
8
+ python3 parse_tsu.py file.tsu --playwright # + Playwright project
9
+ python3 parse_tsu.py file.tsu --all # all outputs
10
+ python3 parse_tsu.py file.tsu --all --force # overwrite hand-edited spec/config
11
+ python3 parse_tsu.py file.tsu --all --out-dir <path> # custom output location
12
+
13
+ Outputs land in `<input_dir>/out/<stem>/` by default. Use --out-dir to override
14
+ (e.g. point everything at a single shared dir, or bypass the per-stem nesting).
15
+ The default keeps the working tree clean — drop `out/` into .gitignore once and
16
+ every parse run is covered.
17
+
18
+ The parser is app-agnostic. Locator priority blends XParam type with
19
+ SelfHealingData weights from the .tsu itself. App-specific test attributes
20
+ (data-test-id, data-cy, etc.) and modules to skip are configurable via
21
+ parse_tsu.config.json placed next to the .tsu OR in the output directory
22
+ (out-dir wins for per-run overrides).
23
+
24
+ Default config (used when no config file present):
25
+ {
26
+ "test_attributes": ["data-test-id", "data-testid", "data-test", "data-cy", "data-qa"],
27
+ "skip_modules": ["TBox Set Buffer", "TBox Window Operation",
28
+ "TBox Start Program", "TBox Evaluation Tool",
29
+ "TBox Dialog", "TBox Buffer"]
30
+ }
31
+ """
32
+
33
+ import sys, json, re, gzip, html as html_mod
34
+ from collections import defaultdict, Counter
35
+ from pathlib import Path
36
+
37
+ # ──────────────────────────────────────────────────────────────────────────────
38
+ # CLI + config
39
+ # ──────────────────────────────────────────────────────────────────────────────
40
+ if len(sys.argv) < 2:
41
+ print(__doc__); sys.exit(1)
42
+
43
+ # Parse args: positional .tsu path, flags, and --out-dir <path>
44
+ _args = sys.argv[1:]
45
+ tsu_path = Path(_args[0])
46
+ flags = set()
47
+ out_dir_override = None
48
+ i = 1
49
+ while i < len(_args):
50
+ a = _args[i]
51
+ if a == '--out-dir' and i + 1 < len(_args):
52
+ out_dir_override = Path(_args[i + 1])
53
+ i += 2
54
+ else:
55
+ flags.add(a)
56
+ i += 1
57
+
58
+ gen_pw = '--all' in flags or '--playwright' in flags
59
+ gen_json = '--all' in flags or '--steps-json' in flags
60
+ force = '--force' in flags
61
+
62
+ # Outputs go to out/<stem>/ next to the input by default. Keeps the workspace
63
+ # clean (everything generated lives under one predictable subdir, easy to
64
+ # .gitignore). Override with --out-dir <path>.
65
+ if out_dir_override is not None:
66
+ out_dir = out_dir_override
67
+ else:
68
+ out_dir = tsu_path.parent / 'out' / tsu_path.stem
69
+ out_dir.mkdir(parents=True, exist_ok=True)
70
+
71
+ DEFAULT_CFG = {
72
+ 'test_attributes': ['data-test-id', 'data-testid', 'data-test', 'data-cy', 'data-qa'],
73
+ 'skip_modules': ['TBox Set Buffer', 'TBox Window Operation', 'TBox Start Program',
74
+ 'TBox Evaluation Tool', 'TBox Dialog', 'TBox Buffer'],
75
+ }
76
+ # Config file is read from BOTH the input dir (project-level shared config) and
77
+ # the output dir (per-run override). Per-run wins when both exist.
78
+ cfg = dict(DEFAULT_CFG)
79
+ for _cfg_loc in (tsu_path.parent / 'parse_tsu.config.json',
80
+ out_dir / 'parse_tsu.config.json'):
81
+ if _cfg_loc.exists():
82
+ cfg = {**cfg, **json.loads(_cfg_loc.read_text(encoding='utf-8'))}
83
+
84
+ # ──────────────────────────────────────────────────────────────────────────────
85
+ # Tosca constants
86
+ # ──────────────────────────────────────────────────────────────────────────────
87
+ ACTION_MODE = {'1':'input', '37':'set', '69':'verify', '101':'waitFor',
88
+ '165':'bufferRead', '517':'optionalSet'}
89
+ CLICK_TOKENS = {'CLICK', 'DOUBLECLICK', 'RIGHTCLICK', 'CLICKDOWN', 'CLICKUP'}
90
+ KEY_TOKENS = {'ENTER', 'TAB', 'ESCAPE', 'SPACE', 'BACKSPACE', 'DELETE',
91
+ 'ARROWUP', 'ARROWDOWN', 'ARROWLEFT', 'ARROWRIGHT', 'HOME', 'END'}
92
+
93
+ # Boolean-property assertions for verify/waitFor: prop → (true_assertion, false_assertion)
94
+ ASSERT_PROPS = {
95
+ 'Visible': ('toBeVisible()', 'toBeHidden()'),
96
+ 'Enabled': ('toBeEnabled()', 'toBeDisabled()'),
97
+ 'Disabled': ('toBeDisabled()', 'toBeEnabled()'),
98
+ 'Checked': ('toBeChecked()', 'not.toBeChecked()'),
99
+ 'Selected': ('toBeChecked()', 'not.toBeChecked()'),
100
+ 'Focused': ('toBeFocused()', 'not.toBeFocused()'),
101
+ 'Editable': ('toBeEditable()', 'not.toBeEditable()'),
102
+ 'ReadOnly': ('not.toBeEditable()', 'toBeEditable()'),
103
+ 'Exists': ('toBeAttached()', 'not.toBeAttached()'),
104
+ }
105
+
106
+ # XParam Names that carry framework state, not locator hints
107
+ META_XPARAMS = {'Engine', 'BusinessAssociation', 'ControlFramework', 'FireEvent',
108
+ 'SelfHealingData', 'RelativeId', 'UserSimulation',
109
+ 'IgnoreAriaControls', 'EnableSlotContentHandling', 'ScrollingBehavior',
110
+ 'SpecialExecutionTask', 'WaitBefore', 'WaitAfter', 'ConstraintIndex'}
111
+
112
+ ANGULAR_CLASS_RE = re.compile(r'ng-tns-c\d+-\d+')
113
+ DYNAMIC_XPATH_RE = re.compile(r"id\('(pn_id_[^']+|p-(?:menubarsub|menubar)_[^']+)'\)")
114
+ TOSCA_REF_RE = re.compile(r'^\{(PL|B|CP|XL)\[([^\]]+)\]\}\*?$')
115
+ TOSCA_TOKEN_RE = re.compile(r'^\{(\w+)\}$')
116
+ TOSCA_TOKEN_ARG_RE = re.compile(r'^\{(\w+)\[([^\]]+)\]\}$') # {KEY[Ctrl+A]}, {SELECT[3]}
117
+ TOSCA_EXPR_RE = re.compile(r'^\{[A-Z][A-Z0-9_]*\[') # {CALC[…]}, {TRIM[…]}, {STRINGREPLACE[…]…}
118
+ TOSCA_ENCRYPTED_RE = re.compile(
119
+ r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
120
+ r'[A-Za-z0-9+/=]{20,}$'
121
+ )
122
+ RESERVED_ENV = {'USERNAME','USER','PASSWORD','HOME','PATH','SHELL','TERM','LANG',
123
+ 'LOGNAME','PWD','OLDPWD','SHLVL','TMPDIR','TEMP','TMP',
124
+ 'COMPUTERNAME','USERDOMAIN','APPDATA','SYSTEMROOT'}
125
+
126
+ ROLE_MAP = {'BUTTON':'button', 'A':'link', 'INPUT':'textbox', 'IMG':'img',
127
+ 'H1':'heading', 'H2':'heading', 'H3':'heading', 'H4':'heading', 'H5':'heading',
128
+ 'NAV':'navigation', 'UL':'list', 'OL':'list', 'LI':'listitem'}
129
+ STANDARD_TAGS = {'BUTTON','A','INPUT','IMG','DIV','H1','H2','H3','H4','H5','SPAN',
130
+ 'P','FORM','SELECT','TEXTAREA','NAV','UL','LI','HEADER','FOOTER',
131
+ 'TABLE','TR','TD','TH','SECTION','ARTICLE','MAIN','ASIDE','LABEL',
132
+ 'I','SVG','PATH','OL'}
133
+
134
+ # ──────────────────────────────────────────────────────────────────────────────
135
+ # Decompress + index
136
+ # ──────────────────────────────────────────────────────────────────────────────
137
+ data = json.loads(gzip.open(tsu_path, 'rb').read())
138
+ ents = {e['Surrogate']: e for e in data['Entities']}
139
+
140
+ xparam_by_attr = defaultdict(list)
141
+ sv_top_by_step = defaultdict(list) # step → top-level SVs (those without ParentValue)
142
+ sv_children = defaultdict(list) # parent SV sur → child SVs
143
+ sv_to_attr = {}
144
+ step_to_module = {}
145
+ attr_to_module_dir = {} # attrs that have a direct Module assoc
146
+ attr_parent_attr = {} # attr_sur → parent attr_sur
147
+
148
+ for e in data['Entities']:
149
+ cls = e['ObjectClass']; asc = e.get('Assocs', {}); sur = e['Surrogate']
150
+ if cls == 'XParam':
151
+ for s in asc.get('ExtendableObject', []):
152
+ xparam_by_attr[s].append(e)
153
+ elif cls == 'XModuleAttribute':
154
+ for ms in asc.get('Module', []):
155
+ attr_to_module_dir[sur] = ents.get(ms)
156
+ for ps in asc.get('ParentAttribute', []):
157
+ attr_parent_attr[sur] = ps
158
+ elif cls == 'XTestStepValue':
159
+ parents = asc.get('ParentValue', [])
160
+ if parents:
161
+ sv_children[parents[0]].append(e)
162
+ else:
163
+ for ts in asc.get('TestStep', []):
164
+ sv_top_by_step[ts].append(e)
165
+ for a_sur in asc.get('ModuleAttribute', []):
166
+ sv_to_attr[sur] = ents.get(a_sur)
167
+ elif cls == 'XTestStep':
168
+ for ms in asc.get('Module', []):
169
+ step_to_module[sur] = ents.get(ms)
170
+
171
+ def attr_top_module(attr_sur):
172
+ """Walk ParentAttribute chain upward until we find an attr with a Module assoc."""
173
+ seen = set(); cur = attr_sur
174
+ while cur and cur not in seen:
175
+ seen.add(cur)
176
+ if cur in attr_to_module_dir:
177
+ return attr_to_module_dir[cur]
178
+ cur = attr_parent_attr.get(cur)
179
+ return None
180
+
181
+ # Module → all attrs (including transitively-owned children)
182
+ module_attrs = defaultdict(list)
183
+ for ma in data['Entities']:
184
+ if ma['ObjectClass'] != 'XModuleAttribute': continue
185
+ mod = attr_top_module(ma['Surrogate'])
186
+ if mod: module_attrs[mod['Surrogate']].append(ma)
187
+
188
+ def parent_attr_chain(attr_sur):
189
+ chain = []; seen = set(); cur = attr_parent_attr.get(attr_sur)
190
+ while cur and cur not in seen:
191
+ seen.add(cur); chain.append(cur)
192
+ cur = attr_parent_attr.get(cur)
193
+ return chain
194
+
195
+ def walk_svs(sv):
196
+ """Yield SV and all its descendants."""
197
+ yield sv
198
+ for ch in sv_children.get(sv['Surrogate'], []):
199
+ yield from walk_svs(ch)
200
+
201
+ # ──────────────────────────────────────────────────────────────────────────────
202
+ # Per-call ParameterLayer index — for {PL[X]} resolution
203
+ # ──────────────────────────────────────────────────────────────────────────────
204
+ plr_by_call = {} # TestStepFolderReference sur → {param_name: outer_value}
205
+ for e in data['Entities']:
206
+ if e['ObjectClass'] != 'TestStepFolderReference': continue
207
+ plr_surs = e.get('Assocs', {}).get('ParameterLayerReference', [])
208
+ if not plr_surs: continue
209
+ plr = ents.get(plr_surs[0])
210
+ if not plr: continue
211
+ layer = {}
212
+ for pref_sur in plr.get('Assocs', {}).get('AllParameterReferences', []):
213
+ pref = ents.get(pref_sur)
214
+ if not pref: continue
215
+ param_surs = pref.get('Assocs', {}).get('Parameter', [])
216
+ if not param_surs: continue
217
+ pname = ents[param_surs[0]]['Attributes'].get('Name', '')
218
+ if pname:
219
+ layer[pname] = pref['Attributes'].get('Value', '')
220
+ plr_by_call[e['Surrogate']] = layer
221
+
222
+ # ──────────────────────────────────────────────────────────────────────────────
223
+ # XParam helpers
224
+ # ──────────────────────────────────────────────────────────────────────────────
225
+ def xparams(attr_sur):
226
+ return {p['Attributes']['Name']: p['Attributes']['Value']
227
+ for p in xparam_by_attr.get(attr_sur, [])
228
+ if p['Attributes'].get('Name') not in META_XPARAMS
229
+ and p['Attributes'].get('Value')}
230
+
231
+ def xparam_meta(attr_sur):
232
+ """Return {name: value} for meta XParams (timing, constraint index)."""
233
+ return {p['Attributes']['Name']: p['Attributes']['Value']
234
+ for p in xparam_by_attr.get(attr_sur, [])
235
+ if p['Attributes'].get('Name') in ('WaitBefore','WaitAfter','ConstraintIndex')
236
+ and p['Attributes'].get('Value')}
237
+
238
+ def self_healing(attr_sur):
239
+ for p in xparam_by_attr.get(attr_sur, []):
240
+ if p['Attributes'].get('Name') != 'SelfHealingData': continue
241
+ try:
242
+ shd = json.loads(p['Attributes']['Value'])
243
+ return [{'name': c['Name'], 'value': c.get('Value', ''),
244
+ 'weight': float(c.get('Weight', 0))}
245
+ for c in shd.get('HealingParameters', {}).get('$values', [])
246
+ if c.get('Value') and c['Value'] not in ('<No label associated>', '')]
247
+ except Exception:
248
+ return []
249
+ return []
250
+
251
+ def relative_ctx(attr_sur):
252
+ for p in xparam_by_attr.get(attr_sur, []):
253
+ if p['Attributes'].get('Name') != 'RelativeId': continue
254
+ raw = p['Attributes']['Value']
255
+ keys = re.findall(r'<Key>([^<]+)</Key>', raw)
256
+ vals = re.findall(r'<Value>([^<]+)</Value>', raw)
257
+ ctx = dict(zip(keys, vals))
258
+ for k in ('Engine', 'BusinessAssociation'): ctx.pop(k, None)
259
+ return ctx
260
+ return {}
261
+
262
+ # ──────────────────────────────────────────────────────────────────────────────
263
+ # Locator candidate ranking — data-driven, weight-blended
264
+ # ──────────────────────────────────────────────────────────────────────────────
265
+ def _esc(s): return s.replace("'", "\\'").replace('"', '\\"')
266
+
267
+ def _normalize_xpath(xp: str) -> str:
268
+ """Convert Tosca's XPath conventions to standard XPath that Playwright accepts:
269
+ 1. Tosca often wraps the expression in literal double quotes ("id('X')/...")
270
+ — strip those.
271
+ 2. Tosca uses XPath 1.0 id('X')/path syntax that Playwright's injected
272
+ script can't evaluate; rewrite to //*[@id='X']/path.
273
+ """
274
+ if not xp: return xp
275
+ s = xp.strip()
276
+ if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
277
+ s = s[1:-1]
278
+ s = re.sub(r"id\(['\"]([^'\"]+)['\"]\)", r"//*[@id='\1']", s)
279
+ return s
280
+ def _ts(s): return json.dumps(s)
281
+
282
+ def _is_dynamic_xpath(xp): return bool(DYNAMIC_XPATH_RE.search(xp)) if xp else False
283
+
284
+ def _stable_class(cls):
285
+ if not cls: return ''
286
+ return ' '.join(t for t in cls.split() if not ANGULAR_CLASS_RE.match(t) and t)
287
+
288
+ def collect_candidates(attr_sur, value_hint=''):
289
+ """Build a scored list of locator candidates from XParams + SelfHealingData."""
290
+ xp = xparams(attr_sur)
291
+ meta = xparam_meta(attr_sur)
292
+ sh = self_healing(attr_sur)
293
+ sh_w = {h['name'].lower(): h['weight'] for h in sh}
294
+ def w(name, default): return sh_w.get(name.lower(), default)
295
+
296
+ nth = meta.get('ConstraintIndex', '')
297
+ def with_nth(sel):
298
+ if nth and nth.isdigit() and int(nth) > 0:
299
+ return f"{sel}.nth({int(nth)-1})"
300
+ return sel
301
+
302
+ cands = []
303
+
304
+ # data-test-id family (configurable list of test attributes)
305
+ seen_attrs = set()
306
+ for ta in cfg['test_attributes']:
307
+ for key in (f'attributes_{ta}', ta):
308
+ v = xp.get(key, '')
309
+ if v and not v.startswith('{') and '*' not in v:
310
+ seen_attrs.add(key)
311
+ cands.append({
312
+ 'sel': with_nth(f"page.locator('[{ta}=\"{_esc(v)}\"]')"),
313
+ 'score': 100 + w(key, 1.0),
314
+ 'kind': f'attr:{ta}',
315
+ })
316
+
317
+ # id
318
+ if xp.get('Id') and not xp['Id'].startswith('{'):
319
+ cands.append({
320
+ 'sel': f"page.locator('#{_esc(xp['Id'])}')",
321
+ 'score': 90 + w('Id', 1.0),
322
+ 'kind': 'id',
323
+ })
324
+
325
+ # any other attributes_* (generic handler)
326
+ for k, v in xp.items():
327
+ if not k.startswith('attributes_') or k in seen_attrs: continue
328
+ if not v or v.startswith('{'): continue
329
+ attr_name = k[len('attributes_'):]
330
+ if attr_name in ('class',): continue # use ClassName path instead
331
+ cands.append({
332
+ 'sel': with_nth(f"page.locator('[{attr_name}=\"{_esc(v)}\"]')"),
333
+ 'score': 70 + w(k, 0.4),
334
+ 'kind': f'attr:{attr_name}',
335
+ })
336
+
337
+ # aria-label
338
+ aria = xp.get('AriaLabel') or xp.get('attributes_aria-label') or ''
339
+ if aria and not aria.startswith('{'):
340
+ cands.append({
341
+ 'sel': with_nth(f"page.getByLabel({_ts(aria)}, {{ exact: true }})"),
342
+ 'score': 65 + w('AriaLabel', 0.7),
343
+ 'kind': 'aria',
344
+ })
345
+
346
+ # role + name (when tag maps to a role and we have visible text)
347
+ tag = xp.get('Tag', '')
348
+ inner = xp.get('InnerText') or xp.get('innerText') or ''
349
+ sh_label = next((h['value'] for h in sh
350
+ if h['name'] == 'Label' and h['value']
351
+ and not h['value'].startswith('{')
352
+ and len(h['value']) <= 80), '')
353
+ name_text = next((t for t in (inner, sh_label, value_hint)
354
+ if t and not t.startswith('{') and len(t) <= 80 and '\n' not in t), '')
355
+ if tag in ROLE_MAP and name_text:
356
+ cands.append({
357
+ 'sel': with_nth(f"page.getByRole('{ROLE_MAP[tag]}', "
358
+ f"{{ name: {_ts(name_text)}, exact: true }})"),
359
+ 'score': 60,
360
+ 'kind': 'role+name',
361
+ })
362
+
363
+ # href
364
+ href = xp.get('Href') or xp.get('attributes_href') or ''
365
+ if tag == 'A' and href and href.startswith('http'):
366
+ path = href.split('/', 3)[-1]
367
+ cands.append({
368
+ 'sel': f"page.locator('a[href*={_ts(path)}]')",
369
+ 'score': 50 + w('Href', 0.5),
370
+ 'kind': 'href',
371
+ })
372
+
373
+ # img src (skip CDN-volatile sources)
374
+ src = xp.get('Src') or ''
375
+ if tag == 'IMG' and src and 'kc-usercontent.com' not in src and 'opentext.cloud' not in src:
376
+ seg = src.split('/')[-1][:40]
377
+ cands.append({
378
+ 'sel': f"page.locator('img[src*={_ts(seg)}]')",
379
+ 'score': 45,
380
+ 'kind': 'src',
381
+ })
382
+
383
+ # plain text
384
+ if name_text and not aria and tag not in ROLE_MAP:
385
+ cands.append({
386
+ 'sel': with_nth(f"page.getByText({_ts(name_text)}, {{ exact: true }})"),
387
+ 'score': 40,
388
+ 'kind': 'text',
389
+ })
390
+
391
+ # stable class
392
+ cls = _stable_class(xp.get('ClassName', ''))
393
+ if cls:
394
+ primary_cls = cls.split()[0]
395
+ sel = f"{tag.lower()}.{primary_cls}" if tag and tag in STANDARD_TAGS else f".{primary_cls}"
396
+ cands.append({
397
+ 'sel': with_nth(f"page.locator('{sel}')"),
398
+ 'score': 25 + w('ClassName', 0),
399
+ 'kind': 'class',
400
+ })
401
+
402
+ # custom tag alone (web component)
403
+ if tag and tag not in STANDARD_TAGS:
404
+ cands.append({
405
+ 'sel': with_nth(f"page.locator('{tag.lower()}')"),
406
+ 'score': 20,
407
+ 'kind': 'tag',
408
+ })
409
+
410
+ # XPath (last; flag if dynamic)
411
+ xpath = xp.get('XPath') or xp.get('Xpath') or ''
412
+ if xpath:
413
+ is_dyn = _is_dynamic_xpath(xpath)
414
+ cands.append({
415
+ 'sel': f"page.locator('xpath={_esc(_normalize_xpath(xpath))}')",
416
+ 'score': 5 if is_dyn else 15,
417
+ 'kind': 'xpath',
418
+ 'warn': 'dynamic-xpath' if is_dyn else '',
419
+ })
420
+
421
+ # Promote SelfHealing-only candidates the XParams missed
422
+ for h in sh:
423
+ if h['weight'] < 0.3: continue
424
+ n, v = h['name'], h['value']
425
+ if n in ('XPath','Xpath') and not _is_dynamic_xpath(v):
426
+ cands.append({'sel': f"page.locator('xpath={_esc(_normalize_xpath(v))}')",
427
+ 'score': 14 + h['weight'], 'kind': 'sh:xpath'})
428
+ elif n == 'Url' and v.startswith('http'):
429
+ path = v.split('/', 3)[-1]
430
+ cands.append({'sel': f"page.locator('a[href*={_ts(path)}]')",
431
+ 'score': 48 + h['weight'], 'kind': 'sh:url'})
432
+
433
+ cands.sort(key=lambda c: -c['score'])
434
+ return cands
435
+
436
+ def build_locator(attr_sur, action_property='', value_hint=''):
437
+ """Return (primary, fallback, notes) for a Tosca attribute."""
438
+ if not attr_sur:
439
+ return None, None, []
440
+
441
+ # Suppress system-token value hints
442
+ if (action_property in ('Visible','Enabled','Checked')
443
+ or value_hint in ('True','False','')
444
+ or (value_hint.startswith('{') and value_hint.endswith('}'))):
445
+ value_hint = ''
446
+
447
+ cands = collect_candidates(attr_sur, value_hint=value_hint)
448
+ if not cands:
449
+ return None, None, []
450
+
451
+ primary = cands[0]['sel']
452
+ fallback = cands[1]['sel'] if len(cands) > 1 and cands[1]['sel'] != primary else None
453
+ notes = []
454
+ if cands[0].get('warn') == 'dynamic-xpath':
455
+ notes.append('⚠ dynamic XPath – may break on re-render')
456
+
457
+ # Scope under nearest custom-tag parent for uniqueness (e.g. <app-terms>...)
458
+ parent_tag = ''
459
+ for pa_sur in parent_attr_chain(attr_sur):
460
+ ptag = xparams(pa_sur).get('Tag', '')
461
+ if ptag and ptag not in STANDARD_TAGS:
462
+ parent_tag = ptag.lower(); break
463
+ if parent_tag and primary.startswith('page.locator(') and 'xpath=' not in primary:
464
+ scoped = primary.replace('page.locator(', f"page.locator('{parent_tag}').locator(", 1)
465
+ if not fallback: fallback = primary
466
+ primary = scoped
467
+
468
+ return primary, fallback, notes
469
+
470
+ # ──────────────────────────────────────────────────────────────────────────────
471
+ # PL/Buffer resolution
472
+ # ──────────────────────────────────────────────────────────────────────────────
473
+ EMBEDDED_REF_RE = re.compile(r'\{(PL|B|CP|XL)\[([^\]]+)\]\}')
474
+
475
+ def _lookup_ref(kind, name, pl_stack, buffer_map):
476
+ if kind == 'PL':
477
+ for layer in reversed(pl_stack):
478
+ if name in layer: return layer[name]
479
+ elif kind == 'B':
480
+ if name in buffer_map: return buffer_map[name]
481
+ elif kind == 'CP':
482
+ return f'$CONFIG:{name}'
483
+ elif kind == 'XL':
484
+ return f'$XL:{name}'
485
+ return None
486
+
487
+ def resolve_value(val, pl_stack, buffer_map, max_hops=6):
488
+ """Resolve Tosca refs in `val`. Whole-string refs unwrap until literal;
489
+ embedded refs are substituted in-place. Bounded by max_hops."""
490
+ if not val or not isinstance(val, str) or max_hops <= 0: return val
491
+ seen = set()
492
+ for _ in range(max_hops):
493
+ if val in seen: break
494
+ seen.add(val)
495
+ m = TOSCA_REF_RE.match(val)
496
+ if not m: break
497
+ nxt = _lookup_ref(m.group(1), m.group(2), pl_stack, buffer_map)
498
+ if nxt is None or nxt == val: break
499
+ val = nxt
500
+ if not EMBEDDED_REF_RE.search(val): return val
501
+ def _sub(m):
502
+ nxt = _lookup_ref(m.group(1), m.group(2), pl_stack, buffer_map)
503
+ if nxt is None: return m.group(0)
504
+ return resolve_value(nxt, pl_stack, buffer_map, max_hops - 1)
505
+ return EMBEDDED_REF_RE.sub(_sub, val)
506
+
507
+ # ──────────────────────────────────────────────────────────────────────────────
508
+ # Step resolver
509
+ # ──────────────────────────────────────────────────────────────────────────────
510
+ def step_actions(step_ent, pl_stack, buffer_map):
511
+ actions = []
512
+ for top_sv in sv_top_by_step.get(step_ent['Surrogate'], []):
513
+ for sv in walk_svs(top_sv):
514
+ attrs = sv['Attributes']
515
+ mode = ACTION_MODE.get(attrs.get('ActionMode',''), attrs.get('ActionMode',''))
516
+ prop = attrs.get('ActionProperty', '')
517
+ val = attrs.get('Value', '')
518
+ ma = sv_to_attr.get(sv['Surrogate'])
519
+ if not ma: continue
520
+ # Skip pure-container leaves (no value AND has children — children carry the action)
521
+ if val == '{NULL}' and sv_children.get(sv['Surrogate']):
522
+ continue
523
+ attr_sur = ma['Surrogate']
524
+ attr_name = ma['Attributes'].get('Name', '')
525
+ primary, fallback, notes = build_locator(attr_sur, prop, val)
526
+ meta = xparam_meta(attr_sur)
527
+ actions.append({
528
+ 'mode': mode,
529
+ 'action_property': prop,
530
+ 'element_name': attr_name,
531
+ 'explicit_name': attrs.get('ExplicitName', ''),
532
+ 'value': val,
533
+ 'value_resolved': resolve_value(val, pl_stack, buffer_map),
534
+ 'primary_locator': primary,
535
+ 'fallback_locator': fallback,
536
+ 'notes': notes,
537
+ 'attr_sur': attr_sur,
538
+ 'wait_before': meta.get('WaitBefore', ''),
539
+ 'wait_after': meta.get('WaitAfter', ''),
540
+ })
541
+ return actions
542
+
543
+ def resolve_steps(sur_list, depth=0, pl_stack=None, buffer_map=None):
544
+ if pl_stack is None: pl_stack = []
545
+ if buffer_map is None: buffer_map = {}
546
+ out = []
547
+ for sur in sur_list:
548
+ e = ents.get(sur)
549
+ if not e: continue
550
+ cls = e['ObjectClass']
551
+ name = e['Attributes'].get('Name', '')
552
+
553
+ if cls == 'XTestStep':
554
+ mod = step_to_module.get(sur)
555
+ mod_name = mod['Attributes']['Name'] if mod else ''
556
+ acts = step_actions(e, pl_stack, buffer_map)
557
+ # Replay TBox Set Buffer assignments into buffer_map for later steps
558
+ if mod_name == 'TBox Set Buffer':
559
+ for a in acts:
560
+ en = a.get('explicit_name', '')
561
+ if not en: continue
562
+ # Prefer the resolved value (handles {PL[X]} → outer literal chains)
563
+ rv = a.get('value_resolved') or a.get('value', '')
564
+ if rv and not rv.startswith('{'):
565
+ buffer_map[en] = rv
566
+ out.append({'type':'step', 'name':name, 'module':mod_name,
567
+ 'actions':acts, 'depth':depth})
568
+ for sub in e.get('Assocs', {}).get('Items', []):
569
+ out += resolve_steps([sub], depth+1, pl_stack, buffer_map)
570
+
571
+ elif cls == 'TestStepFolder':
572
+ out.append({'type':'folder', 'name':name, 'depth':depth})
573
+ out += resolve_steps(e.get('Assocs', {}).get('Items', []),
574
+ depth+1, pl_stack, buffer_map)
575
+ out.append({'type':'folder_end', 'name':name, 'depth':depth})
576
+
577
+ elif cls == 'TestStepFolderReference':
578
+ layer = plr_by_call.get(sur, {})
579
+ pl_stack.append(layer)
580
+ for r in e.get('Assocs', {}).get('ReusedItem', []):
581
+ tgt = ents.get(r)
582
+ if not tgt: continue
583
+ bn = tgt['Attributes'].get('Name', '')
584
+ out.append({'type':'block_start', 'name':bn, 'depth':depth,
585
+ 'parameters': dict(layer)})
586
+ out += resolve_steps(tgt.get('Assocs', {}).get('Items', []),
587
+ depth+1, pl_stack, buffer_map)
588
+ out.append({'type':'block_end', 'name':bn, 'depth':depth})
589
+ pl_stack.pop()
590
+
591
+ elif cls == 'TestCaseControlFlowItem':
592
+ cffs = {}
593
+ for cs in e.get('Assocs', {}).get('ControlFlowFolders', []):
594
+ cf = ents.get(cs)
595
+ if cf: cffs[cf['Attributes'].get('Name', '')] = cf
596
+
597
+ # Pull condition expression
598
+ cond_text = ''
599
+ cond_folder = cffs.get('Condition')
600
+ if cond_folder:
601
+ for it in cond_folder.get('Assocs', {}).get('Items', []):
602
+ c_ent = ents.get(it)
603
+ if not c_ent: continue
604
+ for sv in sv_top_by_step.get(c_ent['Surrogate'], []):
605
+ cond_text = sv['Attributes'].get('Value', '') or cond_text
606
+ cond_resolved = resolve_value(cond_text, pl_stack, buffer_map) if cond_text else ''
607
+
608
+ out.append({'type':'if', 'name':name, 'depth':depth,
609
+ 'condition': cond_text, 'condition_resolved': cond_resolved})
610
+ for branch in ('Then', 'Loop', 'Else'):
611
+ cf = cffs.get(branch)
612
+ if not cf: continue
613
+ out.append({'type':branch.lower()+'_start', 'depth':depth+1, 'name':branch})
614
+ out += resolve_steps(cf.get('Assocs', {}).get('Items', []),
615
+ depth+2, pl_stack, buffer_map)
616
+ out.append({'type':branch.lower()+'_end', 'depth':depth+1, 'name':branch})
617
+ out.append({'type':'if_end', 'name':name, 'depth':depth})
618
+
619
+ elif cls == 'TestCaseControlFlowFolder':
620
+ out += resolve_steps(e.get('Assocs', {}).get('Items', []),
621
+ depth, pl_stack, buffer_map)
622
+ return out
623
+
624
+ # ──────────────────────────────────────────────────────────────────────────────
625
+ # Walk the test case
626
+ # ──────────────────────────────────────────────────────────────────────────────
627
+ # Closure helper: which entity surrogates does this test case touch?
628
+ # Walking from the TC through items/folders/blocks/steps/SVs/attributes/
629
+ # modules/RTBs/control-flow/parameter layers (transitively, including RTBs
630
+ # called by RTBs). The set returned is the per-TC "filter" for
631
+ # multi-TC .tsu outputs so each test case only ships the modules it
632
+ # actually uses.
633
+ _TC_CLOSURE_EDGES = {
634
+ 'TestCase': ['Items'],
635
+ 'TestStepFolder': ['Items'],
636
+ 'TestStepFolderReference': ['ReusedItem', 'ParameterLayerReference'],
637
+ 'ReuseableTestStepBlock': ['Items', 'ParameterLayer'],
638
+ 'XTestStep': ['TestStepValues', 'Module'],
639
+ 'XTestStepValue': ['SubValues', 'ModuleAttribute'],
640
+ 'XModuleAttribute': ['Properties', 'ParentAttribute', 'Module'],
641
+ 'XModule': ['Attributes'],
642
+ 'TestCaseControlFlowItem': ['ControlFlowFolders'],
643
+ 'TestCaseControlFlowFolder': ['Items'],
644
+ 'ParameterLayer': ['Parameters'],
645
+ 'ParameterLayerReference': ['AllParameterReferences', 'ParameterLayer'],
646
+ 'ParameterReference': ['Parameter'],
647
+ }
648
+ def tc_closure(tc_sur):
649
+ seen, stack = set(), [tc_sur]
650
+ while stack:
651
+ s = stack.pop()
652
+ if s in seen: continue
653
+ seen.add(s)
654
+ e = ents.get(s)
655
+ if not e: continue
656
+ for edge in _TC_CLOSURE_EDGES.get(e['ObjectClass'], ()):
657
+ for ns in e.get('Assocs', {}).get(edge, ()):
658
+ if ns not in seen: stack.append(ns)
659
+ return seen
660
+
661
+ def _tc_stem(tc_entity):
662
+ """Sanitize a TestCase name into a filesystem-safe stem.
663
+ Preserves the bracketed test ID when present (e.g. [1034698]) and the
664
+ main descriptive part of the name."""
665
+ name = tc_entity['Attributes'].get('Name', '') or 'unnamed_tc'
666
+ # Extract test ID like [1034698] if present
667
+ id_m = re.search(r'\[(\d{5,})\]', name)
668
+ test_id = id_m.group(1) + '_' if id_m else ''
669
+ # Strip all bracketed prefixes [X][Y][Z] then sanitize
670
+ rest = re.sub(r'\[[^\]]*\]', '', name).strip()
671
+ rest = re.sub(r'[^a-zA-Z0-9]+', '_', rest).strip('_').lower()
672
+ rest = rest[:60] # cap length
673
+ return f'{test_id}{rest}' or tc_entity['Surrogate'][:8]
674
+
675
+
676
+ # Generic Tosca workspace folders that aren't useful for grouping tests.
677
+ # Anything else in the parent chain becomes part of the area folder name.
678
+ _AREA_FOLDER_NOISE = {'TestCases', 'Library', 'Components', 'TBox',
679
+ 'Modules', 'Configuration', 'Project', ''}
680
+
681
+ def _tc_area(tc):
682
+ """Derive a sanitized 'area' folder for shared playwright-test/tests/.
683
+ Walks the immediate parent chain; takes the first meaningful folder name,
684
+ skipping generic Tosca workspace folders (TestCases, Library, etc.).
685
+ Returns '' when no meaningful folder is found (test lands in tests/ flat)."""
686
+ parents = tc.get('Assocs', {}).get('ParentFolder', [])
687
+ while parents:
688
+ p_sur = parents[0]
689
+ p = ents.get(p_sur)
690
+ if not p: break
691
+ nm = (p['Attributes'].get('Name') or '').strip()
692
+ if nm and nm not in _AREA_FOLDER_NOISE:
693
+ return re.sub(r'[^a-zA-Z0-9]+', '_', nm).strip('_').lower()
694
+ parents = p.get('Assocs', {}).get('ParentFolder', [])
695
+ return ''
696
+
697
+ # Module-level accumulator for env vars across multi-TC runs. Each per-TC
698
+ # call's safe_env() populates this; we write the union to .env.example
699
+ # once after the dispatch loop.
700
+ env_vars_used = {}
701
+
702
+ # Last per-TC base_url; used as the default for the shared config in multi-TC.
703
+ # (Each spec sets its own test.use({ baseURL }) so this is just a fallback.)
704
+ _last_base_url = ''
705
+
706
+ _PACKAGE_JSON = """{
707
+ "name": "tosca-playwright",
708
+ "version": "1.0.0",
709
+ "scripts": {
710
+ "test": "playwright test",
711
+ "test:headed": "playwright test --headed",
712
+ "report": "playwright show-report"
713
+ },
714
+ "devDependencies": {
715
+ "@playwright/test": "^1.44.0",
716
+ "typescript": "^5.4.0",
717
+ "dotenv": "^16.0.0"
718
+ }
719
+ }
720
+ """
721
+
722
+ def _build_env_lines(base_url, env_vars):
723
+ """Render the .env.example body. Used for both single-TC (per-call) and
724
+ multi-TC (post-loop, with the accumulated union)."""
725
+ lines = [
726
+ "# Auto-generated by parse_tsu.py — list of environment variables the",
727
+ "# generated spec references. Copy to `.env` and fill in real values.",
728
+ "",
729
+ f"# Recorded base URL: {base_url}",
730
+ "# Override the default baseURL in playwright.config.ts (and all per-spec",
731
+ "# `test.use({ baseURL })` defaults) without editing the spec:",
732
+ f"# BASE_URL={base_url}",
733
+ "",
734
+ ]
735
+ if env_vars:
736
+ lines.append("# Credential / config parameters referenced by spec actions:")
737
+ for name in sorted(env_vars):
738
+ sources = env_vars[name]
739
+ hint = f" (from CP[{sources[0][0]}]" + (f" / {sources[0][1]}" if sources[0][1] else "") + ")"
740
+ lines.append(f"{name}={hint}")
741
+ lines.append("")
742
+ return lines
743
+
744
+ def _write_shared_pw_artifacts(pw_dir, base_url, force_overwrite):
745
+ """Write playwright.config.ts, package.json, .env.example ONCE for the
746
+ shared multi-TC playwright project. Uses the module-level env_vars_used
747
+ accumulated across all per-TC pipelines."""
748
+ pw_dir.mkdir(parents=True, exist_ok=True)
749
+ config_content = (
750
+ "import { defineConfig, devices } from '@playwright/test';\n"
751
+ "import 'dotenv/config';\n\n"
752
+ "export default defineConfig({\n"
753
+ " testDir: './tests',\n"
754
+ " fullyParallel: true,\n"
755
+ " timeout: 300_000,\n"
756
+ " reporter: 'html',\n"
757
+ " use: {\n"
758
+ f" baseURL: process.env.BASE_URL || '{base_url}',\n"
759
+ " screenshot: 'only-on-failure',\n"
760
+ " video: 'on',\n"
761
+ " trace: 'on-first-retry',\n"
762
+ " },\n"
763
+ " projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],\n"
764
+ "});\n"
765
+ )
766
+ cfg_p = pw_dir / 'playwright.config.ts'
767
+ if not cfg_p.exists() or force_overwrite:
768
+ cfg_p.write_text(config_content)
769
+ print(f"[✓] Shared config → playwright-test/playwright.config.ts (baseURL: {base_url})")
770
+ pkg_p = pw_dir / 'package.json'
771
+ if not pkg_p.exists() or force_overwrite:
772
+ pkg_p.write_text(_PACKAGE_JSON)
773
+ print(f"[✓] Shared package → playwright-test/package.json")
774
+ env_p = pw_dir / '.env.example'
775
+ env_p.write_text("\n".join(_build_env_lines(base_url, env_vars_used)))
776
+ print(f"[✓] Shared env template → playwright-test/.env.example ({len(env_vars_used)} vars across all cases)")
777
+
778
+
779
+ def _per_tc_pipeline(tc, project, base_out_dir, multi_tc):
780
+ """Run the full HTML/JSON/Playwright generation pipeline for one TC.
781
+ Single-TC: outputs at base_out_dir/{<stem>_steps.json, <stem>_report.html, playwright-test/...}.
782
+ Multi-TC: per-case JSON+HTML at base_out_dir/cases/<tc_stem>/, and a SHARED
783
+ playwright project at base_out_dir/playwright-test/ where each spec lives
784
+ in tests/<area>/<tc_stem>.spec.ts and pages/ holds the union of all
785
+ referenced modules."""
786
+ # Per-TC paths
787
+ if multi_tc:
788
+ case_dir = base_out_dir / 'cases' / _tc_stem(tc)
789
+ case_dir.mkdir(parents=True, exist_ok=True)
790
+ out_dir = case_dir # JSON + HTML go here
791
+ pw_root = base_out_dir / 'playwright-test' # SHARED across all TCs
792
+ area = _tc_area(tc)
793
+ print(f" [tc] {tc['Attributes'].get('Name','')[:80]}")
794
+ print(f" → cases/{_tc_stem(tc)}/ + playwright-test/tests/{area+'/' if area else ''}{_tc_stem(tc)}.spec.ts")
795
+ else:
796
+ out_dir = base_out_dir
797
+ pw_root = base_out_dir / 'playwright-test'
798
+ area = ''
799
+
800
+ # Closure of this TC's reachable entities — used to filter outputs so
801
+ # this case's report/pages only include modules it actually uses.
802
+ tc_set = tc_closure(tc['Surrogate'])
803
+
804
+ # NOTE: env_vars_used, unmapped_actions, urls etc. are local to this
805
+ # function (defined further down). Each per-TC call gets a fresh set
806
+ # automatically — no manual reset needed.
807
+
808
+ # tc and project come in as parameters from the dispatch loop —
809
+ # don't re-bind them here (the original `tc = next(...)` would always
810
+ # pick the FIRST TestCase, defeating multi-TC iteration).
811
+ all_steps = resolve_steps(tc.get('Assocs', {}).get('Items', []))
812
+
813
+ # Final buffer_map snapshot (replay all TBox Set Buffer steps in order)
814
+ buffer_map = {}
815
+ for s in all_steps:
816
+ if s.get('type') == 'step' and s.get('module') == 'TBox Set Buffer':
817
+ for a in s.get('actions', []):
818
+ en, v = a.get('explicit_name', ''), a.get('value', '')
819
+ if en and v and not v.startswith('{'):
820
+ buffer_map[en] = v
821
+
822
+ # ──────────────────────────────────────────────────────────────────────────────
823
+ # URL collection + base URL
824
+ # ──────────────────────────────────────────────────────────────────────────────
825
+ urls = set()
826
+ for e in data['Entities']:
827
+ if e['ObjectClass'] != 'XParam': continue
828
+ # Per-TC filter: only collect URLs from XParams in this TC's closure
829
+ # (i.e. attached to module-attributes this case actually touches).
830
+ if e['Surrogate'] not in tc_set: continue
831
+ v = e['Attributes'].get('Value', '')
832
+ if isinstance(v, str):
833
+ if v.startswith('http'): urls.add(v)
834
+ if e['Attributes'].get('Name') == 'SelfHealingData':
835
+ urls.update(re.findall(r'"Value":"(https?://[^"]+)"', v))
836
+
837
+ def _root(u):
838
+ m = re.match(r'(https?://[^/]+(?:/[a-z]{2}-[A-Z]{2})?(?:/pro)?)', u)
839
+ return m.group(1) if m else u.split('?')[0]
840
+
841
+ b2b = sorted({_root(u) for u in urls if re.search(r'/[a-z]{2}-[A-Z]{2}/pro\b', u)})
842
+ loc = sorted({_root(u) for u in urls if re.search(r'/[a-z]{2}-[A-Z]{2}\b', u)})
843
+ base_url = (b2b or loc or sorted({_root(u) for u in urls}) or [''])[0]
844
+ # Track for post-loop shared config (multi-TC). Last seen wins; per-spec
845
+ # test.use({baseURL}) overrides at runtime anyway.
846
+ global _last_base_url
847
+ _last_base_url = base_url or _last_base_url
848
+
849
+ # ──────────────────────────────────────────────────────────────────────────────
850
+ # JSON manifest
851
+ # ──────────────────────────────────────────────────────────────────────────────
852
+ def raw_locator(attr_sur):
853
+ if not attr_sur: return {}
854
+ xp = xparams(attr_sur); meta = xparam_meta(attr_sur)
855
+ ctx = relative_ctx(attr_sur); sh = self_healing(attr_sur)
856
+ out = {k: v for k, v in xp.items() if v}
857
+ if meta: out['_meta'] = meta
858
+ if ctx: out['_parent_relid'] = ctx
859
+ chain = parent_attr_chain(attr_sur)
860
+ if chain:
861
+ out['_parent_chain'] = []
862
+ for s in chain:
863
+ if s not in ents: continue
864
+ pxp = xparams(s)
865
+ entry = {'name': ents[s]['Attributes'].get('Name', ''),
866
+ 'tag': pxp.get('Tag', '')}
867
+ test_attrs = {k: pxp[k] for k in pxp
868
+ if k.startswith('attributes_') and any(ta in k for ta in cfg['test_attributes'])}
869
+ if test_attrs: entry['test_attributes'] = test_attrs
870
+ out['_parent_chain'].append(entry)
871
+ if sh:
872
+ out['_self_healing'] = [
873
+ {'name': h['name'], 'value': h['value'], 'weight': round(h['weight'], 3)}
874
+ for h in sorted(sh, key=lambda x: -x['weight'])
875
+ ]
876
+ return out
877
+
878
+ def serialize_steps(steps):
879
+ out = []
880
+ for s in steps:
881
+ node = {'type': s['type'], 'name': s.get('name', ''), 'depth': s.get('depth', 0)}
882
+ if s['type'] == 'step':
883
+ node['module'] = s.get('module', '')
884
+ acts = []
885
+ for a in s.get('actions', []):
886
+ if not a['value'] and not a['primary_locator']: continue
887
+ act = {'mode': a['mode'],
888
+ 'element': a['element_name'] or a['action_property'] or '',
889
+ 'value': a['value']}
890
+ if a.get('explicit_name'):
891
+ act['explicit_name'] = a['explicit_name']
892
+ if a['action_property']:
893
+ act['property'] = a['action_property']
894
+ if a['value_resolved'] != a['value']:
895
+ act['value_resolved'] = a['value_resolved']
896
+ if a['primary_locator']:
897
+ locator = {'primary': a['primary_locator']}
898
+ if a['fallback_locator']: locator['fallback'] = a['fallback_locator']
899
+ raw = raw_locator(a.get('attr_sur'))
900
+ if raw: locator['raw'] = raw
901
+ act['locator'] = locator
902
+ if a['notes']: act['notes'] = a['notes']
903
+ if a.get('wait_before'): act['wait_before_ms'] = int(a['wait_before'])
904
+ if a.get('wait_after'): act['wait_after_ms'] = int(a['wait_after'])
905
+ acts.append(act)
906
+ node['actions'] = acts
907
+ elif s['type'] == 'if':
908
+ node['condition'] = s.get('condition', '')
909
+ if s.get('condition_resolved') and s['condition_resolved'] != s.get('condition', ''):
910
+ node['condition_resolved'] = s['condition_resolved']
911
+ elif s['type'] == 'block_start':
912
+ if s.get('parameters'): node['parameters'] = s['parameters']
913
+ out.append(node)
914
+ return out
915
+
916
+ # ──────────────────────────────────────────────────────────────────────────────
917
+ # Spec generation — dispatch-or-log
918
+ # ──────────────────────────────────────────────────────────────────────────────
919
+ # unmapped[] collects every action we couldn't translate, surfaced in both
920
+ # the JSON manifest (meta.unmapped) and as TODO comments in the spec.
921
+ unmapped_actions = []
922
+
923
+ # env_vars_used is at MODULE scope (see top-level definition near
924
+ # _per_tc_pipeline). Multi-TC runs accumulate vars across all cases so
925
+ # the shared playwright-test/.env.example written post-loop covers
926
+ # the union of every spec's needs. Don't reset here.
927
+
928
+ def safe_env(raw_name, hint=''):
929
+ n = re.sub(r'[^A-Z0-9_]', '_', raw_name.upper()).strip('_')
930
+ if n in RESERVED_ENV:
931
+ h = re.sub(r'[^A-Z0-9_]', '_', (hint or 'APP').upper()).strip('_')
932
+ n = (h + '_' + n).lstrip('_')
933
+ env_vars_used.setdefault(n, []).append((raw_name, hint))
934
+ return n
935
+
936
+ # Walk every ParameterReference now, capture CP[*] targets, register them as
937
+ # env vars. parse_tsu's flow only registers CP[*] as it walks XTestStepValues
938
+ # during action emission — but URL-style parameters reach the spec only via
939
+ # RTB ParameterLayer indirection (PL[X] → CP[Y]) and miss that path. Surface
940
+ # them up-front so .env.example is complete.
941
+ for _pref in data['Entities']:
942
+ if _pref['ObjectClass'] != 'ParameterReference': continue
943
+ _val = _pref['Attributes'].get('Value', '') or ''
944
+ for _m in re.finditer(r'\{CP\[([^\]]+)\]\}', _val):
945
+ _cp_name = _m.group(1)
946
+ # Hint: which Parameter (in which RTB) this CP feeds
947
+ _param_surs = _pref.get('Assocs', {}).get('Parameter', [])
948
+ _param_hint = ents.get(_param_surs[0], {}).get('Attributes', {}).get('Name', '') if _param_surs else ''
949
+ safe_env(_cp_name, _param_hint)
950
+
951
+ def loc_expr(primary, fallback):
952
+ if fallback and primary: return f"({primary}).or({fallback})"
953
+ return primary or ''
954
+
955
+ # Existence-style assertion props where appending .first() to a standalone
956
+ # locator is safe — multiple matches just confirm "exists"; .first() avoids
957
+ # strict-mode collisions without changing semantics.
958
+ EXISTENCE_PROPS = {'Visible', 'Hidden', 'Exists', 'Disabled', 'Enabled'}
959
+
960
+ def loc_for_assert(primary, fallback, prop=''):
961
+ """Locator expression for `expect(...).matcher()`: appends .first() when
962
+ the chain has an `.or()` fallback (strict-mode hot zone) OR when the
963
+ matcher is existence-style. Other assertions on standalone locators
964
+ keep their original strictness so multi-match issues surface."""
965
+ base = loc_expr(primary, fallback)
966
+ if not base: return base
967
+ if fallback or prop in EXISTENCE_PROPS:
968
+ return f'{base}.first()'
969
+ return base
970
+
971
+ def loc_for_action(primary, fallback):
972
+ """Locator expression for `.click()/.fill()/.press()`: appends .first()
973
+ when the chain has `.or()`. Bare locators are left strict — if they
974
+ match multiple, the test should fail loudly so the locator gets fixed."""
975
+ base = loc_expr(primary, fallback)
976
+ if not base: return base
977
+ return f'{base}.first()' if fallback else base
978
+
979
+ _KEY_ALIASES = {
980
+ 'CTRL':'Control', 'CONTROL':'Control', 'CMD':'Meta', 'META':'Meta',
981
+ 'WIN':'Meta', 'OPT':'Alt', 'ALT':'Alt', 'SHIFT':'Shift',
982
+ 'DEL':'Delete', 'DELETE':'Delete', 'ESC':'Escape', 'ESCAPE':'Escape',
983
+ 'PGUP':'PageUp', 'PGDN':'PageDown', 'INS':'Insert', 'INSERT':'Insert',
984
+ 'TAB':'Tab', 'ENTER':'Enter', 'RETURN':'Enter', 'SPACE':' ',
985
+ 'BACKSPACE':'Backspace', 'BS':'Backspace',
986
+ 'UP':'ArrowUp', 'DOWN':'ArrowDown', 'LEFT':'ArrowLeft', 'RIGHT':'ArrowRight',
987
+ 'HOME':'Home', 'END':'End',
988
+ }
989
+ def _norm_key(s):
990
+ """Tosca chord 'Ctrl+A' or 'CONTROL+a' → Playwright 'Control+a'."""
991
+ parts = re.split(r'\s*\+\s*', s)
992
+ out = []
993
+ for p in parts:
994
+ u = p.upper()
995
+ if u in _KEY_ALIASES: out.append(_KEY_ALIASES[u])
996
+ elif len(p) == 1: out.append(p.lower())
997
+ else: out.append(p[0].upper() + p[1:].lower())
998
+ return '+'.join(out)
999
+
1000
+ # Recognise concatenated Tosca tokens like:
1001
+ # {click}{sendkeys[{B[X]}]} → click() + fill(X)
1002
+ # {B[X]} {TAB} → fill(X) + press('Tab')
1003
+ # {SENDKEYS[hello]} → fill('hello')
1004
+ # {SENDKEYS["^{a}"]}{SENDKEYS["{DEL}"]}{SENDKEYS[X]} → press Control+a, Delete, fill X
1005
+ _FRAGMENT_RE = re.compile(r'\{([A-Za-z]+)(?:\[([^\]]*)\])?\}|([^{}\s]+)|\s+')
1006
+
1007
+ def _compose_action(val, loc, resolved, catch, action):
1008
+ """Try to decompose a composite Tosca value into a sequence of PW calls.
1009
+ Returns ('emit', [lines]) | ('todo', reason) | None (caller continues).
1010
+ Returns None for plain (non-composite) values so callers handle them."""
1011
+ if not val or not loc: return None
1012
+ # Skip plain singletons — let regular dispatch handle them
1013
+ if TOSCA_REF_RE.match(val) or TOSCA_TOKEN_RE.match(val) or TOSCA_TOKEN_ARG_RE.match(val):
1014
+ return None
1015
+ # Parse over `resolved` when it differs — embedded {B[X]} are pre-expanded,
1016
+ # which avoids regex confusion from nested brackets.
1017
+ src = resolved if (resolved and resolved != val and not resolved.startswith('{B[')
1018
+ and not resolved.startswith('{PL[')) else val
1019
+ parts = []
1020
+ todo_reasons = []
1021
+ for m in _FRAGMENT_RE.finditer(src):
1022
+ tok, arg, lit = m.group(1), m.group(2), m.group(3)
1023
+ if tok:
1024
+ up = tok.upper()
1025
+ if up in CLICK_TOKENS:
1026
+ parts.append(('click', None))
1027
+ elif up in ('SENDKEYS', 'TYPE', 'TEXT', 'TEXTINPUT'):
1028
+ if arg is None: parts.append(('press', 'Backspace')) # rare
1029
+ else:
1030
+ # Inner content may itself contain {B[X]} or {KEYS}
1031
+ inner = arg.strip().strip('"').strip("'")
1032
+ if (mref := TOSCA_REF_RE.match(inner)):
1033
+ kind, name = mref.group(1), mref.group(2)
1034
+ if kind == 'B' and not resolved.startswith('{'):
1035
+ parts.append(('fill', resolved))
1036
+ elif kind == 'PL':
1037
+ parts.append(('fill_env', name))
1038
+ else:
1039
+ todo_reasons.append(f'sendkeys with {kind}[{name}]')
1040
+ parts.append(('comment', f'sendkeys[{inner}]'))
1041
+ elif inner.startswith('^') or inner.startswith('{'):
1042
+ # ^{a} = Ctrl+A, {DEL} = Delete — Tosca shorthand
1043
+ chord = inner.replace('^','Control+').replace('{','').replace('}','')
1044
+ parts.append(('press', _norm_key(chord) if '+' in chord else chord.title()))
1045
+ else:
1046
+ parts.append(('fill', inner))
1047
+ elif up in KEY_TOKENS:
1048
+ parts.append(('press', up.title() if len(up) > 1 else up.lower()))
1049
+ elif up in ('KEYPRESS','KEYDOWN','KEYUP','KEY') and arg:
1050
+ parts.append(('press', _norm_key(arg)))
1051
+ elif up == 'TAB':
1052
+ parts.append(('press', 'Tab'))
1053
+ elif up in ('B','PL','CP','XL'):
1054
+ # {B[X]} matched as a fragment (no surrounding chars). Treat as ref.
1055
+ if up == 'B' and not resolved.startswith('{'):
1056
+ parts.append(('fill', resolved))
1057
+ elif up == 'PL':
1058
+ parts.append(('fill_env', arg))
1059
+ else:
1060
+ todo_reasons.append(f'composite with {up}[{arg}]')
1061
+ parts.append(('comment', f'{up}[{arg}]'))
1062
+ else:
1063
+ todo_reasons.append(f'unknown token {{{up}}}')
1064
+ parts.append(('comment', f'{{{up}{("["+arg+"]") if arg else ""}}}'))
1065
+ elif lit:
1066
+ mref = TOSCA_REF_RE.match(lit)
1067
+ if mref:
1068
+ kind, name = mref.group(1), mref.group(2)
1069
+ if kind == 'B' and not resolved.startswith('{'):
1070
+ parts.append(('fill', resolved))
1071
+ elif kind == 'PL':
1072
+ parts.append(('fill_env', name))
1073
+ else:
1074
+ todo_reasons.append(f'composite with {kind}[{name}]')
1075
+ parts.append(('comment', f'{kind}[{name}]'))
1076
+ else:
1077
+ parts.append(('fill', lit))
1078
+ if not parts: return None
1079
+ # Coalesce {KEYDOWN[X]} … {KEYPRESS[Y]} … {KEYUP[X]} sequences into a chord.
1080
+ # Marker for keydown/keyup: we tagged them as ('press', X). After parse,
1081
+ # a triple where parts[i]=parts[i+2] (modifier) and parts[i+1] is a key,
1082
+ # merges into ('press', f'{X}+{Y}').
1083
+ coalesced = []
1084
+ i = 0
1085
+ while i < len(parts):
1086
+ if (i + 2 < len(parts) and parts[i][0] == 'press' and parts[i+1][0] == 'press'
1087
+ and parts[i+2][0] == 'press' and parts[i][1] == parts[i+2][1]
1088
+ and parts[i][1] in _KEY_ALIASES.values()):
1089
+ coalesced.append(('press', f"{parts[i][1]}+{parts[i+1][1]}"))
1090
+ i += 3
1091
+ else:
1092
+ coalesced.append(parts[i]); i += 1
1093
+ parts = coalesced
1094
+ out = []
1095
+ for kind, arg in parts:
1096
+ if kind == 'click':
1097
+ out.append(f"await {loc}.click(){catch};")
1098
+ elif kind == 'fill':
1099
+ out.append(f"await {loc}.fill({json.dumps(arg)}){catch};")
1100
+ elif kind == 'fill_env':
1101
+ env = safe_env(arg, action.get('element_name', ''))
1102
+ out.append(f"await {loc}.fill(process.env.{env} ?? ''){catch};")
1103
+ elif kind == 'press':
1104
+ out.append(f"await {loc}.press({json.dumps(arg)}){catch};")
1105
+ elif kind == 'comment':
1106
+ out.append(f"// TODO unmapped fragment: {arg}")
1107
+ if todo_reasons and not any(p[0] != 'comment' for p in parts):
1108
+ return ('todo', '; '.join(todo_reasons))
1109
+ return ('emit', out)
1110
+
1111
+ def gen_action_line(action, step_context=''):
1112
+ """Return (line_or_None, unmapped_info_or_None).
1113
+
1114
+ line=None → action intentionally skipped (NULL value, container, etc.)
1115
+ line=str → emitted Playwright code
1116
+ info=dict set → action could not be mapped; line is a TODO comment and
1117
+ the same dict is appended to unmapped_actions for the
1118
+ manifest's meta.unmapped[].
1119
+ """
1120
+ mode = action['mode']
1121
+ prop = action['action_property']
1122
+ val = action['value']
1123
+ resolved = action.get('value_resolved', val)
1124
+ primary = action['primary_locator']; fallback = action['fallback_locator']
1125
+ notes = action['notes']
1126
+ wb, wa = action.get('wait_before', ''), action.get('wait_after', '')
1127
+
1128
+ pfx = ''
1129
+ for note in notes: pfx += f' // NOTE: {note}\n'
1130
+ if wb and wb.isdigit():
1131
+ pfx += f' await page.waitForTimeout({wb}); // WaitBefore\n'
1132
+ sfx = f'\n await page.waitForTimeout({wa}); // WaitAfter' if wa and wa.isdigit() else ''
1133
+ # Two locator forms — assert-side decides .first() based on prop, action-side
1134
+ # always adds .first() when chain has .or() fallback.
1135
+ loc = loc_expr(primary, fallback) # raw, for compose actions etc.
1136
+ loc_act = loc_for_action(primary, fallback)
1137
+ loc_assert = lambda p='': loc_for_assert(primary, fallback, p)
1138
+
1139
+ def line(code): return f"{pfx} {code}{sfx}" if code else None
1140
+ def emit(code): return (line(code), None)
1141
+ def skip(): return (None, None)
1142
+ def todo(reason):
1143
+ info = {
1144
+ 'step': step_context,
1145
+ 'element': action.get('element_name', ''),
1146
+ 'mode': mode,
1147
+ 'property': prop,
1148
+ 'value': val if len(val) <= 200 else val[:200] + '…',
1149
+ 'reason': reason,
1150
+ }
1151
+ unmapped_actions.append(info)
1152
+ return (line(f"// TODO unmapped ({reason}): mode={mode} prop={prop!r} val={val!r}"), info)
1153
+
1154
+ # Token parsing — but only if it isn't a Tosca reference (PL/B/CP/XL)
1155
+ tok_m = None
1156
+ tok = ''
1157
+ tok_arg = None
1158
+ if val and not TOSCA_REF_RE.match(val):
1159
+ if (m := TOSCA_TOKEN_ARG_RE.match(val)) and m.group(1).upper() not in ('PL','B','CP','XL'):
1160
+ tok_m, tok, tok_arg = m, m.group(1).upper(), m.group(2)
1161
+ elif (m := TOSCA_TOKEN_RE.match(val)):
1162
+ tok_m, tok, tok_arg = m, m.group(1).upper(), None
1163
+
1164
+ # ── waitFor (ActionMode 101) ─────────────────────────────────────────────
1165
+ if mode == 'waitFor':
1166
+ if not loc: return skip()
1167
+ if prop in ASSERT_PROPS:
1168
+ true_a, false_a = ASSERT_PROPS[prop]
1169
+ return emit(f"await expect({loc_assert(prop)}).{false_a if val == 'False' else true_a};")
1170
+ if prop == 'Count' and val.isdigit():
1171
+ return emit(f"await expect({loc_assert(prop)}).toHaveCount({val});")
1172
+ if prop == 'Value':
1173
+ target = resolved if not resolved.startswith('{') else val
1174
+ return emit(f"await expect({loc_assert(prop)}).toHaveValue({json.dumps(target)});")
1175
+ if val and val not in ('True', 'False'):
1176
+ target = resolved if not resolved.startswith('{') else val
1177
+ return emit(f"await expect({loc_assert()}).toContainText({json.dumps(target.strip('*'))});")
1178
+ if not val: return skip()
1179
+ return todo('unhandled waitFor property')
1180
+
1181
+ # ── verify (ActionMode 69) ───────────────────────────────────────────────
1182
+ if mode == 'verify':
1183
+ if not loc or not val: return skip()
1184
+ if prop in ASSERT_PROPS:
1185
+ true_a, false_a = ASSERT_PROPS[prop]
1186
+ return emit(f"await expect({loc_assert(prop)}).{false_a if val == 'False' else true_a};")
1187
+ if prop == 'Count' and val.isdigit():
1188
+ return emit(f"await expect({loc_assert(prop)}).toHaveCount({val});")
1189
+ if prop == 'Value':
1190
+ target = resolved if not resolved.startswith('{') else val
1191
+ return emit(f"await expect({loc_assert(prop)}).toHaveValue({json.dumps(target)});")
1192
+ if prop == 'InnerText' or prop == '':
1193
+ target = resolved if not resolved.startswith('{') else val
1194
+ if target.startswith('{'):
1195
+ return todo('verify InnerText with unresolved value')
1196
+ return emit(f"await expect({loc_assert()}).toContainText({json.dumps(target.strip('*'))});")
1197
+ return todo(f'unhandled verify property {prop}')
1198
+
1199
+ # ── set / optionalSet / input ────────────────────────────────────────────
1200
+ if mode in ('set', 'optionalSet', 'input'):
1201
+ catch = '.catch(() => {})' if mode == 'optionalSet' else ''
1202
+ if not val or val == '{NULL}': return skip()
1203
+
1204
+ # Token-based interactions
1205
+ if tok and not tok_arg:
1206
+ if tok in CLICK_TOKENS:
1207
+ call = {'CLICK':'click()', 'DOUBLECLICK':'dblclick()',
1208
+ 'RIGHTCLICK':'click({ button: "right" })',
1209
+ 'CLICKDOWN':'click({ button: "left" })',
1210
+ 'CLICKUP':'click({ button: "left" })'}.get(tok, 'click()')
1211
+ return emit(f"await {loc_act}.{call}{catch};") if loc else skip()
1212
+ if tok == 'HOVER':
1213
+ return emit(f"await {loc_act}.hover(){catch};") if loc else skip()
1214
+ if tok in ('SCROLL','SCROLLTO','SCROLLINTOVIEW'):
1215
+ return emit(f"await {loc_act}.scrollIntoViewIfNeeded(){catch};") if loc else skip()
1216
+ if tok == 'FOCUS':
1217
+ return emit(f"await {loc_act}.focus(){catch};") if loc else skip()
1218
+ if tok == 'BLUR':
1219
+ return emit(f"await {loc_act}.blur(){catch};") if loc else skip()
1220
+ if tok in KEY_TOKENS:
1221
+ key = tok.title() if len(tok) > 1 else tok.lower()
1222
+ return emit(f"await {loc_act}.press({json.dumps(key)}){catch};") if loc else skip()
1223
+ return todo(f'unknown token {{{tok}}}')
1224
+
1225
+ # Token with arg: {KEY[Ctrl+A]}, {SELECT[3]}, {SELECT[Option Name]}
1226
+ if tok and tok_arg:
1227
+ if tok == 'KEY':
1228
+ return emit(f"await {loc_act}.press({json.dumps(_norm_key(tok_arg))}){catch};") if loc else skip()
1229
+ if tok == 'SELECT':
1230
+ if tok_arg.isdigit():
1231
+ return emit(f"await {loc_act}.selectOption({{ index: {int(tok_arg)-1} }}){catch};") if loc else skip()
1232
+ return emit(f"await {loc_act}.selectOption({json.dumps(tok_arg)}){catch};") if loc else skip()
1233
+ if tok == 'WAIT' and tok_arg.isdigit():
1234
+ return emit(f"await page.waitForTimeout({int(tok_arg)});")
1235
+ return todo(f'unknown token {{{tok}[{tok_arg}]}}')
1236
+
1237
+ if not loc: return skip()
1238
+
1239
+ # Tosca reference values
1240
+ m = TOSCA_REF_RE.match(val)
1241
+ if m:
1242
+ kind, name = m.group(1), m.group(2)
1243
+ if kind == 'PL':
1244
+ env = safe_env(name, action.get('element_name', ''))
1245
+ return emit(f"await {loc_act}.fill(process.env.{env} ?? ''){catch};")
1246
+ if kind == 'B':
1247
+ if not resolved.startswith('{'):
1248
+ return emit(f"await {loc_act}.fill({json.dumps(resolved)}){catch};")
1249
+ return todo(f'unresolved buffer reference {val}')
1250
+ if kind == 'CP':
1251
+ env = safe_env(name)
1252
+ return emit(f"await {loc_act}.fill(process.env.{env} ?? ''){catch}; // from CP[{name}]")
1253
+ if kind == 'XL':
1254
+ return todo(f'external-layer reference {val}')
1255
+
1256
+ # Tosca-encrypted credential blob
1257
+ if TOSCA_ENCRYPTED_RE.match(val):
1258
+ env = safe_env(action.get('element_name', '') or 'CREDENTIAL')
1259
+ return emit(f"await {loc_act}.fill(process.env.{env} ?? ''){catch}; // ⚠ Tosca-encrypted")
1260
+
1261
+ # Composite patterns: {click}{sendkeys[…]}, {B[X]} {TAB}, {SENDKEYS[X]}, etc.
1262
+ # Decompose into multiple Playwright calls. Returns combined emit or todo.
1263
+ composite = _compose_action(val, loc_act, resolved, catch, action)
1264
+ if composite is not None:
1265
+ kind, payload = composite
1266
+ if kind == 'emit':
1267
+ return (f"{pfx} " + (f"\n ".join(payload)) + sfx, None)
1268
+ if kind == 'todo':
1269
+ return todo(payload)
1270
+
1271
+ # Generic Tosca expression: {CALC[…]}, {TRIM[…]}, {STRINGREPLACE[…]…}
1272
+ if TOSCA_EXPR_RE.match(val):
1273
+ return todo(f'Tosca expression — needs evaluation')
1274
+
1275
+ # Plain literal
1276
+ if not val.startswith('{'):
1277
+ return emit(f"await {loc_act}.fill({json.dumps(val)}){catch};")
1278
+
1279
+ return todo('value contains unresolved braces')
1280
+
1281
+ # ── bufferRead (ActionMode 165) ──────────────────────────────────────────
1282
+ if mode == 'bufferRead':
1283
+ if not loc: return skip()
1284
+ var = re.sub(r'[^a-zA-Z0-9]', '_', val.lower()).strip('_') if val else 'captured'
1285
+ return (f"{pfx} const {var} = await {loc_act}.textContent() ?? '';", None)
1286
+
1287
+ return todo(f'unknown ActionMode {mode!r}')
1288
+
1289
+ # ── Build spec via state machine ──────────────────────────────────────────────
1290
+ # Run unconditionally so unmapped_actions populates regardless of --playwright.
1291
+ _COND_RE = re.compile(r'^\s*"?([^"]*?)"?\s*(==|!=)\s*"?([^"]*?)"?\s*$')
1292
+ def eval_cond(cond):
1293
+ if not cond: return None
1294
+ m = _COND_RE.match(cond)
1295
+ if not m: return None
1296
+ lhs, op, rhs = m.group(1), m.group(2), m.group(3)
1297
+ if any(c in lhs+rhs for c in '{}'): return None
1298
+ return (lhs == rhs) if op == '==' else (lhs != rhs)
1299
+
1300
+ tc_name = tc['Attributes']['Name']
1301
+ test_name = re.sub(r'\[\d+\]\s*', '', tc_name).strip()
1302
+ spec_lines = [
1303
+ "import { test, expect } from '@playwright/test';",
1304
+ "",
1305
+ "// Auto-generated from Tosca .tsu — generic scaffold.",
1306
+ "// Treat this as a starting point: app-specific helpers (cookie banners,",
1307
+ "// spinners, login flows) are not auto-injected. Add them in this file.",
1308
+ f"// Test case: {tc_name}",
1309
+ f"// Project: {project['Attributes']['Name']} (Revision {tc['Attributes'].get('Revision','')})",
1310
+ "",
1311
+ # Pin the baseURL inside the spec — each .tsu was recorded against a
1312
+ # specific environment (often differs across test cases in the same project).
1313
+ # test.use() overrides the global playwright.config.ts default for this
1314
+ # file only, so the spec is self-contained.
1315
+ f"test.use({{ baseURL: process.env.BASE_URL || {json.dumps(base_url)} }});",
1316
+ "",
1317
+ f"test({json.dumps(test_name)}, async ({{ page }}) => {{",
1318
+ " await page.goto('/');",
1319
+ "",
1320
+ ]
1321
+ if buffer_map:
1322
+ spec_lines.append(" // Test data (resolved from Tosca TBox Set Buffer preconditions)")
1323
+ for k, v in buffer_map.items():
1324
+ spec_lines.append(f" const {re.sub(r'[^a-zA-Z0-9]', '_', k)} = {json.dumps(v)};")
1325
+ spec_lines.append(" void [" + ", ".join(re.sub(r'[^a-zA-Z0-9]', '_', k) for k in buffer_map) + "];")
1326
+ spec_lines.append("")
1327
+
1328
+ depth = 0
1329
+ step_name = None
1330
+ step_body = []
1331
+ elide_stack = []
1332
+
1333
+ def flush():
1334
+ nonlocal step_name, step_body
1335
+ if step_name is None: return
1336
+ if step_body:
1337
+ spec_lines.append(f" await test.step({json.dumps(step_name)}, async () => {{")
1338
+ spec_lines.extend(step_body)
1339
+ spec_lines.append(" });")
1340
+ else:
1341
+ spec_lines.append(f" // [{step_name}] – no Playwright actions generated")
1342
+ spec_lines.append("")
1343
+ step_name = None; step_body = []
1344
+
1345
+ def in_elided_branch(): return any(b == 'SUPPRESS' for b in elide_stack)
1346
+
1347
+ def _mq(s):
1348
+ """Quote a name for embedding in a single-line @tosca marker. Strips
1349
+ newlines, escapes backslashes/double-quotes."""
1350
+ if s is None: return ''
1351
+ return str(s).replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ')
1352
+
1353
+
1354
+ for s in all_steps:
1355
+ t = s['type']; nm = s.get('name', '')
1356
+
1357
+ if t in ('folder','block_start'):
1358
+ depth += 1
1359
+ kind = 'folder' if t == 'folder' else 'block'
1360
+ if depth == 1:
1361
+ flush()
1362
+ step_name = nm
1363
+ step_body = []
1364
+ # Top-level: emitted as await test.step(name, ...). We still drop a
1365
+ # marker so the reverse parser unambiguously knows what kind.
1366
+ step_body.append(f' // @tosca {kind}: "{_mq(nm)}"')
1367
+ if t == 'block_start' and s.get('parameters'):
1368
+ params = ', '.join(f"{k}={v}" for k, v in list(s['parameters'].items())[:5])
1369
+ step_body.append(f" // Block parameters: {params}")
1370
+ elif not in_elided_branch():
1371
+ step_body.append(f' // @tosca {kind}: "{_mq(nm)}"')
1372
+ step_body.append(f" // ── {nm}")
1373
+
1374
+ elif t in ('folder_end','block_end'):
1375
+ kind = 'folder' if t == 'folder_end' else 'block'
1376
+ if depth > 1 and not in_elided_branch():
1377
+ step_body.append(f' // @tosca /{kind}')
1378
+ if depth == 1:
1379
+ step_body.append(f' // @tosca /{kind}')
1380
+ flush()
1381
+ depth = max(0, depth - 1)
1382
+
1383
+ elif t == 'if':
1384
+ cond = s.get('condition_resolved') or s.get('condition','')
1385
+ verdict = eval_cond(cond)
1386
+ if not in_elided_branch():
1387
+ step_body.append(f' // @tosca if: "{_mq(nm)}" cond="{_mq(cond)}"'
1388
+ + (f' verdict={verdict}' if verdict is not None else ''))
1389
+ step_body.append(f" // [if {nm}] condition: {cond}"
1390
+ + (f" → {verdict}" if verdict is not None else ""))
1391
+ elide_stack.append({'verdict': verdict})
1392
+
1393
+ elif t == 'if_end':
1394
+ if elide_stack: elide_stack.pop()
1395
+ if not in_elided_branch():
1396
+ step_body.append(f' // @tosca /if')
1397
+ step_body.append(f" // [end if {nm}]")
1398
+
1399
+ elif t in ('then_start','else_start','loop_start'):
1400
+ branch = t.split('_')[0]
1401
+ if elide_stack and isinstance(elide_stack[-1], dict):
1402
+ verdict = elide_stack[-1]['verdict']
1403
+ if verdict is True and branch == 'else':
1404
+ elide_stack.append('SUPPRESS')
1405
+ elif verdict is False and branch == 'then':
1406
+ elide_stack.append('SUPPRESS')
1407
+ else:
1408
+ elide_stack.append('KEEP')
1409
+ if not in_elided_branch():
1410
+ step_body.append(f' // @tosca {branch}')
1411
+ step_body.append(f" // [{branch.title()}]")
1412
+
1413
+ elif t in ('then_end','else_end','loop_end'):
1414
+ if elide_stack and elide_stack[-1] in ('SUPPRESS','KEEP'):
1415
+ kind = elide_stack[-1]
1416
+ elide_stack.pop()
1417
+ if kind == 'KEEP' and not in_elided_branch():
1418
+ step_body.append(f' // @tosca /branch')
1419
+
1420
+ elif t == 'step' and not in_elided_branch():
1421
+ mod = s.get('module', '')
1422
+ if mod == 'TBox Wait':
1423
+ dur = next((a['value'] for a in s.get('actions', [])
1424
+ if a.get('element_name') == 'Duration' and (a.get('value') or '').isdigit()), None)
1425
+ if dur:
1426
+ step_body.append(f' // @tosca wait: {dur} name="{_mq(nm)}"')
1427
+ step_body.append(f" // TBox Wait: {dur} ms")
1428
+ step_body.append(f" await page.waitForTimeout({dur});")
1429
+ continue
1430
+ if mod in cfg['skip_modules']:
1431
+ # Emit a marker so the reverse parser sees the step (no action lines
1432
+ # — those modules carry framework operations that don't map to
1433
+ # Playwright code anyway).
1434
+ step_body.append(f' // @tosca step: "{_mq(nm)}" module="{_mq(mod)}"')
1435
+ if mod == 'TBox Set Buffer':
1436
+ acts_serial = []
1437
+ for a in s.get('actions', []):
1438
+ en = a.get('explicit_name', '') or ''
1439
+ val = a.get('value', '')
1440
+ if en:
1441
+ acts_serial.append(f'{en}={_mq(val)}')
1442
+ if acts_serial:
1443
+ step_body.append(f' // @tosca buffers: ' + '; '.join(acts_serial))
1444
+ continue
1445
+ step_body.append(f' // @tosca step: "{_mq(nm)}" module="{_mq(mod)}"')
1446
+ step_body.append(f" // {nm}")
1447
+ for a in s.get('actions', []):
1448
+ ln, _info = gen_action_line(a, step_context=nm)
1449
+ if ln: step_body.append(ln)
1450
+
1451
+ flush()
1452
+ spec_lines += ["});", ""]
1453
+
1454
+ # ──────────────────────────────────────────────────────────────────────────────
1455
+ # JSON manifest
1456
+ # ──────────────────────────────────────────────────────────────────────────────
1457
+ if gen_json:
1458
+ manifest = {
1459
+ 'meta': {
1460
+ 'test_name': tc['Attributes']['Name'],
1461
+ 'project': project['Attributes']['Name'],
1462
+ 'revision': tc['Attributes'].get('Revision', ''),
1463
+ 'surrogate': tc['Surrogate'],
1464
+ 'base_url': base_url,
1465
+ 'source_file': tsu_path.name,
1466
+ 'all_urls': sorted(urls),
1467
+ 'config': cfg,
1468
+ 'unmapped': unmapped_actions,
1469
+ },
1470
+ 'test_data': buffer_map,
1471
+ 'steps': serialize_steps(all_steps),
1472
+ }
1473
+ # Multi-TC: per-case JSON named just steps.json inside cases/<tc_stem>/
1474
+ # Single-TC: legacy <stem>_steps.json next to .tsu's out dir.
1475
+ json_path = out_dir / ('steps.json' if multi_tc
1476
+ else (tsu_path.stem + '_steps.json'))
1477
+ json_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
1478
+ print(f"[✓] Steps JSON → {json_path.relative_to(base_out_dir) if multi_tc else json_path.name} ({len(unmapped_actions)} unmapped action(s))")
1479
+
1480
+ # ──────────────────────────────────────────────────────────────────────────────
1481
+ # HTML report
1482
+ # ──────────────────────────────────────────────────────────────────────────────
1483
+ def esc(t): return html_mod.escape(str(t)) if t else ''
1484
+
1485
+ ACTION_INFO = {'verify':('b-verify','Verify'),'set':('b-set','Set'),
1486
+ 'input':('b-input','Input'),'optionalSet':('b-optional','Optional'),
1487
+ 'waitFor':('b-wait','Wait'),'bufferRead':('b-other','Read')}
1488
+ SEVERITY_ORDER = ['dynamic-xpath','angular-class','fragile-parent','long-innertext',
1489
+ 'cdn-src','class-only','generic-heading','custom-tag','custom-parent']
1490
+ BADGE_INFO = {
1491
+ 'dynamic-xpath': ('danger','&#128308; Dynamic XPath'),
1492
+ 'angular-class': ('danger','&#128308; Angular auto-class'),
1493
+ 'fragile-parent': ('danger','&#128308; Fragile parent scope'),
1494
+ 'long-innertext': ('warn', '&#128992; Long InnerText'),
1495
+ 'cdn-src': ('warn', '&#128992; CDN Src URL'),
1496
+ 'class-only': ('warn', '&#128992; Class-only locator'),
1497
+ 'generic-heading':('warn', '&#128992; Generic heading'),
1498
+ 'custom-tag': ('info', '&#128309; Custom web component'),
1499
+ 'custom-parent': ('info', '&#128309; Custom parent scope'),
1500
+ }
1501
+
1502
+ def locator_block(attr_sur):
1503
+ if not attr_sur: return ''
1504
+ xp = xparams(attr_sur); ctx = relative_ctx(attr_sur); sh = self_healing(attr_sur)
1505
+ rows = ''.join('<tr><td class="ln">'+esc(n)+'</td><td class="lv">'+esc(v)+'</td></tr>'
1506
+ for n, v in xp.items() if v)
1507
+ chain = parent_attr_chain(attr_sur)
1508
+ chain_html = ''
1509
+ if chain:
1510
+ chain_html = '<div class="ctx-row">↑ parent: ' + ' &raquo; '.join(
1511
+ '<span class="ctxv">'+esc(ents[s]['Attributes'].get('Name',''))+'</span>'
1512
+ for s in chain if s in ents) + '</div>'
1513
+ sh_rows = ''.join(
1514
+ '<tr><td class="ln">'+esc(h['name'])+'</td><td class="lv">'+esc(h['value'])+'</td>'
1515
+ '<td class="lw">'+str(round(h['weight'], 2))+'</td></tr>'
1516
+ for h in sorted(sh, key=lambda x: -x['weight'])
1517
+ if h['value'] not in ('<No label associated>', ''))
1518
+ out = ''
1519
+ if rows: out += '<table class="lt"><tbody>'+rows+'</tbody></table>'
1520
+ if chain_html: out += chain_html
1521
+ if sh_rows:
1522
+ out += ('<details class="shd"><summary>Self-healing ('+str(len(sh))+')</summary>'
1523
+ '<table class="lt"><thead><tr><th>Property</th><th>Value</th><th>W</th></tr></thead>'
1524
+ '<tbody>'+sh_rows+'</tbody></table></details>')
1525
+ return out or '<span class="no-locs">—</span>'
1526
+
1527
+ def render_steps_html(steps):
1528
+ out = ''
1529
+ for s in steps:
1530
+ t = s['type']
1531
+ if t == 'folder':
1532
+ out += ('<div class="folder"><div class="fhdr"><span>&#128193;</span>'
1533
+ '<span class="fn">'+esc(s['name'])+'</span></div><div class="fb">')
1534
+ elif t == 'folder_end':
1535
+ out += '</div></div>'
1536
+ elif t == 'block_start':
1537
+ param_str = ''
1538
+ if s.get('parameters'):
1539
+ param_str = ' <span class="fb-params">[' + ', '.join(
1540
+ f"{esc(k)}={esc(v)}" for k,v in list(s['parameters'].items())[:4]
1541
+ ) + (']' if len(s['parameters']) <= 4 else ', …]') + '</span>'
1542
+ out += ('<div class="folder fblock"><div class="fhdr"><span>&#128279;</span>'
1543
+ '<span class="fn">'+esc(s['name'])+'</span>'
1544
+ '<span class="fb-badge">reusable block</span>'+param_str+'</div><div class="fb">')
1545
+ elif t == 'block_end':
1546
+ out += '</div></div>'
1547
+ elif t == 'if':
1548
+ cr = s.get('condition_resolved', '')
1549
+ cr_html = '<span class="cf-resolved">→ '+esc(cr)+'</span>' if cr and cr != s.get('condition','') else ''
1550
+ out += ('<div class="folder fcf"><div class="fhdr"><span>&#9881;</span>'
1551
+ '<span class="fn">'+esc(s['name'])+'</span>'
1552
+ '<span class="cf-cond">'+esc(s.get('condition',''))+'</span>'+cr_html+'</div><div class="fb">')
1553
+ elif t == 'if_end':
1554
+ out += '</div></div>'
1555
+ elif t in ('then_start','else_start','loop_start'):
1556
+ out += ('<div class="cf-branch cf-'+t.split('_')[0]+'">'
1557
+ '<div class="cf-branch-hdr">'+esc(s.get('name',t.split('_')[0].title()))+'</div>')
1558
+ elif t in ('then_end','else_end','loop_end'):
1559
+ out += '</div>'
1560
+ elif t == 'step':
1561
+ rows = ''
1562
+ for a in s['actions']:
1563
+ if not a['value']: continue
1564
+ mc, ml = ACTION_INFO.get(a['mode'], ('b-other', a['mode']))
1565
+ attr_n = esc(a['element_name'] or a['action_property'] or '—')
1566
+ val_html = '<span class="svv">'+esc(a['value'])
1567
+ if a['value_resolved'] != a['value']:
1568
+ val_html += '<span class="svr"> → '+esc(a['value_resolved'])+'</span>'
1569
+ val_html += '</span>'
1570
+ pw_html = ''
1571
+ if a['primary_locator']:
1572
+ pw_html = '<div class="pw-loc"><span class="pw-badge">PW</span><code>'+esc(a['primary_locator'])+'</code></div>'
1573
+ if a['fallback_locator']:
1574
+ pw_html += '<div class="pw-loc pw-fb"><span class="pw-badge pw-fb-badge">fallback</span><code>'+esc(a['fallback_locator'])+'</code></div>'
1575
+ for note in a['notes']:
1576
+ pw_html += '<div class="pw-note">'+esc(note)+'</div>'
1577
+ rows += ('<div class="svr"><div class="svh">'
1578
+ '<span class="badge '+mc+'">'+ml+'</span>'
1579
+ '<span class="sva">'+attr_n+'</span>'
1580
+ '<span class="svarrow">&#8594;</span>'+val_html
1581
+ +'</div>'+(('<div class="svl">'+pw_html+'</div>') if pw_html else '')+'</div>')
1582
+ mod_html = ('<span class="sm">'+esc(s['module'])+'</span>') if s['module'] else ''
1583
+ out += ('<div class="step"><div class="step-hdr"><span class="si">&#9654;</span>'
1584
+ '<span class="sn">'+esc(s['name'])+'</span>'+mod_html+'</div>'
1585
+ +(('<div class="step-body">'+rows+'</div>') if rows else '')+'</div>')
1586
+ return out
1587
+
1588
+ # challenge analysis
1589
+ challenges = []
1590
+ for ent in data['Entities']:
1591
+ if ent['ObjectClass'] != 'XModuleAttribute': continue
1592
+ attr_sur = ent['Surrogate']
1593
+ attr_name = ent['Attributes'].get('Name', '')
1594
+ mod = attr_top_module(attr_sur)
1595
+ if not mod: continue
1596
+ mod_name = mod['Attributes'].get('Name', '')
1597
+ xp = xparams(attr_sur); ctx = relative_ctx(attr_sur)
1598
+ tag = xp.get('Tag', ''); id_ = xp.get('Id', ''); cls = xp.get('ClassName', '')
1599
+ inner = xp.get('InnerText', ''); xpath = xp.get('XPath', ''); src = xp.get('Src', '')
1600
+ issues = []
1601
+ has_dtid = any(xp.get(f'attributes_{ta}') for ta in cfg['test_attributes'])
1602
+ if has_dtid: continue # data-test-id elements aren't challenges
1603
+ if tag and tag not in STANDARD_TAGS:
1604
+ issues.append(('custom-tag','Custom web component: <'+tag+'>','Non-standard HTML element.'))
1605
+ ctx_tag = ctx.get('Tag', ''); ctx_inner = ctx.get('InnerText', '')
1606
+ if ctx_tag and ctx_tag not in STANDARD_TAGS:
1607
+ issues.append(('custom-parent','Scoped inside: <'+ctx_tag+'>','Custom parent container.'))
1608
+ if ctx_tag == 'DIV' and ctx_inner:
1609
+ issues.append(('fragile-parent','Parent DIV by InnerText','Sibling text change will break parent scoping.'))
1610
+ if xpath and DYNAMIC_XPATH_RE.search(xpath):
1611
+ issues.append(('dynamic-xpath','Dynamic PrimNG XPath','pn_id_* changes on re-render.'))
1612
+ if cls and ANGULAR_CLASS_RE.search(cls):
1613
+ ng = ANGULAR_CLASS_RE.search(cls).group()
1614
+ issues.append(('angular-class','Angular auto-class: '+ng,'Changes every build.'))
1615
+ if inner and len(inner) > 60 and not id_ and not xpath:
1616
+ issues.append(('long-innertext','Long InnerText locator','Content change breaks this.'))
1617
+ if src and 'kc-usercontent.com' in src:
1618
+ issues.append(('cdn-src','CDN image Src','Asset URL changes on publish.'))
1619
+ if not id_ and not xpath and not src and tag in STANDARD_TAGS and cls and not inner:
1620
+ if not ANGULAR_CLASS_RE.search(cls):
1621
+ issues.append(('class-only','ClassName-only locator','Class may change on framework upgrade.'))
1622
+ if tag in ('H2','H3','H4','H1','H5') and not id_ and not inner and not xpath:
1623
+ issues.append(('generic-heading','Generic <'+tag+'> – no text or ID','Matches first heading in scope.'))
1624
+ if issues:
1625
+ challenges.append({'module':mod_name,'element':attr_name,'tag':tag,'id':id_,
1626
+ 'cls':cls,'inner':inner,'xpath':xpath,'ctx':ctx,'issues':issues})
1627
+
1628
+ def sev(c):
1629
+ codes = [i[0] for i in c['issues']]
1630
+ return min((SEVERITY_ORDER.index(cd) if cd in SEVERITY_ORDER else 99) for cd in codes)
1631
+ challenges.sort(key=sev)
1632
+ type_counts = Counter(i[0] for c in challenges for i in c['issues'])
1633
+ summary_chips = ''.join('<span class="summary-chip">'+BADGE_INFO.get(code,('','&#x26A0; '+code))[1]+' &times; '+str(cnt)+'</span>'
1634
+ for code, cnt in sorted(type_counts.items(), key=lambda x: -x[1]))
1635
+
1636
+ challenges_html = ''
1637
+ for c in challenges:
1638
+ locs = []
1639
+ if c['tag']: locs.append('tag=<b>'+esc(c['tag'])+'</b>')
1640
+ if c['id']: locs.append('id=<b>'+esc(c['id'])+'</b>')
1641
+ if c['xpath']: locs.append('xpath=<b>'+esc(c['xpath'][:60])+'</b>')
1642
+ if c['inner']: locs.append('text=<b>'+esc(c['inner'][:60])+('...' if len(c['inner'])>60 else '')+'</b>')
1643
+ if c['cls']: locs.append('class=<b>'+esc(c['cls'][:70])+('...' if len(c['cls'])>70 else '')+'</b>')
1644
+ ctx_parts = ' '.join('<span class="ctxk">'+esc(k)+'</span>=<span class="ctxv">'+esc(v)+'</span>' for k,v in c['ctx'].items())
1645
+ iss_html = ''.join('<div class="issue issue-'+BADGE_INFO.get(i[0],('info',''))[0]+'">'
1646
+ '<div class="issue-label">'+BADGE_INFO.get(i[0],('','⚠'))[1]+'</div>'
1647
+ '<div class="issue-short">'+esc(i[1])+'</div>'
1648
+ '<div class="issue-detail">'+esc(i[2])+'</div></div>' for i in c['issues'])
1649
+ challenges_html += ('<div class="chal-card"><div class="chal-header">'
1650
+ '<div class="chal-mod">'+esc(c['module'])+'</div>'
1651
+ '<div class="chal-elem">'+esc(c['element'])+'</div>'
1652
+ '<div class="chal-locs">'+' | '.join(locs)+'</div>'
1653
+ +(('<div class="chal-ctx">Parent: '+ctx_parts+'</div>') if ctx_parts else '')
1654
+ +'</div><div class="chal-issues">'+iss_html+'</div></div>')
1655
+
1656
+ def render_modules_html():
1657
+ out = []
1658
+ for ent in data['Entities']:
1659
+ if ent['ObjectClass'] != 'XModule': continue
1660
+ # Per-TC filter: only show modules this case actually uses.
1661
+ if ent['Surrogate'] not in tc_set: continue
1662
+ mn = ent['Attributes'].get('Name', '')
1663
+ itype = {'0':'Action','1':'HTML'}.get(str(ent['Attributes'].get('InterfaceType', '')), '')
1664
+ attrs = module_attrs.get(ent['Surrogate'], [])
1665
+ elems = ''.join('<div class="ec"><div class="en">'+esc(a['Attributes'].get('Name',''))+'</div>'
1666
+ '<div class="el">'+locator_block(a['Surrogate'])+'</div></div>' for a in attrs)
1667
+ out.append('<div class="mc"><div class="mhdr"><span class="mn">'+esc(mn)+'</span>'
1668
+ '<span class="mb">'+esc(itype)+'</span></div>'
1669
+ '<div class="mb2">'+(elems or '<div class="empty">No elements</div>')+'</div></div>')
1670
+ return ''.join(out)
1671
+
1672
+ params_html = ''
1673
+ seen = set()
1674
+ for ent in data['Entities']:
1675
+ if ent['ObjectClass'] != 'Parameter': continue
1676
+ nm = ent['Attributes'].get('Name', ''); dv = ent['Attributes'].get('DefaultValue', '')
1677
+ if nm in seen: continue
1678
+ seen.add(nm)
1679
+ params_html += '<span class="pill"><span class="pk">'+esc(nm)+'</span><span class="pv">'+(esc(dv) or '&mdash;')+'</span></span>'
1680
+ urls_html = ''.join('<a class="up" href="'+esc(u)+'" target="_blank">'+esc(u)+'</a>' for u in sorted(urls))
1681
+
1682
+ CSS = """
1683
+ :root{--bg:#0f1117;--s1:#1a1d26;--s2:#22263a;--bd:#2e3350;--ac:#5b8dee;--gn:#3ecf8e;--or:#f7a23a;--rd:#e05252;--pu:#9b6dff;--tx:#d0d4e8;--mu:#7a80a0;--co:#a8b4e8;--r:8px}
1684
+ *{box-sizing:border-box;margin:0;padding:0}
1685
+ body{background:var(--bg);color:var(--tx);font-family:"Inter","Segoe UI",sans-serif;font-size:13px;line-height:1.6}
1686
+ a{color:var(--ac);text-decoration:none}a:hover{text-decoration:underline}
1687
+ .ph{background:linear-gradient(135deg,#1a1d26,#12162b);border-bottom:1px solid var(--bd);padding:24px 32px}
1688
+ .pl{font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--mu);margin-bottom:4px}
1689
+ .pt{font-size:20px;font-weight:700;color:#fff;margin-bottom:8px}
1690
+ .pm{display:flex;gap:14px;flex-wrap:wrap}.pmi{font-size:11px;color:var(--mu)}.pmi strong{color:var(--tx)}
1691
+ .nav{display:flex;background:var(--s2);border-bottom:1px solid var(--bd);padding:0 32px}
1692
+ .nav a{padding:12px 18px;font-size:12px;color:var(--mu);border-bottom:3px solid transparent;display:block}
1693
+ .nav a:hover{color:var(--tx);text-decoration:none}.nav a.active{color:var(--ac);border-color:var(--ac)}
1694
+ .wrap{max-width:1280px;margin:0 auto;padding:24px 32px}
1695
+ .tab-panel{display:none}.tab-panel.active{display:block}
1696
+ .sec{margin-bottom:32px}
1697
+ .st{font-size:11px;text-transform:uppercase;letter-spacing:.1em;color:var(--mu);border-bottom:1px solid var(--bd);padding-bottom:7px;margin-bottom:14px}
1698
+ .pill{display:inline-flex;align-items:center;gap:6px;background:var(--s2);border:1px solid var(--bd);border-radius:16px;padding:4px 12px;margin:0 6px 6px 0}
1699
+ .pk{color:var(--ac);font-weight:600}.pv{color:var(--mu);font-size:11px}
1700
+ .up{display:block;background:var(--s1);border:1px solid var(--bd);border-radius:var(--r);padding:6px 12px;margin-bottom:5px;font-family:monospace;font-size:12px;color:var(--co)}
1701
+ .up:hover{border-color:var(--ac)}
1702
+ .summary-chips{margin-bottom:18px;display:flex;flex-wrap:wrap;gap:8px}
1703
+ .summary-chip{font-size:12px;padding:4px 12px;background:var(--s2);border:1px solid var(--bd);border-radius:16px;color:var(--tx)}
1704
+ .chal-card{background:var(--s1);border:1px solid var(--bd);border-radius:var(--r);margin-bottom:12px;overflow:hidden}
1705
+ .chal-header{background:var(--s2);padding:10px 14px;border-bottom:1px solid var(--bd)}
1706
+ .chal-mod{font-size:11px;color:var(--mu);margin-bottom:2px}
1707
+ .chal-elem{font-size:14px;font-weight:700;color:#fff;margin-bottom:4px}
1708
+ .chal-locs{font-family:monospace;font-size:11px;color:var(--co)}.chal-locs b{color:#fff}
1709
+ .chal-ctx{font-size:11px;color:var(--mu);margin-top:2px}.ctxk{color:var(--mu)}.ctxv{color:var(--or)}
1710
+ .chal-issues{padding:10px 14px;display:flex;flex-direction:column;gap:8px}
1711
+ .issue{border-radius:6px;padding:8px 12px}.issue-label{font-weight:700;font-size:12px;margin-bottom:3px}
1712
+ .issue-short{font-weight:600;font-size:12px;color:#fff;margin-bottom:2px}.issue-detail{font-size:12px;color:var(--mu)}
1713
+ .issue-danger{background:#2a1a1a;border:1px solid #5a2a2a}.issue-danger .issue-label{color:var(--rd)}
1714
+ .issue-warn{background:#2a2410;border:1px solid #5a4a10}.issue-warn .issue-label{color:var(--or)}
1715
+ .issue-info{background:#1a1a2a;border:1px solid #2a2a4a}.issue-info .issue-label{color:var(--ac)}
1716
+ .folder{border:1px solid var(--bd);border-radius:var(--r);margin-bottom:8px;overflow:hidden}
1717
+ .fhdr{background:var(--s2);padding:9px 13px;display:flex;align-items:center;gap:8px;font-weight:600;color:#fff}
1718
+ .fn{flex:1}.fc{font-size:11px;color:var(--mu);background:var(--bd);padding:1px 8px;border-radius:10px}
1719
+ .fb{padding:10px 13px;background:var(--s1)}
1720
+ .fblock .fhdr{background:#162030;border-left:3px solid var(--ac)}
1721
+ .fcf .fhdr{background:#1f1830;border-left:3px solid var(--pu)}
1722
+ .fb-badge{font-size:10px;color:var(--ac);background:#0f1e2e;border:1px solid #1a3050;padding:1px 7px;border-radius:10px}
1723
+ .fb-params{font-size:10px;color:var(--mu);font-family:monospace}
1724
+ .cf-cond{font-size:11px;color:var(--or);font-family:monospace;background:#241a10;padding:1px 6px;border-radius:4px}
1725
+ .cf-resolved{font-size:11px;color:var(--gn);font-family:monospace}
1726
+ .cf-branch{margin:6px 0;border-left:2px solid #2a2a4a;padding-left:10px}
1727
+ .cf-branch-hdr{font-size:10px;text-transform:uppercase;letter-spacing:.1em;color:var(--mu);margin-bottom:4px}
1728
+ .cf-then{border-color:var(--gn)}.cf-then .cf-branch-hdr{color:var(--gn)}
1729
+ .cf-else{border-color:var(--rd)}.cf-else .cf-branch-hdr{color:var(--rd)}
1730
+ .cf-loop{border-color:var(--or)}.cf-loop .cf-branch-hdr{color:var(--or)}
1731
+ .empty{color:var(--mu);font-style:italic;font-size:12px}
1732
+ .step{background:var(--s1);border:1px solid var(--bd);border-radius:var(--r);margin-bottom:7px;overflow:hidden}
1733
+ .step-hdr{padding:8px 12px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;background:var(--s2)}
1734
+ .si{color:var(--ac);font-size:11px}.sn{font-weight:600;color:#fff;flex:1}
1735
+ .sm{font-size:11px;color:var(--mu);background:var(--s1);border:1px solid var(--bd);padding:1px 7px;border-radius:4px;max-width:320px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1736
+ .step-body{padding:9px 12px}
1737
+ .svr{margin-bottom:8px;border:1px solid var(--bd);border-radius:6px;overflow:hidden}
1738
+ .svh{display:flex;align-items:center;gap:7px;padding:6px 10px;background:var(--s2);flex-wrap:wrap}
1739
+ .sva{font-weight:600;color:var(--co)}.svarrow{color:var(--mu)}
1740
+ .svv{font-family:monospace;color:#fff;background:var(--bg);padding:1px 6px;border-radius:4px}
1741
+ .svv .svr{color:var(--gn)}
1742
+ .svl{padding:7px 10px}
1743
+ .badge{font-size:11px;padding:2px 8px;border-radius:12px;font-weight:600;white-space:nowrap}
1744
+ .b-verify{background:#1a3a2a;color:var(--gn);border:1px solid #2a5a3a}
1745
+ .b-set{background:#2a2a0a;color:var(--or);border:1px solid #4a4a1a}
1746
+ .b-input{background:#1a1a3a;color:var(--ac);border:1px solid #2a2a5a}
1747
+ .b-optional{background:#2a1a3a;color:var(--pu);border:1px solid #4a2a5a}
1748
+ .b-wait{background:#2a1a3a;color:var(--pu);border:1px solid #4a2a5a}
1749
+ .b-other{background:var(--s2);color:var(--mu);border:1px solid var(--bd)}
1750
+ .lt{width:100%;border-collapse:collapse;font-size:12px;margin-bottom:3px}
1751
+ .lt td,.lt th{padding:4px 8px;border-top:1px solid var(--bd);vertical-align:top;text-align:left}
1752
+ .lt thead tr{background:#1e2038}.lt th{font-size:10px;text-transform:uppercase;letter-spacing:.05em;color:var(--mu);font-weight:600}
1753
+ .ln{color:var(--ac);font-family:monospace;width:160px;white-space:nowrap}
1754
+ .lv{color:var(--tx);font-family:monospace;word-break:break-all}
1755
+ .lw{color:var(--mu);width:44px;text-align:right;font-size:11px}
1756
+ .no-locs{color:var(--mu);font-style:italic;font-size:12px}
1757
+ .ctx-row{font-size:11px;color:var(--mu);padding:4px 2px;margin-top:3px}
1758
+ .shd{margin-top:4px}.shd summary{font-size:11px;color:var(--mu);cursor:pointer;padding:3px}.shd summary:hover{color:var(--tx)}
1759
+ .pw-loc{font-size:11px;font-family:monospace;padding:3px 4px;display:flex;align-items:flex-start;gap:6px;margin-bottom:3px}
1760
+ .pw-badge{background:#1a2a4a;color:var(--ac);border:1px solid #2a3a6a;padding:1px 5px;border-radius:4px;font-size:10px;white-space:nowrap;flex-shrink:0}
1761
+ .pw-fb .pw-fb-badge{background:#2a1a3a;color:var(--pu);border-color:#4a2a5a}
1762
+ .pw-loc code{color:var(--co);word-break:break-all}
1763
+ .pw-note{font-size:11px;color:var(--or);padding:3px 4px}
1764
+ .mg{display:grid;grid-template-columns:repeat(auto-fill,minmax(500px,1fr));gap:16px}
1765
+ .mc{background:var(--s1);border:1px solid var(--bd);border-radius:var(--r);overflow:hidden}
1766
+ .mhdr{background:linear-gradient(90deg,#1e2040,#1a1d26);padding:10px 13px;display:flex;align-items:center;gap:8px;border-bottom:1px solid var(--bd)}
1767
+ .mn{font-weight:700;color:#fff;flex:1}.mb{font-size:11px;padding:2px 7px;border-radius:12px;background:var(--s2);color:var(--mu);border:1px solid var(--bd)}
1768
+ .mb2{padding:10px 13px}
1769
+ .ec{border:1px solid var(--bd);border-radius:6px;margin-bottom:8px;overflow:hidden}
1770
+ .en{background:var(--s2);padding:6px 10px;font-weight:600;color:var(--ac);font-size:12px;border-bottom:1px solid var(--bd)}
1771
+ .el{padding:7px 10px}
1772
+ """
1773
+
1774
+ flow_html = render_steps_html(all_steps)
1775
+ HTML = ('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">'
1776
+ '<title>Tosca – '+esc(tc["Attributes"]["Name"])+'</title>'
1777
+ '<style>'+CSS+'</style></head><body>'
1778
+ '<div class="ph">'
1779
+ ' <div class="pl">Tosca &middot; '+esc(project["Attributes"]["Name"])+'</div>'
1780
+ ' <div class="pt">'+esc(tc["Attributes"]["Name"])+'</div>'
1781
+ ' <div class="pm">'
1782
+ ' <div class="pmi">Revision <strong>'+esc(tc["Attributes"].get("Revision",""))+'</strong></div>'
1783
+ ' <div class="pmi" style="font-family:monospace;font-size:11px">'+esc(tc["Surrogate"])+'</div>'
1784
+ ' </div>'
1785
+ '</div>'
1786
+ '<nav class="nav">'
1787
+ ' <a href="#" class="active" onclick="showTab(\'challenges\',this);return false">&#9888; Locator Challenges ('+str(len(challenges))+')</a>'
1788
+ ' <a href="#" onclick="showTab(\'flow\',this);return false">&#9654; Execution Flow + Playwright Locators</a>'
1789
+ ' <a href="#" onclick="showTab(\'modules\',this);return false">&#129513; Module Catalogue</a>'
1790
+ ' <a href="#" onclick="showTab(\'meta\',this);return false">&#8505; Meta</a>'
1791
+ '</nav>'
1792
+ '<div class="wrap">'
1793
+ ' <div id="tab-challenges" class="tab-panel active">'
1794
+ ' <div class="sec"><div class="st">Locator Risk Analysis</div>'
1795
+ ' <div class="summary-chips">'+summary_chips+'</div>'
1796
+ ' '+challenges_html+''
1797
+ ' </div>'
1798
+ ' </div>'
1799
+ ' <div id="tab-flow" class="tab-panel">'
1800
+ ' <div class="sec"><div class="st">Execution Flow</div>'+flow_html+'</div>'
1801
+ ' </div>'
1802
+ ' <div id="tab-modules" class="tab-panel">'
1803
+ ' <div class="sec"><div class="st">Module Catalogue</div>'
1804
+ ' <div class="mg">'+render_modules_html()+'</div>'
1805
+ ' </div>'
1806
+ ' </div>'
1807
+ ' <div id="tab-meta" class="tab-panel">'
1808
+ ' <div class="sec"><div class="st">Parameters</div>'+params_html+'</div>'
1809
+ ' <div class="sec"><div class="st">URLs</div>'+urls_html+'</div>'
1810
+ ' </div>'
1811
+ '</div>'
1812
+ '<script>'
1813
+ 'function showTab(id,el){'
1814
+ ' document.querySelectorAll(\'.tab-panel\').forEach(p=>p.classList.remove(\'active\'));'
1815
+ ' document.querySelectorAll(\'.nav a\').forEach(a=>a.classList.remove(\'active\'));'
1816
+ ' document.getElementById(\'tab-\'+id).classList.add(\'active\');'
1817
+ ' el.classList.add(\'active\');'
1818
+ '}'
1819
+ '</script></body></html>')
1820
+ report_path = out_dir / ('report.html' if multi_tc
1821
+ else (tsu_path.stem + '_report.html'))
1822
+ report_path.write_text(HTML, encoding='utf-8')
1823
+ print(f"[✓] HTML report → {report_path.relative_to(base_out_dir) if multi_tc else report_path.name}")
1824
+
1825
+ # ──────────────────────────────────────────────────────────────────────────────
1826
+ # Playwright scaffold (mechanical; uses control-flow walking, no app helpers)
1827
+ # ──────────────────────────────────────────────────────────────────────────────
1828
+ if not gen_pw:
1829
+ print(" (add --playwright to also generate Playwright project files)")
1830
+ return # Per-TC pipeline done; let the dispatch loop continue with next TC
1831
+
1832
+ # Multi-TC: pw_dir is shared across cases (pw_root, set at top of function);
1833
+ # tests live in tests/<area>/<tc>.spec.ts. Single-TC: pw_dir = out_dir/playwright-test.
1834
+ pw_dir = pw_root
1835
+ (pw_dir / 'tests').mkdir(parents=True, exist_ok=True)
1836
+ (pw_dir / 'pages').mkdir(parents=True, exist_ok=True)
1837
+
1838
+ def to_camel(s): return re.sub(r'[^a-zA-Z0-9]', ' ', s).title().replace(' ', '')
1839
+ def to_snake(s):
1840
+ s = re.sub(r'[^a-zA-Z0-9]+', '_', s).strip('_').lower()
1841
+ return re.sub(r'_+', '_', s)
1842
+
1843
+ # Generate page object per module
1844
+ page_object_files = {}
1845
+ for ent in data['Entities']:
1846
+ if ent['ObjectClass'] != 'XModule': continue
1847
+ # Per-TC filtering: skip XModules this TC doesn't actually use.
1848
+ # tc_set is the transitive closure built earlier; for multi-TC mode
1849
+ # this trims each case's pages/ to only the modules it touches.
1850
+ if ent['Surrogate'] not in tc_set: continue
1851
+ mod_name = ent['Attributes'].get('Name', '')
1852
+ if not mod_name or mod_name in cfg['skip_modules']: continue
1853
+ elem_locs = {}
1854
+ for attr in module_attrs.get(ent['Surrogate'], []):
1855
+ attr_name = attr['Attributes'].get('Name', '')
1856
+ p, fb, notes = build_locator(attr['Surrogate'])
1857
+ if p: elem_locs[attr_name] = (p, fb, notes)
1858
+ if not elem_locs: continue
1859
+ class_name = to_camel(mod_name) + 'Page'
1860
+ lines = ["import { type Page, type Locator } from '@playwright/test';", "",
1861
+ f"export class {class_name} {{", " readonly page: Page;", ""]
1862
+ seen_props = set()
1863
+ for elem_name in elem_locs:
1864
+ prop = to_snake(elem_name)
1865
+ if not prop or prop in seen_props: continue
1866
+ seen_props.add(prop)
1867
+ lines.append(f" readonly {prop}: Locator;")
1868
+ lines += ["", f" constructor(page: Page) {{", " this.page = page;"]
1869
+ seen_props = set()
1870
+ for elem_name, (primary, fallback, notes) in elem_locs.items():
1871
+ prop = to_snake(elem_name)
1872
+ if not prop or prop in seen_props: continue
1873
+ seen_props.add(prop)
1874
+ for note in notes: lines.append(f" // NOTE: {note}")
1875
+ if fallback:
1876
+ lines.append(f" this.{prop} = {primary}")
1877
+ lines.append(f" .or({fallback});")
1878
+ else:
1879
+ lines.append(f" this.{prop} = {primary};")
1880
+ lines += [" }", "}", ""]
1881
+ fname = to_snake(mod_name) + '.page.ts'
1882
+ page_object_files[mod_name] = (fname, class_name, '\n'.join(lines))
1883
+
1884
+ for mod_name, (fname, cls_name, content) in page_object_files.items():
1885
+ fpath = pw_dir / 'pages' / fname
1886
+ if not fpath.exists() or force:
1887
+ fpath.write_text(content, encoding='utf-8')
1888
+ print(f"[✓] Page object → {fpath.name} ({cls_name})")
1889
+
1890
+ # playwright.config.ts — baseURL is env-overridable; per-spec test.use({baseURL})
1891
+ # overrides this default for individual specs (each .tsu pins its own URL).
1892
+ config_content = f"""import {{ defineConfig, devices }} from '@playwright/test';
1893
+ import 'dotenv/config';
1894
+
1895
+ export default defineConfig({{
1896
+ testDir: './tests',
1897
+ fullyParallel: true,
1898
+ timeout: 300_000,
1899
+ reporter: 'html',
1900
+ use: {{
1901
+ baseURL: process.env.BASE_URL || '{base_url}',
1902
+ screenshot: 'only-on-failure',
1903
+ video: 'on',
1904
+ trace: 'on-first-retry',
1905
+ }},
1906
+ projects: [{{ name: 'chromium', use: {{ ...devices['Desktop Chrome'] }} }}],
1907
+ }});
1908
+ """
1909
+ # config + package + .env.example: written ONCE for multi-TC (after the
1910
+ # dispatch loop, by _write_shared_pw_artifacts) so they reflect the union
1911
+ # across all cases. For single-TC, write here as before.
1912
+ if not multi_tc:
1913
+ config_path = pw_dir / 'playwright.config.ts'
1914
+ if not config_path.exists() or force:
1915
+ config_path.write_text(config_content)
1916
+ print(f"[✓] Config → playwright.config.ts (baseURL: {base_url})")
1917
+ else:
1918
+ print(f"[~] Config → playwright.config.ts (skipped – use --force to overwrite)")
1919
+
1920
+ # .env.example — list every env var the generated spec references.
1921
+ env_example_path = pw_dir / '.env.example'
1922
+ env_lines = _build_env_lines(base_url, env_vars_used)
1923
+ if not env_example_path.exists() or force:
1924
+ env_example_path.write_text("\n".join(env_lines))
1925
+ print(f"[✓] Env template → .env.example ({len(env_vars_used)} vars)")
1926
+ else:
1927
+ print(f"[~] Env template → .env.example (skipped – use --force to overwrite)")
1928
+
1929
+ pkg_path = pw_dir / 'package.json'
1930
+ if not pkg_path.exists() or force:
1931
+ pkg_path.write_text(_PACKAGE_JSON)
1932
+
1933
+ # Spec — multi-TC: pw_dir/tests/<area>/<tc_stem>.spec.ts; single-TC: legacy name.
1934
+ if multi_tc:
1935
+ spec_path = pw_dir / 'tests' / area / (_tc_stem(tc) + '.spec.ts') if area \
1936
+ else pw_dir / 'tests' / (_tc_stem(tc) + '.spec.ts')
1937
+ spec_path.parent.mkdir(parents=True, exist_ok=True)
1938
+ else:
1939
+ spec_path = pw_dir / 'tests' / (to_snake(test_name) + '.spec.ts')
1940
+ if not spec_path.exists() or force:
1941
+ spec_path.write_text('\n'.join(spec_lines), encoding='utf-8')
1942
+ rel = spec_path.relative_to(base_out_dir) if multi_tc else spec_path.name
1943
+ print(f"[✓] Test spec → {rel} ({len(unmapped_actions)} TODO unmapped)")
1944
+ else:
1945
+ print(f"[~] Test spec → {spec_path.name} (skipped – use --force to overwrite)")
1946
+
1947
+ print(f"\nSetup:")
1948
+ print(f" cd {pw_dir}")
1949
+ print(f" npm install")
1950
+ print(f" npx playwright install chromium")
1951
+ print(f" npm test")
1952
+
1953
+
1954
+ # ──────────────────────────────────────────────────────────────────────────────
1955
+ # Multi-TC dispatch: discover all TestCases, run the per-TC pipeline for each.
1956
+ # Single-TC .tsu keeps the original output layout (base_out_dir/...).
1957
+ # Multi-TC .tsu writes per-case isolated outputs under base_out_dir/<tc_stem>/.
1958
+ # ──────────────────────────────────────────────────────────────────────────────
1959
+ _test_cases = [x for x in data['Entities'] if x['ObjectClass'] == 'TestCase']
1960
+ _project = next((x for x in data['Entities'] if x['ObjectClass'] == 'TCProject'), None)
1961
+ if not _test_cases:
1962
+ sys.exit('error: no TestCase entity found in .tsu')
1963
+ if _project is None:
1964
+ sys.exit('error: no TCProject entity found in .tsu')
1965
+
1966
+ _multi = len(_test_cases) > 1
1967
+ _base = out_dir
1968
+ if _multi:
1969
+ print(f'[i] {len(_test_cases)} test cases — shared playwright project under {_base}/playwright-test/, '
1970
+ f'per-case JSON+HTML under {_base}/cases/<tc_stem>/')
1971
+ for _tc in _test_cases:
1972
+ _per_tc_pipeline(_tc, _project, _base, _multi)
1973
+
1974
+ # Multi-TC post-pass: write shared playwright artifacts (config + package +
1975
+ # union .env.example) once. Single-TC handled them inside the per-TC pipeline.
1976
+ if _multi and gen_pw:
1977
+ _write_shared_pw_artifacts(_base / 'playwright-test', _last_base_url, force)
1978
+ if _multi:
1979
+ print(f'[✓] All {len(_test_cases)} test cases emitted.')