var d=class{async generate(a){throw new Error("TestGenerationStrategy.generate() must be implemented")}canGenerate(a){throw new Error("TestGenerationStrategy.canGenerate() must be implemented")}getName(){throw new Error("TestGenerationStrategy.getName() must be implemented")}getPriority(){return 0}};import{readFileSync as w,writeFileSync as G}from"node:fs";var b=class extends d{constructor(){super("mcp-ref","MCP Reference Replay (Exact 1:1)",200)}canGenerate(a){let t=a.eventsPath||`${a.sessionPath}/execute_live/events.json`;try{return JSON.parse(w(t,"utf-8")).some(p=>p.data?.params?.element)?(console.log("[MCPRefStrategy] \u2705 MCP element descriptions available"),!0):(console.log("[MCPRefStrategy] \u274C No MCP element descriptions found in events"),!1)}catch(s){return console.log("[MCPRefStrategy] \u274C Failed to read events:",s.message),!1}}getName(){return"MCP Reference Replay (Exact 1:1)"}getPriority(){return 200}async generate(a){let{testFilePath:t,sessionPath:s,state:o}=a,p=`${s}/execute_live/events.json`,x=o?.title||"Generated Test";console.log("[MCPRefStrategy] \u{1F3AF} Generating test using MCP element descriptions (1:1 replay)"),console.log(`[MCPRefStrategy]    events: ${p}`),console.log(`[MCPRefStrategy]    output: ${t}`);let u=JSON.parse(w(p,"utf-8")).filter(n=>["navigate","type","fill","click","select_option"].includes(n.type)),e=`import { test, expect } from '@playwright/test';
`;e+=`import { ZibbyRuntime } from '@zibby/core';

`,e+=`test('${x}', async ({ page }) => {
`,e+=`  const timestamp = Date.now();

`;for(let n of u){let l=n.data?.params?.element||"element",m=n.data?.params?.ref,r=n.enrichedData?.traceActualText,c=n.enrichedData?.traceActualRole,$=n.enrichedData?.traceActualAriaLabel,i=n.enrichedData?.actualText,g=r||i,k=c||n.enrichedData?.actualRole,M=g||l,y=g||this._extractName(l),_=k||this._extractRole(l),v=r?" [accessibility-tree]":i?" [live]":" [AI]";if(n.type==="navigate")e+=`  await page.goto('${n.data.params.url}');

`;else if(n.type==="click")e+=`  // ${l}${g?` (actual: "${g}")${v}`:""}
`,e+=`  await ZibbyRuntime.step(page, {
`,e+=`    name: '${this._escapeString(l)}',
`,e+=`    action: 'click',
`,e+=`    strategies: [
`,e+=`      { type: 'role', role: '${_}', name: '${this._escapeString(y)}' },
`,e+=`      { type: 'text', text: '${this._escapeString(y)}' }
`,e+=`    ]
`,e+=`  });

`;else if(n.type==="fill"||n.type==="type"){let f=n.data.params.text;e+=`  // ${l}${g?` (actual: "${g}")${v}`:""}
`,e+=`  await ZibbyRuntime.step(page, {
`,e+=`    name: '${this._escapeString(l)}',
`,e+=`    action: 'fill',
`,e+=`    value: '${this._escapeString(f)}',
`,e+=`    strategies: [
`,e+=`      { type: 'role', role: '${_}', name: '${this._escapeString(y)}' },
`,e+=`      { type: 'attributes', placeholder: '${this._escapeString(y)}' }
`,e+=`    ]
`,e+=`  });

`}else if(n.type==="select_option"){let f=n.data.params.values,C=Array.isArray(f)?f[0]:f;e+=`  // ${l}${g?` (actual: "${g}")${v}`:""}
`,e+=`  await ZibbyRuntime.step(page, {
`,e+=`    name: '${this._escapeString(l)}',
`,e+=`    action: 'select',
`,e+=`    value: '${this._escapeString(C)}',
`,e+=`    strategies: [
`,e+=`      { type: 'role', role: 'combobox', name: '${this._escapeString(y)}' }
`,e+=`    ]
`,e+=`  });

`}}return e+=`});
`,G(t,e),console.log(`[MCPRefStrategy] \u2705 Generated test with ${u.length} actions using MCP descriptions`),{success:!0,testPath:t,method:"MCP Reference Replay (1:1)",actionsGenerated:u.length}}_extractRole(a){let t=a.toLowerCase();return t.includes("button")?"button":t.includes("textbox")?"textbox":t.includes("link")?"link":t.includes("checkbox")?"checkbox":t.includes("radio")?"radio":t.includes("combobox")?"combobox":t.includes("heading")?"heading":"button"}_extractName(a){return a.replace(/\s+(button|textbox|link|checkbox|radio|combobox)$/i,"").trim()}_escapeRegex(a){return a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}_escapeString(a){return a.replace(/'/g,"\\'").replace(/\n/g,"\\n")}};import{readFileSync as R,writeFileSync as N}from"node:fs";var h=class extends d{constructor(){super("stable-id","Stable ID Injection (Experimental)",300)}canGenerate(a){let t=a.eventsPath||`${a.sessionPath}/execute_live/events.json`;try{return JSON.parse(R(t,"utf-8")).some(p=>p.stableId||p.data?.stableId)?(console.log("[StableIdStrategy] \u2705 Stable IDs available"),!0):(console.log("[StableIdStrategy] \u274C No stable IDs found in events"),!1)}catch(s){return console.log("[StableIdStrategy] \u274C Failed to read events:",s.message),!1}}getName(){return"Stable ID Injection (Experimental)"}getPriority(){return 300}async generate(a){let{testFilePath:t,sessionPath:s,state:o}=a,p=`${s}/execute_live/events.json`,x=o?.title||"Generated Test";console.log("[StableIdStrategy] \u{1F3AF} Generating test using stable IDs"),console.log(`[StableIdStrategy]    events: ${p}`),console.log(`[StableIdStrategy]    output: ${t}`);let u=JSON.parse(R(p,"utf-8")).filter(m=>["navigate","type","fill","click","select_option","select"].includes(m.type)),e=`import { test, expect } from '@playwright/test';
`;e+=`import { StableIdRuntime } from '@zibby/core';

`,e+=`test('${x}', async ({ page }) => {
`;let n=!1,l=null;for(let m=0;m<u.length;m++){let r=u[m],c=r.stableId||r.data?.stableId,$=r.data?.element||r.data?.params?.element||"element";if(r.type==="click"&&c&&c===l){console.log(`[StableIdStrategy] Skipping duplicate click on ${c}`);continue}if(r.type==="navigate"){let i=r.data?.url||r.data?.params?.url;i&&!n&&(e+=`  await page.goto('${i}');
`,e+=`  await StableIdRuntime.injectStableIds(page);

`)}else if(r.type==="click")if(n=!0,l=c,c)e+=`  await StableIdRuntime.clickWithRetry(page, '${c}');
`;else{let i=this._generateSemanticSelector($);e+=`  await ${i}.click();
`,e+=`  await StableIdRuntime.afterNavigation(page);
`}else if(r.type==="fill"||r.type==="type"){n=!1;let i=r.data?.text||r.data?.params?.text||"";c?e+=`  await StableIdRuntime.fillWithRetry(page, '${c}', '${this._escapeString(i)}');
`:e+=`  await page.getByPlaceholder('${this._escapeString($)}').fill('${this._escapeString(i)}');
`}else if(r.type==="select_option"||r.type==="select"){n=!1;let i=r.data?.values||r.data?.params?.values,g=Array.isArray(i)?i[0]:i||"";c?e+=`  await StableIdRuntime.selectWithRetry(page, '${c}', '${this._escapeString(g)}');
`:e+=`  await page.locator('select').selectOption('${this._escapeString(g)}');
`}}return e+=`});
`,N(t,e),console.log(`[StableIdStrategy] \u2705 Generated test with ${u.length} actions using stable IDs`),{success:!0,testPath:t,method:"Stable ID Injection (Experimental)",actionsGenerated:u.length}}_escapeString(a){return a.replace(/'/g,"\\'").replace(/\n/g,"\\n")}_generateSemanticSelector(a){let t=a.toLowerCase(),s="locator",o=a;return t.includes("button")?(s="button",o=a.replace(/\s*button\s*/gi,"").trim()):t.includes("link")?(s="link",o=a.replace(/\s*link\s*/gi,"").trim()):t.includes("textbox")?(s="textbox",o=a.replace(/\s*textbox\s*/gi,"").trim()):t.includes("checkbox")?(s="checkbox",o=a.replace(/\s*checkbox\s*/gi,"").trim()):(t.includes("combobox")||t.includes("dropdown")||t.includes("select"))&&(s="combobox",o=a.replace(/\s*(combobox|dropdown|select)\s*/gi,"").trim()),s!=="locator"&&o?`page.getByRole('${s}', { name: '${this._escapeString(o)}' })`:`page.getByText('${this._escapeString(a)}')`}};var P=class{constructor(){this.strategies=[new h,new b],this.strategies.sort((a,t)=>t.getPriority()-a.getPriority())}registerStrategy(a){this.strategies.push(a),this.strategies.sort((t,s)=>s.getPriority()-t.getPriority())}async generate(a){console.log(`
\u{1F4CB} Available generation strategies (${this.strategies.length}):`),this.strategies.forEach(t=>{let s=t.canGenerate(a);console.log(`   ${s?"\u2713":"\u2717"} ${t.getName()} (priority: ${t.getPriority()})`)});for(let t of this.strategies)if(t.canGenerate(a))return console.log(`
\u{1F3AF} Selected: ${t.getName()}`),t.generate(a);throw new Error("No generation strategy available for this context")}getStrategy(a){return this.strategies.find(t=>t.getName().includes(a))||null}},E=new P,B=E;export{b as MCPRefStrategy,h as StableIdStrategy,d as TestGenerationStrategy,P as TestGenerationStrategyManager,B as default,E as testGenerationManager};
