@capagents/forgeqe 2.7.1 → 2.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOW_TO_USE.md +82 -18
- package/THIRD_PARTY_NOTICES.md +62 -22
- package/bin/forgeqe.js +1 -1
- package/dist/docs-site/docs/architecture/index.html +1 -1
- package/dist/docs-site/docs/containers/index.html +1 -1
- package/dist/docs-site/docs/index.html +71 -2
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +1775 -1520
- package/dist/web/THIRD_PARTY_NOTICES.md +578 -51
- package/dist/web/assets/Agent-DU51Em-3.js +4 -0
- package/dist/web/assets/ApiTests-D6YhbfPF.js +10 -0
- package/dist/web/assets/Chat-CQsQvyDs.js +3 -0
- package/dist/web/assets/Data-Djj0u25X.js +3 -0
- package/dist/web/assets/Evidence-R2GZ5yW9.js +1 -0
- package/dist/web/assets/Features-C1qvr-oy.js +1 -0
- package/dist/web/assets/Jobs-BOr2nkQa.js +5 -0
- package/dist/web/assets/KindPage-CB2gMzhI.js +6 -0
- package/dist/web/assets/Migration-71lvv1zU.js +2 -0
- package/dist/web/assets/Product-BAQtMlzO.js +7 -0
- package/dist/web/assets/Product-DLioOiRN.css +1 -0
- package/dist/web/assets/Quality-DeUvoOND.js +1 -0
- package/dist/web/assets/Record-CPjgxHRX.js +2 -0
- package/dist/web/assets/Regression-D8V0CNAw.js +5 -0
- package/dist/web/assets/Reports-Bhv6gqFl.js +2 -0
- package/dist/web/assets/Response-CXyWQxrt.js +4 -0
- package/dist/web/assets/Runs-Ba8X4nId.js +2 -0
- package/dist/web/assets/Shell-BoXDubsc.js +3 -0
- package/dist/web/assets/TestCases-DEciDMh1.js +1 -0
- package/dist/web/assets/TestData-DY6MVYdx.js +2 -0
- package/dist/web/assets/Tosca-BzNnPm0_.js +2 -0
- package/dist/web/assets/WhatsNew-7O1MlqCy.js +1 -0
- package/dist/web/assets/dataParts-0a9Sjn2u.js +3 -0
- package/dist/web/assets/index-C9TchKsF.css +2 -0
- package/dist/web/assets/index-DcmN4YB2.js +43 -0
- package/dist/web/assets/logos-BnPN8M-S.js +1 -0
- package/dist/web/assets/parts-mP2z3tbH.js +1 -0
- package/dist/web/assets/productParts-B2wO-b1i.js +1 -0
- package/dist/web/assets/qualityParts-ByR8_rNE.js +1 -0
- package/dist/web/assets/segmented-BZcnZadS.js +1 -0
- package/dist/web/assets/{thread-CHhZJi-Y.js → thread-DLf1W085.js} +2 -2
- package/dist/web/assets/usePageChat-lpZh_ziF.js +1 -0
- package/dist/web/index.html +3 -3
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/CONTAINERS.md +1 -1
- package/docs/EVIDENCE.md +9 -4
- package/docs/GRAPHIFY.md +178 -0
- package/docs/PRODUCT_KNOWLEDGE.md +25 -4
- package/docs/PRODUCT_VIEWS.md +5 -2
- package/docs/prompts/graphify-evidence.md +167 -0
- package/docs/user-guide.html +71 -2
- package/evals/evidence/domain/base/orders-api/src/report.ts +4 -0
- package/evals/evidence/domain/base/orders-api/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-function-removed/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/bad-function-removed/case.json +14 -0
- package/evals/evidence/domain/cases/bad-signature-changed/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/bad-signature-changed/case.json +14 -0
- package/evals/evidence/domain/cases/bad-state-set-directly/after/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-untested-change/after/src/routes/admin.ts +2 -1
- package/evals/evidence/domain/cases/bad-untested-helper/after/src/report.ts +4 -0
- package/evals/evidence/domain/cases/bad-untested-helper/case.json +14 -0
- package/evals/evidence/domain/cases/good-optional-parameter/after/src/workflow.ts +6 -0
- package/evals/evidence/domain/cases/good-optional-parameter/case.json +12 -0
- package/evals/evidence/domain/cases/good-tested-helper/after/src/clients/payments.ts +8 -0
- package/evals/evidence/domain/cases/good-tested-helper/case.json +12 -0
- package/forgeqe.example.yaml +14 -1
- package/package.json +17 -14
- package/prompts/README.md +1 -0
- package/prompts/product-investigate.md +1 -1
- package/prompts/tosca.md +64 -0
- package/py/forgeqe_desktop/models.py +14 -5
- package/py/forgeqe_engine/__init__.py +1 -1
- package/py/forgeqe_knowledge/graphify_bridge.py +156 -0
- package/py/forgeqe_tosca/__init__.py +85 -0
- package/py/forgeqe_tosca/__main__.py +50 -0
- package/py/forgeqe_tosca/ntir.py +484 -0
- package/py/forgeqe_tosca/render.py +128 -0
- package/py/forgeqe_tosca/tsu.py +187 -0
- package/py/forgeqe_tosca/vendor/toscatsu/LICENSE +26 -0
- package/py/forgeqe_tosca/vendor/toscatsu/UPSTREAM +7 -0
- package/py/forgeqe_tosca/vendor/toscatsu/gen_tsu.py +735 -0
- package/py/forgeqe_tosca/vendor/toscatsu/parse_tsu.py +1979 -0
- package/py/forgeqe_tosca/vendor/toscatsu/spec_to_manifest.py +878 -0
- package/py/forgeqe_tosca/vendored.py +50 -0
- package/skills/tosca-knowledge/SKILL.md +56 -0
- package/skills/tosca-knowledge/references/actions-and-values.md +63 -0
- package/skills/tosca-knowledge/references/locators.md +29 -0
- package/skills/tosca-knowledge/references/mapping-cypress.md +21 -0
- package/skills/tosca-knowledge/references/mapping-playwright.md +31 -0
- package/skills/tosca-knowledge/references/mapping-selenium-webdriverio.md +26 -0
- package/skills/tosca-knowledge/references/ntir.md +46 -0
- package/dist/web/assets/Agent-Ol1sf0Me.js +0 -4
- package/dist/web/assets/ApiTests-BfN5VysH.js +0 -10
- package/dist/web/assets/Chat-Bk2ECB9h.js +0 -3
- package/dist/web/assets/Data-DSZ9xkqr.js +0 -3
- package/dist/web/assets/Evidence-BVjGRwcr.js +0 -1
- package/dist/web/assets/Features-DQEzR0Mz.js +0 -1
- package/dist/web/assets/Jobs-chEiiqmE.js +0 -5
- package/dist/web/assets/KindPage-D-Jah0cx.js +0 -6
- package/dist/web/assets/Migration-DMIBgW27.js +0 -2
- package/dist/web/assets/Product-B3buEWja.js +0 -1
- package/dist/web/assets/Quality-DuELzB5I.js +0 -1
- package/dist/web/assets/Record-DLTuuxTP.js +0 -2
- package/dist/web/assets/Regression-Bjz4Xfbo.js +0 -5
- package/dist/web/assets/Reports-p8Qp2KwM.js +0 -2
- package/dist/web/assets/Response-DGJAmOI0.js +0 -4
- package/dist/web/assets/Runs-CnPPwEq7.js +0 -2
- package/dist/web/assets/Shell-Molb7AUz.js +0 -3
- package/dist/web/assets/TestCases-CUZ-kHja.js +0 -1
- package/dist/web/assets/TestData-B3P1fBRO.js +0 -2
- package/dist/web/assets/WhatsNew-CdiZ0Eob.js +0 -1
- package/dist/web/assets/arrow-down-D5oPK0MM.js +0 -1
- package/dist/web/assets/arrow-right-2yt0QgFJ.js +0 -1
- package/dist/web/assets/circle-DIklM9wF.js +0 -1
- package/dist/web/assets/circle-dashed-BZvX5dyl.js +0 -1
- package/dist/web/assets/circle-dot-Cd20PWQi.js +0 -1
- package/dist/web/assets/dataParts-D0dUqael.js +0 -3
- package/dist/web/assets/index-BC72t3H1.js +0 -43
- package/dist/web/assets/index-BiJ_Nvm1.css +0 -2
- package/dist/web/assets/keyboard-Dab5j5YB.js +0 -1
- package/dist/web/assets/pencil-DeEsXRZX.js +0 -1
- package/dist/web/assets/productParts-Ciuentrl.js +0 -1
- package/dist/web/assets/qualityParts-CZCG8hDs.js +0 -1
- package/dist/web/assets/segmented-BMOboT4H.js +0 -1
- package/dist/web/assets/usePageChat-eO0J5JlP.js +0 -1
|
@@ -0,0 +1,878 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
spec_to_manifest.py — Playwright .spec.ts → parse_tsu-shaped manifest JSON.
|
|
4
|
+
|
|
5
|
+
Used by gen_tsu.py via `--spec`. Walks the spec tree-sitter AST, cross-
|
|
6
|
+
references locator texts against a `pages/*.page.ts` catalog, reconstructs
|
|
7
|
+
folder/block/control-flow structure from comments, and emits a manifest
|
|
8
|
+
that matches the schema parse_tsu produces.
|
|
9
|
+
|
|
10
|
+
Three input shapes the parser tries to handle:
|
|
11
|
+
|
|
12
|
+
1. **Inline with comments** (auto-generated by parse_tsu, the round-trip path):
|
|
13
|
+
- `// CDE | Cookie window` → module name marker
|
|
14
|
+
- `// Click Submit btn` → step name
|
|
15
|
+
- `// ── Folder Name` → folder boundary
|
|
16
|
+
- `// [if Foo] condition: 1=="1"` → control flow open
|
|
17
|
+
- `// [Then]` / `// [Else]` / `// [Loop]` → branch open
|
|
18
|
+
- `// [end if Foo]` → control flow close
|
|
19
|
+
- `// TBox Wait: 3000 ms` → synthesizes wait step
|
|
20
|
+
- `await page.locator(…).click()` → action
|
|
21
|
+
|
|
22
|
+
2. **POM-style** (`pageObj.field.action()`): the field reference is resolved
|
|
23
|
+
through the page-objects catalog (locator text + module + attribute name).
|
|
24
|
+
|
|
25
|
+
3. **Bare inline** (no comments, no POM imports): each locator is matched
|
|
26
|
+
against the page-objects catalog by source text; if not found, the step
|
|
27
|
+
is emitted with a synthetic module name so the user can hand-fix.
|
|
28
|
+
|
|
29
|
+
Public entry point:
|
|
30
|
+
build_manifest_from_spec(spec_path, pages_dir, base_manifest=None)
|
|
31
|
+
→ dict in parse_tsu manifest format
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
import re
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from collections import defaultdict
|
|
37
|
+
import tree_sitter as ts
|
|
38
|
+
import tree_sitter_typescript as tsts
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
42
|
+
# Tree-sitter setup
|
|
43
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
44
|
+
_LANG = ts.Language(tsts.language_typescript())
|
|
45
|
+
_PARSER = ts.Parser(_LANG)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _src(node, source: bytes) -> str:
|
|
49
|
+
"""Return the literal source text of a node."""
|
|
50
|
+
return source[node.start_byte:node.end_byte].decode('utf-8', errors='replace')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _children_by_type(node, type_name: str):
|
|
54
|
+
return [c for c in node.children if c.type == type_name]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
58
|
+
# Page-object parser → catalog
|
|
59
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
60
|
+
# Each catalog entry: {
|
|
61
|
+
# 'class_name': 'LoginPagePage',
|
|
62
|
+
# 'module_name': 'Login page', # derived; user can override via JSON map
|
|
63
|
+
# 'fields': [{'name': 'email_address', 'locator_text': 'page.locator(\'#signInName\')'}],
|
|
64
|
+
# }
|
|
65
|
+
#
|
|
66
|
+
# We also build a reverse index normalized_locator_text → (class_name, field_name)
|
|
67
|
+
# so that the spec parser can match `page.locator('#signInName')` back to
|
|
68
|
+
# (LoginPagePage, email_address).
|
|
69
|
+
|
|
70
|
+
_FIELD_ASSIGN_QUERY = _LANG.query("""
|
|
71
|
+
(assignment_expression
|
|
72
|
+
left: (member_expression
|
|
73
|
+
object: (this)
|
|
74
|
+
property: (property_identifier) @field)
|
|
75
|
+
right: (_) @rhs) @assign
|
|
76
|
+
""")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _camel_to_words(name: str) -> str:
|
|
80
|
+
"""LoginPagePage → 'Login Page' (drop trailing 'Page' if present)."""
|
|
81
|
+
if name.endswith('Page'):
|
|
82
|
+
name = name[:-4]
|
|
83
|
+
parts = re.findall(r'[A-Z][a-z0-9]*|[a-z0-9]+', name)
|
|
84
|
+
return ' '.join(p.capitalize() for p in parts) if parts else name
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _normalize_locator_text(text: str) -> str:
|
|
88
|
+
"""Collapse whitespace + line continuations so two formattings match."""
|
|
89
|
+
t = re.sub(r'\s+', ' ', text)
|
|
90
|
+
t = re.sub(r'\s*\.\s*', '.', t)
|
|
91
|
+
t = re.sub(r'\s*,\s*', ', ', t)
|
|
92
|
+
return t.strip()
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def parse_pages_dir(pages_dir: Path):
|
|
96
|
+
"""Walk a pages/ directory; return list of {class_name, module_name, fields[]}.
|
|
97
|
+
|
|
98
|
+
Plus a reverse map: { normalized_locator_text → (class_name, field_name) }."""
|
|
99
|
+
catalog = []
|
|
100
|
+
rev_index = {}
|
|
101
|
+
|
|
102
|
+
for ts_path in sorted(pages_dir.glob('*.page.ts')):
|
|
103
|
+
source = ts_path.read_bytes()
|
|
104
|
+
tree = _PARSER.parse(source)
|
|
105
|
+
root = tree.root_node
|
|
106
|
+
# find each class declaration
|
|
107
|
+
for cls_node in _walk_find(root, 'class_declaration'):
|
|
108
|
+
name_node = cls_node.child_by_field_name('name')
|
|
109
|
+
if not name_node: continue
|
|
110
|
+
class_name = _src(name_node, source)
|
|
111
|
+
# Constructor body: find method with name='constructor'
|
|
112
|
+
ctor = _find_constructor(cls_node)
|
|
113
|
+
fields = []
|
|
114
|
+
if ctor is not None:
|
|
115
|
+
body = ctor.child_by_field_name('body')
|
|
116
|
+
if body:
|
|
117
|
+
matches = _FIELD_ASSIGN_QUERY.matches(body)
|
|
118
|
+
for _id, captures in matches:
|
|
119
|
+
field_node = captures.get('field', [None])[0]
|
|
120
|
+
rhs_node = captures.get('rhs', [None])[0]
|
|
121
|
+
if field_node is None or rhs_node is None: continue
|
|
122
|
+
fname = _src(field_node, source)
|
|
123
|
+
if fname == 'page': # skip the 'this.page = page;' binding
|
|
124
|
+
continue
|
|
125
|
+
rhs_text = _src(rhs_node, source)
|
|
126
|
+
fields.append({'name': fname, 'locator_text': rhs_text})
|
|
127
|
+
rev_index[_normalize_locator_text(rhs_text)] = (class_name, fname)
|
|
128
|
+
# Also index the .or(...) right-hand-side primary alone, so that
|
|
129
|
+
# specs that drop the .or() fallback can still match.
|
|
130
|
+
primary_only = re.split(r'\s*\.\s*or\s*\(', rhs_text)[0]
|
|
131
|
+
rev_index.setdefault(_normalize_locator_text(primary_only),
|
|
132
|
+
(class_name, fname))
|
|
133
|
+
catalog.append({
|
|
134
|
+
'class_name': class_name,
|
|
135
|
+
'module_name': _camel_to_words(class_name),
|
|
136
|
+
'pages_file': str(ts_path),
|
|
137
|
+
'fields': fields,
|
|
138
|
+
})
|
|
139
|
+
return catalog, rev_index
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _walk_find(node, type_name: str):
|
|
143
|
+
"""DFS yield all descendants of a given type."""
|
|
144
|
+
if node.type == type_name:
|
|
145
|
+
yield node
|
|
146
|
+
for c in node.children:
|
|
147
|
+
yield from _walk_find(c, type_name)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _find_constructor(class_node):
|
|
151
|
+
body = class_node.child_by_field_name('body')
|
|
152
|
+
if not body: return None
|
|
153
|
+
for c in body.children:
|
|
154
|
+
if c.type == 'method_definition':
|
|
155
|
+
name = c.child_by_field_name('name')
|
|
156
|
+
if name and name.type == 'property_identifier':
|
|
157
|
+
if name.text == b'constructor':
|
|
158
|
+
return c
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
163
|
+
# Spec parser → flat node stream (manifest.steps shape)
|
|
164
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
165
|
+
# We walk the spec linearly: every comment gets read in order, every
|
|
166
|
+
# `await page.<...>.<action>(...)` becomes a tentative action. A comment-state
|
|
167
|
+
# machine emits folder/block/if/then/else/loop/step boundary nodes.
|
|
168
|
+
|
|
169
|
+
# Structured @tosca markers (emitted by parse_tsu.py for unambiguous round-trip).
|
|
170
|
+
# These are the PRIMARY source of structural truth; legacy heuristics below are
|
|
171
|
+
# fallback for hand-written specs without markers.
|
|
172
|
+
TOSCA_MARKERS = [
|
|
173
|
+
('folder_open', re.compile(r'^//\s*@tosca\s+folder:\s*"((?:\\.|[^"])*)"\s*$')),
|
|
174
|
+
('folder_close', re.compile(r'^//\s*@tosca\s+/folder\s*$')),
|
|
175
|
+
('block_open', re.compile(r'^//\s*@tosca\s+block:\s*"((?:\\.|[^"])*)"\s*$')),
|
|
176
|
+
('block_close', re.compile(r'^//\s*@tosca\s+/block\s*$')),
|
|
177
|
+
('if_open', re.compile(r'^//\s*@tosca\s+if:\s*"((?:\\.|[^"])*)"\s+cond="((?:\\.|[^"])*)"(?:\s+verdict=(True|False))?\s*$')),
|
|
178
|
+
('if_close', re.compile(r'^//\s*@tosca\s+/if\s*$')),
|
|
179
|
+
('branch_open', re.compile(r'^//\s*@tosca\s+(then|else|loop)\s*$')),
|
|
180
|
+
('branch_close', re.compile(r'^//\s*@tosca\s+/branch\s*$')),
|
|
181
|
+
('step_marker', re.compile(r'^//\s*@tosca\s+step:\s*"((?:\\.|[^"])*)"\s+module="((?:\\.|[^"])*)"\s*$')),
|
|
182
|
+
('wait_marker', re.compile(r'^//\s*@tosca\s+wait:\s*(\d+)(?:\s+name="((?:\\.|[^"])*)")?\s*$')),
|
|
183
|
+
('buffers', re.compile(r'^//\s*@tosca\s+buffers:\s*(.*)$')),
|
|
184
|
+
]
|
|
185
|
+
|
|
186
|
+
# Legacy heuristic patterns (used only when no @tosca markers are present in
|
|
187
|
+
# the spec — i.e. for hand-written specs). They're noisier but degrade
|
|
188
|
+
# gracefully.
|
|
189
|
+
LEGACY_PATTERNS = [
|
|
190
|
+
('folder', re.compile(r'^//\s*──\s*(.+?)\s*$')),
|
|
191
|
+
('legacy_if_open', re.compile(r'^//\s*\[if\s+(.+?)\]\s*condition:\s*(.*?)(?:\s*→\s*(True|False))?\s*$')),
|
|
192
|
+
('legacy_branch', re.compile(r'^//\s*\[(Then|Else|Loop)\]\s*$')),
|
|
193
|
+
('legacy_if_close',re.compile(r'^//\s*\[end if\s+(.+?)\]\s*$')),
|
|
194
|
+
('legacy_wait', re.compile(r'^//\s*TBox Wait:\s*(\d+)\s*ms\s*$')),
|
|
195
|
+
('encrypted', re.compile(r'^//\s*.+Tosca-encrypted')),
|
|
196
|
+
('step_or_module', re.compile(r'^//\s*(.+?)\s*$')),
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _unquote(s: str) -> str:
|
|
201
|
+
"""Reverse the _mq() escape used by parse_tsu's marker emitter."""
|
|
202
|
+
return s.replace('\\"', '"').replace('\\\\', '\\')
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
PLAYWRIGHT_ACTIONS = {
|
|
206
|
+
# action method → manifest mode
|
|
207
|
+
'click': ('set', '{Click}'),
|
|
208
|
+
'dblclick': ('set', '{DOUBLECLICK}'),
|
|
209
|
+
'fill': ('set', None), # value comes from arg
|
|
210
|
+
'press': ('set', None), # value formatted as {KEY[arg]}
|
|
211
|
+
'pressSequentially': ('set', None),
|
|
212
|
+
'hover': ('set', '{HOVER}'),
|
|
213
|
+
'check': ('set', '{Click}'),
|
|
214
|
+
'uncheck': ('set', '{Click}'),
|
|
215
|
+
'selectOption': ('set', None),
|
|
216
|
+
'focus': ('set', '{FOCUS}'),
|
|
217
|
+
'blur': ('set', '{BLUR}'),
|
|
218
|
+
'scrollIntoViewIfNeeded': ('set', '{SCROLLINTOVIEW}'),
|
|
219
|
+
'textContent': ('bufferRead', ''),
|
|
220
|
+
'innerText': ('bufferRead', ''),
|
|
221
|
+
'inputValue': ('bufferRead', ''),
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
# expect(...).<matcher>(...) — manifest mode='verify' or 'waitFor'
|
|
225
|
+
EXPECT_MATCHERS = {
|
|
226
|
+
'toBeVisible': ('verify', 'Visible', 'True'),
|
|
227
|
+
'toBeHidden': ('verify', 'Visible', 'False'),
|
|
228
|
+
'toBeEnabled': ('verify', 'Enabled', 'True'),
|
|
229
|
+
'toBeDisabled': ('verify', 'Disabled', 'True'),
|
|
230
|
+
'toBeChecked': ('verify', 'Checked', 'True'),
|
|
231
|
+
'toBeFocused': ('verify', 'Focused', 'True'),
|
|
232
|
+
'toBeEditable': ('verify', 'Editable', 'True'),
|
|
233
|
+
'toBeAttached': ('verify', 'Exists', 'True'),
|
|
234
|
+
'toContainText': ('verify', '', None), # value is the text arg
|
|
235
|
+
'toHaveText': ('verify', '', None),
|
|
236
|
+
'toHaveValue': ('verify', 'Value', None),
|
|
237
|
+
'toHaveCount': ('verify', 'Count', None),
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _strip_or_chain(loc_text: str) -> str:
|
|
242
|
+
"""For inline `(page.locator(X)).or(page.locator(Y))` — return primary only."""
|
|
243
|
+
return re.split(r'\s*\.\s*or\s*\(', loc_text)[0].strip().lstrip('(').rstrip(')').strip()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
# Chain methods that decorate a locator/action without being the action itself.
|
|
247
|
+
# When identifying the action verb (rightmost meaningful call), skip these.
|
|
248
|
+
CHAIN_DECORATORS_TAIL = {'catch'} # comes AFTER the action: .click({...}).catch(...)
|
|
249
|
+
CHAIN_DECORATORS_MID = {'first', 'filter', 'nth'} # locator decorators: .first()/.filter()/.nth()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _strip_action_options(args_text: str) -> str:
|
|
253
|
+
"""Strip Playwright action option objects from args. The option object
|
|
254
|
+
can be the only argument (.click({timeout:3000})) or trail a value
|
|
255
|
+
(.fill('hi', {timeout:3000})). We detect a trailing ',' followed by
|
|
256
|
+
'{' OR a leading '{' if no preceding string/identifier."""
|
|
257
|
+
s = args_text.strip()
|
|
258
|
+
if not s: return s
|
|
259
|
+
# Trailing option object: 'value', { ... }
|
|
260
|
+
s = re.sub(r',\s*\{[^}]*\}\s*$', '', s)
|
|
261
|
+
# Sole option object: { timeout: 3000 } as the only arg
|
|
262
|
+
if re.match(r'^\{[^}]*\}\s*$', s):
|
|
263
|
+
return ''
|
|
264
|
+
return s
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _strip_locator_decorators(loc_text: str) -> str:
|
|
268
|
+
"""Strip trailing locator decorators (.first(), .filter({...}), .nth(N))
|
|
269
|
+
so the locator text matches what's in the page-objects catalog."""
|
|
270
|
+
s = loc_text.strip()
|
|
271
|
+
# Iteratively strip suffix decorators
|
|
272
|
+
while True:
|
|
273
|
+
m = re.search(r'\.(first|filter|nth)\([^)]*\)\s*$', s)
|
|
274
|
+
if not m: break
|
|
275
|
+
s = s[:m.start()].rstrip()
|
|
276
|
+
return s
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _key_arg_to_token(arg: str) -> str:
|
|
280
|
+
"""'Control+a' → '{KEY[Control+a]}', 'Tab' → '{TAB}', 'Delete' → '{DELETE}'."""
|
|
281
|
+
a = arg.strip().strip('"\'')
|
|
282
|
+
bare_keys = {'Tab','Enter','Escape','Space','Home','End','Backspace','Delete',
|
|
283
|
+
'ArrowUp','ArrowDown','ArrowLeft','ArrowRight'}
|
|
284
|
+
if a in bare_keys:
|
|
285
|
+
return '{' + a.upper() + '}'
|
|
286
|
+
return '{KEY[' + a + ']}'
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _parse_action_arg(arg_text: str) -> str:
|
|
290
|
+
"""Extract a literal string arg from a function call argument expression."""
|
|
291
|
+
arg_text = arg_text.strip()
|
|
292
|
+
# Strip trailing nullish coalescing: `process.env.X ?? ''` → 'process.env.X'
|
|
293
|
+
arg_text = re.sub(r'\s*\?\?\s*[\'"][^\'\"]*[\'"]$', '', arg_text)
|
|
294
|
+
# `process.env.FOO` → '{CP[FOO]}' so re-emission round-trips
|
|
295
|
+
m = re.match(r'^process\.env\.([A-Z0-9_]+)\s*$', arg_text)
|
|
296
|
+
if m: return '{CP[' + m.group(1) + ']}'
|
|
297
|
+
# String literal
|
|
298
|
+
m = re.match(r'^[\'"](.*)[\'"]$', arg_text, re.DOTALL)
|
|
299
|
+
if m: return m.group(1)
|
|
300
|
+
return arg_text
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _walk_stream(root, source: bytes):
|
|
304
|
+
"""Yield (line_no, kind, payload) tuples in document order.
|
|
305
|
+
|
|
306
|
+
kind ∈ {'comment', 'await_call', 'test_step_open', 'test_step_close', 'test_open', 'test_close'}.
|
|
307
|
+
payload differs by kind.
|
|
308
|
+
"""
|
|
309
|
+
# Strategy: walk all descendants; collect interesting nodes; sort by start_byte.
|
|
310
|
+
items = []
|
|
311
|
+
for n in _walk_find(root, 'comment'):
|
|
312
|
+
items.append((n.start_byte, 'comment', n))
|
|
313
|
+
# await expressions
|
|
314
|
+
for n in _walk_find(root, 'await_expression'):
|
|
315
|
+
items.append((n.start_byte, 'await', n))
|
|
316
|
+
# `test(...)` and `test.step(...)` calls
|
|
317
|
+
for n in _walk_find(root, 'call_expression'):
|
|
318
|
+
fn = n.child_by_field_name('function')
|
|
319
|
+
if fn is None: continue
|
|
320
|
+
text = _src(fn, source)
|
|
321
|
+
if text == 'test' or text.startswith('test('):
|
|
322
|
+
items.append((n.start_byte, 'test_open', n))
|
|
323
|
+
elif text == 'test.step':
|
|
324
|
+
items.append((n.start_byte, 'test_step_open', n))
|
|
325
|
+
# `test.use(...)` is the per-spec config override emitted by parse_tsu;
|
|
326
|
+
# it's metadata, not a test step. Skip it explicitly so the call doesn't
|
|
327
|
+
# get treated as anything else later in the walk.
|
|
328
|
+
# (No item added for test.use; it's just ignored.)
|
|
329
|
+
items.sort(key=lambda it: it[0])
|
|
330
|
+
return items
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _arg_node_text(call_node, source: bytes) -> str:
|
|
334
|
+
args = call_node.child_by_field_name('arguments')
|
|
335
|
+
if args is None: return ''
|
|
336
|
+
return _src(args, source)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _call_chain(node, source: bytes):
|
|
340
|
+
"""Walk a call chain like `page.locator('#x').or(page.locator('#y')).fill('hi')`
|
|
341
|
+
and return list of (method, args_text) in left-to-right order."""
|
|
342
|
+
chain = []
|
|
343
|
+
|
|
344
|
+
def visit(n):
|
|
345
|
+
if n.type == 'call_expression':
|
|
346
|
+
fn = n.child_by_field_name('function')
|
|
347
|
+
args = n.child_by_field_name('arguments')
|
|
348
|
+
if fn is not None and fn.type == 'member_expression':
|
|
349
|
+
obj = fn.child_by_field_name('object')
|
|
350
|
+
method = fn.child_by_field_name('property')
|
|
351
|
+
if obj is not None: visit(obj)
|
|
352
|
+
if method is not None:
|
|
353
|
+
args_text = _src(args, source) if args else ''
|
|
354
|
+
# arg text is "(...)" — strip outer parens
|
|
355
|
+
if args_text.startswith('(') and args_text.endswith(')'):
|
|
356
|
+
args_text = args_text[1:-1]
|
|
357
|
+
chain.append((_src(method, source), args_text))
|
|
358
|
+
else:
|
|
359
|
+
# bare function call like `expect(loc)`
|
|
360
|
+
if fn is not None:
|
|
361
|
+
chain.append((_src(fn, source), _arg_node_text(n, source).strip('()')))
|
|
362
|
+
elif n.type == 'member_expression':
|
|
363
|
+
obj = n.child_by_field_name('object')
|
|
364
|
+
prop = n.child_by_field_name('property')
|
|
365
|
+
if obj: visit(obj)
|
|
366
|
+
if prop: chain.append((_src(prop, source), None)) # property access, no args
|
|
367
|
+
elif n.type == 'parenthesized_expression':
|
|
368
|
+
inner = n.children[1] if len(n.children) > 2 else None
|
|
369
|
+
if inner: visit(inner)
|
|
370
|
+
# else: leaf (identifier, etc.) — terminator
|
|
371
|
+
|
|
372
|
+
visit(node)
|
|
373
|
+
return chain
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
377
|
+
# Manifest builder
|
|
378
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
379
|
+
class SpecToManifest:
|
|
380
|
+
def __init__(self, page_catalog, rev_index, base_manifest=None):
|
|
381
|
+
self.catalog = page_catalog
|
|
382
|
+
self.rev_index = rev_index
|
|
383
|
+
self.base = base_manifest or {}
|
|
384
|
+
# Comment-state
|
|
385
|
+
self.last_step_name = ''
|
|
386
|
+
self.last_module_name = ''
|
|
387
|
+
self.next_step_module = '' # set by the next @tosca step: marker
|
|
388
|
+
self.next_step_name = ''
|
|
389
|
+
self.pending_step_actions = [] # accumulator until next step boundary
|
|
390
|
+
# Output manifest
|
|
391
|
+
self.steps = []
|
|
392
|
+
self.test_data = dict(self.base.get('test_data', {}))
|
|
393
|
+
self.unmapped = []
|
|
394
|
+
self.test_name = ''
|
|
395
|
+
# Folder/block stack
|
|
396
|
+
self.folder_stack = [] # depth tracking
|
|
397
|
+
# Control-flow open conditions (so we can emit if_end with the right name)
|
|
398
|
+
self.if_stack = [] # list of names
|
|
399
|
+
|
|
400
|
+
# ── public ─────────────────────────────────────────────────────────────
|
|
401
|
+
def build(self, spec_path: Path) -> dict:
|
|
402
|
+
source = spec_path.read_bytes()
|
|
403
|
+
tree = _PARSER.parse(source)
|
|
404
|
+
root = tree.root_node
|
|
405
|
+
# Top-level test() name — first call to test(...)
|
|
406
|
+
for n in _walk_find(root, 'call_expression'):
|
|
407
|
+
fn = n.child_by_field_name('function')
|
|
408
|
+
if fn is not None and _src(fn, source) == 'test':
|
|
409
|
+
args = n.child_by_field_name('arguments')
|
|
410
|
+
if args and len(args.children) >= 2:
|
|
411
|
+
first_arg = args.children[1] # skip '('
|
|
412
|
+
if first_arg.type in ('string', 'template_string'):
|
|
413
|
+
self.test_name = _parse_action_arg(_src(first_arg, source))
|
|
414
|
+
break
|
|
415
|
+
# Drive the comment+await stream
|
|
416
|
+
self._drive_stream(root, source)
|
|
417
|
+
# Flush any pending step actions
|
|
418
|
+
self._flush_step()
|
|
419
|
+
return {
|
|
420
|
+
'meta': {
|
|
421
|
+
'test_name': self.test_name,
|
|
422
|
+
'project': self.base.get('meta', {}).get('project', ''),
|
|
423
|
+
'base_url': self.base.get('meta', {}).get('base_url', ''),
|
|
424
|
+
'all_urls': self.base.get('meta', {}).get('all_urls', []),
|
|
425
|
+
'config': self.base.get('meta', {}).get('config', {}),
|
|
426
|
+
'unmapped': self.unmapped,
|
|
427
|
+
},
|
|
428
|
+
'test_data': self.test_data,
|
|
429
|
+
'steps': self.steps,
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
# ── stream drive ───────────────────────────────────────────────────────
|
|
433
|
+
def _drive_stream(self, root, source):
|
|
434
|
+
items = _walk_stream(root, source)
|
|
435
|
+
# Detect whether the spec is structured (has @tosca markers) or legacy.
|
|
436
|
+
self.has_markers = any(
|
|
437
|
+
kind == 'comment' and '@tosca' in _src(node, source)
|
|
438
|
+
for _, kind, node in items
|
|
439
|
+
)
|
|
440
|
+
# test_step_open emits a folder boundary; @tosca folder/block markers
|
|
441
|
+
# supersede that for nested levels.
|
|
442
|
+
for byte, kind, node in items:
|
|
443
|
+
if kind == 'comment':
|
|
444
|
+
self._on_comment(_src(node, source).strip(), source)
|
|
445
|
+
elif kind == 'test_step_open':
|
|
446
|
+
# Top-level await test.step("...") — only treat as folder open
|
|
447
|
+
# when we DON'T already have an active @tosca folder/block from
|
|
448
|
+
# the marker comment that immediately precedes it.
|
|
449
|
+
args = node.child_by_field_name('arguments')
|
|
450
|
+
name = ''
|
|
451
|
+
if args and len(args.children) >= 2:
|
|
452
|
+
n0 = args.children[1]
|
|
453
|
+
if n0.type in ('string','template_string'):
|
|
454
|
+
name = _parse_action_arg(_src(n0, source))
|
|
455
|
+
if not self.has_markers:
|
|
456
|
+
self._flush_step()
|
|
457
|
+
self._close_folders_to_depth(0)
|
|
458
|
+
self._open_folder(name)
|
|
459
|
+
# When markers present, the @tosca folder/block markers already
|
|
460
|
+
# opened the right kind; we just consume the test.step call as
|
|
461
|
+
# a no-op container and let nested awaits/comments populate.
|
|
462
|
+
elif kind == 'await':
|
|
463
|
+
self._on_await(node, source)
|
|
464
|
+
|
|
465
|
+
# ── comment handling ───────────────────────────────────────────────────
|
|
466
|
+
def _on_comment(self, text: str, source):
|
|
467
|
+
# 1) Structured markers (preferred)
|
|
468
|
+
for kind, pat in TOSCA_MARKERS:
|
|
469
|
+
m = pat.match(text)
|
|
470
|
+
if not m: continue
|
|
471
|
+
return self._on_marker(kind, m)
|
|
472
|
+
# 2) Legacy heuristics (only when no markers in spec)
|
|
473
|
+
if self.has_markers:
|
|
474
|
+
return # ignore decorative comments when markers are authoritative
|
|
475
|
+
for kind, pat in LEGACY_PATTERNS:
|
|
476
|
+
m = pat.match(text)
|
|
477
|
+
if not m: continue
|
|
478
|
+
return self._on_legacy(kind, m)
|
|
479
|
+
|
|
480
|
+
def _on_marker(self, kind: str, m):
|
|
481
|
+
if kind == 'folder_open':
|
|
482
|
+
self._flush_step()
|
|
483
|
+
self._open_folder(_unquote(m.group(1)))
|
|
484
|
+
elif kind == 'folder_close':
|
|
485
|
+
self._flush_step()
|
|
486
|
+
self._close_folder()
|
|
487
|
+
elif kind == 'block_open':
|
|
488
|
+
self._flush_step()
|
|
489
|
+
self._open_block(_unquote(m.group(1)))
|
|
490
|
+
elif kind == 'block_close':
|
|
491
|
+
self._flush_step()
|
|
492
|
+
self._close_block()
|
|
493
|
+
elif kind == 'if_open':
|
|
494
|
+
self._flush_step()
|
|
495
|
+
name = _unquote(m.group(1))
|
|
496
|
+
cond = _unquote(m.group(2))
|
|
497
|
+
verdict = m.group(3)
|
|
498
|
+
node = {'type': 'if', 'name': name, 'condition': cond,
|
|
499
|
+
'depth': len(self.folder_stack)}
|
|
500
|
+
if verdict:
|
|
501
|
+
node['condition_resolved'] = ('1=="1"' if verdict == 'True' else '0=="1"')
|
|
502
|
+
self.steps.append(node)
|
|
503
|
+
self.if_stack.append(name)
|
|
504
|
+
elif kind == 'if_close':
|
|
505
|
+
self._flush_step()
|
|
506
|
+
name = self.if_stack.pop() if self.if_stack else ''
|
|
507
|
+
self.steps.append({'type': 'if_end', 'name': name,
|
|
508
|
+
'depth': len(self.folder_stack)})
|
|
509
|
+
elif kind == 'branch_open':
|
|
510
|
+
self._flush_step()
|
|
511
|
+
kw = m.group(1).lower() + '_start'
|
|
512
|
+
self.steps.append({'type': kw, 'name': m.group(1).title(),
|
|
513
|
+
'depth': len(self.folder_stack)})
|
|
514
|
+
elif kind == 'branch_close':
|
|
515
|
+
self._flush_step()
|
|
516
|
+
# Determine which branch is closing: the most recent open one.
|
|
517
|
+
# We don't track explicitly; assume then→then_end, else→else_end, loop→loop_end
|
|
518
|
+
# based on the trailing branch_start. For simplicity emit `then_end` style based
|
|
519
|
+
# on inspection of the last branch_start node in self.steps.
|
|
520
|
+
kind_name = self._last_branch_kind()
|
|
521
|
+
self.steps.append({'type': kind_name + '_end', 'name': kind_name.title(),
|
|
522
|
+
'depth': len(self.folder_stack)})
|
|
523
|
+
elif kind == 'step_marker':
|
|
524
|
+
# Each @tosca step: marker delimits one logical step. We push a
|
|
525
|
+
# step entry immediately; awaited action calls between this marker
|
|
526
|
+
# and the next structural marker append to its actions list.
|
|
527
|
+
# Steps with no actions (skipped TBox modules) round-trip cleanly
|
|
528
|
+
# this way.
|
|
529
|
+
self._flush_step()
|
|
530
|
+
self.last_step_name = _unquote(m.group(1))
|
|
531
|
+
self.last_module_name = _unquote(m.group(2))
|
|
532
|
+
self.pending_step_actions = (self.last_step_name, self.last_module_name), []
|
|
533
|
+
elif kind == 'wait_marker':
|
|
534
|
+
self._flush_step()
|
|
535
|
+
ms = m.group(1)
|
|
536
|
+
wait_name = _unquote(m.group(2) or '') or 'TBox Wait'
|
|
537
|
+
self.steps.append({
|
|
538
|
+
'type': 'step', 'name': wait_name, 'module': 'TBox Wait',
|
|
539
|
+
'depth': len(self.folder_stack),
|
|
540
|
+
'actions': [{'mode': 'set', 'element': 'Duration', 'value': ms}],
|
|
541
|
+
})
|
|
542
|
+
elif kind == 'buffers':
|
|
543
|
+
# `// @tosca buffers: A=value1; B=value2; ...` — append to the
|
|
544
|
+
# pending step set up by the prior @tosca step marker. The step
|
|
545
|
+
# marker named the step (e.g. "Set buffer for tinted product");
|
|
546
|
+
# buffers carries the actual XTestStepValues.
|
|
547
|
+
kvs = m.group(1).strip()
|
|
548
|
+
buf_actions = []
|
|
549
|
+
for chunk in [c.strip() for c in kvs.split(';') if c.strip()]:
|
|
550
|
+
if '=' not in chunk: continue
|
|
551
|
+
k, v = chunk.split('=', 1)
|
|
552
|
+
k = k.strip(); v = v.strip()
|
|
553
|
+
buf_actions.append({'mode': 'set', 'element': '<Buffername>',
|
|
554
|
+
'value': v, 'explicit_name': k})
|
|
555
|
+
self.test_data[k] = v
|
|
556
|
+
if buf_actions:
|
|
557
|
+
if (self.pending_step_actions
|
|
558
|
+
and self.pending_step_actions[0][1] == 'TBox Set Buffer'):
|
|
559
|
+
# Append to the existing pending step
|
|
560
|
+
self.pending_step_actions[1].extend(buf_actions)
|
|
561
|
+
else:
|
|
562
|
+
# No prior step marker — create a fresh one
|
|
563
|
+
self._flush_step()
|
|
564
|
+
self.pending_step_actions = (
|
|
565
|
+
('Set Buffers', 'TBox Set Buffer'), buf_actions
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
def _last_branch_kind(self) -> str:
|
|
569
|
+
"""Look back through steps to find the most recently opened
|
|
570
|
+
then/else/loop_start that hasn't been closed yet."""
|
|
571
|
+
depth = 0
|
|
572
|
+
for s in reversed(self.steps):
|
|
573
|
+
t = s.get('type', '')
|
|
574
|
+
if t.endswith('_end') and t.split('_')[0] in ('then', 'else', 'loop'):
|
|
575
|
+
depth += 1
|
|
576
|
+
elif t.endswith('_start') and t.split('_')[0] in ('then', 'else', 'loop'):
|
|
577
|
+
if depth == 0:
|
|
578
|
+
return t.split('_')[0]
|
|
579
|
+
depth -= 1
|
|
580
|
+
return 'then'
|
|
581
|
+
|
|
582
|
+
def _on_legacy(self, kind: str, m):
|
|
583
|
+
if kind == 'folder':
|
|
584
|
+
self.last_module_name = m.group(1)
|
|
585
|
+
elif kind == 'legacy_if_open':
|
|
586
|
+
self._flush_step()
|
|
587
|
+
cond = m.group(2); verdict = m.group(3)
|
|
588
|
+
node = {'type': 'if', 'name': m.group(1), 'condition': cond,
|
|
589
|
+
'depth': len(self.folder_stack)}
|
|
590
|
+
if verdict:
|
|
591
|
+
node['condition_resolved'] = ('1=="1"' if verdict == 'True' else '0=="1"')
|
|
592
|
+
self.steps.append(node)
|
|
593
|
+
self.if_stack.append(m.group(1))
|
|
594
|
+
elif kind == 'legacy_branch':
|
|
595
|
+
self._flush_step()
|
|
596
|
+
kw = m.group(1).lower() + '_start'
|
|
597
|
+
self.steps.append({'type': kw, 'name': m.group(1), 'depth': len(self.folder_stack)})
|
|
598
|
+
elif kind == 'legacy_if_close':
|
|
599
|
+
self._flush_step()
|
|
600
|
+
name = self.if_stack.pop() if self.if_stack else m.group(1)
|
|
601
|
+
self.steps.append({'type': 'if_end', 'name': name, 'depth': len(self.folder_stack)})
|
|
602
|
+
elif kind == 'legacy_wait':
|
|
603
|
+
self._flush_step()
|
|
604
|
+
ms = m.group(1)
|
|
605
|
+
self.steps.append({
|
|
606
|
+
'type': 'step', 'name': 'TBox Wait', 'module': 'TBox Wait',
|
|
607
|
+
'depth': len(self.folder_stack),
|
|
608
|
+
'actions': [{'mode': 'set', 'element': 'Duration', 'value': ms}],
|
|
609
|
+
})
|
|
610
|
+
elif kind == 'encrypted':
|
|
611
|
+
pass
|
|
612
|
+
elif kind == 'step_or_module':
|
|
613
|
+
txt = m.group(1)
|
|
614
|
+
if '|' in txt:
|
|
615
|
+
self.last_module_name = txt.split('|', 1)[0].strip()
|
|
616
|
+
self.last_step_name = txt
|
|
617
|
+
|
|
618
|
+
# ── await call handling ────────────────────────────────────────────────
|
|
619
|
+
def _on_await(self, await_node, source):
|
|
620
|
+
# await_expression → call_expression chain
|
|
621
|
+
# We want the leftmost terminator (locator builder) and the final method
|
|
622
|
+
# (the action verb).
|
|
623
|
+
# Find the inner call_expression (the awaited thing)
|
|
624
|
+
inner = None
|
|
625
|
+
for c in await_node.children:
|
|
626
|
+
if c.type == 'call_expression':
|
|
627
|
+
inner = c
|
|
628
|
+
break
|
|
629
|
+
if inner is None: return
|
|
630
|
+
chain = _call_chain(inner, source)
|
|
631
|
+
if not chain: return
|
|
632
|
+
# chain is a list of (method, args). The locator-construction part is the
|
|
633
|
+
# prefix; the last call is the action.
|
|
634
|
+
# Identify expect(...) chains specially.
|
|
635
|
+
head_method, head_args = chain[0] if chain else (None, None)
|
|
636
|
+
if head_method == 'expect':
|
|
637
|
+
self._handle_expect(chain, source)
|
|
638
|
+
return
|
|
639
|
+
# For await page.locator(...).fill(...): chain is
|
|
640
|
+
# [('page', None), ('locator','"#x"'), ('fill','"hi"')]
|
|
641
|
+
# parse_tsu now also emits decorators around the action:
|
|
642
|
+
# [..., ('first', ''), ('click', '{ timeout: 3000 }'), ('catch', '() => {}')]
|
|
643
|
+
# Strip trailing tail decorators (.catch) before identifying the action.
|
|
644
|
+
i = len(chain) - 1
|
|
645
|
+
while i >= 0 and chain[i][0] in CHAIN_DECORATORS_TAIL:
|
|
646
|
+
i -= 1
|
|
647
|
+
if i < 0: return
|
|
648
|
+
action_method, action_args = chain[i]
|
|
649
|
+
# Strip mid-chain locator decorators (.first, .filter, .nth) when
|
|
650
|
+
# building the builder_chain so the locator text matches catalog form.
|
|
651
|
+
builder_chain = [c for c in chain[:i] if c[0] not in CHAIN_DECORATORS_MID]
|
|
652
|
+
# Action verb in PLAYWRIGHT_ACTIONS?
|
|
653
|
+
if action_method not in PLAYWRIGHT_ACTIONS:
|
|
654
|
+
# Unknown — emit as TODO note and move on (likely page.goto, page.waitForTimeout)
|
|
655
|
+
if action_method == 'waitForTimeout':
|
|
656
|
+
# Already handled by TBox Wait comment; ignore here.
|
|
657
|
+
return
|
|
658
|
+
return
|
|
659
|
+
mode, fixed_value = PLAYWRIGHT_ACTIONS[action_method]
|
|
660
|
+
# Compute value
|
|
661
|
+
if fixed_value is not None:
|
|
662
|
+
value = fixed_value
|
|
663
|
+
else:
|
|
664
|
+
# action_args may include trailing options like ', { timeout: 3000 }'
|
|
665
|
+
# or be just the options object alone (when the action has no value
|
|
666
|
+
# arg, e.g. .click({timeout: 3000})). Strip options before parsing.
|
|
667
|
+
action_args = _strip_action_options(action_args or '')
|
|
668
|
+
# Convert action args to a Tosca value
|
|
669
|
+
if action_method == 'press':
|
|
670
|
+
value = _key_arg_to_token(action_args or '')
|
|
671
|
+
elif action_method == 'selectOption':
|
|
672
|
+
# selectOption("X") → {SELECT[X]}; selectOption({index:N}) → {SELECT[N+1]}
|
|
673
|
+
m = re.match(r'\{\s*index\s*:\s*(\d+)\s*\}', (action_args or '').strip())
|
|
674
|
+
if m:
|
|
675
|
+
value = '{SELECT[' + str(int(m.group(1))+1) + ']}'
|
|
676
|
+
else:
|
|
677
|
+
value = '{SELECT[' + _parse_action_arg(action_args or '') + ']}'
|
|
678
|
+
else:
|
|
679
|
+
value = _parse_action_arg(action_args or '')
|
|
680
|
+
# Build locator text from builder_chain
|
|
681
|
+
loc_text = self._chain_to_locator_text(builder_chain, source)
|
|
682
|
+
# Reverse-lookup against catalog
|
|
683
|
+
module, attr = self._resolve_locator(loc_text)
|
|
684
|
+
# Step name from latest non-special comment, module from prior context
|
|
685
|
+
step_name = self.last_step_name or 'step'
|
|
686
|
+
module_name = module or self.last_module_name or ''
|
|
687
|
+
self._emit_or_extend_step(step_name, module_name, {
|
|
688
|
+
'mode': mode,
|
|
689
|
+
'element': attr or '',
|
|
690
|
+
'value': value,
|
|
691
|
+
'locator': {'primary': loc_text} if loc_text else None,
|
|
692
|
+
})
|
|
693
|
+
|
|
694
|
+
def _handle_expect(self, chain, source):
|
|
695
|
+
# chain looks like [('expect', '<arg>'), ('matcher', '<arg>'), ...]
|
|
696
|
+
if len(chain) < 2: return
|
|
697
|
+
_, expect_arg = chain[0]
|
|
698
|
+
# subject of expect — that's the locator. Strip outer parens; this is
|
|
699
|
+
# the source text we look up.
|
|
700
|
+
subject = (expect_arg or '').strip()
|
|
701
|
+
# Some chains have intermediate `.not` (chain[1] = ('not', None))
|
|
702
|
+
matcher_idx = 1
|
|
703
|
+
is_not = False
|
|
704
|
+
if matcher_idx < len(chain) and chain[matcher_idx][0] == 'not':
|
|
705
|
+
is_not = True
|
|
706
|
+
matcher_idx += 1
|
|
707
|
+
if matcher_idx >= len(chain): return
|
|
708
|
+
matcher, m_args = chain[matcher_idx]
|
|
709
|
+
if matcher not in EXPECT_MATCHERS:
|
|
710
|
+
return
|
|
711
|
+
mode, prop, fixed_val = EXPECT_MATCHERS[matcher]
|
|
712
|
+
# Apply 'not' inversion for boolean matchers
|
|
713
|
+
if is_not and prop in ('Visible', 'Enabled', 'Checked', 'Focused', 'Editable',
|
|
714
|
+
'Disabled', 'Exists', 'ReadOnly'):
|
|
715
|
+
# Invert: orig matcher result → flip the True/False
|
|
716
|
+
# For simplicity, we keep prop and toggle by setting value to 'False'
|
|
717
|
+
value_default = 'False'
|
|
718
|
+
else:
|
|
719
|
+
value_default = 'True'
|
|
720
|
+
if fixed_val is None:
|
|
721
|
+
# Value is the matcher arg
|
|
722
|
+
value = _parse_action_arg(m_args or '')
|
|
723
|
+
if matcher == 'toContainText': value = '*' + value + '*'
|
|
724
|
+
else:
|
|
725
|
+
value = value_default
|
|
726
|
+
loc_text = self._normalize_subject(subject)
|
|
727
|
+
# Strip trailing locator decorators (.first()/.filter()) before catalog
|
|
728
|
+
# lookup; preserve original loc_text in the manifest so re-emission
|
|
729
|
+
# round-trips faithfully.
|
|
730
|
+
lookup_text = _strip_locator_decorators(loc_text)
|
|
731
|
+
module, attr = self._resolve_locator(lookup_text)
|
|
732
|
+
step_name = self.last_step_name or 'verify'
|
|
733
|
+
module_name = module or self.last_module_name or ''
|
|
734
|
+
self._emit_or_extend_step(step_name, module_name, {
|
|
735
|
+
'mode': mode,
|
|
736
|
+
'element': attr or '',
|
|
737
|
+
'value': value,
|
|
738
|
+
'property': prop,
|
|
739
|
+
'locator': {'primary': loc_text} if loc_text else None,
|
|
740
|
+
})
|
|
741
|
+
|
|
742
|
+
def _normalize_subject(self, subject: str) -> str:
|
|
743
|
+
s = subject.strip()
|
|
744
|
+
if s.startswith('(') and s.endswith(')'):
|
|
745
|
+
s = s[1:-1].strip()
|
|
746
|
+
return s
|
|
747
|
+
|
|
748
|
+
def _chain_to_locator_text(self, builder_chain, source) -> str:
|
|
749
|
+
"""Given a chain like [('page',None),('locator','"#x"'),('or','page.locator(\"y\")')],
|
|
750
|
+
reconstruct the original source text — easier: take the leftmost call's
|
|
751
|
+
node and rebuild the full text up to (but not including) the action verb."""
|
|
752
|
+
# Build by joining: <head>.<m1>(args1).<m2>(args2)...
|
|
753
|
+
if not builder_chain: return ''
|
|
754
|
+
out = []
|
|
755
|
+
for i, (m, a) in enumerate(builder_chain):
|
|
756
|
+
if i == 0:
|
|
757
|
+
out.append(m)
|
|
758
|
+
else:
|
|
759
|
+
if a is None:
|
|
760
|
+
out.append('.' + m) # property access (e.g. .nth)
|
|
761
|
+
else:
|
|
762
|
+
out.append('.' + m + '(' + a + ')')
|
|
763
|
+
return ''.join(out)
|
|
764
|
+
|
|
765
|
+
def _resolve_locator(self, loc_text: str):
|
|
766
|
+
"""Match loc_text against page-objects catalog. Returns (module, attribute)
|
|
767
|
+
or (None, None) if unmatched."""
|
|
768
|
+
if not loc_text: return None, None
|
|
769
|
+
norm = _normalize_locator_text(loc_text)
|
|
770
|
+
if norm in self.rev_index:
|
|
771
|
+
class_name, field_name = self.rev_index[norm]
|
|
772
|
+
module = self._class_to_module(class_name)
|
|
773
|
+
return module, self._field_to_attr(class_name, field_name)
|
|
774
|
+
# Try primary-only (strip .or fallback)
|
|
775
|
+
primary = _strip_or_chain(loc_text)
|
|
776
|
+
norm_p = _normalize_locator_text(primary)
|
|
777
|
+
if norm_p in self.rev_index:
|
|
778
|
+
class_name, field_name = self.rev_index[norm_p]
|
|
779
|
+
return self._class_to_module(class_name), self._field_to_attr(class_name, field_name)
|
|
780
|
+
return None, None
|
|
781
|
+
|
|
782
|
+
def _class_to_module(self, class_name: str) -> str:
|
|
783
|
+
for c in self.catalog:
|
|
784
|
+
if c['class_name'] == class_name:
|
|
785
|
+
return c['module_name']
|
|
786
|
+
return _camel_to_words(class_name)
|
|
787
|
+
|
|
788
|
+
def _field_to_attr(self, class_name, field_name):
|
|
789
|
+
# Snake-case → original attr name (best-effort): "email_address" → "email address"
|
|
790
|
+
# The catalog doesn't carry the original Tosca attribute name; the
|
|
791
|
+
# manifest builder layer can substitute the env's true name when the
|
|
792
|
+
# base .tsu has it.
|
|
793
|
+
return field_name.replace('_', ' ')
|
|
794
|
+
|
|
795
|
+
# ── folder + step builders ─────────────────────────────────────────────
|
|
796
|
+
def _open_folder(self, name: str):
|
|
797
|
+
self.folder_stack.append(('folder', name))
|
|
798
|
+
self.steps.append({'type': 'folder', 'name': name, 'depth': len(self.folder_stack) - 1})
|
|
799
|
+
|
|
800
|
+
def _close_folder(self):
|
|
801
|
+
if self.folder_stack:
|
|
802
|
+
kind, name = self.folder_stack.pop()
|
|
803
|
+
self.steps.append({'type': 'folder_end', 'name': name,
|
|
804
|
+
'depth': len(self.folder_stack)})
|
|
805
|
+
|
|
806
|
+
def _open_block(self, name: str):
|
|
807
|
+
self.folder_stack.append(('block', name))
|
|
808
|
+
self.steps.append({'type': 'block_start', 'name': name,
|
|
809
|
+
'depth': len(self.folder_stack) - 1})
|
|
810
|
+
|
|
811
|
+
def _close_block(self):
|
|
812
|
+
if self.folder_stack:
|
|
813
|
+
kind, name = self.folder_stack.pop()
|
|
814
|
+
self.steps.append({'type': 'block_end', 'name': name,
|
|
815
|
+
'depth': len(self.folder_stack)})
|
|
816
|
+
|
|
817
|
+
def _close_folders_to_depth(self, depth: int):
|
|
818
|
+
while len(self.folder_stack) > depth:
|
|
819
|
+
kind, name = self.folder_stack.pop()
|
|
820
|
+
self.steps.append({'type': f'{kind}_end', 'name': name,
|
|
821
|
+
'depth': len(self.folder_stack)})
|
|
822
|
+
|
|
823
|
+
def _emit_or_extend_step(self, step_name: str, module_name: str, action: dict):
|
|
824
|
+
# If we already have a step open for this name+module pair, append.
|
|
825
|
+
if (self.pending_step_actions
|
|
826
|
+
and self.pending_step_actions[0] == (step_name, module_name)):
|
|
827
|
+
self.pending_step_actions[1].append(action)
|
|
828
|
+
return
|
|
829
|
+
# Different step → flush previous, start new
|
|
830
|
+
self._flush_step()
|
|
831
|
+
self.pending_step_actions = (step_name, module_name), [action]
|
|
832
|
+
|
|
833
|
+
def _flush_step(self):
|
|
834
|
+
if not self.pending_step_actions: return
|
|
835
|
+
if isinstance(self.pending_step_actions, list) and not self.pending_step_actions:
|
|
836
|
+
return
|
|
837
|
+
(name, module), actions = self.pending_step_actions
|
|
838
|
+
# Drop locator None for waiting-style
|
|
839
|
+
clean_acts = []
|
|
840
|
+
for a in actions:
|
|
841
|
+
ca = {k: v for k, v in a.items() if v is not None}
|
|
842
|
+
if 'locator' in ca and not ca['locator'].get('primary'):
|
|
843
|
+
ca.pop('locator', None)
|
|
844
|
+
clean_acts.append(ca)
|
|
845
|
+
# Emit step even when actions is empty — the @tosca step marker is the
|
|
846
|
+
# source of truth (skipped TBox modules have no actions but still need
|
|
847
|
+
# the step entity for round-trip).
|
|
848
|
+
self.steps.append({
|
|
849
|
+
'type': 'step', 'name': name, 'module': module,
|
|
850
|
+
'depth': len(self.folder_stack),
|
|
851
|
+
'actions': clean_acts,
|
|
852
|
+
})
|
|
853
|
+
self.pending_step_actions = []
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
857
|
+
# Entry point used by gen_tsu.py
|
|
858
|
+
# ──────────────────────────────────────────────────────────────────────────────
|
|
859
|
+
def build_manifest_from_spec(spec_path, pages_dir, base_manifest=None):
|
|
860
|
+
spec_path = Path(spec_path)
|
|
861
|
+
pages_dir = Path(pages_dir) if pages_dir else None
|
|
862
|
+
catalog, rev_index = ([], {})
|
|
863
|
+
if pages_dir and pages_dir.exists():
|
|
864
|
+
catalog, rev_index = parse_pages_dir(pages_dir)
|
|
865
|
+
builder = SpecToManifest(catalog, rev_index, base_manifest)
|
|
866
|
+
return builder.build(spec_path)
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
if __name__ == '__main__':
|
|
870
|
+
import sys, json
|
|
871
|
+
if len(sys.argv) < 3:
|
|
872
|
+
print('usage: spec_to_manifest.py <spec.ts> <pages_dir> [base_manifest.json]')
|
|
873
|
+
sys.exit(1)
|
|
874
|
+
base = None
|
|
875
|
+
if len(sys.argv) >= 4:
|
|
876
|
+
base = json.loads(Path(sys.argv[3]).read_text())
|
|
877
|
+
out = build_manifest_from_spec(sys.argv[1], sys.argv[2], base)
|
|
878
|
+
print(json.dumps(out, ensure_ascii=False, indent=2))
|