ripplo 0.7.31 → 0.7.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-APYROHWG.js +163 -0
- package/dist/chunk-DP5GPMT3.js +238 -0
- package/dist/daemon-WKOUQS3E.js +90 -0
- package/dist/daemon-XBKRUQRS.js +2 -0
- package/dist/index.js +185 -178
- package/package.json +3 -3
- package/dist/chunk-MJXQ6SVH.js +0 -164
- package/dist/chunk-WJ7CHQ7B.js +0 -228
- package/dist/daemon-EWT54KJZ.js +0 -90
- package/dist/daemon-PU4XNBMZ.js +0 -2
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{R as ze,U as Je,a as N,b as Ne,g as De,i as _e,j as qe,k as He,l as g,m as We,o as h,p as A,q as Be,u as v,z as Ve}from"./chunk-APYROHWG.js";import{b as Le,d as f,e as m,g as Ue,h as w,i as Oe}from"./chunk-5VRJXHWH.js";import Ge from"fs";import W from"path";import{config as yt}from"dotenv";import{z as q}from"zod";import{err as gt,ok as Xe}from"neverthrow";import _ from"fs";import se from"path";import{err as ie,ok as Ke}from"neverthrow";import{z as D}from"zod";var ut=se.join(".ripplo","project.json"),ae=[".env",".env.local"],pt=D.object({envFiles:D.array(D.string().min(1)).optional(),projectId:D.string().min(1)});function Qe(e){return se.join(e,ut)}function le(e){let n=Qe(e);return _.existsSync(n)?ft(n).andThen(t=>{let r=pt.safeParse(t);return r.success?Ke({envFiles:r.data.envFiles??ae,projectId:r.data.projectId}):ie({issues:r.error.issues.map(o=>`${o.path.join(".")}: ${o.message}`),kind:"project-file-invalid",path:n})}):ie({kind:"project-file-missing",path:n})}function de(e){return le(e).match(n=>n,()=>{})}function ft(e){try{return Ke(JSON.parse(_.readFileSync(e,"utf8")))}catch(n){return ie({issues:[n instanceof Error?n.message:String(n)],kind:"project-file-invalid",path:e})}}function Ni({cwd:e,envFiles:n,projectId:t}){let r=Qe(e);_.mkdirSync(se.dirname(r),{recursive:!0});let o={projectId:t};n!=null&&!mt(n)&&(o.envFiles=[...n]),_.writeFileSync(r,JSON.stringify(o,null,2)+`
|
|
3
|
+
`)}function mt(e){return e.length!==ae.length?!1:e.every((n,t)=>n===ae[t])}function zi(e){let t=de(e)?.envFiles??[".env",".env.local"],r=W.join(e,".ripplo");t.forEach(o=>{let i=W.resolve(r,o);Ge.existsSync(i)&&yt({override:!0,path:i,quiet:!0})}),H=void 0}var ht=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?Xe(H):kt().map(e=>(H=e,e))}function Rt(e){let t=de(e)?.envFiles??[],r=W.join(e,".ripplo");return t.map(o=>W.resolve(r,o)).filter(o=>!Ge.existsSync(o))}function kt(){let e=ht.safeParse(process.env);if(!e.success)return gt({issues:e.error.issues.map(t=>`${t.path.join(".")}: ${t.message}`),kind:"env-invalid",missingEnvFiles:Rt(process.cwd())});let n=e.data;return Xe({appUrl:n.RIPPLO_APP_URL,engineUrl:n.RIPPLO_ENGINE_URL,webhookSecret:n.RIPPLO_WEBHOOK_SECRET})}import{readFileSync as St}from"fs";import{z as Ye}from"zod";var xt=Ye.object({version:Ye.string()});function V(){let e=St(new URL("../package.json",import.meta.url),"utf8");return xt.parse(JSON.parse(e)).version}import me from"fs";import z from"path";import{createJiti as At}from"jiti";import{err as L,ok as tn}from"neverthrow";import wt from"fs";import F from"path";import I from"typescript";function Ze(e){let n=F.join(e,"index.ts"),t=vt(e);wt.mkdirSync(F.dirname(t.tsBuildInfoFile??""),{recursive:!0});let r=I.createIncrementalCompilerHost(t),o=I.createIncrementalProgram({host:r,options:t,rootNames:[n]}),i=[...o.getSyntacticDiagnostics(),...o.getSemanticDiagnostics()];o.emit();let s=i.filter(c=>bt(c,e));if(s.length===0)return{diagnostics:[],ok:!0};let l={getCanonicalFileName:c=>c,getCurrentDirectory:()=>F.dirname(e),getNewLine:()=>`
|
|
4
|
+
`};return{diagnostics:I.formatDiagnosticsWithColorAndContext(s,l).split(`
|
|
5
|
+
`).filter(c=>c.length>0),ok:!1}}function bt(e,n){let t=e.file?.fileName;return t==null?!0:t.startsWith(n)}var Et=F.join(".local","tsbuildinfo");function vt(e){return{allowImportingTsExtensions:!0,allowJs:!1,esModuleInterop:!0,incremental:!0,module:I.ModuleKind.Preserve,moduleResolution:I.ModuleResolutionKind.Bundler,noEmit:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!1,target:I.ScriptTarget.ES2022,tsBuildInfoFile:F.join(e,Et)}}import{createHash as It}from"crypto";import en from"fs/promises";import ce from"path";import{err as P,ok as ue,Result as Pt}from"neverthrow";var M=".ripplo/fixtures",pe=10*1024*1024,fe=50*1024*1024;async function nn(e,n){let t=Ct(n);if(t.length===0)return ue({});let r=ce.join(e,M),o=await Promise.all(t.map(i=>Tt({fixturesRoot:r,name:i})));return Pt.combine(o).andThen(jt)}function Ct(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 Tt({fixturesRoot:e,name:n}){if(n.includes("..")||ce.isAbsolute(n))return P({kind:"fixture-invalid-name",name:n});let t=ce.join(e,n),r=await en.lstat(t).catch(()=>null);if(r==null)return P({kind:"fixture-missing",name:n,path:t});if(r.isSymbolicLink())return P({kind:"fixture-symlink",name:n});if(!r.isFile())return P({kind:"fixture-not-file",name:n});let o=await en.readFile(t);if(o.byteLength>pe)return P({kind:"fixture-too-large",name:n,size:o.byteLength});let i=It("sha256").update(o).digest("hex");return ue([n,{sha256:i,size:o.byteLength}])}function jt(e){let n=e.reduce((t,[,r])=>t+r.size,0);return n>fe?P({kind:"fixtures-total-too-large",total:n}):ue(Object.fromEntries(e))}var C=".ripplo/ripplo.lock",$;async function rn(e){let{result:n}=await ye(e);return n}async function ye(e){let n=Mt(z.join(e,".ripplo"));if($!=null&&$.fingerprint===n&&$.result.isOk())return{fingerprint:n,result:$.result};let t=await U(e);return $={fingerprint:n,result:t},{fingerprint:n,result:t}}async function U(e){let n=z.join(e,".ripplo"),t=z.join(n,"index.ts"),r=Ze(n);return r.ok?(await $t(t)).andThen(s=>Ut({entryPath:t,exported:s})).match(async s=>(await nn(e,s)).map(u=>({...s,fixtures:u})).mapErr(u=>({error:u,kind:"fixture-failed"})),s=>Promise.resolve(L(s))):L({diagnostics:r.diagnostics,kind:"typecheck-failed"})}var Ft=new Set([".local","debug","node_modules"]);function Mt(e){return on(e).toSorted((n,t)=>n.localeCompare(t)).join("|")}function on(e){return(me.existsSync(e)?me.readdirSync(e,{withFileTypes:!0}):[]).flatMap(t=>{if(Ft.has(t.name))return[];let r=z.join(e,t.name);if(t.isDirectory())return on(r);let o=me.statSync(r);return[`${r}:${String(o.mtimeMs)}:${String(o.size)}`]})}async function $t(e){try{let t=await At(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 tn(r)}catch(n){return L({kind:"load-threw",message:Lt(n)})}}function Lt(e){return e instanceof Error?e.message:String(e)}function Ut({entryPath:e,exported:n}){if(n==null||typeof n!="object"||!("lockfile"in n))return L({entryPath:e,kind:"not-ripplo"});let t=De.safeParse(Reflect.get(n,"lockfile"));return t.success?tn(t.data):L({issues:t.error.issues.map(r=>`${r.path.join(".")}: ${r.message}`),kind:"invalid-lockfile"})}function T(e,n){return n==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${n}.`}function ma(e){return e.length===1?T(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: ${Ot(e)}`,T("create","DSL authoring + lint rules")].join(`
|
|
6
|
+
`)}function ka(){return`${C} is up to date`}function Sa(e){return[`${C} is ${e==="missing"?"missing":"out of date"} \u2014 run \`npx ripplo compile\` and commit the result`,T("setup")].join(`
|
|
7
|
+
`)}function xa(){return`Wrote ${C}`}function Ot(e){switch(e.kind){case"typecheck-failed":return["TypeScript errors in .ripplo/:",...an(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?):",...an(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 Nt(e.error)}}function an(e,n=8){return e.length<=n?e:[...e.slice(0,n),`\u2026 and ${String(e.length-n)} more`]}function Nt(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(pe)} per-file limit.`;case"fixtures-total-too-large":return`Fixtures total ${J(e.total)} \u2014 over the ${J(fe)} 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 Pa(e){return e instanceof Q?ge(e.failure):e instanceof Error?e.message:String(e)}function ge(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).",T("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 Dt(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 Dt(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 Ht,ok as Wt}from"neverthrow";import{z as he}from"zod";var _t="https://ripplo.ai";function ln(){return cn().RIPPLO_SERVER_URL}function dn(){return cn().RIPPLO_PROJECT_ID}var qt=he.object({RIPPLO_PROJECT_ID:he.string().min(1).optional(),RIPPLO_SERVER_URL:he.string().min(1).default(_t)}),sn;function cn(){return sn??=qt.parse(process.env),sn}import un from"fs";import Re from"path";function pn(e){let n=un.realpathSync(e),t=n,r=Re.dirname(t);for(;r!==t;){if(un.existsSync(Re.join(t,".git")))return t;t=r,r=Re.dirname(t)}return n}function fn(e){return le(e).andThen(n=>B().andThen(t=>{let r=ln(),o=Oe(r);return o==null?Ht({kind:"not-authenticated"}):Wt({appUrl:t.appUrl,cwd:pn(e),engineUrl:t.engineUrl,projectId:dn()??n.projectId,ripploServerUrl:r,token:o,tunnelAuth:void 0,webhookSecret:t.webhookSecret})}))}import mn from"fs";import{checkSync as Bt,lockSync as Vt}from"proper-lockfile";var zt="dev.pid",yn=15e3;function gn(e){return w(e,zt)}function hn(e){try{return Bt(gn(e),{realpath:!1,stale:yn})}catch{return!1}}var ke=class extends Error{pid;cwd;constructor({cwd:n,pid:t}){super("dev-lock-held"),this.name="DevLockHeldError",this.pid=t,this.cwd=n}};function Ba({cwd:e,onCompromised:n}){Ue(e);let t=gn(e),r=Jt({cwd:e,onCompromised:n,path:t});return mn.writeFileSync(t,String(process.pid)),()=>{try{r()}catch{}}}function Jt({cwd:e,onCompromised:n,path:t}){try{return Vt(t,{realpath:!1,stale:yn,onCompromised:()=>{n()}})}catch(r){throw Kt(r)?new ke({cwd:e,pid:Qt(t)}):r}}function Kt(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:n}=e;return n==="ELOCKED"}function Qt(e){try{let n=mn.readFileSync(e,"utf8").trim(),t=Number.parseInt(n,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}import Gt from"p-queue";var Xt=4,Yt={"p0-ui":3,"p1-cli":2,"p2-cover":1,"p3-explore":0},G=new Gt({concurrency:Xt}),k={headedActive:0,interactiveActive:0,interactiveQueued:0},Rn={current:null};function Ja({headed:e,task:n,workClass:t}){let r=Yt[t];return t==="p3-explore"?G.add(n,{priority:r}):(k.interactiveQueued+=1,X(),G.add(()=>Zt({headed:e,task:n}),{priority:r}))}function Ka(e){!Number.isFinite(e)||e<1||(G.concurrency=Math.floor(e),X())}function Se(){return{active:k.interactiveActive,headedActive:k.headedActive,poolSize:G.concurrency,queued:k.interactiveQueued}}function Qa(e){Rn.current=e}async function Zt({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(){Rn.current?.()}import xe from"fs";import we from"path";function kn(e){try{let n=er(e);if(n==null)return;let t=we.join(n,"HEAD"),r=xe.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 er(e){let n=we.join(e,".git");if(xe.statSync(n).isDirectory())return n;let r=xe.readFileSync(n,"utf8").trim(),o="gitdir:";if(!r.startsWith(o))return;let i=r.slice(o.length).trim();if(i.length!==0)return we.resolve(e,i)}import nr from"crypto";import{readFile as Sn}from"fs/promises";import xn from"path";import{graphql as tr}from"gql.tada";import{err as rr,ok as or}from"neverthrow";var ir=tr(`
|
|
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 cs(e,n){let t=await U(e);if(t.isErr())return rr({error:t.error,kind:"compilation-failed"});let r=await be({config:n,cwd:e,lockfile:t.value});return or({devSessionId:r.devSessionId,lockfile:t.value})}async function be(e){let n=qe(e.lockfile);return sr({config:e.config,cwd:e.cwd,fixtures:e.lockfile.fixtures,payload:n})}function ar(e){return nr.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function sr({config:e,cwd:n,fixtures:t,payload:r}){let o=ar(r),i=kn(n),s=await dr(n),l=await lr(n,t),u=await f({config:e,document:ir,variables:{branch:i??null,cwd:n,fixtures:l,lockfileContent:s,preconditions:r.preconditions.map(c=>({depends:[...c.depends],description:c.description,name:c.name,returns:[...c.returns]})),projectId:e.projectId,singletons:r.singletons.map(c=>({defaultValue:c.defaultValue,description:c.description,name:c.name,type:c.type})),workflows:r.workflows.map(c=>({expectedOutcome:c.expectedOutcome,name:c.name,preconditions:[...c.preconditions],requiresKeys:c.requiresKeys.map(p=>({namespace:p.namespace,preconditionName:p.preconditionName})),slug:c.slug,sourcePath:c.sourcePath,spec:JSON.stringify(c.spec)}))}});if(u.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:u.syncDevSession.id,hash:o,hooksPaused:u.syncDevSession.hooksPaused}}async function lr(e,n){let t=Object.entries(n);return Promise.all(t.map(async([r,o])=>({contentBase64:(await Sn(xn.join(e,M,r))).toString("base64"),sha256:o.sha256})))}async function dr(e){try{return await Sn(xn.join(e,C),"utf8")}catch{return null}}import{randomUUID as Hr}from"crypto";import{createId as Wr}from"@paralleldrive/cuid2";import{CancellationTokenSource as Br,ResponseError as Vr}from"vscode-jsonrpc/node";import{graphql as cr}from"gql.tada";var ur=cr(`
|
|
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 wn(e){try{let t=(await f({config:e.config,document:ur,variables:pr(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 fr(n)}}function pr({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 fr(e){return e instanceof Le?{detail:e.message,kind:"infra-error"}:Y({detail:e instanceof Error?e.message:String(e),type:"generic"})}import{createMessageConnection as mr,NotificationType as bn,RequestType as yr,RequestType0 as En,SocketMessageReader as gr,SocketMessageWriter as hr}from"vscode-jsonrpc/node";import{z as a}from"zod";var Rr="daemon.sock",kr="daemon.log";function ks(e){return w(e,Rr)}function Ss(e){return w(e,kr)}function vn(e){return mr(new gr(e),new hr(e))}var In=a.object({all:a.boolean(),headed:a.boolean(),tests:a.array(a.string())}),xs=a.object({jobId:a.string(),total:a.number()}),Sr=a.enum(["on","off"]),xr=a.object({attempts:a.number(),findings:a.number()}),ws=a.object({active:a.number(),explorer:Sr,exploring:a.number(),progress:xr,queued:a.number(),sseHealth:a.object({detail:a.string().optional(),ok:a.boolean()}).optional(),version:a.string().optional()}),wr=a.enum(["MAX_RUNS","OVERAGE_CAP","MAX_AGENTS","MAX_CONCURRENT_RUNS","MAX_PROJECTS"]),br=a.discriminatedUnion("type",[a.object({code:wr,type:a.literal("limit")}),a.object({detail:a.string(),type:a.literal("generic")})]),Ee=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:br}),a.object({detail:a.string(),kind:a.literal("dispatch-timeout")}),a.object({detail:a.string(),kind:a.literal("infra-error")})]),Er=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:Ee,runId:a.string(),testName:a.string(),workflowName:a.string()})]),bs=a.object({event:Er,jobId:a.string()}),Es=a.object({failed:a.number(),jobId:a.string(),notRun:a.number(),passed:a.number()}),vs=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")})]),Pn=new yr("ripplo/enqueue"),Cn=new En("ripplo/status"),Tn=new En("ripplo/shutdownIfIdle"),jn=new bn("ripplo/jobEvent"),An=new bn("ripplo/jobDone");import{graphql as vr}from"gql.tada";async function Fn(e,n){let r=(await f({config:e,document:Ir,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 Ir=vr(`
|
|
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 Pr}from"vscode-jsonrpc/node";function ve(e){return`${e.workflowSlug}/${e.testSlug}`}function Mn(e){let{headed:n,inflight:t,jobId:r,lockfileHashValue:o,onExpire:i,runId:s,selection:l,timeoutMs:u}=e,c=ve(l),p=`${c}@${o}@${String(n)}`,d=t.get(p);if(d!=null)return d.jobIds.add(r),null;let y={cancellation:new Pr,claimed:!1,claimKey:c,headed:n,inflightKey:p,jobIds:new Set([r]),runId:s,testName:l.testName,timer:null,workflowName:l.workflowName};return y.timer=setTimeout(()=>{Z(t,y),i(y)},u),t.set(p,y),y}function Z(e,n){n.timer!=null&&(clearTimeout(n.timer),n.timer=null),e.delete(n.inflightKey)}function Ie(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 $n(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 Pe,ok as Ln}from"neverthrow";function On({all:e,ids:n,lockfile:t}){if(e&&n.length>0)return Pe({kind:"conflicting-flags"});if(e)return Ln(t.workflows.filter(i=>!i.stub).flatMap(i=>i.tests.map(s=>h(s))));if(n.length===0)return Pe({kind:"nothing-selected"});let r=n.map(i=>({id:i,refs:Tr(t,i)})),o=r.filter(i=>i.refs.length===0).map(i=>i.id);return o.length>0?Pe({kind:"unknown-ids",known:Cr(t),unknown:o}):Ln([...new Set(r.flatMap(i=>i.refs))])}function Nn(e,n){let t=new Map(A(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 Cr(e){return e.workflows.map(n=>g(n.name))}function Tr(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)):A(e).filter(r=>r.ref===n||Un(r.ref)===Un(n)).map(r=>r.ref)}function Un(e){let n=e.lastIndexOf("/");return n===-1?g(e):`${g(e.slice(0,n))}/${g(e.slice(n+1))}`}import{err as Ce,ok as _n}from"neverthrow";import{graphql as qn}from"gql.tada";import{execFileSync as jr}from"child_process";var Ar=256*1024*1024;function ee(e,n){return jr("git",[...e],{cwd:n,encoding:"utf8",maxBuffer:Ar,stdio:["ignore","pipe","pipe"]})}async function Hn({config:e,cwd:n,lockfile:t}){await Mr({config:e,cwd:n,lockfile:t});let r=await Lr(e);if(r.isErr())return Ce(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?Ce({kind:"scope-empty"}):_n(i)}var Fr=qn(`
|
|
90
|
+
mutation AddDirtyTestsToScope($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
91
|
+
addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
92
|
+
__typename
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
`);async function Mr({config:e,cwd:n,lockfile:t}){let r=new Set(Ur(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:Fr,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:o}}).catch(i=>{m.warn({err:i},"auto-scope of dirty tests failed")})}var $r=qn(`
|
|
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 Lr(e){try{let t=(await f({config:e,document:$r,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession?.scopeItems??[];return _n(t.flatMap(r=>r.workflow==null?[]:[r.workflow.slug]))}catch(n){return Ce({detail:n instanceof Error?n.message:String(n),kind:"scope-fetch-failed"})}}var Dn=".ripplo/workflows/";function Ur(e){try{return ee(["status","--porcelain","--",".ripplo/workflows"],e).split(`
|
|
112
|
+
`).map(n=>n.slice(3).trim()).filter(n=>n.startsWith(Dn)&&n.endsWith(".ts")).map(n=>n.slice(Dn.length)).filter(n=>n!=="index.ts"&&!n.endsWith("/index.ts"))}catch{return[]}}import{graphql as Or}from"gql.tada";var Nr=2e3,Dr=Or(`
|
|
113
|
+
query DaemonCloudRunStatus($runId: String!) {
|
|
114
|
+
run(id: $runId) {
|
|
115
|
+
status
|
|
116
|
+
failureReason
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
`);function Bn({config:e,onComplete:n,onStarted:t,runId:r,signal:o}){let i=!1,s,l=!1,u=async()=>{if(i||o.aborted)return;let c=await _r(e,r).catch(()=>"unknown");if(!l&&(c==="running"||Wn(c))&&(l=!0,t()),Wn(c)){i=!0,n(qr(c));return}s=setTimeout(()=>{u()},Nr)};return u(),{stop:()=>{i=!0,s!=null&&clearTimeout(s)}}}async function _r(e,n){let r=(await f({config:e,document:Dr,variables:{runId:n}})).run?.status;return r??"unknown"}function Wn(e){return e==="passed"||e==="failed"||e==="warning"||e==="cancelled"||e==="unready"}function qr(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 zr=12e4,Jr=-32099;function Kr(e){let n=new AbortController;return e.isCancellationRequested?(n.abort(),n.signal):(e.onCancellationRequested(()=>{n.abort()}),n.signal)}function cl(e){let n={...e,inflight:new Map,jobs:new Map};return{claim:t=>Zr(n,t),handleConnection:t=>{Qr(n,t)},idle:()=>Jn(n)}}function Qr(e,n){let t=vn(n);t.onRequest(Pn,(r,o)=>Gr({connection:t,ctx:e,params:r,token:o})),t.onRequest(Cn,()=>{let r=Se();return{active:r.active,queued:r.queued,sseHealth:e.sseHealth(),version:V(),...e.explorationStatus()}}),t.onRequest(Tn,()=>{let r=Jn(e);return r&&e.onShutdownRequest(),r}),t.onClose(()=>{Xr(e,t)}),t.onError(r=>{m.warn({err:r},"ipc connection error")}),n.on("error",r=>{m.warn({err:r},"ipc socket error")}),t.listen()}function Jn(e){let n=Se();return e.jobs.size===0&&n.active===0&&n.queued===0}async function Gr({connection:e,ctx:n,params:t,token:r}){let o=In.safeParse(t);if(!o.success)throw Vn({code:"bad-message"});await n.ready;let i=await no({config:n.config,cwd:n.cwd,message:o.data});if(i.kind==="error")throw Vn(i.error);let s=Hr(),l=new Br;return r.onCancellationRequested(()=>{Kn(n,s)}),n.jobs.set(s,{cancellation:l,connection:e,failed:0,notRun:0,passed:0,total:i.selections.length}),co({ctx:n,headed:o.data.headed,jobId:s,lockfileHashValue:i.lockfileHashValue,selections:i.selections,targetsByClaimKey:i.targetsByClaimKey,token:l.token}).catch(u=>{m.error({err:u},"ipc dispatch failed")}),{jobId:s,total:i.selections.length}}function Vn(e){return new Vr(Jr,e.code,e)}function Kn(e,n){let t=e.jobs.get(n);t!=null&&(t.cancellation.cancel(),e.jobs.delete(n),$n(e.inflight,n))}function Xr(e,n){[...e.jobs.entries()].filter(([,t])=>t.connection===n).forEach(([t])=>{Kn(e,t)})}function Qn(e,n,t){let r=e.jobs.get(n);r!=null&&(zn(()=>r.connection.sendNotification(jn,{event:t,jobId:n})),t.kind==="test-outcome"&&(Yr(r,t.outcome.kind),r.passed+r.failed+r.notRun>=r.total&&(zn(()=>r.connection.sendNotification(An,{failed:r.failed,jobId:n,notRun:r.notRun,passed:r.passed})),e.jobs.delete(n))))}function zn(e){e().catch(n=>{m.warn({err:n},"ipc notification failed")})}function Yr(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 j(e,n,t){n.jobIds.forEach(r=>{Qn(e,r,t)})}function Zr(e,n){let t=Ie(e.inflight,n);return t==null?null:{headed:t.headed,token:t.cancellation.token,finished:(r,o)=>{e.inflight.delete(t.inflightKey),j(e,t,{kind:"test-outcome",outcome:o,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},started:()=>{j(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}}}function eo(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 no({config:e,cwd:n,message:t}){return(await rn(n)).match(o=>to({config:e,cwd:n,lockfile:o,message:t}),o=>Promise.resolve({error:{code:"compile-failed",detail:o.kind,diagnostics:[...eo(o)]},kind:"error"}))}async function to({config:e,cwd:n,lockfile:t,message:r}){let o=await oo(e.appUrl);if(o!=null)return{error:{code:"app-unreachable",detail:o,url:e.appUrl},kind:"error"};let i=await io({config:e,cwd:n,lockfile:t});return i!=null?{error:{code:"sync-failed",detail:i},kind:"error"}:(await ao({config:e,cwd:n,lockfile:t,message:r})).match(async l=>({kind:"ready",lockfileHashValue:_e(t),selections:Nn(t,l),targetsByClaimKey:await Fn(e,n)}),l=>Promise.resolve({error:l,kind:"error"}))}var ro=2e3;async function oo(e){try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(ro)}),null}catch(n){return n instanceof Error?n.message:String(n)}}async function io(e){try{return await be(e),null}catch(n){return n instanceof Error?n.message:String(n)}}async function ao({config:e,cwd:n,lockfile:t,message:r}){return!r.all&&r.tests.length===0?(await Hn({config:e,cwd:n,lockfile:t})).mapErr(so):On({all:r.all,ids:r.tests,lockfile:t}).mapErr(lo)}function so(e){return e.kind==="scope-empty"?{code:"selection-nothing-selected"}:{code:"scope-failed",detail:e.detail}}function lo(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 co(e){await e.selections.reduce((n,t)=>n.then(()=>uo(e,t)),Promise.resolve())}async function uo(e,n){let{ctx:t,headed:r,jobId:o,lockfileHashValue:i,targetsByClaimKey:s,token:l}=e;if(l.isCancellationRequested)return;let u=ve(n),c=s.get(u);if(c==null){Qn(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=Mn({headed:r,inflight:t.inflight,jobId:o,lockfileHashValue:i,runId:Wr(),selection:n,timeoutMs:zr,onExpire:y=>{j(t,y,{kind:"test-outcome",outcome:{detail:"dispatch-timeout",kind:"dispatch-timeout"},runId:"",testName:y.testName,workflowName:y.workflowName})}});if(p==null)return;let d=await po(t,c,p.runId,i);if(d!=null){Z(t.inflight,p),j(t,p,{kind:"test-outcome",outcome:d,runId:"",testName:n.testName,workflowName:n.workflowName});return}t.executor==="cloud"&&fo(t,p)}function po(e,n,t,r){return wn({config:e.config,executor:e.executor,lockfileHash:r,runId:t,target:n})}function fo(e,n){let t=Ie(e.inflight,n.runId);t!=null&&Bn({config:e.config,runId:t.runId,signal:Kr(t.cancellation.token),onComplete:r=>{e.inflight.delete(t.inflightKey),j(e,t,{kind:"test-outcome",outcome:r,runId:t.runId,testName:t.testName,workflowName:t.workflowName})},onStarted:()=>{j(e,t,{kind:"test-started",runId:t.runId,testName:t.testName,workflowName:t.workflowName})}})}import mo from"fs";import yo from"path";async function Rl(e){let n=yo.join(e,".ripplo","index.ts");if(!mo.existsSync(n))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let t=await U(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:ge(r),path:""}],valid:!1,warnings:[]}))}async function kl(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 Sl({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 ko from"fs";import go from"fs";import Te from"path";var ho=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function Gn(e){let n=Ro(e);return n==null?!1:ho.some(t=>go.existsSync(Te.join(n,t)))}function Ro(e){try{let n=ee(["rev-parse","--git-dir"],e).trim();return n.length===0?null:Te.isAbsolute(n)?n:Te.resolve(e,n)}catch{return null}}function So(e){return w(e,"hooks-paused")}function jl(e){return ko.existsSync(So(e))||Gn(e)?!1:hn(e)}import{createMessageConnection as Xn,IPCMessageReader as Yn,IPCMessageWriter as Zn,NotificationType as xo,NotificationType0 as et,RequestType as nt,RequestType0 as wo}from"vscode-jsonrpc/node";import{z as R}from"zod";var Ul=R.object({headed:R.boolean(),runId:R.string().min(1),testRef:R.string().min(1)}),Ol=R.object({lockfileJson:R.string().optional(),unavailable:R.string().optional()}),Nl=R.object({runId:R.string().min(1),span:Ne}),Dl=R.object({outcome:Ee,serverNotified:R.boolean()}),_l=new et("worker/ready"),ql=new nt("worker/run"),Hl=new wo("worker/lockfile"),Wl=new nt("worker/exploreTrail"),Bl=new xo("worker/span"),Vl=new et("worker/shutdown");function zl(e){let n=Xn(new Yn(e),new Zn(e));return n.listen(),n}function Jl(){let e=Xn(new Yn(process),new Zn(process));return e.listen(),e}import{graphql as E}from"gql.tada";import{gzip as jo}from"zlib";import{promisify as Ao}from"util";import{existsSync as Ae,readFileSync as Fe}from"fs";import ne from"path";import{graphql as b}from"gql.tada";function tt(e){return[e.kind,e.target,e.value].filter(n=>n.length>0).join(" ")}var bo={"no-effect":"noEffect","required-state-unsatisfied":"requiredStateUnsatisfied",unresolvable:"unresolvable"},Eo={"data-rule":"dataRule","page-rule":"pageRule",step:"step"},vo={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 rt(e){return e.kind==="consistency"?{consistency:{mismatch:Co(e.mismatch),pending:e.pending}}:e.kind==="pending-check"?{pendingCheck:{budget:e.budget,source:Eo[e.source.kind],...Io(e.source)}}:e.kind==="unrunnable"?{unrunnable:{reason:bo[e.reason]}}:e.kind==="driver-error"?{driverError:{errorKind:vo[e.error.kind],message:To(e.error)}}:{impossibleAction:{subject:Po(e.step.action)}}}function Io(e){return"check"in e?ot(e.check,!1):{checkKind:void 0,expected:void 0,negated:void 0,subject:void 0}}function ot(e,n){return e.kind==="not"?ot(e.inner,!n):e.kind==="browser"?{checkKind:"browser",expected:e.value,negated:n,subject:e.name}: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 Po(e){let n=e.locator==null?e.url??"":N(e.locator);return`${e.kind} ${n}`.trim()}function Co(e){return e.kind==="wrong-value"?{wrongValue:{entity:e.entity,field:e.field,key:e.key,snapshot:O(e.snapshot),sut:O(e.sut)}}:e.kind==="expected-change"?{expectedChange:{entity:e.entity,field:e.field,key:e.key,value:O(e.value)}}:e.kind==="singleton-mismatch"?{singletonMismatch:{singleton:e.singleton,snapshot:O(e.snapshot),sut:O(e.sut)}}:e.kind==="unexpected-row"?{unexpectedRow:{entity:e.entity,key:e.key}}:{missingRow:{entity:e.entity,key:e.key}}}function O(e){return e==null?null:String(e)}function To(e){return"message"in e?e.message:"detail"in e?e.detail:null}async function Fo({config:e,cwd:n,fixturesDir:t,headed:r,lockfile:o,runId:i,session:s,signal:l,test:u}){if(!await ri(e,i))return{kind:"dispatch-failed",reason:"already-claimed",runId:i};let p=ne.join(n,".ripplo","debug"),d=[];return(await s.runOnce({capture:!0,lockfile:o,onPhase:void 0,options:{baseUrl:e.appUrl,engineUrl:e.engineUrl,fixturesDir:t,generate:v,headed:r,secret:e.webhookSecret,tunnelAuth:e.tunnelAuth},params:void 0,runId:i,sequence:void 0,test:u,onEvent:S=>{d.push(S)}},l)).match(async S=>{let x=at(d).flatMap(ct=>ct.findings),$e=Mo(x);return $e!=null?(await it({config:e,debugDir:p,events:d,recordingOptional:!0,runId:i,stepSources:void 0}),{error:$e,kind:"error",runId:i}):(await te({config:e,debugDir:p,events:d,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 Mo(e){let n=e.find(t=>t.kind==="driver-error"&&We(t.error));return n!=null&&n.kind==="driver-error"?n.error:void 0}async function te(e){let n=await it(e);await ti(e.config,e.runId,n),await Lo(e.config,e.debugDir,e.runId)}async function it({config:e,debugDir:n,events:t,recordingOptional:r,runId:o,stepSources:i}){let s=at(t),l=Oo(n,o);if(l==null&&!r)throw new Error("recording-missing");return await Vo({aliases:[..._o(t),...qo(s)],config:e,generated:Ho(t),generatedSingletons:Wo(t),origin:l==null?Uo(s):l.origin,records:s,rrwebEvents:l==null?[]:l.events,runId:o,stepSources:i}),l!=null&&await ni(e,o,l),s}var $o=b(`
|
|
120
|
+
mutation ClipUploadUrl($runId: ID!) {
|
|
121
|
+
clipUploadUrl(runId: $runId)
|
|
122
|
+
}
|
|
123
|
+
`);async function Lo(e,n,t){let r=ne.join(n,t,"clip.gif");if(Ae(r))try{let o=await f({config:e,document:$o,variables:{runId:t}});if(o.clipUploadUrl==null)return;let i=await fetch(o.clipUploadUrl,{body:new Uint8Array(Fe(r)),headers:{"Content-Type":"image/gif"},method:"PUT"});i.ok||m.warn({runId:t,status:i.status},"Clip upload failed")}catch(o){m.warn({err:o,runId:t},"Clip upload skipped")}}function Uo(e){return e.reduce((n,t)=>Math.min(n,t.startMs),e[0]?.startMs??0)}function at(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 Oo(e,n){let t=ne.join(e,n,"behavior.jsonl");if(!Ae(t))return null;let r=Fe(t,"utf8").split(`
|
|
124
|
+
`).filter(i=>i.length>0).map(i=>No(i)).flatMap(i=>Do(i)?[i.event]:[]),o=r[0];return o==null?null:{events:r,origin:o.timestamp}}function No(e){return JSON.parse(e)}function Do(e){return typeof e=="object"&&e!=null&&Reflect.get(e,"kind")==="rrweb"}function _o(e){return e.flatMap(n=>n.kind==="world"?n.aliases:[])}function qo(e){return e.flatMap(n=>{let t=Bo(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 Ho(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generated.map(t=>st(t)):[]))}function st({entity:e,field:n,key:t}){return`${e}\0${t}\0${n}`}function Wo(e){return new Set(e.flatMap(n=>n.kind==="world"?n.generatedSingletons:[]))}function Bo(e){return e==null?[]:e.expect.flatMap(n=>je(n))}function je(e){return e.kind==="state"&&e.assertion.kind==="created"?[{as:e.assertion.as,entity:e.entity}]:e.kind==="and"?e.predicates.flatMap(n=>je(n)):e.kind==="when"?e.branches.flatMap(n=>n.consequence.flatMap(t=>je(t))):[]}async function Vo({aliases:e,config:n,generated:t,generatedSingletons:r,origin:o,records:i,rrwebEvents:s,runId:l,stepSources:u}){let c=i.map((p,d)=>Qo({aliases:e,generated:t,generatedSingletons:r,origin:o,record:p,rrwebEvents:s,sourceTest:u?.[d]??null}));await f({config:n,document:ii,variables:{items:[{runId:l,steps:c}]}})}var zo=3,Jo=0;function Ko({endMs:e,rrwebEvents:n,startMs:t}){let r=n.find(o=>o.type===zo&&o.data?.source===Jo&&o.timestamp>=t&&o.timestamp<=e);return r==null?t:r.timestamp}function Qo({aliases:e,generated:n,generatedSingletons:t,origin:r,record:o,rrwebEvents:i,sourceTest:s}){let l=He(o.source,o.index),u=Ko({endMs:o.endMs,rrwebEvents:i,startMs:o.startMs}),c=o.annotations.map(d=>({kind:d.kind,label:d.label,outcome:d.outcome,recordingStartMs:Math.max(0,(d.kind==="action"?u:d.atMs)-r),rrwebIds:[...d.rrwebIds],url:d.url})),p=o.annotations.find(d=>d.kind==="action")?.rrwebIds??[];return{annotations:c,detail:null,duration:Math.max(0,o.endMs-o.startMs),findings:o.findings.map(d=>rt(d)),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(d=>Go({aliases:e,generated:n,row:d})),stateSingletons:o.state.singletons.map(d=>({changed:d.changed,generated:t.has(d.name),name:d.name,value:d.value==null?null:String(d.value)})),status:o.findings.length>0?"failed":"passed",stepIndex:o.index,title:tt(l),url:o.url}}function Go({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(st({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 Xo=Ao(jo);async function lt(e,n){await f({config:e,document:li,variables:{runIds:[n]}})}var Yo="application/x-ndjson";async function Zo({config:e,debugDir:n,runId:t}){let r=ne.join(n,t,"behavior.jsonl");if(Ae(r))try{let o=await f({config:e,document:ei,variables:{runId:t}}),i=await fetch(o.debugArtifactUploadUrl,{body:Fe(r),headers:{"content-type":Yo},method:"PUT"});if(!i.ok){m.warn({runId:t,status:i.status},"behavior upload PUT failed");return}await lt(e,t)}catch(o){m.warn({error:o,runId:t},"behavior upload failed")}}var ei=b(`
|
|
125
|
+
mutation DebugArtifactUploadUrl($runId: String!) {
|
|
126
|
+
debugArtifactUploadUrl(runId: $runId)
|
|
127
|
+
}
|
|
128
|
+
`);async function ni(e,n,t){let r=t.events.map(s=>JSON.stringify(s)).join(`
|
|
129
|
+
`),o=await Xo(Buffer.from(r,"utf8")),i=t.events.at(-1);await f({config:e,document:ai,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 ti(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:si,variables:{items:[{duration:i,failCount:r,passCount:o,runId:n,status:r>0?"failed":"passed",summary:null,warnCount:0}]}})}async function ri(e,n){return((await f({config:e,document:oi,variables:{runIds:[n]}})).startRunsBatch??[]).some(r=>r.id===n)}var oi=b(`
|
|
130
|
+
mutation StartRunsBatch($runIds: [String!]!) {
|
|
131
|
+
startRunsBatch(runIds: $runIds) {
|
|
132
|
+
id
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
`),ii=b(`
|
|
136
|
+
mutation SubmitRunStepsBatch($items: [SubmitRunStepsItem!]!) {
|
|
137
|
+
submitRunStepsBatch(items: $items)
|
|
138
|
+
}
|
|
139
|
+
`),ai=b(`
|
|
140
|
+
mutation SubmitRunRecordingChunk($input: SubmitRunRecordingChunkInput!) {
|
|
141
|
+
submitRunRecordingChunk(input: $input)
|
|
142
|
+
}
|
|
143
|
+
`),si=b(`
|
|
144
|
+
mutation CompleteRunsBatch($items: [CompleteRunItem!]!) {
|
|
145
|
+
completeRunsBatch(items: $items) {
|
|
146
|
+
id
|
|
147
|
+
status
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
`),li=b(`
|
|
151
|
+
mutation MarkRunArtifactsUploadedBatch($runIds: [String!]!) {
|
|
152
|
+
markRunArtifactsUploadedBatch(runIds: $runIds)
|
|
153
|
+
}
|
|
154
|
+
`);function di(e){let n=e.trail;if(!(n==null||!ci(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 ci(e){return e==="clean"||e==="flaky"||e==="finding"}async function Me({baseState:e,branchName:n,category:t,commitSha:r,config:o,debugDir:i,devSessionId:s,events:l,lockfileHash:u,reproJson:c,runId:p,signature:d,spec:y,stepSources:S}){await f({config:o,document:yi,variables:{branchName:n??null,commitSha:r??null,devSessionId:s??null,lockfileHash:u??null,projectId:o.projectId,reproJson:c,runId:p,spec:y??null}}),await te({config:o,debugDir:i,events:l,recordingOptional:!0,runId:p,stepSources:S}),await f({config:o,document:gi,variables:{baseState:e,category:t,projectId:o.projectId,reproRunId:p,signature:d}})}async function re(e,n,t){return(await f({config:e,document:hi,variables:{lockfileHash:t,projectId:e.projectId,signature:n}})).exploreFindingExists}async function ui({attempts:e,config:n,devSessionId:t,findings:r,trail:o}){await f({config:n,document:mi,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 pi(e,n,t){let r=await f({config:e,document:fi,variables:{devSessionId:n}}).catch(i=>(m.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 fi=E(`
|
|
155
|
+
query ExploreScope($devSessionId: String!) {
|
|
156
|
+
exploreScope(devSessionId: $devSessionId)
|
|
157
|
+
}
|
|
158
|
+
`);var mi=E(`
|
|
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
|
+
`),md=E(`
|
|
173
|
+
mutation ReportExploreUnhealthy($devSessionId: String!) {
|
|
174
|
+
reportExploreUnhealthy(devSessionId: $devSessionId)
|
|
175
|
+
}
|
|
176
|
+
`),yi=E(`
|
|
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
|
+
`),gi=E(`
|
|
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
|
+
`),yd=E(`
|
|
219
|
+
mutation SetExploreFindingStatus(
|
|
220
|
+
$projectId: String!
|
|
221
|
+
$signature: String!
|
|
222
|
+
$status: ExploreFindingStatus!
|
|
223
|
+
) {
|
|
224
|
+
setExploreFindingStatus(projectId: $projectId, signature: $signature, status: $status)
|
|
225
|
+
}
|
|
226
|
+
`),hi=E(`
|
|
227
|
+
query ExploreFindingExists($projectId: String!, $signature: String!, $lockfileHash: String!) {
|
|
228
|
+
exploreFindingExists(projectId: $projectId, signature: $signature, lockfileHash: $lockfileHash)
|
|
229
|
+
}
|
|
230
|
+
`);import{graphql as dt}from"gql.tada";async function Ri(e,n,t){await f({config:e,document:ki,variables:{reason:t,runId:n}}).catch(r=>{m.error(r,"failRun submission failed")})}var ki=dt(`
|
|
231
|
+
mutation FailRun($runId: String!, $reason: String!) {
|
|
232
|
+
failRun(runId: $runId, reason: $reason)
|
|
233
|
+
}
|
|
234
|
+
`),kd=dt(`
|
|
235
|
+
mutation MarkRunUnready($runId: String!, $cause: RunUnreadyCause!) {
|
|
236
|
+
markRunUnready(runId: $runId, cause: $cause)
|
|
237
|
+
}
|
|
238
|
+
`);import{randomUUID as Si}from"crypto";async function xi({assign:e,config:n,debugDir:t,devSessionId:r,fixturesDir:o,headed:i,lockfile:s,report:l,session:u,signal:c}){let p=Be(s);if(e.stepRuns.length===0)return{kind:"error",reason:"empty-trail"};let d=ji(p,e.stepRuns),y=await Je({baseState:{name:h(e.baseStateTest),test:e.baseStateTest},corpus:p,lockfile:s,options:{baseUrl:n.appUrl,engineUrl:n.engineUrl,fixturesDir:o,generate:v,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-${Si()}-${String(x)}`},c),S=l?await Pi({baseStateTest:e.baseStateTest,config:n,debugDir:t,devSessionId:r,lockfileHash:e.lockfileHash,outcome:y,reproJson:vi(p,e),stepSources:Ii(d)}):!1;return Ei(y,d.length),Ai(y,S,wi(d,e,y))}function wi(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:bi(e)}}function bi(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 Ei(e,n){if(e.kind==="error"){m.info({kind:e.kind,reason:e.error.kind,steps:n},"explore trail");return}if(e.kind==="aborted"){m.info({kind:e.kind,steps:n},"explore trail");return}let t=e.timing.detect,r=e.timing.confirm;m.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 vi(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 Ii(e){return e.flatMap(n=>{let t=n.label.split("#")[0]??n.label;return n.actions.map(()=>t)})}async function Pi({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)?(m.info({devSessionId:r,signature:i.signature},"explore finding already reported, skipping duplicate"),!1):(await Me({baseState:i.baseState,branchName:void 0,category:Ci(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:Ti(e,i.captureEvents),stepSources:l}).catch(u=>{m.warn({error:u},"explore finding report failed")}),!0)}function Ci(e){return e==="data-rule"?"dataRule":e==="page-rule"?"pageRule":e}function Ti(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 ji(e,n){return n.flatMap(t=>{let r=e[t.idx];return r==null?[]:[{actions:[...r.nav,...r.steps].map(o=>Ve(o.action)),label:`${r.test}#${String(r.index)}`}]})}function Ai(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 Fi from"path";import{randomUUID as Mi}from"crypto";async function qd({cwd:e,onReady:n,ref:t,signal:r,step:o}){let i=fn(e).match(d=>({config:d}),d=>({failure:d}));if("failure"in i)return{failure:i.failure,kind:"config-failed"};let s=i.config,l=await ye(e);if(l.result.isErr())return{error:l.result.error,kind:"compile-failed"};let u=l.result.value,c=A(u).find(d=>d.ref===t);return c==null?{kind:"no-test",ref:t}:(await ze({lockfile:u,onReady:n,options:{baseUrl:s.appUrl,engineUrl:s.engineUrl,fixturesDir:Fi.join(s.cwd,M),generate:v,headed:!0,secret:s.webhookSecret,tunnelAuth:s.tunnelAuth},params:void 0,runId:`teleport-${Mi()}`,stopAfterStep:o,test:c.test},r)).match(d=>({kind:"done",result:d}),d=>({error:d,kind:"run-failed"}))}export{Ni as a,zi as b,B as c,Rt as d,V as e,M as f,C as g,rn as h,ye as i,U as j,T as k,ma as l,K as m,ka as n,Sa as o,xa as p,Pa as q,ge as r,ln as s,cn as t,fn as u,hn as v,ke as w,Ba as x,ee as y,Gn as z,Rl as A,kl as B,Sl as C,So as D,jl as E,ks as F,Ss as G,vn as H,xs as I,ws as J,bs as K,Es as L,vs as M,Pn as N,Cn as O,Tn as P,jn as Q,An as R,Ul as S,Nl as T,Dl as U,_l as V,ql as W,Hl as X,Wl as Y,Bl as Z,Vl as _,zl as $,Jl as aa,Ja as ba,Ka as ca,Se as da,Qa as ea,kn as fa,cs as ga,be as ha,Kr as ia,cl as ja,Fo as ka,Zo as la,Ri as ma,di as na,ui as oa,pi as pa,xi as qa,qd as ra};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as Ee,B as ne,D as de,F as ue,U as ke,V as ve,W as we,X as be,Y as xe,Z as Pe,_ as he,b as J,ba as h,ca as E,da as Re,e as V,ea as M,fa as Ce,h as x,ha as O,i as Z,ia as Te,j as H,ja as Ie,m as _,ma as R,na as We,oa as Ae,pa as Le,r as ee,ra as De,u as P,w as re,x as oe}from"./chunk-DP5GPMT3.js";import{$ as Se,E as ie,H as ae,I as se,J as le,S as ce,X as pe,Y as fe,Z as me,_ as ye,aa as ge,e as K,h as X,i as D,l as Y,o as te}from"./chunk-APYROHWG.js";import{b as He}from"./chunk-RLXQYG7H.js";import{c as Q,d as k,e as l,f as L,g as G}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import Wo from"path";import{createClient as Ao}from"graphql-sse";import Lo,{AbortError as Do}from"p-retry";import{graphql as j}from"gql.tada";import{graphql as Tr}from"gql.tada";import{print as Ir}from"graphql";async function _e({config:r,cwd:e,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:s,workflowSlug:c}){let u=await x(e);if(u.isErr())return await R(r,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let d=Cr(u.value,{testSlug:a,workflowSlug:c});if(d==null)return await R(r,t,`no-test:${c}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${c}/${a}`,type:"generic"}};let p=await h({headed:o,workClass:s,task:()=>n.execute({headed:o,runId:t,testRef:d},i)});return!p.serverNotified&&p.outcome.kind==="error"&&await R(r,t,p.outcome.detail),p.outcome}function Cr(r,{testSlug:e,workflowSlug:o}){let t=r.workflows.find(i=>Y(i.name)===o)?.tests.find(i=>i.slug===e);return t==null?void 0:te(t)}var Wr=6e4,Ar=Tr(`
|
|
3
|
+
subscription RunRequestedWatch($devSessionId: String!) {
|
|
4
|
+
runRequested(devSessionId: $devSessionId) {
|
|
5
|
+
runId
|
|
6
|
+
testSlug
|
|
7
|
+
workflowId
|
|
8
|
+
workflowSlug
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
`);async function Me(r){let e=Math.min(1e3*2**r,Wr)+Hr();await new Promise(o=>setTimeout(o,e))}function Oe({claim:r,cwd:e,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let s=new Set;return i.subscribe({query:Ir(Ar),variables:{devSessionId:o}},{complete:()=>{},error:c=>{let u=c instanceof Error?c.message:String(c);l.warn("runRequested SSE failed: %s; re-registering session",u),n(u)},next:c=>{Lr({claim:r,cwd:e,event:c.data?.runRequested,inFlightRunIds:s,pool:t})}},{connected:()=>{a.onConnected()},connecting:c=>{a.onConnecting(c),c&&l.debug("runRequested SSE reconnecting")}})}function Lr({claim:r,cwd:e,event:o,inFlightRunIds:n,pool:t}){if(o==null)return;if(n.has(o.runId)){l.warn({runId:o.runId,workflowSlug:o.workflowSlug},"duplicate runRequested event; skipping dispatch");return}n.add(o.runId),process.stdout.write(`ripplo: run ${o.workflowSlug}
|
|
12
|
+
`),J(e);let i=P(e).match(s=>s,s=>{l.error({failure:s,runId:o.runId},"failed to load env for run dispatch; skipping")});if(i==null){n.delete(o.runId);return}let a=Dr(r(o.runId),o);a.started(),_e({config:i,cwd:e,headed:a.headed,pool:t,runId:o.runId,signal:a.signal,testSlug:o.testSlug,workClass:a.workClass,workflowSlug:o.workflowSlug}).then(s=>{a.finished(s)}).catch(s=>{l.error({err:s,runId:o.runId,workflowSlug:o.workflowSlug},"run execution failed; daemon continuing"),a.finished({detail:s instanceof Error?s.message:String(s),kind:"error"})}).finally(()=>{n.delete(o.runId)})}function Dr(r,e){return r==null?(l.debug({runId:e.runId,workflowSlug:e.workflowSlug},"dispatching unclaimed run (externally triggered or replayed)"),{headed:!1,signal:new AbortController().signal,workClass:"p0-ui",finished:()=>{},started:()=>{}}):{headed:r.headed,signal:Te(r.token),workClass:"p1-cli",finished:o=>{r.finished(e.runId,o)},started:()=>{r.started(e.runId)}}}function Hr(){return Math.floor(Math.random()*2700)+300}import{graphql as _r}from"gql.tada";import{print as Mr}from"graphql";var Or=_r(`
|
|
13
|
+
subscription TeleportRequestedWatch($devSessionId: String!) {
|
|
14
|
+
teleportRequested(devSessionId: $devSessionId) {
|
|
15
|
+
runId
|
|
16
|
+
stepIndex
|
|
17
|
+
testSlug
|
|
18
|
+
workflowSlug
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
`);function qe({cwd:r,devSessionId:e,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:Mr(Or),variables:{devSessionId:e}},{complete:()=>{},error:a=>{let s=a instanceof Error?a.message:String(a);l.warn("teleportRequested SSE failed: %s; re-registering session",s),o(s)},next:a=>{qr({cwd:r,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function qr({cwd:r,event:e,running:o}){if(e==null)return;let n=`${e.workflowSlug}/${e.testSlug}`,t=new AbortController;o.add(t),process.stdout.write(`ripplo: teleport ${n} step ${String(e.stepIndex+1)}
|
|
22
|
+
`),De({cwd:r,onReady:Fr,ref:n,signal:t.signal,step:e.stepIndex+1}).then(i=>{i.kind!=="done"&&l.warn({kind:i.kind,ref:n},"teleport could not open")}).catch(i=>{l.error({err:i,ref:n},"teleport failed; daemon continuing")}).finally(()=>{o.delete(t)})}function Fr(){}function Fe(){let r=!0,e,o=null,n=()=>{o!=null&&(clearTimeout(o),o=null)};return{markUnhealthy:t=>{r=!1,e=t,n()},onConnected:()=>{n(),o=setTimeout(()=>{r=!0,e=void 0,o=null},1e4)},onConnecting:()=>{n()},snapshot:()=>({detail:e,ok:r})}}import Nr from"fs";import je from"net";import{err as Be,ok as Ur}from"neverthrow";async function ze({cwd:r,onConnection:e}){G(r);let o=ue(r),n=await Ne({onConnection:e,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(Ue(o)).mapErr($e(o)):await $r(o)?Be({kind:"already-running",socketPath:o}):(Qe(o),(await Ne({onConnection:e,socketPath:o})).map(Ue(o)).mapErr($e(o)))}function $r(r){return new Promise(e=>{let o=je.connect(r);o.once("connect",()=>{o.destroy(),e(!0)}),o.once("error",()=>{e(!1)})})}async function Ne(r){let e=await jr(r);return e.kind==="listening"?Ur(e.server):Be(e.error)}function jr({onConnection:r,socketPath:e}){return new Promise(o=>{let n=je.createServer(r);n.once("error",t=>{o({error:t.code==="EADDRINUSE"?{kind:"stale-candidate"}:{kind:"listen-failed",message:t.message},kind:"failed"})}),n.listen(e,()=>{o({kind:"listening",server:n})})})}function Ue(r){return e=>({socketPath:r,close:()=>{e.close(),Qe(r)}})}function Qe(r){Nr.rmSync(r,{force:!0})}function $e(r){return e=>e.kind==="stale-candidate"?{kind:"already-running",socketPath:r}:{kind:"bind-failed",message:e.message}}import{randomInt as Br,randomUUID as zr}from"crypto";function Ke(r){let e={attempts:0,consecutiveErrors:0,findings:0,haltedUntil:0,lockfile:null,prepared:null,preparing:!1,refreshing:!1,scopedAt:0,scopedTests:new Set,scoping:!1,windowAttempts:0,windowFindings:0,windowStartMs:Date.now()},o=q(r,e);return{priority:"p3",next:()=>Xr(r,e),onResult:()=>{},ready:()=>o,status:()=>({attempts:e.attempts,findings:e.findings}),stop:()=>Promise.resolve()}}var Qr=10;async function q(r,e){if(!e.preparing){e.preparing=!0;try{let o=await r.loadLockfile(),n=o==null?null:await Gr(o);if(n==null||o==null)return;e.lockfile=o.lockfile,e.scopedAt=0,e.prepared=n,e.consecutiveErrors=0,e.haltedUntil=0,r.notifyWork()}finally{e.preparing=!1}}}async function Gr({lockfile:r}){let e=await se(r);return e==null?null:{exploration:e,lockfileHashValue:D(r),strategy:ie("even")}}var Ge=20,Je=3e5;async function Jr(r,e){if(!(e.refreshing||e.preparing||e.prepared==null)){e.refreshing=!0;try{let o=await r.loadLockfile();if(o==null||D(o.lockfile)===e.prepared.lockfileHashValue)return;l.info("workflow definitions changed, re-preparing exploration"),e.prepared=null,await q(r,e)}finally{e.refreshing=!1}}}var Vr=15e3;async function Kr(r,e){if(!(e.scoping||e.lockfile==null||Date.now()-e.scopedAt<Vr)){e.scoping=!0;try{e.scopedTests=await r.scopedTestRefs(e.lockfile),e.scopedAt=Date.now()}finally{e.scoping=!1}}}function Xr(r,e){Jr(r,e),Kr(r,e);let o=e.prepared;if(o==null||Date.now()<e.haltedUntil)return null;let n=le({lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:Yr,scopedTests:e.scopedTests,strategy:{...o.strategy,maxAttemptLength:r.maxTrailLength()}});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${zr()}`,label:t,run:i=>Zr({assign:n,params:r,signal:i,state:e})}}var Ve=2**31;function Yr(){return Br(Ve)/Ve}async function Zr({assign:r,params:e,signal:o,state:n}){if(!await e.probeApp()){Xe(n,"app-unreachable");return}let t=await e.executeTrail(r,o);if(t.kind==="aborted")return;if(t.kind==="error"){ro({params:e,reason:t.reason,state:n});return}n.consecutiveErrors=0,n.attempts+=1,n.windowAttempts+=1;let i=t.kind==="finding";i&&(n.findings+=1,n.windowFindings+=1,l.info("exploration finding recorded")),e.reportProgress({attempts:1,findings:i?1:0,result:t}),n.windowAttempts>=Qr&&eo(n)}function eo(r){let e=Date.now()-r.windowStartMs;l.info({attempts:r.windowAttempts,avgTrailMs:Math.round(e/r.windowAttempts),findings:r.windowFindings,windowMs:e,yield:Number((r.windowFindings/r.windowAttempts).toFixed(3))},"explore window"),r.windowAttempts=0,r.windowFindings=0,r.windowStartMs=Date.now()}function ro({params:r,reason:e,state:o}){if(e?.startsWith("lockfile:daemon-load-failed")===!0){oo(r,o);return}Xe(o,e)}function oo(r,e){e.preparing||(e.prepared=null,q(r,e))}function Xe(r,e){r.consecutiveErrors+=1,l.debug("exploration trail error: %s",e),r.consecutiveErrors>=Ge&&(r.haltedUntil=Date.now()+Je,r.consecutiveErrors=0,l.warn("exploration cooling down for %ds after %d consecutive trail errors (last: %s)",Je/1e3,Ge,e))}function no(r){let{backoffActive:e,exploreEnabled:o,headedActive:n,interactiveActive:t,interactiveQueued:i}=r,{explorationActive:a,exploreConcurrency:s,poolSize:c}=r;if(!o||n||i>0)return{abortCount:a,refillCount:0};if(e)return{abortCount:0,refillCount:0};let u=Math.min(s,c-1,c-t);return{abortCount:0,refillCount:Math.max(0,u-a)}}function er(r){let e={active:new Map,backoffUntil:0,cancelBackoffTimer:null,cancelHeartbeat:null,prevInteractiveActive:r.probe().interactiveActive,stopped:!1};return rr(e,r),{explorationActive:()=>e.active.size,notifyQueueChange:()=>{to(e,r)},stop:()=>{e.stopped=!0,e.cancelBackoffTimer?.(),e.cancelBackoffTimer=null,e.cancelHeartbeat?.(),e.cancelHeartbeat=null,or(e,e.active.size)}}}function rr(r,e){r.stopped||(r.cancelHeartbeat=e.setTimer(()=>{C(r,e),rr(r,e)},15e3))}function C(r,e){if(r.stopped)return;let o=e.probe(),n=no({backoffActive:e.now()<r.backoffUntil,explorationActive:r.active.size,exploreConcurrency:e.exploreConcurrency(),exploreEnabled:e.exploreEnabled(),headedActive:o.headedActive>0,interactiveActive:o.interactiveActive,interactiveQueued:o.interactiveQueued,poolSize:o.poolSize});or(r,n.abortCount),nr({count:n.refillCount,params:e,state:r})}function or(r,e){[...r.active.values()].slice(0,e).forEach(({controller:o})=>{o.abort()})}function to(r,e){let o=e.probe();o.interactiveActive<r.prevInteractiveActive&&io(r,e),r.prevInteractiveActive=o.interactiveActive,C(r,e)}function io(r,e){r.backoffUntil=e.now()+3e4,r.cancelBackoffTimer?.(),r.cancelBackoffTimer=e.setTimer(()=>{r.cancelBackoffTimer=null,C(r,e)},3e4)}function nr({count:r,params:e,state:o}){if(r<=0)return;let n=ao(e.sources);n!=null&&(so({params:e,pulled:n,state:o}),nr({count:r-1,params:e,state:o}))}function ao(r){return r.reduce((e,o)=>{if(e!=null)return e;let n=o.next();return n==null?null:{job:n,source:o}},null)}function so({params:r,pulled:e,state:o}){let{job:n,source:t}=e,i=new AbortController;o.active.set(n.id,{controller:i,job:n,source:t}),r.execute({job:n,priority:t.priority,signal:i.signal}).then(()=>{Ze({job:n,outcome:Ye(i.signal,null),params:r,source:t,state:o})}).catch(a=>{Ze({job:n,outcome:Ye(i.signal,{error:a}),params:r,source:t,state:o})})}function Ye(r,e){return r.aborted?{kind:"aborted"}:e==null?{kind:"completed"}:{error:e.error,kind:"error"}}function Ze({job:r,outcome:e,params:o,source:n,state:t}){t.active.delete(r.id),n.onResult(r,e),C(t,o)}function F(r){return{priority:r,next:()=>null,onResult:()=>{}}}var co=12;function tr({config:r,executor:e,pool:o}){return uo({appUrl:r.appUrl,cwd:r.cwd,localExecutor:e==="local",executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function uo({appUrl:r,cwd:e,executeTrail:o,localExecutor:n}){let t={concurrency:2,enabled:!1,maxTrailLength:co},i={notify:()=>{}},a={report:d=>{}},s={fetch:d=>Promise.resolve(new Set)},c=po({appUrl:r,cwd:e,executeTrail:o,maxTrailLength:()=>t.maxTrailLength,notifyWork:()=>{i.notify()},reportProgress:d=>{a.report(d)},scopedTestRefs:d=>s.fetch(d)}),u=er({now:Date.now,probe:fo,setTimer:mo,sources:[F("p0"),F("p1"),c],execute:({job:d,priority:p,signal:S})=>h({headed:!1,workClass:yo(p),task:()=>d.run(S)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled});return M(()=>{u.notifyQueueChange()}),i.notify=()=>{u.notifyQueueChange()},{progress:()=>c.status(),setConcurrency:d=>{n&&d!==t.concurrency&&l.info({workers:d},"explore local worker count changed"),t.concurrency=d,u.notifyQueueChange()},setEnabled:d=>{t.enabled=d&&n,u.notifyQueueChange()},setMaxTrailLength:d=>{t.maxTrailLength=d},setReportProgress:d=>{a.report=d},setScopedTestRefs:d=>{s.fetch=d},status:()=>({explorer:t.enabled?"on":"off",exploring:u.explorationActive(),progress:c.status()}),stop:()=>{u.stop(),M(null),c.stop()}}}function po({appUrl:r,cwd:e,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,scopedTestRefs:a}){return Ke({cwd:e,executeTrail:o,maxTrailLength:n,notifyWork:t,reportProgress:i,scopedTestRefs:a,loadLockfile:async()=>{let{fingerprint:s,result:c}=await Z(e);return c.match(u=>({fingerprint:s,lockfile:u}),()=>null)},probeApp:async()=>await ne(r)==null})}function fo(){let r=Re();return{headedActive:r.headedActive,interactiveActive:r.active,interactiveQueued:r.queued,poolSize:r.poolSize}}function mo(r,e){let o=setTimeout(r,e);return()=>{clearTimeout(o)}}function yo(r){switch(r){case"p0":return"p0-ui";case"p1":return"p1-cli";case"p2":return"p2-cover";case"p3":return"p3-explore"}}import{fork as So}from"child_process";import ir from"os";import{CancellationTokenSource as ar,ResponseError as sr}from"vscode-jsonrpc/node";function lr(r,e){return()=>{let o=So(r,["run-worker"],{cwd:e,detached:!0,stdio:["ignore","inherit","inherit","ipc"]});return{connection:Ee(o),kill:()=>{go(o)},onExit:n=>{o.once("exit",n)}}}}function cr(r){let e={closed:!1,lockfileProvider:r.lockfileProvider,nextId:0,size:r.initialSize,spawn:r.spawn,waiters:[],workers:[]};return{close:async()=>{e.closed=!0,await Promise.all([...e.workers].map(o=>N(o,e)))},execute:(o,n)=>vo(o,n,e),exploreTrail:(o,n)=>xo(o,n,e),routeSpan:(o,n)=>{let t=e.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(Pe,{runId:o,span:n})},setSize:o=>{ho(o,e)}}}function go(r){let e=r.pid;if(e!=null)try{process.kill(-e,"SIGKILL")}catch{r.kill("SIGKILL")}}var ko=1e4,dr=-32800;async function vo(r,e,o){let n=await ur(o);if(n.runId=r.runId,!n.alive)return T(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new ar,i=()=>{t.cancel()};e.aborted&&t.cancel(),e.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(we,r,t.token),s=ke.safeParse(a);return s.success?s.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return bo(a,n)}finally{e.removeEventListener("abort",i),t.dispose(),T(n,o)}}async function ur(r){let e=r.workers.find(o=>o.alive&&o.runId===void 0);if(e!=null)return e.runId="pending",e;if(r.workers.length<r.size){let o=wo(r);return o.runId="pending",await o.ready,o}return new Promise(o=>{r.waiters.push(n=>{n.runId="pending",o(n)})})}function wo(r){let e=r.spawn(),o={resolve:()=>{}},n={alive:!0,id:r.nextId,ready:new Promise(t=>{o.resolve=t,e.connection.onNotification(ve,t)}),runId:void 0,worker:e};return r.nextId+=1,e.connection.onRequest(be,()=>r.lockfileProvider()),e.onExit(()=>{n.alive=!1,r.workers=r.workers.filter(t=>t!==n),e.connection.dispose(),o.resolve()}),r.workers.push(n),n}function T(r,e){if(r.runId=void 0,!r.alive||e.closed)return;if(e.workers.length>e.size){N(r,e);return}let o=e.waiters.shift();o?.(r)}async function N(r,e){if(e.workers=e.workers.filter(t=>t!==r),!r.alive)return;let o=new Promise(t=>{r.worker.onExit(t)});await r.worker.connection.sendNotification(he).catch(()=>{});let n=setTimeout(()=>{r.worker.kill()},ko);await o,clearTimeout(n)}function bo(r,e){return r instanceof sr&&r.code===dr?{outcome:{detail:"aborted",kind:"error"},serverNotified:!1}:e.alive?{outcome:{detail:r instanceof Error?r.message:String(r),kind:"error"},serverNotified:!1}:{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1}}async function xo(r,e,o){let n=await ur(o);if(n.runId="explore",!n.alive)return T(n,o),{kind:"error"};let t=new ar,i=()=>{t.cancel()};e.aborted&&t.cancel(),e.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(xe,r,t.token),s=ae.safeParse(a);return s.success?s.data:{kind:"error"}}catch(a){return Po(a)}finally{e.removeEventListener("abort",i),t.dispose(),T(n,o)}}function Po(r){return r instanceof sr&&r.code===dr?{kind:"aborted"}:{kind:"error",reason:`transport:${r instanceof Error?r.message.slice(0,120):"unknown"}`}}function ho(r,e){e.size=r,r>ir.availableParallelism()&&l.warn({cores:ir.availableParallelism(),size:r},"worker pool size exceeds available cores");let o=e.workers.filter(t=>t.alive&&t.runId===void 0),n=e.workers.length-r;o.slice(0,Math.max(0,n)).forEach(t=>{N(t,e)})}import I from"fs";import{graphql as W}from"gql.tada";import{print as U}from"graphql";var Eo=W(`
|
|
23
|
+
query DaemonExploration($devSessionId: String!) {
|
|
24
|
+
exploration(devSessionId: $devSessionId) {
|
|
25
|
+
active
|
|
26
|
+
localWorkers
|
|
27
|
+
maxTrailLength
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
`),Ro=W(`
|
|
31
|
+
subscription WatchExplorationChanged($devSessionId: String!) {
|
|
32
|
+
explorationChanged(devSessionId: $devSessionId) {
|
|
33
|
+
exploration {
|
|
34
|
+
active
|
|
35
|
+
localWorkers
|
|
36
|
+
maxTrailLength
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
`);function pr({config:r,devSessionId:e,machinery:o,sseClient:n}){return Co({config:r,devSessionId:e,machinery:o}),n.subscribe({query:U(Ro),variables:{devSessionId:e}},{complete:()=>{},error:t=>{l.error(t,"exploration subscription error")},next:t=>{fr(o,t.data?.explorationChanged.exploration)}})}async function Co({config:r,devSessionId:e,machinery:o}){let n=await k({config:r,document:Eo,variables:{devSessionId:e}});fr(o,n.exploration)}function fr(r,e){e!=null&&(r.setMaxTrailLength(e.maxTrailLength),r.setConcurrency(e.localWorkers),r.setEnabled(e.active))}function mr({config:r,devSessionId:e,machinery:o}){o.setScopedTestRefs(n=>Le(r,e,n)),o.setReportProgress(n=>{Ae({attempts:n.attempts,config:r,devSessionId:e,findings:n.findings,trail:We(n.result)}).catch(t=>{l.warn({error:t},"exploration progress report failed")})})}var To=W(`
|
|
41
|
+
subscription HooksPausedWatch($projectId: String!) {
|
|
42
|
+
hooksPausedRequested(projectId: $projectId) {
|
|
43
|
+
paused
|
|
44
|
+
projectId
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
`),Io=W(`
|
|
48
|
+
subscription WatchLocalConcurrencyChanged {
|
|
49
|
+
myMaxLocalConcurrentRunsChanged
|
|
50
|
+
}
|
|
51
|
+
`);function yr({pool:r,sseClient:e}){return e.subscribe({query:U(Io)},{complete:()=>{},error:o=>{l.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(E(n),r.setSize(n))}})}function Sr({cwd:r,projectId:e,sseClient:o}){return o.subscribe({query:U(To),variables:{projectId:e}},{complete:()=>{},error:n=>{l.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&$({cwd:r,paused:t})}})}function $({cwd:r,paused:e}){let o=de(r);if(e&&!I.existsSync(o)){I.writeFileSync(o,"");return}!e&&I.existsSync(o)&&I.unlinkSync(o)}var Ho=6e4,gr=500,_o=15e3,kr=6e4,Mo=3,Oo=j(`
|
|
52
|
+
mutation HeartbeatDevSessionWatch($id: String!) {
|
|
53
|
+
heartbeatDevSession(id: $id) {
|
|
54
|
+
__typename
|
|
55
|
+
... on DevSession {
|
|
56
|
+
id
|
|
57
|
+
}
|
|
58
|
+
... on DevSessionEndedError {
|
|
59
|
+
message
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
`),qo=j(`
|
|
64
|
+
query WatchLocalConcurrency {
|
|
65
|
+
currentUser {
|
|
66
|
+
id
|
|
67
|
+
maxLocalConcurrentRuns
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
`),Fo=j(`
|
|
71
|
+
mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
|
|
72
|
+
endDevSession(projectId: $projectId, cwd: $cwd) {
|
|
73
|
+
__typename
|
|
74
|
+
... on DevSession {
|
|
75
|
+
id
|
|
76
|
+
}
|
|
77
|
+
... on NoActiveDevSessionError {
|
|
78
|
+
message
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
`);async function _t(r){let{executor:e}=r;nn();let o=Zo(process.cwd()),n=o.cwd,t=Jo(n),i=Yo(),a=tr({config:o,executor:e,pool:i.pool}),s={handler:()=>{}},c=Ko(),u=Fe(),d=Ie({config:o,cwd:n,executor:e,explorationStatus:a.status,ready:c.promise,onShutdownRequest:()=>{s.handler()},sseHealth:()=>u.snapshot()}),p=await Xo({cwd:n,ipc:d,releasePid:t}),S=await H(n);S.isErr()&&(process.stderr.write(`ripplo: ${_(S.error)}
|
|
83
|
+
`),process.exit(1));let v=S.value,g=await vr(()=>O({config:o,cwd:n,lockfile:v}),{config:o,label:"initial sync"}),b=await an(o);$({cwd:n,paused:g.hooksPaused});let f=Ce(n);f!=null&&l.info("watching branch %s in %s",f,n);let m=Ao({headers:{Authorization:`Bearer ${o.token}`},retry:Me,retryAttempts:1/0,url:`${o.ripploServerUrl}/graphql`}),y=Go({cwd:n,initialConcurrency:b});i.provide(y);let A=await $o({cwd:n,pool:y}),B=zo({claim:d.claim,config:o,cwd:n,initialId:g.devSessionId,pool:y,sseClient:m,sseHealth:u}),wr=Sr({cwd:n,projectId:o.projectId,sseClient:m}),br=yr({pool:y,sseClient:m}),xr=pr({config:o,devSessionId:g.devSessionId,machinery:a,sseClient:m});mr({config:o,devSessionId:g.devSessionId,machinery:a});let Pr=Bo({config:o,session:B}),hr=on(),z=await No({config:o,devSessionId:g.devSessionId,executor:e});c.resolve(),jo({devSessionId:g.devSessionId,executor:e,tunnel:z});let Er=async()=>{Pr(),hr(),a.stop(),p.close(),B.stop(),wr(),br(),xr(),await y.close(),await Uo(z),await A.stop().catch(()=>{}),await Promise.race([k({config:o,document:Fo,variables:{cwd:o.cwd,projectId:o.projectId}}).catch(()=>{}),new Promise(Rr=>setTimeout(Rr,3e3))]),t()},w=()=>{Er().finally(()=>process.exit(0))};s.handler=w,process.on("SIGINT",w),process.on("SIGTERM",w),process.on("SIGHUP",w),process.on("SIGBREAK",w),await new Promise(()=>{})}async function No({config:r,devSessionId:e,executor:o}){if(o==="cloud")return He({config:r,devSessionId:e})}async function Uo(r){r!=null&&await r.stop()}function $o({cwd:r,pool:e}){return ce({localDir:Wo.join(r,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&e.routeSpan(n,o)}})}function jo({devSessionId:r,executor:e,tunnel:o}){process.stdout.write(`${ye({devSessionId:r,executor:e,tunnelHostname:o?.hostname,version:V()})}
|
|
84
|
+
`)}function Bo({config:r,session:e}){let o=async()=>{try{let t=await k({config:r,document:Oo,variables:{id:e.getId()}});t.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(l.warn("dev session ended server-side (%s); re-registering",t.heartbeatDevSession.message),await e.reregister())}catch(t){l.warn("heartbeat failed: %s",t instanceof Error?t.message:String(t))}},n=setInterval(()=>{o()},_o);return()=>{clearInterval(n)}}function zo({claim:r,config:e,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let s=n,c=null,u=0,d=0,p=f=>{b(f)},S=()=>{let f=Oe({claim:r,cwd:o,devSessionId:s,onSubscriptionDead:p,pool:t,sseClient:i,sseHealth:a}),m=qe({cwd:o,devSessionId:s,onSubscriptionDead:p,sseClient:i});return()=>{f(),m()}},v=S(),g=async f=>{let m=Date.now();u=m-d>kr*2?1:u+1,d=m,u>=Mo&&a.markUnhealthy(f),await Qo(Math.min(1e3*2**(u-1),kr));let y=await H(o);if(y.isErr()){l.error("re-register: compile failed: %s",_(y.error));return}let A=await vr(()=>O({config:e,cwd:o,lockfile:y.value}),{config:e,label:"re-register sync"});v(),s=A.devSessionId,v=S(),l.info("re-registered dev session as %s",s)},b=f=>(c!=null||(c=g(f).finally(()=>{c=null})),c);return{getId:()=>s,reregister:()=>b("dev session ended server-side"),stop:()=>{v()}}}function Qo(r){return new Promise(e=>setTimeout(e,r))}function Go({cwd:r,initialConcurrency:e}){return cr({initialSize:e,spawn:lr(sn(),r),lockfileProvider:async()=>{let o=await x(r);return o.isErr()?{unavailable:`daemon-load-failed:${o.error.kind}`}:{lockfileJson:K(X,o.value)}}})}function Jo(r){try{return oe({cwd:r,onCompromised:Vo})}catch(e){throw e instanceof re&&(process.stderr.write(`${Se({cwd:e.cwd,pid:e.pid})}
|
|
85
|
+
`),process.exit(1)),e}}function Vo(){l.error("daemon lock compromised; shutting down"),process.stderr.write(`${ge()}
|
|
86
|
+
`),process.exit(1)}function Ko(){let r={handler:()=>{}};return{promise:new Promise(o=>{r.handler=o}),resolve:()=>{r.handler()}}}async function Xo({cwd:r,ipc:e,releasePid:o}){return(await ze({cwd:r,onConnection:e.handleConnection})).match(t=>t,t=>{process.stderr.write(`${pe(t)}
|
|
87
|
+
`),o(),process.exit(1)})}function Yo(){let r={provide:()=>{}};return{pool:new Promise(o=>{r.provide=o}),provide:o=>{r.provide(o)}}}function Zo(r){return P(r).match(e=>e,e=>{process.stderr.write(`${ee(e)}
|
|
88
|
+
`),process.exit(1)})}function vr(r,{config:e,label:o}){let n=e.ripploServerUrl.includes("localhost")||e.ripploServerUrl.includes("127.0.0.1");return Lo(async()=>{try{return await r()}catch(t){en({config:e,error:t});let i=t instanceof Error?t.message:String(t);throw rn(i)?t:(l.error("%s failed: %s",o,i),new Do(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:t,error:i})=>{l.warn("%s attempt %d failed \u2014 retrying: %s",o,t,i.message)}})}function en({config:r,error:e}){let o=Q(e);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${me()}
|
|
89
|
+
`),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${fe({projectId:r.projectId,serverUrl:r.ripploServerUrl})}
|
|
90
|
+
`),process.exit(1))}function rn(r){return r.includes("status 502")||r.includes("ECONNREFUSED")||r.includes("Failed to connect")||r.includes("fetch failed")}function on(){L({maxRuns:gr});let r=setInterval(()=>{L({maxRuns:gr})},Ho);return()=>{clearInterval(r)}}function nn(){process.on("unhandledRejection",r=>{l.error({err:r},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",r=>{l.error({err:r},"uncaughtException in watch; continuing")})}var tn=4;async function an(r){try{let o=(await k({config:r,document:qo,variables:void 0})).currentUser?.maxLocalConcurrentRuns;if(o!=null)return E(o),o}catch(e){l.warn({err:e},"failed to fetch local concurrency setting; using default")}return tn}function sn(){let r=process.argv[1];if(r==null)throw new Error("cli entry unavailable");return r}export{_t as runDaemon};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as f,W as a,X as b,Y as c,Z as d,_ as e,aa as g,ba as h,ca as i,da as j,ea as k}from"./chunk-APYROHWG.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};
|