ripplo 0.7.35 → 0.7.37

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.
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+ import{B as Je,V as Ke,W as Qe,Z as Ge,_ as Xe,a as N,b as De,g as _e,i as qe,j as He,k as We,l as g,m as Be,o as Ve,p as ie,q as h,r as F,s as ze,w as I}from"./chunk-ITI53W73.js";import{b as Ue,d as f,e as y,g as Oe,h as w,i as Ne}from"./chunk-5VRJXHWH.js";import en from"fs";import W from"path";import{config as kt}from"dotenv";import{z as q}from"zod";import{err as St,ok as nn}from"neverthrow";import _ from"fs";import le from"path";import{err as ae,ok as Ye}from"neverthrow";import{z as D}from"zod";var mt=le.join(".ripplo","project.json"),se=[".env",".env.local"],gt=D.object({envFiles:D.array(D.string().min(1)).optional(),projectId:D.string().min(1)});function Ze(e){return le.join(e,mt)}function de(e){let n=Ze(e);return _.existsSync(n)?ht(n).andThen(t=>{let r=gt.safeParse(t);return r.success?Ye({envFiles:r.data.envFiles??se,projectId:r.data.projectId}):ae({issues:r.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`),kind:"project-file-invalid",path:n})}):ae({kind:"project-file-missing",path:n})}function ce(e){return de(e).match(n=>n,()=>{})}function ht(e){try{return Ye(JSON.parse(_.readFileSync(e,"utf8")))}catch(n){return ae({issues:[n instanceof Error?n.message:String(n)],kind:"project-file-invalid",path:e})}}function zi({cwd:e,envFiles:n,projectId:t}){let r=Ze(e);_.mkdirSync(le.dirname(r),{recursive:!0});let o={projectId:t};n!=null&&!Rt(n)&&(o.envFiles=[...n]),_.writeFileSync(r,JSON.stringify(o,null,2)+`
3
+ `)}function Rt(e){return e.length!==se.length?!1:e.every((n,t)=>n===se[t])}function ea(e){let t=ce(e)?.envFiles??[".env",".env.local"],r=W.join(e,".ripplo");t.forEach(o=>{let i=W.resolve(r,o);en.existsSync(i)&&kt({override:!0,path:i,quiet:!0})}),H=void 0}var xt=q.object({RIPPLO_APP_URL:q.url(),RIPPLO_ENGINE_URL:q.url(),RIPPLO_WEBHOOK_SECRET:q.string().min(1)}),H;function B(){return H!=null?nn(H):bt().map(e=>(H=e,e))}function wt(e){let t=ce(e)?.envFiles??[],r=W.join(e,".ripplo");return t.map(o=>W.resolve(r,o)).filter(o=>!en.existsSync(o))}function bt(){let e=xt.safeParse(process.env);if(!e.success)return St({issues:e.error.issues.map(t=>`${t.path.join(".")}: ${t.message}`),kind:"env-invalid",missingEnvFiles:wt(process.cwd())});let n=e.data;return nn({appUrl:n.RIPPLO_APP_URL,engineUrl:n.RIPPLO_ENGINE_URL,webhookSecret:n.RIPPLO_WEBHOOK_SECRET})}import{readFileSync as Et}from"fs";import{z as tn}from"zod";var vt=tn.object({version:tn.string()});function V(){let e=Et(new URL("../package.json",import.meta.url),"utf8");return vt.parse(JSON.parse(e)).version}import me from"fs";import z from"path";import{createJiti as Lt}from"jiti";import{err as U,ok as sn}from"neverthrow";import It from"fs";import M from"path";import P from"typescript";function rn(e){let n=M.join(e,"index.ts"),t=Tt(e);It.mkdirSync(M.dirname(t.tsBuildInfoFile??""),{recursive:!0});let r=P.createIncrementalCompilerHost(t),o=P.createIncrementalProgram({host:r,options:t,rootNames:[n]}),i=[...o.getSyntacticDiagnostics(),...o.getSemanticDiagnostics()];o.emit();let s=i.filter(d=>Pt(d,e));if(s.length===0)return{diagnostics:[],ok:!0};let l={getCanonicalFileName:d=>d,getCurrentDirectory:()=>M.dirname(e),getNewLine:()=>`
4
+ `};return{diagnostics:P.formatDiagnosticsWithColorAndContext(s,l).split(`
5
+ `).filter(d=>d.length>0),ok:!1}}function Pt(e,n){let t=e.file?.fileName;return t==null?!0:t.startsWith(n)}var Ct=M.join(".local","tsbuildinfo");function Tt(e){return{allowImportingTsExtensions:!0,allowJs:!1,esModuleInterop:!0,incremental:!0,module:P.ModuleKind.Preserve,moduleResolution:P.ModuleResolutionKind.Bundler,noEmit:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!1,target:P.ScriptTarget.ES2022,tsBuildInfoFile:M.join(e,Ct)}}import{createHash as jt}from"crypto";import on from"fs/promises";import ue from"path";import{err as C,ok as pe,Result as At}from"neverthrow";var $=".ripplo/fixtures",fe=10*1024*1024,ye=50*1024*1024;async function an(e,n){let t=Ft(n);if(t.length===0)return pe({});let r=ue.join(e,$),o=await Promise.all(t.map(i=>Mt({fixturesRoot:r,name:i})));return At.combine(o).andThen($t)}function Ft(e){let t=e.workflows.flatMap(r=>[...r.steps,...r.tests.flatMap(o=>o.steps)]).flatMap(r=>r.action.kind==="upload"?r.action.files:[]);return[...new Set(t)].toSorted((r,o)=>r.localeCompare(o))}async function Mt({fixturesRoot:e,name:n}){if(n.includes("..")||ue.isAbsolute(n))return C({kind:"fixture-invalid-name",name:n});let t=ue.join(e,n),r=await on.lstat(t).catch(()=>null);if(r==null)return C({kind:"fixture-missing",name:n,path:t});if(r.isSymbolicLink())return C({kind:"fixture-symlink",name:n});if(!r.isFile())return C({kind:"fixture-not-file",name:n});let o=await on.readFile(t);if(o.byteLength>fe)return C({kind:"fixture-too-large",name:n,size:o.byteLength});let i=jt("sha256").update(o).digest("hex");return pe([n,{sha256:i,size:o.byteLength}])}function $t(e){let n=e.reduce((t,[,r])=>t+r.size,0);return n>ye?C({kind:"fixtures-total-too-large",total:n}):pe(Object.fromEntries(e))}var T=".ripplo/ripplo.lock",L;async function ln(e){let{result:n}=await ge(e);return n}async function ge(e){let n=Ot(z.join(e,".ripplo"));if(L!=null&&L.fingerprint===n&&L.result.isOk())return{fingerprint:n,result:L.result};let t=await O(e);return L={fingerprint:n,result:t},{fingerprint:n,result:t}}async function O(e){let n=z.join(e,".ripplo"),t=z.join(n,"index.ts"),r=rn(n);return r.ok?(await Nt(t)).andThen(s=>_t({entryPath:t,exported:s})).match(async s=>(await an(e,s)).map(u=>({...s,fixtures:u})).mapErr(u=>({error:u,kind:"fixture-failed"})),s=>Promise.resolve(U(s))):U({diagnostics:r.diagnostics,kind:"typecheck-failed"})}var Ut=new Set([".local","debug","node_modules"]);function Ot(e){return dn(e).toSorted((n,t)=>n.localeCompare(t)).join("|")}function dn(e){return(me.existsSync(e)?me.readdirSync(e,{withFileTypes:!0}):[]).flatMap(t=>{if(Ut.has(t.name))return[];let r=z.join(e,t.name);if(t.isDirectory())return dn(r);let o=me.statSync(r);return[`${r}:${String(o.mtimeMs)}:${String(o.size)}`]})}async function Nt(e){try{let t=await Lt(import.meta.url,{fsCache:!1,moduleCache:!1,sourceMaps:!0}).import(e),r=t!=null&&typeof t=="object"&&"default"in t?Reflect.get(t,"default"):t;return sn(r)}catch(n){return U({kind:"load-threw",message:Dt(n)})}}function Dt(e){return e instanceof Error?e.message:String(e)}function _t({entryPath:e,exported:n}){if(n==null||typeof n!="object"||!("lockfile"in n))return U({entryPath:e,kind:"not-ripplo"});let t=_e.safeParse(Reflect.get(n,"lockfile"));return t.success?sn(t.data):U({issues:t.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`),kind:"invalid-lockfile"})}function j(e,n){return n==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${n}.`}function wa(e){return e.length===1?j(e[0]):`Before proceeding, load the ${e.map(t=>`\`/ripplo:${t}\``).join(" and ")} skills \u2014 every one, each carries rules the others don't.`}function K(e){return[`Compilation failed: ${qt(e)}`,j("create","DSL authoring + lint rules")].join(`
6
+ `)}function Pa(){return`${T} is up to date`}function Ca(e){return[`${T} is ${e==="missing"?"missing":"out of date"} \u2014 run \`npx ripplo compile\` and commit the result`,j("setup")].join(`
7
+ `)}function Ta(){return`Wrote ${T}`}function qt(e){switch(e.kind){case"typecheck-failed":return["TypeScript errors in .ripplo/:",...cn(e.diagnostics)].join(`
8
+ `);case"not-ripplo":return`${e.entryPath} must default-export a Ripplo (createRipplo({ entities, singletons, workflows })). Check that the default export is the value returned by createRipplo, not a function or a re-export.`;case"invalid-lockfile":return["Lockfile failed schema validation (stale or hand-edited .ripplo/ripplo.lock?):",...cn(e.issues),"Regenerate with `npx ripplo compile` \u2014 never hand-edit the lockfile."].join(`
9
+ `);case"load-threw":return[`.ripplo/index.ts threw while loading: ${e.message}`,"Usually a bad import or a top-level throw in .ripplo/ \u2014 run `npx ripplo compile` for the stack."].join(`
10
+ `);case"fixture-failed":return Ht(e.error)}}function cn(e,n=8){return e.length<=n?e:[...e.slice(0,n),`\u2026 and ${String(e.length-n)} more`]}function Ht(e){switch(e.kind){case"fixture-missing":return`Fixture "${e.name}" not found at ${e.path} \u2014 add the file under .ripplo/fixtures/ or fix the upload() name.`;case"fixture-invalid-name":return`Invalid fixture name "${e.name}" \u2014 upload() takes a bare name under .ripplo/fixtures/, no .. or absolute paths.`;case"fixture-symlink":return`Fixture "${e.name}" is a symlink \u2014 only regular files are allowed.`;case"fixture-not-file":return`Fixture "${e.name}" is not a regular file.`;case"fixture-too-large":return`Fixture "${e.name}" is ${J(e.size)} \u2014 over the ${J(fe)} per-file limit.`;case"fixtures-total-too-large":return`Fixtures total ${J(e.total)} \u2014 over the ${J(ye)} limit.`}}function J(e){return`${String(Math.round(e/(1024*1024)*10)/10)} MB`}var Q=class extends Error{failure;constructor(n){super(n.kind),this.name="CliError",this.failure=n}};function La(e){return e instanceof Q?he(e.failure):e instanceof Error?e.message:String(e)}function he(e){switch(e.kind){case"project-file-missing":return[`Missing ${e.path} \u2014 this directory is not a Ripplo project.`,"Run `npx ripplo init` to create it (or cd into the project root).",j("setup")].join(`
11
+ `);case"project-file-invalid":return[`${e.path} is invalid:`,...e.issues.map(n=>` ${n}`),"Fix the file by hand or re-run `npx ripplo init`."].join(`
12
+ `);case"not-authenticated":return["Not signed in. Run `npx ripplo auth login`.","(Claude Code: run it yourself in the background \u2014 the user just approves in the browser.)"].join(`
13
+ `);case"env-invalid":return Wt(e);case"playwright-install-failed":return["Playwright browser install failed \u2014 Chromium is still missing.","Run `npx playwright install chromium` and check its output for network, proxy, or disk-space errors."].join(`
14
+ `);case"gitdir-unrecognized":return`Unrecognized .git file at ${e.marker} \u2014 expected a directory or a "gitdir:" pointer (worktree). Is the repo corrupted?`;case"gitdir-empty":return`Empty gitdir pointer at ${e.marker} \u2014 the worktree's .git file points nowhere. Re-create the worktree.`;case"oauth-device-code-failed":return[`Could not start sign-in (device-code request failed): ${e.description}`,"Is the Ripplo server reachable? Check RIPPLO_SERVER_URL and retry."].join(`
15
+ `);case"oauth-authorization-failed":return[`Sign-in failed (${e.code}): ${e.description}`,e.code==="expired_token"?"The approval window expired \u2014 run `npx ripplo auth login` again.":"Run `npx ripplo auth login` to retry."].join(`
16
+ `);case"compilation-failed":return K(e.error)}}function Wt(e){let n=e.missingEnvFiles.length===0?[]:["Declared env files not found:",...e.missingEnvFiles.map(t=>` ${t}`),"In a git worktree? Env files aren't copied from the main checkout \u2014 recreate them, or symlink to a shared file outside the working tree."];return["Env config invalid:",...e.issues.map(t=>` ${t}`),"Add the missing values to the env files declared in .ripplo/project.json.",...n].join(`
17
+ `)}import{err as zt,ok as Jt}from"neverthrow";import{z as Re}from"zod";var Bt="https://ripplo.ai";function pn(){return yn().RIPPLO_SERVER_URL}function fn(){return yn().RIPPLO_PROJECT_ID}var Vt=Re.object({RIPPLO_PROJECT_ID:Re.string().min(1).optional(),RIPPLO_SERVER_URL:Re.string().min(1).default(Bt)}),un;function yn(){return un??=Vt.parse(process.env),un}import mn from"fs";import ke from"path";function gn(e){let n=mn.realpathSync(e),t=n,r=ke.dirname(t);for(;r!==t;){if(mn.existsSync(ke.join(t,".git")))return t;t=r,r=ke.dirname(t)}return n}function hn(e){return de(e).andThen(n=>B().andThen(t=>{let r=pn(),o=Ne(r);return o==null?zt({kind:"not-authenticated"}):Jt({appUrl:t.appUrl,cwd:gn(e),engineUrl:t.engineUrl,projectId:fn()??n.projectId,ripploServerUrl:r,token:o,tunnelAuth:void 0,webhookSecret:t.webhookSecret})}))}import Rn from"fs";import{checkSync as Kt,lockSync as Qt}from"proper-lockfile";var Gt="dev.pid",kn=15e3;function Sn(e){return w(e,Gt)}function xn(e){try{return Kt(Sn(e),{realpath:!1,stale:kn})}catch{return!1}}var Se=class extends Error{pid;cwd;constructor({cwd:n,pid:t}){super("dev-lock-held"),this.name="DevLockHeldError",this.pid=t,this.cwd=n}};function Ya({cwd:e,onCompromised:n}){Oe(e);let t=Sn(e),r=Xt({cwd:e,onCompromised:n,path:t});return Rn.writeFileSync(t,String(process.pid)),()=>{try{r()}catch{}}}function Xt({cwd:e,onCompromised:n,path:t}){try{return Qt(t,{realpath:!1,stale:kn,onCompromised:()=>{n()}})}catch(r){throw Yt(r)?new Se({cwd:e,pid:Zt(t)}):r}}function Yt(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:n}=e;return n==="ELOCKED"}function Zt(e){try{let n=Rn.readFileSync(e,"utf8").trim(),t=Number.parseInt(n,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}import er from"p-queue";var nr=4,tr={"p0-ui":3,"p1-cli":2,"p2-cover":1,"p3-explore":0},G=new er({concurrency:nr}),k={headedActive:0,interactiveActive:0,interactiveQueued:0},wn={current:null};function ns({headed:e,task:n,workClass:t}){let r=tr[t];return t==="p3-explore"?G.add(n,{priority:r}):(k.interactiveQueued+=1,X(),G.add(()=>rr({headed:e,task:n}),{priority:r}))}function ts(e){!Number.isFinite(e)||e<1||(G.concurrency=Math.floor(e),X())}function xe(){return{active:k.interactiveActive,headedActive:k.headedActive,poolSize:G.concurrency,queued:k.interactiveQueued}}function rs(e){wn.current=e}async function rr({headed:e,task:n}){k.interactiveQueued-=1,k.interactiveActive+=1,k.headedActive+=e?1:0,X();try{return await n()}finally{k.interactiveActive-=1,k.headedActive-=e?1:0,X()}}function X(){wn.current?.()}import we from"fs";import be from"path";function bn(e){try{let n=or(e);if(n==null)return;let t=be.join(n,"HEAD"),r=we.readFileSync(t,"utf8").trim(),o="ref: refs/heads/";return r.startsWith(o)?r.slice(o.length):r.length===0?void 0:r.slice(0,7)}catch{return}}function or(e){let n=be.join(e,".git");if(we.statSync(n).isDirectory())return n;let r=we.readFileSync(n,"utf8").trim(),o="gitdir:";if(!r.startsWith(o))return;let i=r.slice(o.length).trim();if(i.length!==0)return be.resolve(e,i)}import ir from"crypto";import{readFile as En}from"fs/promises";import vn from"path";import{graphql as ar}from"gql.tada";import{err as sr,ok as lr}from"neverthrow";var dr=ar(`
18
+ mutation SyncDevSession(
19
+ $projectId: String!
20
+ $cwd: String!
21
+ $branch: String
22
+ $lockfileContent: String
23
+ $fixtures: [SyncDevFixtureInput!]
24
+ $preconditions: [SyncDevPreconditionInput!]!
25
+ $singletons: [SyncDevSingletonInput!]
26
+ $workflows: [SyncDevWorkflowInput!]!
27
+ ) {
28
+ syncDevSession(
29
+ projectId: $projectId
30
+ cwd: $cwd
31
+ branch: $branch
32
+ lockfileContent: $lockfileContent
33
+ fixtures: $fixtures
34
+ preconditions: $preconditions
35
+ singletons: $singletons
36
+ workflows: $workflows
37
+ ) {
38
+ id
39
+ hooksPaused
40
+ }
41
+ }
42
+ `);async function Rs(e,n){let t=await O(e);if(t.isErr())return sr({error:t.error,kind:"compilation-failed"});let r=await Ee({config:n,cwd:e,lockfile:t.value});return lr({devSessionId:r.devSessionId,lockfile:t.value})}async function Ee(e){let n=He(e.lockfile);return ur({config:e.config,cwd:e.cwd,fixtures:e.lockfile.fixtures,payload:n})}function cr(e){return ir.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function ur({config:e,cwd:n,fixtures:t,payload:r}){let o=cr(r),i=bn(n),s=await fr(n),l=await pr(n,t),u=await f({config:e,document:dr,variables:{branch:i??null,cwd:n,fixtures:l,lockfileContent:s,preconditions:r.preconditions.map(d=>({depends:[...d.depends],description:d.description,name:d.name,returns:[...d.returns]})),projectId:e.projectId,singletons:r.singletons.map(d=>({defaultValue:d.defaultValue,description:d.description,name:d.name,type:d.type})),workflows:r.workflows.map(d=>({expectedOutcome:d.expectedOutcome,name:d.name,preconditions:[...d.preconditions],requiresKeys:d.requiresKeys.map(p=>({namespace:p.namespace,preconditionName:p.preconditionName})),slug:d.slug,sourcePath:d.sourcePath,spec:JSON.stringify(d.spec)}))}});if(u.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:u.syncDevSession.id,hash:o,hooksPaused:u.syncDevSession.hooksPaused}}async function pr(e,n){let t=Object.entries(n);return Promise.all(t.map(async([r,o])=>({contentBase64:(await En(vn.join(e,$,r))).toString("base64"),sha256:o.sha256})))}async function fr(e){try{return await En(vn.join(e,T),"utf8")}catch{return null}}import{randomUUID as zr}from"crypto";import{createId as Jr}from"@paralleldrive/cuid2";import{CancellationTokenSource as Kr,ResponseError as Qr}from"vscode-jsonrpc/node";import{graphql as yr}from"gql.tada";var mr=yr(`
43
+ mutation DaemonCreateRun(
44
+ $id: String
45
+ $workflowId: String!
46
+ $testId: String
47
+ $clientVersion: String
48
+ $executor: RunExecutor
49
+ $target: RunTarget
50
+ $lockfileHash: String
51
+ ) {
52
+ createRun(
53
+ id: $id
54
+ workflowId: $workflowId
55
+ testId: $testId
56
+ executor: $executor
57
+ target: $target
58
+ clientVersion: $clientVersion
59
+ lockfileHash: $lockfileHash
60
+ ) {
61
+ __typename
62
+ ... on MutationCreateRunSuccess {
63
+ data {
64
+ id
65
+ }
66
+ }
67
+ ... on LimitExceededError {
68
+ code
69
+ }
70
+ }
71
+ }
72
+ `);async function In(e){try{let t=(await f({config:e.config,document:mr,variables:gr(e)})).createRun;return t==null?Y({detail:"create-run-null",type:"generic"}):t.__typename==="MutationCreateRunSuccess"?null:t.__typename==="LimitExceededError"?Y({code:t.code,type:"limit"}):Y({detail:t.__typename,type:"generic"})}catch(n){return hr(n)}}function gr({executor:e,lockfileHash:n,runId:t,target:r}){return{clientVersion:V(),executor:e,id:t,lockfileHash:n,target:e==="cloud"?"tunnel":void 0,testId:r.testId,workflowId:r.workflowId}}function Y(e){return{kind:"dispatch-error",reason:e}}function hr(e){return e instanceof Ue?{detail:e.message,kind:"infra-error"}:Y({detail:e instanceof Error?e.message:String(e),type:"generic"})}import{createMessageConnection as Rr,NotificationType as Pn,RequestType as kr,RequestType0 as Cn,SocketMessageReader as Sr,SocketMessageWriter as xr}from"vscode-jsonrpc/node";import{z as a}from"zod";var wr="daemon.sock",br="daemon.log";function Ps(e){return w(e,wr)}function Cs(e){return w(e,br)}function Tn(e){return Rr(new Sr(e),new xr(e))}var jn=a.object({all:a.boolean(),headed:a.boolean(),tests:a.array(a.string())}),Ts=a.object({jobId:a.string(),total:a.number()}),Er=a.enum(["on","off"]),vr=a.object({attempts:a.number(),findings:a.number()}),js=a.object({active:a.number(),explorer:Er,exploring:a.number(),progress:vr,queued:a.number(),sseHealth:a.object({detail:a.string().optional(),ok:a.boolean()}).optional(),version:a.string().optional()}),Ir=a.enum(["MAX_RUNS","OVERAGE_CAP","MAX_AGENTS","MAX_CONCURRENT_RUNS","MAX_PROJECTS"]),Pr=a.discriminatedUnion("type",[a.object({code:Ir,type:a.literal("limit")}),a.object({detail:a.string(),type:a.literal("generic")})]),ve=a.discriminatedUnion("kind",[a.object({kind:a.literal("pass")}),a.object({findingLines:a.array(a.string()),kind:a.literal("findings")}),a.object({detail:a.string(),kind:a.literal("error")}),a.object({kind:a.literal("dispatch-error"),reason:Pr}),a.object({detail:a.string(),kind:a.literal("dispatch-timeout")}),a.object({detail:a.string(),kind:a.literal("infra-error")})]),Cr=a.discriminatedUnion("kind",[a.object({kind:a.literal("test-started"),runId:a.string(),testName:a.string(),workflowName:a.string()}),a.object({kind:a.literal("test-outcome"),outcome:ve,runId:a.string(),testName:a.string(),workflowName:a.string()})]),As=a.object({event:Cr,jobId:a.string()}),Fs=a.object({failed:a.number(),jobId:a.string(),notRun:a.number(),passed:a.number()}),Ms=a.discriminatedUnion("code",[a.object({code:a.literal("compile-failed"),detail:a.string(),diagnostics:a.array(a.string()).default([])}),a.object({code:a.literal("selection-conflicting-flags")}),a.object({code:a.literal("selection-nothing-selected")}),a.object({code:a.literal("selection-unknown-ids"),known:a.array(a.string()),unknown:a.array(a.string())}),a.object({code:a.literal("scope-failed"),detail:a.string()}),a.object({code:a.literal("app-unreachable"),detail:a.string(),url:a.string()}),a.object({code:a.literal("sync-failed"),detail:a.string()}),a.object({code:a.literal("bad-message")})]),An=new kr("ripplo/enqueue"),Fn=new Cn("ripplo/status"),Mn=new Cn("ripplo/shutdownIfIdle"),$n=new Pn("ripplo/jobEvent"),Ln=new Pn("ripplo/jobDone");import{graphql as Tr}from"gql.tada";async function Un(e,n){let r=(await f({config:e,document:jr,variables:{cwd:n,projectId:e.projectId}})).project?.devSession?.workflows??[];return new Map(r.flatMap(o=>o.tests.map(i=>[`${o.slug}/${i.slug}`,{testId:i.id,workflowId:o.id}])))}var jr=Tr(`
73
+ query DaemonWorkflows($projectId: String!, $cwd: String!) {
74
+ project(id: $projectId) {
75
+ id
76
+ devSession(cwd: $cwd) {
77
+ id
78
+ workflows {
79
+ id
80
+ slug
81
+ tests {
82
+ id
83
+ slug
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ `);import{CancellationTokenSource as Ar}from"vscode-jsonrpc/node";function Ie(e){return`${e.workflowSlug}/${e.testSlug}`}function On(e){let{headed:n,inflight:t,jobId:r,lockfileHashValue:o,onExpire:i,runId:s,selection:l,timeoutMs:u}=e,d=Ie(l),p=`${d}@${o}@${String(n)}`,c=t.get(p);if(c!=null)return c.jobIds.add(r),null;let m={cancellation:new Ar,claimed:!1,claimKey:d,headed:n,inflightKey:p,jobIds:new Set([r]),runId:s,testName:l.testName,timer:null,workflowName:l.workflowName};return m.timer=setTimeout(()=>{Z(t,m),i(m)},u),t.set(p,m),m}function Z(e,n){n.timer!=null&&(clearTimeout(n.timer),n.timer=null),e.delete(n.inflightKey)}function Pe(e,n){let t=[...e.values()].find(r=>r.runId===n&&!r.claimed);return t==null?null:(t.claimed=!0,t.timer!=null&&(clearTimeout(t.timer),t.timer=null),t)}function Nn(e,n){[...e.values()].filter(t=>t.jobIds.has(n)).forEach(t=>{t.jobIds.delete(n),t.jobIds.size===0&&(Z(e,t),t.cancellation.cancel())})}import{err as Ce,ok as Dn}from"neverthrow";function qn({all:e,ids:n,lockfile:t}){if(e&&n.length>0)return Ce({kind:"conflicting-flags"});if(e)return Dn(t.workflows.filter(i=>!i.stub).flatMap(i=>i.tests.map(s=>h(s))));if(n.length===0)return Ce({kind:"nothing-selected"});let r=n.map(i=>({id:i,refs:Mr(t,i)})),o=r.filter(i=>i.refs.length===0).map(i=>i.id);return o.length>0?Ce({kind:"unknown-ids",known:Fr(t),unknown:o}):Dn([...new Set(r.flatMap(i=>i.refs))])}function Hn(e,n){let t=new Map(F(e).map(r=>[r.ref,{testName:r.test.name,testSlug:r.test.slug,workflowName:r.workflow.name,workflowSlug:g(r.workflow.name)}]));return n.map(r=>{let o=t.get(r);if(o==null)throw new Error(`selectionsFor: ref not in lockfile: ${r}`);return o})}function Fr(e){return e.workflows.map(n=>g(n.name))}function Mr(e,n){let t=e.workflows.find(r=>r.name===n||g(r.name)===g(n));return t!=null?t.tests.map(r=>h(r)):F(e).filter(r=>r.ref===n||_n(r.ref)===_n(n)).map(r=>r.ref)}function _n(e){let n=e.lastIndexOf("/");return n===-1?g(e):`${g(e.slice(0,n))}/${g(e.slice(n+1))}`}import{err as Te,ok as Bn}from"neverthrow";import{graphql as Vn}from"gql.tada";import{execFileSync as $r}from"child_process";var Lr=256*1024*1024;function ee(e,n){return $r("git",[...e],{cwd:n,encoding:"utf8",maxBuffer:Lr,stdio:["ignore","pipe","pipe"]})}async function zn({config:e,cwd:n,lockfile:t}){await Or({config:e,cwd:n,lockfile:t});let r=await Dr(e);if(r.isErr())return Te(r.error);let o=new Map(t.workflows.filter(s=>!s.stub).map(s=>[g(s.name),s])),i=[...new Set(r.value)].flatMap(s=>{let l=o.get(s);return l==null?[]:l.tests.map(u=>h(u))});return i.length===0?Te({kind:"scope-empty"}):Bn(i)}var Ur=Vn(`
90
+ mutation AddDirtyTestsToScope($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
91
+ addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
92
+ __typename
93
+ }
94
+ }
95
+ `);async function Or({config:e,cwd:n,lockfile:t}){let r=new Set(_r(n)),o=t.workflows.filter(i=>i.sourcePath!=null&&r.has(i.sourcePath)).map(i=>g(i.name));o.length!==0&&await f({config:e,document:Ur,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:o}}).catch(i=>{y.warn({err:i},"auto-scope of dirty tests failed")})}var Nr=Vn(`
96
+ query ScopeSelection($projectId: String!, $cwd: String!) {
97
+ project(id: $projectId) {
98
+ id
99
+ devSession(cwd: $cwd) {
100
+ id
101
+ scopeItems {
102
+ id
103
+ workflow {
104
+ id
105
+ slug
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ `);async function Dr(e){try{let t=(await f({config:e,document:Nr,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession?.scopeItems??[];return Bn(t.flatMap(r=>r.workflow==null?[]:[r.workflow.slug]))}catch(n){return Te({detail:n instanceof Error?n.message:String(n),kind:"scope-fetch-failed"})}}var Wn=".ripplo/workflows/";function _r(e){try{return ee(["status","--porcelain","--",".ripplo/workflows"],e).split(`
112
+ `).map(n=>n.slice(3).trim()).filter(n=>n.startsWith(Wn)&&n.endsWith(".ts")).map(n=>n.slice(Wn.length)).filter(n=>n!=="index.ts"&&!n.endsWith("/index.ts"))}catch{return[]}}import{graphql as qr}from"gql.tada";var Hr=2e3,Wr=qr(`
113
+ query DaemonCloudRunStatus($runId: String!) {
114
+ run(id: $runId) {
115
+ status
116
+ failureReason
117
+ }
118
+ }
119
+ `);function Kn({config:e,onComplete:n,onStarted:t,runId:r,signal:o}){let i=!1,s,l=!1,u=async()=>{if(i||o.aborted)return;let d=await Br(e,r).catch(()=>"unknown");if(!(i||o.aborted)){if(!l&&(d==="running"||Jn(d))&&(l=!0,t()),Jn(d)){i=!0,n(Vr(d));return}s=setTimeout(()=>{u()},Hr)}};return u(),{stop:()=>{i=!0,s!=null&&clearTimeout(s)}}}async function Br(e,n){let r=(await f({config:e,document:Wr,variables:{runId:n}})).run?.status;return r??"unknown"}function Jn(e){return e==="passed"||e==="failed"||e==="warning"||e==="cancelled"||e==="unready"}function Vr(e){return e==="passed"?{kind:"pass"}:e==="failed"?{detail:"failed",kind:"error"}:e==="warning"?{findingLines:[],kind:"findings"}:e==="cancelled"?{detail:"cancelled",kind:"error"}:e==="unready"?{detail:"unready",kind:"error"}:{detail:"unknown",kind:"error"}}var Gr=12e4,Xr=-32099;function Yr(e){let n=new AbortController;return e.isCancellationRequested?(n.abort(),n.signal):(e.onCancellationRequested(()=>{n.abort()}),n.signal)}function Rl(e){let n={...e,inflight:new Map,jobs:new Map};return{claim:t=>ro(n,t),handleConnection:t=>{Zr(n,t)},idle:()=>Xn(n)}}function Zr(e,n){let t=Tn(n);t.onRequest(An,(r,o)=>eo({connection:t,ctx:e,params:r,token:o})),t.onRequest(Fn,()=>{let r=xe();return{active:r.active,queued:r.queued,sseHealth:e.sseHealth(),version:V(),...e.explorationStatus()}}),t.onRequest(Mn,()=>{let r=Xn(e);return r&&e.onShutdownRequest(),r}),t.onClose(()=>{no(e,t)}),t.onError(r=>{y.warn({err:r},"ipc connection error")}),n.on("error",r=>{y.warn({err:r},"ipc socket error")}),t.listen()}function Xn(e){let n=xe();return e.jobs.size===0&&n.active===0&&n.queued===0}async function eo({connection:e,ctx:n,params:t,token:r}){let o=jn.safeParse(t);if(!o.success)throw Qn({code:"bad-message"});await n.ready;let i=await io({config:n.config,cwd:n.cwd,message:o.data});if(i.kind==="error")throw Qn(i.error);let s=zr(),l=new Kr;return r.onCancellationRequested(()=>{Yn(n,s)}),n.jobs.set(s,{cancellation:l,connection:e,failed:0,notRun:0,passed:0,total:i.selections.length}),yo({ctx:n,headed:o.data.headed,jobId:s,lockfileHashValue:i.lockfileHashValue,selections:i.selections,targetsByClaimKey:i.targetsByClaimKey,token:l.token}).catch(u=>{y.error({err:u},"ipc dispatch failed")}),{jobId:s,total:i.selections.length}}function Qn(e){return new Qr(Xr,e.code,e)}function Yn(e,n){let t=e.jobs.get(n);t!=null&&(t.cancellation.cancel(),e.jobs.delete(n),Nn(e.inflight,n))}function no(e,n){[...e.jobs.entries()].filter(([,t])=>t.connection===n).forEach(([t])=>{Yn(e,t)})}function Zn(e,n,t){let r=e.jobs.get(n);r!=null&&(Gn(()=>r.connection.sendNotification($n,{event:t,jobId:n})),t.kind==="test-outcome"&&(to(r,t.outcome.kind),r.passed+r.failed+r.notRun>=r.total&&(Gn(()=>r.connection.sendNotification(Ln,{failed:r.failed,jobId:n,notRun:r.notRun,passed:r.passed})),e.jobs.delete(n))))}function Gn(e){Promise.resolve().then(e).catch(n=>{y.warn({err:n},"ipc notification failed")})}function to(e,n){if(n==="pass"){e.passed+=1;return}if(n==="dispatch-error"||n==="dispatch-timeout"||n==="infra-error"){e.notRun+=1;return}e.failed+=1}function A(e,n,t){n.jobIds.forEach(r=>{Zn(e,r,t)})}function ro(e,n){let t=Pe(e.inflight,n);return t==null?null:{headed:t.headed,token:t.cancellation.token,finished:(r,o)=>{e.inflight.delete(t.inflightKey),A(e,t,{kind:"test-outcome",outcome:o,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},started:()=>{A(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}}}function oo(e){return e.kind==="typecheck-failed"?e.diagnostics.slice(0,5):e.kind==="invalid-lockfile"?e.issues.slice(0,5):e.kind==="load-threw"?[e.message]:[]}async function io({config:e,cwd:n,message:t}){return(await ln(n)).match(o=>ao({config:e,cwd:n,lockfile:o,message:t}),o=>Promise.resolve({error:{code:"compile-failed",detail:o.kind,diagnostics:[...oo(o)]},kind:"error"}))}async function ao({config:e,cwd:n,lockfile:t,message:r}){let o=await lo(e.appUrl);if(o!=null)return{error:{code:"app-unreachable",detail:o,url:e.appUrl},kind:"error"};let i=await co({config:e,cwd:n,lockfile:t});return i!=null?{error:{code:"sync-failed",detail:i},kind:"error"}:(await uo({config:e,cwd:n,lockfile:t,message:r})).match(async l=>({kind:"ready",lockfileHashValue:qe(t),selections:Hn(t,l),targetsByClaimKey:await Un(e,n)}),l=>Promise.resolve({error:l,kind:"error"}))}var so=2e3;async function lo(e){try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(so)}),null}catch(n){return n instanceof Error?n.message:String(n)}}async function co(e){try{return await Ee(e),null}catch(n){return n instanceof Error?n.message:String(n)}}async function uo({config:e,cwd:n,lockfile:t,message:r}){return!r.all&&r.tests.length===0?(await zn({config:e,cwd:n,lockfile:t})).mapErr(po):qn({all:r.all,ids:r.tests,lockfile:t}).mapErr(fo)}function po(e){return e.kind==="scope-empty"?{code:"selection-nothing-selected"}:{code:"scope-failed",detail:e.detail}}function fo(e){switch(e.kind){case"conflicting-flags":return{code:"selection-conflicting-flags"};case"nothing-selected":return{code:"selection-nothing-selected"};case"unknown-ids":return{code:"selection-unknown-ids",known:[...e.known],unknown:[...e.unknown]}}}async function yo(e){await e.selections.reduce((n,t)=>n.then(()=>mo(e,t)),Promise.resolve())}async function mo(e,n){let{ctx:t,headed:r,jobId:o,lockfileHashValue:i,targetsByClaimKey:s,token:l}=e;if(l.isCancellationRequested)return;let u=Ie(n),d=s.get(u);if(d==null){Zn(t,o,{kind:"test-outcome",outcome:{kind:"dispatch-error",reason:{detail:"test-not-found",type:"generic"}},runId:"",testName:n.testName,workflowName:n.workflowName});return}let p=On({headed:r,inflight:t.inflight,jobId:o,lockfileHashValue:i,runId:Jr(),selection:n,timeoutMs:Gr,onExpire:m=>{A(t,m,{kind:"test-outcome",outcome:{detail:"dispatch-timeout",kind:"dispatch-timeout"},runId:"",testName:m.testName,workflowName:m.workflowName})}});if(p==null)return;let c=await go(t,d,p.runId,i);if(c!=null){Z(t.inflight,p),A(t,p,{kind:"test-outcome",outcome:c,runId:"",testName:n.testName,workflowName:n.workflowName});return}t.executor==="cloud"&&ho(t,p)}function go(e,n,t,r){return In({config:e.config,executor:e.executor,lockfileHash:r,runId:t,target:n})}function ho(e,n){let t=Pe(e.inflight,n.runId);t!=null&&Kn({config:e.config,runId:t.runId,signal:Yr(t.cancellation.token),onComplete:r=>{e.inflight.delete(t.inflightKey),A(e,t,{kind:"test-outcome",outcome:r,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},onStarted:()=>{A(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}})}import Ro from"fs";import ko from"path";async function Il(e){let n=ko.join(e,".ripplo","index.ts");if(!Ro.existsSync(n))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let t=await O(e);return t.isErr()?{appUrl:void 0,engineUrl:void 0,errors:[{message:K(t.error),path:".ripplo/"}],valid:!1,warnings:[]}:B().match(r=>({appUrl:r.appUrl,engineUrl:r.engineUrl,errors:[],valid:!0,warnings:[]}),r=>({appUrl:void 0,engineUrl:void 0,errors:[{message:he(r),path:""}],valid:!1,warnings:[]}))}async function Pl(e){try{await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return}catch{return`appUrl (${e}) is not responding. Make sure your dev server is running on that port.`}}async function Cl({appUrl:e,engineUrl:n}){let t=n.startsWith("http://")||n.startsWith("https://")?n:`${e}${n}`;try{return(await fetch(`${t}/setup`,{body:JSON.stringify({}),headers:{"Content-Type":"application/json"},method:"PUT",signal:AbortSignal.timeout(5e3)})).ok?"Engine endpoint accepted an unsigned request \u2014 webhook signature verification may be missing.":void 0}catch{return}}import bo from"fs";import So from"fs";import je from"path";var xo=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function et(e){let n=wo(e);return n==null?!1:xo.some(t=>So.existsSync(je.join(n,t)))}function wo(e){try{let n=ee(["rev-parse","--git-dir"],e).trim();return n.length===0?null:je.isAbsolute(n)?n:je.resolve(e,n)}catch{return null}}function Eo(e){return w(e,"hooks-paused")}function Nl(e){return bo.existsSync(Eo(e))||et(e)?!1:xn(e)}import{createMessageConnection as nt,IPCMessageReader as tt,IPCMessageWriter as rt,NotificationType as vo,NotificationType0 as ot,RequestType as it,RequestType0 as Io}from"vscode-jsonrpc/node";import{z as R}from"zod";var Bl=R.object({headed:R.boolean(),runId:R.string().min(1),testRef:R.string().min(1)}),Vl=R.object({lockfileJson:R.string().optional(),unavailable:R.string().optional()}),zl=R.object({runId:R.string().min(1),span:De}),Jl=R.object({outcome:ve,serverNotified:R.boolean()}),Kl=new ot("worker/ready"),Ql=new it("worker/run"),Gl=new Io("worker/lockfile"),Xl=new it("worker/exploreTrail"),Yl=new vo("worker/span"),Zl=new ot("worker/shutdown");function ed(e){let n=nt(new tt(e),new rt(e));return n.listen(),n}function nd(){let e=nt(new tt(process),new rt(process));return e.listen(),e}import{graphql as v}from"gql.tada";import{gzip as $o}from"zlib";import{promisify as Lo}from"util";import{existsSync as Fe,readFileSync as Me}from"fs";import ne from"path";import{graphql as E}from"gql.tada";function at(e){return[e.kind,e.target,e.value].filter(n=>n.length>0).join(" ")}var Po={"no-effect":"noEffect","required-state-unsatisfied":"requiredStateUnsatisfied",unresolvable:"unresolvable"},Co={"data-rule":"dataRule","page-rule":"pageRule",step:"step"},To={aborted:"aborted","action-failed":"actionFailed","check-failed":"checkFailed","client-mount-missing":"clientMountMissing","conflicting-sessions":"conflictingSessions","driver-launch":"driverLaunch","engine-decode":"engineDecode","engine-http":"engineHttp","engine-network":"engineNetwork","engine-unreachable":"engineUnreachable","setup-missing-row":"setupMissingRow","state-identity":"stateIdentity"};function st(e){return e.kind==="consistency"?{consistency:{mismatch:Fo(e.mismatch),pending:e.pending}}:e.kind==="pending-check"?{pendingCheck:{budget:e.budget,source:Co[e.source.kind],...jo(e.source)}}:e.kind==="unrunnable"?{unrunnable:{reason:Po[e.reason]}}:e.kind==="driver-error"?{driverError:{errorKind:To[e.error.kind],message:Mo(e.error)}}:{impossibleAction:{subject:Ao(e.step.action)}}}function jo(e){return"check"in e?lt(e.check,!1):{checkKind:void 0,expected:void 0,negated:void 0,subject:void 0}}function lt(e,n){return e.kind==="not"?lt(e.inner,!n):e.kind==="browser"?{checkKind:"browser",expected:e.value??void 0,negated:n,subject:ie(e.key)}:e.kind==="value"||e.kind==="text"?{checkKind:e.kind,expected:e.value,negated:n,subject:N(e.locator)}:{checkKind:e.kind,expected:void 0,negated:n,subject:N(e.locator)}}function Ao(e){let n=e.locator==null?e.url??"":N(e.locator);return`${e.kind} ${n}`.trim()}function Fo(e){return e.kind==="wrong-value"?{wrongValue:{entity:e.entity,field:e.field,key:e.key,snapshot:b(e.snapshot),sut:b(e.sut)}}:e.kind==="expected-change"?{expectedChange:{entity:e.entity,field:e.field,key:e.key,value:b(e.value)}}:e.kind==="singleton-mismatch"?{singletonMismatch:{singleton:e.singleton,snapshot:b(e.snapshot),sut:b(e.sut)}}:e.kind==="unexpected-row"?{unexpectedRow:{entity:e.entity,key:e.key}}:e.kind==="browser-mismatch"?{singletonMismatch:{singleton:ie(e.key),snapshot:b(e.snapshot),sut:b(e.sut)}}:{missingRow:{entity:e.entity,key:e.key}}}function b(e){return e==null?null:String(e)}function Mo(e){return"message"in e?e.message:"detail"in e?e.detail:null}async function Uo({config:e,cwd:n,fixturesDir:t,headed:r,lockfile:o,runId:i,session:s,signal:l,test:u}){if(!await si(e,i))return{kind:"dispatch-failed",reason:"already-claimed",runId:i};let p=ne.join(n,".ripplo","debug"),c=[];return(await s.runOnce({capture:!0,lockfile:o,onPhase:void 0,options:{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:t,generate:I,headed:r,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth},params:void 0,runId:i,sequence:void 0,test:u,onEvent:S=>{c.push(S)}},l)).match(async S=>{let x=ct(c).flatMap(yt=>yt.findings),Le=Oo(x);return Le!=null?(await dt({config:e,debugDir:p,events:c,recordingOptional:!0,runId:i,stepSources:void 0}),{error:Le,kind:"error",runId:i}):(await te({config:e,debugDir:p,events:c,recordingOptional:!1,runId:i,stepSources:void 0}),x.length>0?{findings:x,kind:"findings",runId:i}:{kind:"pass",runId:i})},S=>Promise.resolve({error:S,kind:"error",runId:i}))}function Oo(e){let n=e.find(t=>t.kind==="driver-error"&&Be(t.error));return n!=null&&n.kind==="driver-error"?n.error:void 0}async function te(e){let n=await dt(e);await ai(e.config,e.runId,n),await Do(e.config,e.debugDir,e.runId)}async function dt({config:e,debugDir:n,events:t,recordingOptional:r,runId:o,stepSources:i}){let s=ct(t),l=qo(n,o);if(l==null&&!r)throw new Error("recording-missing");return await Qo({aliases:[...Bo(t),...Vo(s)],config:e,generated:zo(t),generatedSingletons:Jo(t),origin:l==null?_o(s):l.origin,records:s,rrwebEvents:l==null?[]:l.events,runId:o,stepSources:i}),l!=null&&await ii(e,o,l),s}var No=E(`
120
+ mutation ClipUploadUrl($runId: ID!) {
121
+ clipUploadUrl(runId: $runId)
122
+ }
123
+ `);async function Do(e,n,t){let r=ne.join(n,t,"clip.gif");if(Fe(r))try{let o=await f({config:e,document:No,variables:{runId:t}});if(o.clipUploadUrl==null)return;let i=await fetch(o.clipUploadUrl,{body:new Uint8Array(Me(r)),headers:{"Content-Type":"image/gif"},method:"PUT"});i.ok||y.warn({runId:t,status:i.status},"Clip upload failed")}catch(o){y.warn({err:o,runId:t},"Clip upload skipped")}}function _o(e){return e.reduce((n,t)=>Math.min(n,t.startMs),e[0]?.startMs??0)}function ct(e){return e.flatMap(n=>n.kind==="step"?[{annotations:n.annotations,endMs:n.endMs,findings:n.findings,index:n.index,source:n.source,startMs:n.startMs,state:n.state,url:n.url}]:[])}function qo(e,n){let t=ne.join(e,n,"behavior.jsonl");if(!Fe(t))return null;let r=Me(t,"utf8").split(`
124
+ `).filter(i=>i.length>0).map(i=>Ho(i)).flatMap(i=>Wo(i)?[i.event]:[]),o=r[0];return o==null?null:{events:r,origin:o.timestamp}}function Ho(e){return JSON.parse(e)}function Wo(e){return typeof e=="object"&&e!=null&&Reflect.get(e,"kind")==="rrweb"}function Bo(e){return e.flatMap(n=>n.kind==="world"?n.aliases:[])}function Vo(e){return e.flatMap(n=>{let t=Ko(n.source);return t.flatMap(r=>{let i=t.filter(l=>l.entity===r.entity).indexOf(r),s=n.state.rows.filter(l=>l.status==="created"&&l.entity===r.entity).at(i);return s==null?[]:[{alias:r.as,entity:r.entity,key:s.key}]})})}function zo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generated.map(t=>ut(t)):[]))}function ut({entity:e,field:n,key:t}){return`${e}\0${t}\0${n}`}function Jo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generatedSingletons:[]))}function Ko(e){return e==null?[]:e.expect.flatMap(n=>Ae(n))}function Ae(e){return e.kind==="state"&&e.assertion.kind==="created"?[{as:e.assertion.as,entity:e.entity}]:e.kind==="and"?e.predicates.flatMap(n=>Ae(n)):e.kind==="when"?e.branches.flatMap(n=>n.consequence.flatMap(t=>Ae(t))):[]}async function Qo({aliases:e,config:n,generated:t,generatedSingletons:r,origin:o,records:i,rrwebEvents:s,runId:l,stepSources:u}){let d=i.map((p,c)=>Zo({aliases:e,generated:t,generatedSingletons:r,origin:o,record:p,rrwebEvents:s,sourceTest:u?.[c]??null}));await f({config:n,document:di,variables:{items:[{runId:l,steps:d}]}})}var Go=3,Xo=0;function Yo({endMs:e,rrwebEvents:n,startMs:t}){let r=n.find(o=>o.type===Go&&o.data?.source===Xo&&o.timestamp>=t&&o.timestamp<=e);return r==null?t:r.timestamp}function Zo({aliases:e,generated:n,generatedSingletons:t,origin:r,record:o,rrwebEvents:i,sourceTest:s}){let l=We(o.source,o.index),u=Yo({endMs:o.endMs,rrwebEvents:i,startMs:o.startMs}),d=o.annotations.map(c=>({kind:c.kind,label:c.label,outcome:c.outcome,recordingStartMs:Math.max(0,(c.kind==="action"?u:c.atMs)-r),rrwebIds:[...c.rrwebIds],url:c.url,value:c.value??null})),p=o.annotations.find(c=>c.kind==="action")?.rrwebIds??[];return{annotations:d,detail:null,duration:Math.max(0,o.endMs-o.startMs),findings:o.findings.map(c=>st(c)),nodeType:l.kind,recordingEndMs:Math.max(0,o.endMs-r),recordingStartMs:Math.max(0,u-r),rrwebIds:[...p],snapshotTimestamp:Math.max(0,o.endMs-r),sourceTest:s,stateRows:o.state.rows.map(c=>ei({aliases:e,generated:n,row:c})),stateSingletons:o.state.singletons.map(c=>({changed:c.changed,generated:t.has(c.name),name:c.name,value:c.value==null?null:String(c.value)})),status:o.findings.length>0?"failed":"passed",stepIndex:o.index,title:at(l),url:o.url}}function ei({aliases:e,generated:n,row:t}){let r=e.find(o=>o.entity===t.entity&&o.key===t.key);return{entity:t.entity,fields:t.fields.map(o=>({changed:o.changed,field:o.field,generated:n.has(ut({entity:t.entity,field:o.field,key:t.key})),value:o.value==null?null:String(o.value)})),key:t.key,label:r?.alias??t.key,status:t.status}}var ni=Lo($o);async function pt(e,n){await f({config:e,document:pi,variables:{runIds:[n]}})}var ti="application/x-ndjson";async function ri({config:e,debugDir:n,runId:t}){let r=ne.join(n,t,"behavior.jsonl");if(Fe(r))try{let o=await f({config:e,document:oi,variables:{runId:t}}),i=await fetch(o.debugArtifactUploadUrl,{body:Me(r),headers:{"content-type":ti},method:"PUT"});if(!i.ok){y.warn({runId:t,status:i.status},"behavior upload PUT failed");return}await pt(e,t)}catch(o){y.warn({error:o,runId:t},"behavior upload failed")}}var oi=E(`
125
+ mutation DebugArtifactUploadUrl($runId: String!) {
126
+ debugArtifactUploadUrl(runId: $runId)
127
+ }
128
+ `);async function ii(e,n,t){let r=t.events.map(s=>JSON.stringify(s)).join(`
129
+ `),o=await ni(Buffer.from(r,"utf8")),i=t.events.at(-1);await f({config:e,document:ci,variables:{input:{bodyBase64:o.toString("base64"),chunkIndex:0,endTimestamp:Math.max(0,(i?.timestamp??t.origin)-t.origin),eventCount:t.events.length,runId:n,startTimestamp:0}}})}async function ai(e,n,t){let r=t.filter(s=>s.findings.length>0).length,o=t.length-r,i=t.reduce((s,l)=>s+Math.max(0,l.endMs-l.startMs),0);await f({config:e,document:ui,variables:{items:[{duration:i,failCount:r,passCount:o,runId:n,status:r>0?"failed":"passed",summary:null,warnCount:0}]}})}async function si(e,n){return((await f({config:e,document:li,variables:{runIds:[n]}})).startRunsBatch??[]).some(r=>r.id===n)}var li=E(`
130
+ mutation StartRunsBatch($runIds: [String!]!) {
131
+ startRunsBatch(runIds: $runIds) {
132
+ id
133
+ }
134
+ }
135
+ `),di=E(`
136
+ mutation SubmitRunStepsBatch($items: [SubmitRunStepsItem!]!) {
137
+ submitRunStepsBatch(items: $items)
138
+ }
139
+ `),ci=E(`
140
+ mutation SubmitRunRecordingChunk($input: SubmitRunRecordingChunkInput!) {
141
+ submitRunRecordingChunk(input: $input)
142
+ }
143
+ `),ui=E(`
144
+ mutation CompleteRunsBatch($items: [CompleteRunItem!]!) {
145
+ completeRunsBatch(items: $items) {
146
+ id
147
+ status
148
+ }
149
+ }
150
+ `),pi=E(`
151
+ mutation MarkRunArtifactsUploadedBatch($runIds: [String!]!) {
152
+ markRunArtifactsUploadedBatch(runIds: $runIds)
153
+ }
154
+ `);function fi(e){let n=e.trail;if(!(n==null||!yi(e.kind)))return{baseLabel:n.baseLabel,baseState:n.baseState,durationMs:n.durationMs,outcome:e.kind,runId:e.runId,signature:n.signature,steps:n.steps}}function yi(e){return e==="clean"||e==="flaky"||e==="finding"}async function $e({baseState:e,branchName:n,category:t,commitSha:r,config:o,debugDir:i,devSessionId:s,events:l,lockfileHash:u,reproJson:d,runId:p,signature:c,spec:m,stepSources:S}){await f({config:o,document:xi,variables:{branchName:n??null,commitSha:r??null,devSessionId:s??null,lockfileHash:u??null,projectId:o.projectId,reproJson:d,runId:p,spec:m??null}}),await te({config:o,debugDir:i,events:l,recordingOptional:!0,runId:p,stepSources:S}),await f({config:o,document:wi,variables:{baseState:e,category:t,projectId:o.projectId,reproRunId:p,signature:c}})}async function re(e,n,t){return(await f({config:e,document:bi,variables:{lockfileHash:t,projectId:e.projectId,signature:n}})).exploreFindingExists}async function mi({attempts:e,config:n,devSessionId:t,findings:r,trail:o}){await f({config:n,document:ki,variables:{attempts:e,devSessionId:t,findings:r,trail:o==null?null:{baseLabel:o.baseLabel,baseState:o.baseState,durationMs:o.durationMs,findingRunId:o.runId??null,findingSignature:o.signature??null,outcome:o.outcome,steps:o.steps.map(i=>({test:i.test,text:i.text}))}}})}async function gi(e,n,t){let r=await f({config:e,document:hi,variables:{devSessionId:n}}).catch(i=>(y.warn({error:i},"fetchScopedTestRefs failed"),null)),o=new Set(r?.exploreScope??[]);return o.size===0?new Set:new Set(t.workflows.filter(i=>o.has(g(i.name))).flatMap(i=>i.tests.map(s=>h(s))))}var hi=v(`
155
+ query ExploreScope($devSessionId: String!) {
156
+ exploreScope(devSessionId: $devSessionId)
157
+ }
158
+ `);async function Ri(e,n){return(await f({config:e,document:Si,variables:{devSessionId:n}}).catch(r=>(y.warn({error:r},"reportExploreUnhealthy failed"),null)))?.reportExploreUnhealthy??!1}var ki=v(`
159
+ mutation RecordExplorationProgress(
160
+ $devSessionId: String!
161
+ $attempts: Int!
162
+ $findings: Int!
163
+ $trail: ExploreTrailInput
164
+ ) {
165
+ recordExplorationProgress(
166
+ devSessionId: $devSessionId
167
+ attempts: $attempts
168
+ findings: $findings
169
+ trail: $trail
170
+ )
171
+ }
172
+ `),Si=v(`
173
+ mutation ReportExploreUnhealthy($devSessionId: String!) {
174
+ reportExploreUnhealthy(devSessionId: $devSessionId)
175
+ }
176
+ `),xi=v(`
177
+ mutation CreateExploreRun(
178
+ $projectId: String!
179
+ $runId: String!
180
+ $devSessionId: String
181
+ $branchName: String
182
+ $commitSha: String
183
+ $lockfileHash: String
184
+ $spec: String
185
+ $reproJson: String
186
+ ) {
187
+ createExploreRun(
188
+ projectId: $projectId
189
+ runId: $runId
190
+ devSessionId: $devSessionId
191
+ branchName: $branchName
192
+ commitSha: $commitSha
193
+ lockfileHash: $lockfileHash
194
+ spec: $spec
195
+ reproJson: $reproJson
196
+ ) {
197
+ id
198
+ }
199
+ }
200
+ `),wi=v(`
201
+ mutation SubmitExploreFinding(
202
+ $projectId: String!
203
+ $signature: String!
204
+ $baseState: String!
205
+ $category: ExploreFindingCategory!
206
+ $reproRunId: String!
207
+ ) {
208
+ submitExploreFinding(
209
+ projectId: $projectId
210
+ signature: $signature
211
+ baseState: $baseState
212
+ category: $category
213
+ reproRunId: $reproRunId
214
+ ) {
215
+ id
216
+ }
217
+ }
218
+ `),bd=v(`
219
+ mutation SetExploreFindingStatus(
220
+ $projectId: String!
221
+ $signature: String!
222
+ $status: ExploreFindingStatus!
223
+ ) {
224
+ setExploreFindingStatus(projectId: $projectId, signature: $signature, status: $status)
225
+ }
226
+ `),bi=v(`
227
+ query ExploreFindingExists($projectId: String!, $signature: String!, $lockfileHash: String!) {
228
+ exploreFindingExists(projectId: $projectId, signature: $signature, lockfileHash: $lockfileHash)
229
+ }
230
+ `);import{graphql as ft}from"gql.tada";async function Ei(e,n,t){await f({config:e,document:vi,variables:{reason:t,runId:n}}).catch(r=>{y.error(r,"failRun submission failed")})}var vi=ft(`
231
+ mutation FailRun($runId: String!, $reason: String!) {
232
+ failRun(runId: $runId, reason: $reason)
233
+ }
234
+ `),Pd=ft(`
235
+ mutation MarkRunUnready($runId: String!, $cause: RunUnreadyCause!) {
236
+ markRunUnready(runId: $runId, cause: $cause)
237
+ }
238
+ `);import{randomUUID as Ii}from"crypto";async function Pi({assign:e,config:n,debugDir:t,devSessionId:r,fixturesDir:o,headed:i,lockfile:s,report:l,session:u,signal:d}){let p=ze(s);if(e.stepRuns.length===0)return{kind:"error",reason:"empty-trail"};let c=Ui(p,e.stepRuns),m=await Ge({baseState:{name:h(e.baseStateTest),test:e.baseStateTest},corpus:p,lockfile:s,options:{baseUrl:n.appUrl,engineUrl:n.engineUrl,fixturesDir:o,generate:I,headed:i,secret:n.webhookSecret,tunnelAuth:n.tunnelAuth},seenSignature:l?x=>re(n,x,e.lockfileHash):void 0,session:u,stepRuns:e.stepRuns,runIdFor:x=>`explore-${Ii()}-${String(x)}`},d),S=l?await Mi({baseStateTest:e.baseStateTest,config:n,debugDir:t,devSessionId:r,lockfileHash:e.lockfileHash,outcome:m,reproJson:Ai(p,e),stepSources:Fi(c)}):!1;return ji(m,c.length),Oi(m,S,Ci(c,e,m))}function Ci(e,n,t){if(t.kind==="error"||t.kind==="aborted")return;let r=t.timing.confirm;return{baseLabel:n.baseStateTest.intent,baseState:h(n.baseStateTest),durationMs:Math.round(oe(t.timing.detect)+(r==null?0:oe(r))),signature:t.kind==="finding"?t.signature:void 0,steps:Ti(e)}}function Ti(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(r=>({test:t,text:r}))})}function oe(e){return e.engineMs+e.worldMs+e.browserMs+e.driveMs+e.teardownMs}function ji(e,n){if(e.kind==="error"){y.info({detail:Ve(e.error),kind:e.kind,reason:e.error.kind,steps:n},"explore trail");return}if(e.kind==="aborted"){y.info({kind:e.kind,steps:n},"explore trail");return}let t=e.timing.detect,r=e.timing.confirm;y.info({browserMs:t.browserMs,confirmMs:r==null?void 0:oe(r),detectMs:oe(t),driveMs:t.driveMs,engineMs:t.engineMs,kind:e.kind,steps:n,teardownMs:t.teardownMs,worldMs:t.worldMs},"explore trail")}function Ai(e,n){let t=n.stepRuns.flatMap(o=>{let i=e[o.idx];return i==null?[]:[{index:i.index,params:o.params,test:i.test}]}),r={baseStateRef:h(n.baseStateTest),steps:t};return JSON.stringify(r)}function Fi(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(()=>t)})}async function Mi({baseStateTest:e,config:n,debugDir:t,devSessionId:r,lockfileHash:o,outcome:i,reproJson:s,stepSources:l}){return i.kind!=="finding"||i.captureEvents.length===0?!1:await re(n,i.signature,o)?(y.info({devSessionId:r,signature:i.signature},"explore finding already reported, skipping duplicate"),!1):(await $e({baseState:i.baseState,branchName:void 0,category:$i(i.verifierLayer),commitSha:void 0,config:n,debugDir:t,devSessionId:r,events:i.captureEvents,lockfileHash:o,reproJson:s,runId:i.runId,signature:i.signature,spec:Li(e,i.captureEvents),stepSources:l}).catch(u=>{y.warn({error:u},"explore finding report failed")}),!0)}function $i(e){return e==="data-rule"?"dataRule":e==="page-rule"?"pageRule":e}function Li(e,n){let t=n.flatMap(o=>o.kind==="step"?[o.source]:[]),r={absent:e.absent,exclusive:e.exclusive,intent:e.intent,maybe:[],name:e.name,params:e.params,singletons:e.singletons,steps:t,stub:!1,tests:[],world:e.world};return JSON.stringify(r)}function Ui(e,n){return n.flatMap(t=>{let r=e[t.idx];return r==null?[]:[{actions:[...r.nav,...r.steps].map(o=>Je(o.action)),label:`${r.test}#${String(r.index)}`}]})}function Oi(e,n,t){return e.kind==="error"?{kind:e.kind,reason:`runtime:${e.error.kind}`}:e.kind==="finding"?{kind:e.kind,runId:n?e.runId:void 0,trail:t}:{kind:e.kind,trail:t}}import Ni from"path";import{randomUUID as Di}from"crypto";async function Kd({cwd:e,onReady:n,signal:t,step:r,target:o}){let i=hn(e).match(c=>({config:c}),c=>({failure:c}));if("failure"in i)return{failure:i.failure,kind:"config-failed"};let s=i.config,l=await ge(e);if(l.result.isErr())return{error:l.result.error,kind:"compile-failed"};let u=l.result.value,d=await _i(u,o);return d.kind!=="ok"?d:(await Ke({lockfile:u,onReady:n,options:qi(s),runId:`teleport-${Di()}`,sequence:d.sequence,stopAfterStep:r,test:d.test},t)).match(c=>({kind:"done",result:c}),c=>({error:c,kind:"run-failed"}))}async function _i(e,n){if(n.kind==="explore"){let r=await Xe(e,n.repro);return r.kind==="unplannable"?{kind:"unplannable"}:{kind:"ok",sequence:r.sequence,test:r.baseTest}}let t=F(e).find(r=>r.ref===n.ref);return t==null?{kind:"no-test",ref:n.ref}:{kind:"ok",sequence:Qe(e,t.test,void 0),test:t.test}}function qi(e){return{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:Ni.join(e.cwd,$),generate:I,headed:!0,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth}}export{zi as a,ea as b,B as c,wt as d,V as e,$ as f,T as g,ln as h,ge as i,O as j,j as k,wa as l,K as m,Pa as n,Ca as o,Ta as p,La as q,he as r,pn as s,yn as t,hn as u,xn as v,Se as w,Ya as x,ee as y,et as z,Il as A,Pl as B,Cl as C,Eo as D,Nl as E,Ps as F,Cs as G,Tn as H,Ts as I,js as J,As as K,Fs as L,Ms as M,An as N,Fn as O,Mn as P,$n as Q,Ln as R,Bl as S,zl as T,Jl as U,Kl as V,Ql as W,Gl as X,Xl as Y,Yl as Z,Zl as _,ed as $,nd as aa,ns as ba,ts as ca,xe as da,rs as ea,bn as fa,Rs as ga,Ee as ha,Yr as ia,Rl as ja,Uo as ka,ri as la,Ei as ma,fi as na,mi as oa,gi as pa,Ri as qa,Pi as ra,Kd as sa};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f,ga as g,ha as h,ia as i,ja as j,ka as k}from"./chunk-GLXPGXO6.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";export{b as renderDaemonBindError,g as renderDaemonLockCompromised,f as renderDaemonLockHeld,e as renderDaemonReady,h as renderDaemonStatus,j as renderDaemonVersionNote,i as renderExplorationProgress,d as renderNotSignedIn,c as renderProjectAccessDenied,a as renderTunnelProvisionFailed,k as wireOutcome};
2
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f,ga as g,ha as h,ia as i,ja as j,ka as k}from"./chunk-ITI53W73.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";export{b as renderDaemonBindError,g as renderDaemonLockCompromised,f as renderDaemonLockHeld,e as renderDaemonReady,h as renderDaemonStatus,j as renderDaemonVersionNote,i as renderExplorationProgress,d as renderNotSignedIn,c as renderProjectAccessDenied,a as renderTunnelProvisionFailed,k as wireOutcome};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{$ as Ie,B as ie,D as me,F as ye,U as be,V as xe,W as Pe,X as Re,Y as Ee,Z as Te,_ as Ce,b as K,ba as P,ca as R,da as We,e as Y,ea as M,fa as Ae,h as x,ha as U,i as re,ia as Le,j as H,ja as De,m as _,ma as E,na as He,oa as _e,pa as Me,qa as Ue,r as oe,sa as qe,u as w,w as ne,x as te}from"./chunk-KAILSYCU.js";import{G as se,I as ce,J as de,K as ue,L as pe,T as fe,ba as ge,ca as Se,da as ke,e as X,ea as ve,fa as we,ga as he,h as Z,i as D,l as ee,n as ae,q as le}from"./chunk-GLXPGXO6.js";import{b as Oe}from"./chunk-RLXQYG7H.js";import{c as G,d as g,e as s,f as L,g as V}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import Bo from"path";import{createClient as jo}from"graphql-sse";import zo,{AbortError as Jo}from"p-retry";import{graphql as z}from"gql.tada";import{graphql as Ar}from"gql.tada";import{print as Lr}from"graphql";async function Fe({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:c}){let u=await x(r);if(u.isErr())return await E(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let p=Wr(u.value,{testSlug:a,workflowSlug:c});if(p==null)return await E(e,t,`no-test:${c}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${c}/${a}`,type:"generic"}};let d=await P({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!d.serverNotified&&d.outcome.kind==="error"&&await E(e,t,d.outcome.detail),d.outcome}function Wr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>ee(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:le(t)}var Dr=6e4,Hr=Ar(`
2
+ import{$ as Ie,B as ie,D as me,F as ye,U as be,V as xe,W as Pe,X as Re,Y as Ee,Z as Te,_ as Ce,b as K,ba as P,ca as R,da as We,e as Y,ea as M,fa as Ae,h as x,ha as U,i as re,ia as Le,j as H,ja as De,m as _,ma as E,na as He,oa as _e,pa as Me,qa as Ue,r as oe,sa as qe,u as w,w as ne,x as te}from"./chunk-SM6N6ZSY.js";import{G as se,I as ce,J as de,K as ue,L as pe,T as fe,ba as ge,ca as Se,da as ke,e as X,ea as ve,fa as we,ga as he,h as Z,i as D,l as ee,n as ae,q as le}from"./chunk-ITI53W73.js";import{b as Oe}from"./chunk-RLXQYG7H.js";import{c as G,d as g,e as s,f as L,g as V}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import Bo from"path";import{createClient as jo}from"graphql-sse";import zo,{AbortError as Jo}from"p-retry";import{graphql as z}from"gql.tada";import{graphql as Ar}from"gql.tada";import{print as Lr}from"graphql";async function Fe({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:l,workflowSlug:c}){let u=await x(r);if(u.isErr())return await E(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let p=Wr(u.value,{testSlug:a,workflowSlug:c});if(p==null)return await E(e,t,`no-test:${c}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${c}/${a}`,type:"generic"}};let d=await P({headed:o,workClass:l,task:()=>n.execute({headed:o,runId:t,testRef:p},i)});return!d.serverNotified&&d.outcome.kind==="error"&&await E(e,t,d.outcome.detail),d.outcome}function Wr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>ee(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:le(t)}var Dr=6e4,Hr=Ar(`
3
3
  subscription RunRequestedWatch($devSessionId: String!) {
4
4
  runRequested(devSessionId: $devSessionId) {
5
5
  runId