lantern-harness 0.1.9 → 0.1.11

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 (181) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +6 -6
  3. package/builtin/session/lh-fs.mjs +32 -14
  4. package/dist/500.html +258 -22
  5. package/dist/_astro/Base.Bgxs1QQl.css +1 -0
  6. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.CvbRi7Tl.js +1 -0
  7. package/dist/_astro/CaseExecBoard.Dttqp0wg.js +1 -0
  8. package/dist/_astro/CaseGenerateApp.DqW_nWMc.js +9 -0
  9. package/dist/_astro/CasesLibrary.8aMUUGp_.js +1 -0
  10. package/dist/_astro/ChatApp.BLxf0h1d.js +219 -0
  11. package/dist/_astro/ColumnResize.BEkEW7qw.js +1 -0
  12. package/dist/_astro/{ConfirmDialog.CBVsDJ8f.js → ConfirmDialog.BZzZWDci.js} +1 -1
  13. package/dist/_astro/{DashboardBoard.DCtfrrJz.js → DashboardBoard.CkSbhEDI.js} +3 -3
  14. package/dist/_astro/DatePicker.Bkl71M49.js +1 -0
  15. package/dist/_astro/DocsFileBrowser.MKVCfZrE.js +1 -0
  16. package/dist/_astro/DocsPager.DJY4foYL.js +1 -0
  17. package/dist/_astro/{DrawerField.CWMLhcPX.js → DrawerField.CHRg77LG.js} +1 -1
  18. package/dist/_astro/{ExcelFieldTags.B_XMwNNx.js → ExcelFieldTags.DXMeaDa5.js} +4 -4
  19. package/dist/_astro/KnowledgeLibrary.B-p1aoQN.js +1 -0
  20. package/dist/_astro/NamePromptDialog.Wa9O530a.js +1 -0
  21. package/dist/_astro/NavLibraries.C6LImMO_.js +1 -0
  22. package/dist/_astro/OverflowHint.D6v4Uj2N.js +1 -0
  23. package/dist/_astro/PluginsPage.-97n3x2U.js +39 -0
  24. package/dist/_astro/PluginsPage.DkmRPfbU.js +1 -0
  25. package/dist/_astro/PmBugsBoard.CMT4-eoB.js +1 -0
  26. package/dist/_astro/PmIterationsBoard.BQM_dzdZ.js +1 -0
  27. package/dist/_astro/PmProjectDetail.CzU80pat.js +1 -0
  28. package/dist/_astro/PmProjectsBoard.Cxsa7SYQ.js +1 -0
  29. package/dist/_astro/PmRequirementsBoard.4_JMDDN0.js +1 -0
  30. package/dist/_astro/PmRequirementsBoard.B8HL07cw.js +1 -0
  31. package/dist/_astro/PmShared.Ca2Ao7v_.js +1 -0
  32. package/dist/_astro/PromptsLibrary.C9BcIxKK.js +1 -0
  33. package/dist/_astro/ReportsPage.Fh5DRKLT.js +1 -0
  34. package/dist/_astro/RequirementsLibrary.CBkuWE8X.js +1 -0
  35. package/dist/_astro/SearchableSelect.DnjoSslK.js +1 -0
  36. package/dist/_astro/SelectDropdown.CuuDHa8s.js +1 -0
  37. package/dist/_astro/SettingsDialog.CVB5Gtk4.js +1 -0
  38. package/dist/_astro/SlideOverDrawer.B7B5Wu8I.js +1 -0
  39. package/dist/_astro/{SpaceSwitcher.CI3KDBOA.js → SpaceSwitcher.BVQLt_tL.js} +2 -2
  40. package/dist/_astro/TagSelect.CuN5RdF4.js +1 -0
  41. package/dist/_astro/TasksBoard.Bu-fpIZ7.js +1 -0
  42. package/dist/_astro/TemplatesLibrary.DSylQGlN.js +1 -0
  43. package/dist/_astro/TestStatsBoard.CPyKW4wc.js +1 -0
  44. package/dist/_astro/Toast.R8_2OWRX.js +1 -0
  45. package/dist/_astro/TodosBoard.8kvRTEW-.js +1 -0
  46. package/dist/_astro/UiAutoBoard.DFTiDqCp.js +9 -0
  47. package/dist/_astro/active-element-history.CED-m1Zp.js +1 -0
  48. package/dist/_astro/app-config.BUPzGl9f.js +1 -0
  49. package/dist/_astro/{client.Be_SakrB.js → client.BHNTqLjv.js} +3 -3
  50. package/dist/_astro/dialog.BAPTk9a_.js +1 -0
  51. package/dist/_astro/hydrate-cache.BXX604Bw.js +1 -0
  52. package/dist/_astro/{i18n.B52gLzii.js → i18n.BGPnP1Bg.js} +1 -1
  53. package/dist/_astro/index.astro_astro_type_script_index_0_lang.LPL9mPQY.js +1 -0
  54. package/dist/_astro/jsx-runtime.DUg_B_vD.js +1 -0
  55. package/dist/_astro/{lib.DJNDi_Ht.js → lib.CgXLzMMd.js} +15 -15
  56. package/dist/_astro/listbox.C96OCanh.js +1 -0
  57. package/dist/_astro/markdown-client.DRva7DS9.js +58 -0
  58. package/dist/_astro/menu.IPWdRoNM.js +1 -0
  59. package/dist/_astro/{open-docs-in-session.Xg3OSOfc.js → open-docs-in-session.CyFNgh1I.js} +1 -1
  60. package/dist/_astro/{plugins.BDZqJNOy.js → plugins.C2BMfzv1.js} +1 -1
  61. package/dist/_astro/{pm.Bl3hz9fF.js → pm.CagBA-ht.js} +2 -2
  62. package/dist/_astro/{portal.Cm9XlIPf.js → portal.C0hAhXDF.js} +2 -2
  63. package/dist/_astro/prompts-meta.Bua-j14I.js +2 -0
  64. package/dist/_astro/react-dom.DLW9pGCF.js +1 -0
  65. package/dist/_astro/{react-dom.CqAxpHMt.js → react.Blvh0GOs.js} +1 -1
  66. package/dist/_astro/report-prompt.CAfZ6RIo.js +1 -0
  67. package/dist/_astro/{settings.C6NWuiFO.js → settings.Ceefeil5.js} +2 -2
  68. package/dist/_astro/{spaces-client.k_ciWMai.js → spaces-client.BocUabwy.js} +1 -1
  69. package/dist/_astro/ui-auto-prompt.CX8fju7r.js +3 -0
  70. package/dist/_astro/ui-auto.BmC9JJ_X.js +1 -0
  71. package/dist/_astro/update.CtF8vsag.js +1 -0
  72. package/dist/_astro/use-text-value.DBQvHeNl.js +1 -0
  73. package/dist/_astro/use-tree-walker.DFU2AaAP.js +1 -0
  74. package/dist/_astro/useListAnim.BoerpmsB.js +1 -0
  75. package/dist/_astro/{view-prefs.Dyu_lmN2.js → view-prefs.BEAZRcxF.js} +1 -1
  76. package/dist/case-exec/index.html +458 -22
  77. package/dist/cases/generate/index.html +258 -22
  78. package/dist/cases/library/index.html +458 -22
  79. package/dist/dashboard/index.html +458 -22
  80. package/dist/docs/changelog/index.html +373 -23
  81. package/dist/docs/install/index.html +258 -22
  82. package/dist/docs/manual/index.html +314 -35
  83. package/dist/index.html +2 -281
  84. package/dist/knowledge/index.html +458 -22
  85. package/dist/knowledge//345/212/237/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/347/274/226/345/206/231/350/247/204/350/214/203/index.html +258 -22
  86. package/dist/plugins/index.html +258 -22
  87. package/dist/pm/bugs/index.html +458 -22
  88. package/dist/pm/iterations/index.html +458 -22
  89. package/dist/pm/projects/detail/index.html +458 -22
  90. package/dist/pm/projects/index.html +458 -22
  91. package/dist/pm/requirements/index.html +458 -22
  92. package/dist/prompts/index.html +458 -22
  93. package/dist/reports/index.html +458 -22
  94. package/dist/requirements/index.html +458 -22
  95. package/dist/tasks/index.html +458 -22
  96. package/dist/templates/index.html +458 -22
  97. package/dist/templates//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//345/212/237/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  98. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212//346/200/247/350/203/275/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  99. package/dist/templates//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213//346/200/247/350/203/275/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  100. package/dist/templates//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212//346/216/245/345/217/243/346/265/213/350/257/225/346/212/245/345/221/212/346/250/241/346/235/277/index.html +258 -22
  101. package/dist/templates//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213//350/207/252/345/212/250/345/214/226/346/265/213/350/257/225/347/224/250/344/276/213/346/250/241/346/235/277/index.html +258 -22
  102. package/dist/test-automation/index.html +717 -0
  103. package/dist/test-stats/index.html +458 -22
  104. package/dist/todos/index.html +458 -22
  105. package/dist/workbench/index.html +517 -0
  106. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +80 -43
  107. package/lh-plugins/lh-project-docs.mjs +14 -0
  108. package/lh-plugins/lh-uiauto.mjs +1445 -386
  109. package/lh-plugins/plugin-prompts.mjs +200 -0
  110. package/lh-plugins/storage-domain.mjs +6 -0
  111. package/lh-plugins/uiauto-adapters/index.mjs +57 -0
  112. package/lh-plugins/uiauto-adapters/playwright.mjs +215 -0
  113. package/lh-plugins/uiauto-adapters/pytest.mjs +151 -0
  114. package/lh-plugins/uiauto-adapters/selenium.mjs +163 -0
  115. package/lh-plugins/uiauto-adapters/shared.mjs +371 -0
  116. package/lh-plugins/uiauto-adapters/tasks.mjs +369 -0
  117. package/lh-plugins/uiauto-explorer/apps.mjs +332 -0
  118. package/lh-plugins/uiauto-explorer/diff.mjs +159 -0
  119. package/lh-plugins/uiauto-explorer/emit-files.mjs +506 -0
  120. package/lh-plugins/uiauto-explorer/emit-python.mjs +160 -0
  121. package/lh-plugins/uiauto-explorer/emit-ts.mjs +118 -0
  122. package/lh-plugins/uiauto-explorer/emit.mjs +15 -0
  123. package/lh-plugins/uiauto-explorer/ir.mjs +114 -0
  124. package/lh-plugins/uiauto-explorer/locators.mjs +267 -0
  125. package/lh-plugins/uiauto-explorer/merge.mjs +235 -0
  126. package/lh-plugins/uiauto-explorer/plan.mjs +165 -0
  127. package/lh-plugins/uiauto-explorer/runner.mjs +370 -0
  128. package/lh-plugins/uiauto-explorer/sessions.mjs +1373 -0
  129. package/lh-plugins/uiauto-explorer/snapshot.mjs +492 -0
  130. package/lh-plugins/uiauto-prompt.mjs +122 -0
  131. package/lh-plugins/uiauto-report.mjs +111 -0
  132. package/package.json +1 -1
  133. package/dist/_astro/Base.4X_wsSoR.css +0 -1
  134. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.Dy7fJoxu.js +0 -1
  135. package/dist/_astro/CaseExecBoard.DKdfW5fM.js +0 -1
  136. package/dist/_astro/CaseGenerateApp.Bm8AyH9s.js +0 -9
  137. package/dist/_astro/CasesLibrary.CvVJZ74h.js +0 -1
  138. package/dist/_astro/ChatApp.BS-wLBRa.js +0 -276
  139. package/dist/_astro/ColumnResize.Bs6GL3DJ.js +0 -1
  140. package/dist/_astro/DatePicker.CMfX7F6z.js +0 -1
  141. package/dist/_astro/DocsFileBrowser.BtRoZ787.js +0 -1
  142. package/dist/_astro/DocsPager.C20ue_JZ.js +0 -1
  143. package/dist/_astro/KnowledgeLibrary.CV4DyStj.js +0 -1
  144. package/dist/_astro/NamePromptDialog.Dl5kSnQI.js +0 -1
  145. package/dist/_astro/NavLibraries.DmD2lZBZ.js +0 -1
  146. package/dist/_astro/OverflowHint.lzmplP5j.js +0 -1
  147. package/dist/_astro/PluginsPage.B59AMDrB.js +0 -1
  148. package/dist/_astro/PluginsPage.BEAPymNL.js +0 -39
  149. package/dist/_astro/PmBugsBoard.CPEyBp0l.js +0 -1
  150. package/dist/_astro/PmIterationsBoard.zCeLpcBo.js +0 -1
  151. package/dist/_astro/PmProjectDetail.ejIam5sD.js +0 -1
  152. package/dist/_astro/PmProjectsBoard.DbXzir8o.js +0 -1
  153. package/dist/_astro/PmRequirementsBoard.CynewRfv.js +0 -1
  154. package/dist/_astro/PmRequirementsBoard.D9eUMJWI.js +0 -1
  155. package/dist/_astro/PmShared.BxTHKdjY.js +0 -1
  156. package/dist/_astro/PromptsLibrary.Bkruu80b.js +0 -1
  157. package/dist/_astro/ReportsPage.BoBQshMQ.js +0 -1
  158. package/dist/_astro/RequirementsLibrary.BC0A8qdk.js +0 -1
  159. package/dist/_astro/SearchableSelect.CXa1hiDd.js +0 -1
  160. package/dist/_astro/SelectDropdown.Buv7rQJ_.js +0 -1
  161. package/dist/_astro/SettingsDialog.Dc-9QNJI.js +0 -1
  162. package/dist/_astro/SlideOverDrawer.TPbGEoWn.js +0 -1
  163. package/dist/_astro/TagSelect.u8DTop7v.js +0 -1
  164. package/dist/_astro/TasksBoard.Bb--oVV8.js +0 -1
  165. package/dist/_astro/TemplatesLibrary.D1wZq94E.js +0 -1
  166. package/dist/_astro/TestStatsBoard.DlVezlXl.js +0 -1
  167. package/dist/_astro/TodosBoard.S84wqcWY.js +0 -1
  168. package/dist/_astro/UiAutoBoard.BKp9ifxg.js +0 -1
  169. package/dist/_astro/active-element-history.CeefGkFQ.js +0 -1
  170. package/dist/_astro/app-config.DUyozIL9.js +0 -1
  171. package/dist/_astro/dialog.DXHznyjD.js +0 -1
  172. package/dist/_astro/jsx-runtime.BUXbF_vF.js +0 -1
  173. package/dist/_astro/listbox.Di-t5U37.js +0 -1
  174. package/dist/_astro/menu.Bkluqxic.js +0 -1
  175. package/dist/_astro/prompts-meta.F4wwkjUA.js +0 -2
  176. package/dist/_astro/report-prompt.Cmw4XzfY.js +0 -1
  177. package/dist/_astro/update.Bl_HfSe6.js +0 -1
  178. package/dist/_astro/use-text-value.BuY0Cm1z.js +0 -1
  179. package/dist/_astro/use-tree-walker.CfTHFX43.js +0 -1
  180. package/dist/_astro/useListAnim.CpGB1cft.js +0 -1
  181. package/dist/ui-automation/index.html +0 -281
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 极简行级 diff:给「文件变更」面板用,不引第三方依赖。
3
+ *
4
+ * 做法:先剥掉公共前后缀,再对中间段做 LCS;段太大时退化成整块替换,
5
+ * 宁可粗一点也不要卡住浏览器(AI 生成的 spec 一般几十行,退化很少发生)。
6
+ */
7
+
8
+ const MAX_LINES = 4000;
9
+ const MAX_CELLS = 4_000_000;
10
+
11
+ function toLines(text) {
12
+ const value = String(text ?? '');
13
+ if (!value) return [];
14
+ const lines = value.split(/\r?\n/);
15
+ // 末尾换行不单独算一行,否则每个文件都会多出一条空上下文
16
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
17
+ return lines;
18
+ }
19
+
20
+ /** 中间段 LCS → 操作序列 */
21
+ function diffMiddle(a, b) {
22
+ if (!a.length) return b.map((text) => ({ type: 'add', text }));
23
+ if (!b.length) return a.map((text) => ({ type: 'del', text }));
24
+ if (a.length * b.length > MAX_CELLS) {
25
+ return [
26
+ ...a.map((text) => ({ type: 'del', text })),
27
+ ...b.map((text) => ({ type: 'add', text })),
28
+ ];
29
+ }
30
+ const rows = a.length;
31
+ const cols = b.length;
32
+ // 从后往前填表,回溯时正好从前往后走
33
+ const table = new Uint32Array((rows + 1) * (cols + 1));
34
+ const at = (i, j) => i * (cols + 1) + j;
35
+ for (let i = rows - 1; i >= 0; i -= 1) {
36
+ for (let j = cols - 1; j >= 0; j -= 1) {
37
+ table[at(i, j)] =
38
+ a[i] === b[j]
39
+ ? table[at(i + 1, j + 1)] + 1
40
+ : Math.max(table[at(i + 1, j)], table[at(i, j + 1)]);
41
+ }
42
+ }
43
+ const ops = [];
44
+ let i = 0;
45
+ let j = 0;
46
+ while (i < rows && j < cols) {
47
+ if (a[i] === b[j]) {
48
+ ops.push({ type: 'equal', text: a[i] });
49
+ i += 1;
50
+ j += 1;
51
+ } else if (table[at(i + 1, j)] >= table[at(i, j + 1)]) {
52
+ ops.push({ type: 'del', text: a[i] });
53
+ i += 1;
54
+ } else {
55
+ ops.push({ type: 'add', text: b[j] });
56
+ j += 1;
57
+ }
58
+ }
59
+ while (i < rows) {
60
+ ops.push({ type: 'del', text: a[i] });
61
+ i += 1;
62
+ }
63
+ while (j < cols) {
64
+ ops.push({ type: 'add', text: b[j] });
65
+ j += 1;
66
+ }
67
+ return ops;
68
+ }
69
+
70
+ function diffOps(a, b) {
71
+ const maxPrefix = Math.min(a.length, b.length);
72
+ let prefix = 0;
73
+ while (prefix < maxPrefix && a[prefix] === b[prefix]) prefix += 1;
74
+ let suffix = 0;
75
+ while (suffix < maxPrefix - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) {
76
+ suffix += 1;
77
+ }
78
+ const head = a.slice(0, prefix).map((text) => ({ type: 'equal', text }));
79
+ const middleA = a.slice(prefix, a.length - suffix);
80
+ const middleB = b.slice(prefix, b.length - suffix);
81
+ const tail = suffix ? a.slice(a.length - suffix).map((text) => ({ type: 'equal', text })) : [];
82
+ return [...head, ...diffMiddle(middleA, middleB), ...tail];
83
+ }
84
+
85
+ /**
86
+ * @param {string} before 旧内容(新文件传空串)
87
+ * @param {string} after 新内容
88
+ * @param {{ context?: number, maxLines?: number }} [options]
89
+ */
90
+ export function diffText(before, after, options = {}) {
91
+ const context = Math.max(0, Math.min(20, Number(options.context ?? 3)));
92
+ const maxLines = Math.max(100, Number(options.maxLines ?? MAX_LINES));
93
+ const a = toLines(before);
94
+ const b = toLines(after);
95
+
96
+ if (a.length + b.length > maxLines) {
97
+ return {
98
+ hunks: [],
99
+ added: b.length,
100
+ removed: a.length,
101
+ truncated: true,
102
+ message: `文件较大(${a.length + b.length} 行),只显示增删行数`,
103
+ };
104
+ }
105
+
106
+ const ops = diffOps(a, b);
107
+ const added = ops.filter((op) => op.type === 'add').length;
108
+ const removed = ops.filter((op) => op.type === 'del').length;
109
+
110
+ // 只保留「有改动」的行及其上下文,拼成 hunk
111
+ const keep = new Array(ops.length).fill(false);
112
+ ops.forEach((op, index) => {
113
+ if (op.type === 'equal') return;
114
+ for (let k = index - context; k <= index + context; k += 1) {
115
+ if (k >= 0 && k < ops.length) keep[k] = true;
116
+ }
117
+ });
118
+
119
+ const hunks = [];
120
+ let index = 0;
121
+ // 行号按「改动前的旧文件 / 改动后的新文件」分别累加
122
+ let oldNo = 1;
123
+ let newNo = 1;
124
+ while (index < ops.length) {
125
+ if (!keep[index]) {
126
+ if (ops[index].type !== 'add') oldNo += 1;
127
+ if (ops[index].type !== 'del') newNo += 1;
128
+ index += 1;
129
+ continue;
130
+ }
131
+ const lines = [];
132
+ const oldStart = oldNo;
133
+ const newStart = newNo;
134
+ let oldCount = 0;
135
+ let newCount = 0;
136
+ while (index < ops.length && keep[index]) {
137
+ const op = ops[index];
138
+ lines.push({ type: op.type, text: op.text });
139
+ if (op.type !== 'add') {
140
+ oldNo += 1;
141
+ oldCount += 1;
142
+ }
143
+ if (op.type !== 'del') {
144
+ newNo += 1;
145
+ newCount += 1;
146
+ }
147
+ index += 1;
148
+ }
149
+ hunks.push({ oldStart, oldLines: oldCount, newStart, newLines: newCount, lines });
150
+ }
151
+
152
+ return { hunks, added, removed, truncated: false };
153
+ }
154
+
155
+ /** 写进会话账本的一行统计,不存整份内容 */
156
+ export function summarizeDiff(before, after) {
157
+ const result = diffText(before, after, { context: 0 });
158
+ return { added: result.added, removed: result.removed };
159
+ }
@@ -0,0 +1,506 @@
1
+ /**
2
+ * 多文件出码:主用例 + 按页面拆出的 page object(+ 可选的登录态 fixture、config 补丁建议)。
3
+ *
4
+ * 为什么要拆:一条用例往往要同时改 spec、页面对象、fixture。
5
+ * 只写一个文件的话,用户还得手工把重复的定位器抽出去。
6
+ *
7
+ * 约定:
8
+ * - 导航(goto / wait / 截图 / URL 断言)留在 spec 里,元素操作进 page object。
9
+ * - page object 按 goto 的 URL 分段:/login → LoginPage,/ → HomePage。
10
+ * - 定位器文本是中文时方法名退化到角色名(clickButton),重名再加序号。
11
+ */
12
+ import { emitCode } from './emit.mjs';
13
+ import { locatorCode as tsLocator, valueCode as tsValue } from './emit-ts.mjs';
14
+ import { locatorCode as pyLocator, valueCode as pyValue } from './emit-python.mjs';
15
+ import { normalizeIr, pythonFunctionName, slugify } from './ir.mjs';
16
+
17
+ const q = (value) => JSON.stringify(String(value ?? ''));
18
+
19
+ /** 元素操作(进 page object);导航类动作留在 spec */
20
+ const ELEMENT_ACTIONS = new Set(['click', 'fill', 'select', 'press', 'hover', 'expect']);
21
+
22
+ function pascal(text) {
23
+ const ascii = String(text ?? '')
24
+ .replace(/[^a-zA-Z0-9]+/g, ' ')
25
+ .trim();
26
+ if (!ascii) return '';
27
+ return ascii
28
+ .split(/\s+/)
29
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
30
+ .join('');
31
+ }
32
+
33
+ function snake(text) {
34
+ return String(text ?? '')
35
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
36
+ .replace(/[^a-zA-Z0-9]+/g, '_')
37
+ .replace(/^_+|_+$/g, '')
38
+ .toLowerCase();
39
+ }
40
+
41
+ /** `/cart/list?x=1` → `CartListPage`;`/` → `HomePage` */
42
+ export function pageNameFor(url) {
43
+ const clean = String(url ?? '')
44
+ .split('#')[0]
45
+ .split('?')[0]
46
+ .replace(/^https?:\/\/[^/]+/i, '');
47
+ const base = pascal(clean);
48
+ return `${base || 'Home'}Page`;
49
+ }
50
+
51
+ const KIND_HINT = {
52
+ testid: 'TestId',
53
+ role: 'Role',
54
+ label: 'Label',
55
+ placeholder: 'Placeholder',
56
+ text: 'Text',
57
+ attr: 'ByAttr',
58
+ css: 'Locator',
59
+ };
60
+
61
+ /** 页面内方法名:优先用定位器文本,退化到角色 / 类型 */
62
+ function methodBase(step) {
63
+ const locator = step.locator ?? {};
64
+ const hint =
65
+ pascal(locator.value) ||
66
+ pascal(locator.name) ||
67
+ pascal(locator.role) ||
68
+ pascal(locator.attr) ||
69
+ KIND_HINT[locator.kind] ||
70
+ '';
71
+ const action = step.action;
72
+ const tail = hint || 'Element';
73
+ return `${action}${tail.charAt(0).toUpperCase()}${tail.slice(1)}`;
74
+ }
75
+
76
+ function uniqueName(base, used) {
77
+ if (!used.has(base)) {
78
+ used.add(base);
79
+ return base;
80
+ }
81
+ let index = 2;
82
+ while (used.has(`${base}${index}`)) index += 1;
83
+ const next = `${base}${index}`;
84
+ used.add(next);
85
+ return next;
86
+ }
87
+
88
+ /**
89
+ * 把 IR 的步骤分组:每个 goto 开一段,段内元素操作归到该页面的 page object。
90
+ * 第一段没有 goto 时算「首页」。
91
+ */
92
+ export function splitPages(ir) {
93
+ const segments = [];
94
+ let current = { url: '', steps: [] };
95
+ for (const step of ir.steps) {
96
+ if (step.action === 'goto') {
97
+ if (current.steps.length || current.url) segments.push(current);
98
+ current = { url: String(step.url ?? '/'), steps: [] };
99
+ continue;
100
+ }
101
+ current.steps.push(step);
102
+ }
103
+ if (current.steps.length || current.url) segments.push(current);
104
+ if (!segments.length) segments.push({ url: '/', steps: [] });
105
+
106
+ const pages = [];
107
+ const usedPageNames = new Set();
108
+ for (const segment of segments) {
109
+ const methods = [];
110
+ const used = new Set();
111
+ for (const step of segment.steps) {
112
+ if (!ELEMENT_ACTIONS.has(step.action) || !step.locator) continue;
113
+ methods.push({ step, name: uniqueName(methodBase(step), used) });
114
+ }
115
+ if (!methods.length) continue;
116
+ const name = uniqueName(pageNameFor(segment.url), usedPageNames);
117
+ pages.push({ name, url: segment.url, methods });
118
+ }
119
+ return pages;
120
+ }
121
+
122
+ /** 页面名 → spec 里的变量名:LoginPage → loginPage */
123
+ function varName(pageName) {
124
+ return `${pageName.charAt(0).toLowerCase()}${pageName.slice(1)}`;
125
+ }
126
+
127
+ function tsMethod(method, index) {
128
+ const { step, name } = method;
129
+ const target = tsLocator(step.locator, 'this.page');
130
+ const note = step.note ? ` /** ${step.note.replace(/\s+/g, ' ').slice(0, 120)} */\n` : '';
131
+ if (step.action === 'fill') {
132
+ return `${note} async ${name}(value: string) {\n await ${target}.fill(value);\n }`;
133
+ }
134
+ if (step.action === 'select') {
135
+ return `${note} async ${name}(value: string) {\n await ${target}.selectOption(value);\n }`;
136
+ }
137
+ if (step.action === 'press') {
138
+ return `${note} async ${name}(key = ${q(step.key ?? 'Enter')}) {\n await ${target}.press(key);\n }`;
139
+ }
140
+ if (step.action === 'click') {
141
+ return `${note} async ${name}() {\n await ${target}.click();\n }`;
142
+ }
143
+ if (step.action === 'hover') {
144
+ return `${note} async ${name}() {\n await ${target}.hover();\n }`;
145
+ }
146
+ if (step.action === 'expect') {
147
+ if (step.text) {
148
+ return `${note} async ${name}(text = ${q(step.text)}) {\n await expect(${target}).toContainText(text);\n }`;
149
+ }
150
+ if (step.state === 'hidden') {
151
+ return `${note} async ${name}() {\n await expect(${target}).toBeHidden();\n }`;
152
+ }
153
+ return `${note} async ${name}() {\n await expect(${target}).toBeVisible();\n }`;
154
+ }
155
+ return `${note} async ${name}() {\n // 第 ${index + 1} 步:${step.action}\n }`;
156
+ }
157
+
158
+ export function renderTsPage(page) {
159
+ const lines = [];
160
+ lines.push('/**');
161
+ lines.push(` * ${page.name}:${page.url || '/'} 上的元素操作。`);
162
+ lines.push(' */');
163
+ lines.push("import { expect, type Page } from '@playwright/test';");
164
+ lines.push('');
165
+ lines.push(`export class ${page.name} {`);
166
+ lines.push(' constructor(private readonly page: Page) {}');
167
+ for (let index = 0; index < page.methods.length; index += 1) {
168
+ lines.push('');
169
+ lines.push(tsMethod(page.methods[index], index));
170
+ }
171
+ lines.push('}');
172
+ lines.push('');
173
+ return lines.join('\n');
174
+ }
175
+
176
+ /** spec 里与 page object 无关的步骤:导航 / 等待 / 截图 / URL 断言 */
177
+ function specStepLine(step, index) {
178
+ switch (step.action) {
179
+ case 'expectUrl':
180
+ return ` await expect(page).toHaveURL(${tsValue(step.url ?? '/')});`;
181
+ case 'wait':
182
+ return ` await page.waitForTimeout(${Number(step.ms) || 500});`;
183
+ case 'screenshot': {
184
+ const name = String(step.value ?? `step-${index + 1}`)
185
+ .replace(/[^\w.-]+/g, '-')
186
+ .replace(/^-+|-+$/g, '');
187
+ return ` await page.screenshot({ path: ${q(
188
+ `reports/ai/${name || `step-${index + 1}`}.png`,
189
+ )}, fullPage: true });`;
190
+ }
191
+ case 'press':
192
+ return ` await page.keyboard.press(${q(step.key ?? 'Enter')});`;
193
+ default:
194
+ return '';
195
+ }
196
+ }
197
+
198
+ /** TS spec:导航留在用例里,元素操作调 page object */
199
+ export function renderTsSpec(ir, pages, options = {}) {
200
+ const title = ir.title || 'AI 生成用例';
201
+ const lines = [];
202
+ lines.push('/**');
203
+ lines.push(` * ${title}`);
204
+ if (ir.source) {
205
+ for (const line of String(ir.source).split(/\r?\n/).slice(0, 8)) {
206
+ lines.push(` * ${line.trim()}`);
207
+ }
208
+ }
209
+ lines.push(' */');
210
+ lines.push("import { test, expect } from '@playwright/test';");
211
+ for (const page of pages) {
212
+ lines.push(`import { ${page.name} } from './pages/${page.name}';`);
213
+ }
214
+ if (ir.storageState && options.fixturePath) {
215
+ lines.push(`import { STORAGE_STATE } from '${options.fixtureImport}';`);
216
+ }
217
+ lines.push('');
218
+
219
+ const useOptions = [];
220
+ if (ir.baseURL) useOptions.push(`baseURL: ${q(ir.baseURL)}`);
221
+ if (ir.storageState) {
222
+ useOptions.push(`storageState: ${options.fixturePath ? 'STORAGE_STATE' : q(ir.storageState)}`);
223
+ }
224
+ if (useOptions.length) {
225
+ lines.push(`test.use({ ${useOptions.join(', ')} });`);
226
+ lines.push('');
227
+ }
228
+
229
+ lines.push(`test.describe(${q(title)}, () => {`);
230
+ lines.push(` test(${q(title)}, async ({ page }) => {`);
231
+ if (ir.baseURL) lines.push(` // baseURL: ${ir.baseURL}`);
232
+ for (const page of pages) {
233
+ lines.push(` const ${varName(page.name)} = new ${page.name}(page);`);
234
+ }
235
+
236
+ let pageCursor = 0;
237
+ let current = pages[0] ?? null;
238
+ let methodCursor = 0;
239
+ for (let index = 0; index < ir.steps.length; index += 1) {
240
+ const step = ir.steps[index];
241
+ if (step.note) lines.push(` // ${step.note.replace(/\s+/g, ' ').slice(0, 160)}`);
242
+ if (step.action === 'goto') {
243
+ const target = pages.find(
244
+ (item, i) => i >= pageCursor && item.url === String(step.url ?? '/'),
245
+ );
246
+ if (target) {
247
+ pageCursor = pages.indexOf(target);
248
+ current = target;
249
+ }
250
+ methodCursor = 0;
251
+ lines.push(` await page.goto(${q(step.url ?? '/')});`);
252
+ continue;
253
+ }
254
+ if (ELEMENT_ACTIONS.has(step.action) && step.locator) {
255
+ const method = current?.methods[methodCursor];
256
+ methodCursor += 1;
257
+ if (method && current) {
258
+ const call = `${varName(current.name)}.${method.name}`;
259
+ if (step.action === 'fill' || step.action === 'select') {
260
+ lines.push(` await ${call}(${tsValue(step.value)});`);
261
+ } else if (step.action === 'expect' && step.text) {
262
+ lines.push(` await ${call}(${tsValue(step.text)});`);
263
+ } else if (step.action === 'press' && step.key) {
264
+ lines.push(` await ${call}(${q(step.key)});`);
265
+ } else {
266
+ lines.push(` await ${call}();`);
267
+ }
268
+ continue;
269
+ }
270
+ }
271
+ const line = specStepLine(step, index);
272
+ if (line) lines.push(line);
273
+ }
274
+ lines.push(' });');
275
+ lines.push('});');
276
+ lines.push('');
277
+ return lines.join('\n');
278
+ }
279
+
280
+ function pyMethod(method, index) {
281
+ const { step } = method;
282
+ const name = snake(method.name);
283
+ const target = pyLocator(step.locator, 'self.page');
284
+ const withValue = step.action === 'fill' || step.action === 'select';
285
+ const signature = `def ${name}(self${withValue ? ', value: str' : ''}) -> None:`;
286
+ const note = step.note ? ` # ${step.note.replace(/\s+/g, ' ').slice(0, 120)}\n` : '';
287
+ if (step.action === 'fill') return `${note} ${signature}\n ${target}.fill(value)`;
288
+ if (step.action === 'select') {
289
+ return `${note} ${signature}\n ${target}.select_option(value)`;
290
+ }
291
+ if (step.action === 'press') {
292
+ return `${note} ${signature}\n ${target}.press(${q(step.key ?? 'Enter')})`;
293
+ }
294
+ if (step.action === 'click') return `${note} ${signature}\n ${target}.click()`;
295
+ if (step.action === 'hover') return `${note} ${signature}\n ${target}.hover()`;
296
+ if (step.action === 'expect') {
297
+ if (step.text) {
298
+ return `${note} ${signature}\n expect(${target}).to_contain_text(${q(step.text)})`;
299
+ }
300
+ if (step.state === 'hidden') {
301
+ return `${note} ${signature}\n expect(${target}).to_be_hidden()`;
302
+ }
303
+ return `${note} ${signature}\n expect(${target}).to_be_visible()`;
304
+ }
305
+ return `${note} ${signature}\n pass # 第 ${index + 1} 步:${step.action}`;
306
+ }
307
+
308
+ export function renderPyPage(page) {
309
+ const lines = [];
310
+ lines.push('"""');
311
+ lines.push(`${page.name}:${page.url || '/'} 上的元素操作。`);
312
+ lines.push('"""');
313
+ lines.push('from playwright.sync_api import Page, expect');
314
+ lines.push('');
315
+ lines.push('');
316
+ lines.push(`class ${page.name}:`);
317
+ lines.push(' def __init__(self, page: Page) -> None:');
318
+ lines.push(' self.page = page');
319
+ for (let index = 0; index < page.methods.length; index += 1) {
320
+ lines.push('');
321
+ lines.push(pyMethod(page.methods[index], index));
322
+ }
323
+ lines.push('');
324
+ return lines.join('\n');
325
+ }
326
+
327
+ export function renderPySpec(ir, pages) {
328
+ const title = ir.title || 'AI 生成用例';
329
+ const funcName = pythonFunctionName(title);
330
+ const lines = [];
331
+ lines.push('"""');
332
+ lines.push(title);
333
+ if (ir.source) {
334
+ for (const line of String(ir.source).split(/\r?\n/).slice(0, 8)) {
335
+ lines.push(line.trim());
336
+ }
337
+ }
338
+ lines.push('"""');
339
+ lines.push('import os');
340
+ lines.push('');
341
+ lines.push('from playwright.sync_api import Page, expect');
342
+ for (const page of pages) {
343
+ lines.push(`from pages.${snake(page.name)} import ${page.name}`);
344
+ }
345
+ if (ir.baseURL) {
346
+ lines.push('');
347
+ lines.push(`BASE_URL = os.environ.get("BASE_URL", ${q(ir.baseURL)})`);
348
+ }
349
+ lines.push('');
350
+ lines.push('');
351
+ lines.push(`def ${funcName}(page: Page) -> None:`);
352
+ const url = (value) =>
353
+ ir.baseURL && String(value ?? '/').startsWith('/')
354
+ ? `BASE_URL + ${q(value ?? '/')}`
355
+ : q(value ?? '/');
356
+
357
+ for (const page of pages) {
358
+ lines.push(` ${snake(page.name)} = ${page.name}(page)`);
359
+ }
360
+ let pageCursor = 0;
361
+ let current = pages[0] ?? null;
362
+ let methodCursor = 0;
363
+ for (let index = 0; index < ir.steps.length; index += 1) {
364
+ const step = ir.steps[index];
365
+ if (step.note) lines.push(` # ${step.note.replace(/\s+/g, ' ').slice(0, 160)}`);
366
+ if (step.action === 'goto') {
367
+ const target = pages.find(
368
+ (item, i) => i >= pageCursor && item.url === String(step.url ?? '/'),
369
+ );
370
+ if (target) {
371
+ pageCursor = pages.indexOf(target);
372
+ current = target;
373
+ }
374
+ methodCursor = 0;
375
+ lines.push(` page.goto(${url(step.url)})`);
376
+ continue;
377
+ }
378
+ if (ELEMENT_ACTIONS.has(step.action) && step.locator) {
379
+ const method = current?.methods[methodCursor];
380
+ methodCursor += 1;
381
+ if (method && current) {
382
+ const call = `${snake(current.name)}.${snake(method.name)}`;
383
+ if (step.action === 'fill' || step.action === 'select') {
384
+ lines.push(` ${call}(${pyValue(step.value)})`);
385
+ } else {
386
+ lines.push(` ${call}()`);
387
+ }
388
+ continue;
389
+ }
390
+ }
391
+ if (step.action === 'expectUrl') {
392
+ lines.push(` expect(page).to_have_url(${url(step.url ?? '/')})`);
393
+ } else if (step.action === 'wait') {
394
+ lines.push(` page.wait_for_timeout(${Number(step.ms) || 500})`);
395
+ } else if (step.action === 'screenshot') {
396
+ const name = String(step.value ?? `step-${index + 1}`)
397
+ .replace(/[^\w.-]+/g, '-')
398
+ .replace(/^-+|-+$/g, '');
399
+ const file = `reports/ai/${name || `step-${index + 1}`}.png`;
400
+ lines.push(` page.screenshot(path=${q(file)}, full_page=True)`);
401
+ } else if (step.action === 'press') {
402
+ lines.push(` page.keyboard.press(${q(step.key ?? 'Enter')})`);
403
+ }
404
+ }
405
+ if (!ir.steps.length) lines.push(' pass');
406
+ lines.push('');
407
+ return lines.join('\n');
408
+ }
409
+
410
+ /** TS 登录态常量:让 spec 与项目里其它用例复用同一份 storageState */
411
+ function tsFixture(storageState) {
412
+ return [
413
+ '/**',
414
+ ' * 登录态路径。',
415
+ ' */',
416
+ `export const STORAGE_STATE = ${q(storageState)};`,
417
+ '',
418
+ ].join('\n');
419
+ }
420
+
421
+ function normalizeDir(value, fallback) {
422
+ const raw = String(value ?? '')
423
+ .replace(/\\/g, '/')
424
+ .replace(/^\.?\//, '')
425
+ .replace(/\/+$/, '')
426
+ .trim();
427
+ return raw || fallback;
428
+ }
429
+
430
+ /**
431
+ * 生成一组待写入文件。
432
+ *
433
+ * @returns {{ files: Array<{path:string,content:string,language:string,role:string}>, configPatch: object|null }}
434
+ * role: 'spec' 主用例 / 'page' 页面对象 / 'fixture' 登录态常量
435
+ */
436
+ export function emitFiles(rawIr, target, options = {}) {
437
+ const ir = normalizeIr(rawIr, { target });
438
+ const language = target === 'python' || ir.target === 'python' ? 'python' : 'ts';
439
+ const testDir = normalizeDir(options.testDir, 'tests');
440
+ const single = emitCode(ir, language);
441
+ const pages = splitPages(ir);
442
+ const files = [];
443
+
444
+ if (language === 'python') {
445
+ files.push({
446
+ path: `${testDir}/${single.filename}`,
447
+ content: renderPySpec(ir, pages),
448
+ language: 'python',
449
+ role: 'spec',
450
+ });
451
+ for (const page of pages) {
452
+ files.push({
453
+ path: `${testDir}/pages/${snake(page.name).replace(/_page$/, '')}_page.py`,
454
+ content: renderPyPage(page),
455
+ language: 'python',
456
+ role: 'page',
457
+ });
458
+ }
459
+ } else {
460
+ const fixturePath = `${testDir}/fixtures/auth-state.ts`;
461
+ const fixtureImport = './fixtures/auth-state';
462
+ const useFixture = Boolean(ir.storageState) && options.fixture !== false;
463
+ files.push({
464
+ path: `${testDir}/${single.filename}`,
465
+ content: renderTsSpec(ir, pages, {
466
+ fixturePath: useFixture ? fixturePath : '',
467
+ fixtureImport,
468
+ }),
469
+ language: 'ts',
470
+ role: 'spec',
471
+ });
472
+ for (const page of pages) {
473
+ files.push({
474
+ path: `${testDir}/pages/${page.name}.ts`,
475
+ content: renderTsPage(page),
476
+ language: 'ts',
477
+ role: 'page',
478
+ });
479
+ }
480
+ if (useFixture) {
481
+ files.push({
482
+ path: fixturePath,
483
+ content: tsFixture(ir.storageState),
484
+ language: 'ts',
485
+ role: 'fixture',
486
+ });
487
+ }
488
+ }
489
+
490
+ // 项目没配 baseURL 时只给建议,不替用户改 config
491
+ let configPatch = null;
492
+ if (ir.baseURL && !options.hasBaseURL) {
493
+ configPatch = {
494
+ path: language === 'python' ? 'pytest.ini' : 'playwright.config.ts',
495
+ reason: '项目配置里没有 baseURL,想全局生效可以补上;用例本身不依赖它',
496
+ snippet:
497
+ language === 'python'
498
+ ? `# pytest.ini\n# addopts = --base-url ${ir.baseURL}`
499
+ : `// playwright.config.ts\nuse: { baseURL: ${q(ir.baseURL)} },`,
500
+ };
501
+ }
502
+
503
+ return { files, configPatch };
504
+ }
505
+
506
+ export { slugify, snake };