ripplo 0.7.27 → 0.7.28

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.
@@ -1,92 +0,0 @@
1
- #!/usr/bin/env node
2
- import{$ as Ee,A as oe,C as ce,E as de,S as ge,U as ke,V as ve,W as be,X as xe,Y as he,Z as we,_ as Pe,b as J,ba as E,ca as R,da as Re,e as G,ea as _,fa as Ce,h as v,ha as q,i as H,ia as Ie,ja as Te,l as D,la as C,oa as We,q as Z,t as P,v as ee,w as re}from"./chunk-OPYF32NG.js";import{A as ae,B as se,K as le,P as ue,Q as pe,R as fe,S as me,T as ye,U as Se,b as V,e as K,f as X,i as Y,k as ne,w as te,z as ie}from"./chunk-3DQXKHCR.js";import{b as Ae}from"./chunk-RLXQYG7H.js";import{c as z,d as k,e as l,f as L,g as Q}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import wo from"path";import{createClient as Po}from"graphql-sse";import Eo,{AbortError as Ro}from"p-retry";import{graphql as N}from"gql.tada";import{graphql as Cr}from"gql.tada";import{print as Ir}from"graphql";async function Le({config:e,cwd:r,headed:o,pool:n,runId:t,signal:i,testSlug:a,workClass:s,workflowSlug:c}){let{fingerprint:d,result:u}=await v(r);if(u.isErr())return await C(e,t,`lockfile:${u.error.kind}`),{kind:"dispatch-error",reason:{detail:`lockfile:${u.error.kind}`,type:"generic"}};let g=Rr(u.value,{testSlug:a,workflowSlug:c});if(g==null)return await C(e,t,`no-test:${c}/${a}`),{kind:"dispatch-error",reason:{detail:`no-test:${c}/${a}`,type:"generic"}};let p=await E({headed:o,workClass:s,task:()=>n.execute({headed:o,lockfileFingerprint:d,runId:t,testRef:g},i)});return!p.serverNotified&&p.outcome.kind==="error"&&await C(e,t,p.outcome.detail),p.outcome}function Rr(e,{testSlug:r,workflowSlug:o}){let t=e.workflows.find(i=>Y(i.name)===o)?.tests.find(i=>i.slug===r);return t==null?void 0:ne(t)}var Tr=6e4,Wr=Cr(`
3
- subscription RunRequestedWatch($devSessionId: String!) {
4
- runRequested(devSessionId: $devSessionId) {
5
- runId
6
- testSlug
7
- workflowId
8
- workflowSlug
9
- }
10
- }
11
- `);async function He(e){let r=Math.min(1e3*2**e,Tr)+Hr();await new Promise(o=>setTimeout(o,r))}function De({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let s=new Set;return i.subscribe({query:Ir(Wr),variables:{devSessionId:o}},{complete:()=>{},error:c=>{let d=c instanceof Error?c.message:String(c);l.warn("runRequested SSE failed: %s; re-registering session",d),n(d)},next:c=>{Ar({claim:e,cwd:r,event:c.data?.runRequested,inFlightRunIds:s,pool:t})}},{connected:()=>{a.onConnected()},connecting:c=>{a.onConnecting(c),c&&l.debug("runRequested SSE reconnecting")}})}function Ar({claim:e,cwd:r,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(r);let i=P(r).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=Lr(e(o.runId),o);a.started(),Le({config:i,cwd:r,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 Lr(e,r){return e==null?(l.debug({runId:r.runId,workflowSlug:r.workflowSlug},"dispatching unclaimed run (externally triggered or replayed)"),{headed:!1,signal:new AbortController().signal,workClass:"p0-ui",finished:()=>{},started:()=>{}}):{headed:e.headed,signal:Ie(e.token),workClass:"p1-cli",finished:o=>{e.finished(r.runId,o)},started:()=>{e.started(r.runId)}}}function Hr(){return Math.floor(Math.random()*2700)+300}import{graphql as Dr}from"gql.tada";import{print as _r}from"graphql";var qr=Dr(`
13
- subscription TeleportRequestedWatch($devSessionId: String!) {
14
- teleportRequested(devSessionId: $devSessionId) {
15
- runId
16
- stepIndex
17
- testSlug
18
- workflowSlug
19
- }
20
- }
21
- `);function _e({cwd:e,devSessionId:r,onSubscriptionDead:o,sseClient:n}){let t=new Set,i=n.subscribe({query:_r(qr),variables:{devSessionId:r}},{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=>{Or({cwd:e,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function Or({cwd:e,event:r,running:o}){if(r==null)return;let n=`${r.workflowSlug}/${r.testSlug}`,t=new AbortController;o.add(t),process.stdout.write(`ripplo: teleport ${n} step ${String(r.stepIndex+1)}
22
- `),We({cwd:e,ref:n,signal:t.signal,step:r.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 qe(){let e=!0,r,o=null,n=()=>{o!=null&&(clearTimeout(o),o=null)};return{markUnhealthy:t=>{e=!1,r=t,n()},onConnected:()=>{n(),o=setTimeout(()=>{e=!0,r=void 0,o=null},1e4)},onConnecting:()=>{n()},snapshot:()=>({detail:r,ok:e})}}import Fr from"fs";import Ue from"net";import{err as $e,ok as Mr}from"neverthrow";async function Ne({cwd:e,onConnection:r}){Q(e);let o=de(e),n=await Oe({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(Fe(o)).mapErr(Me(o)):await Ur(o)?$e({kind:"already-running",socketPath:o}):(je(o),(await Oe({onConnection:r,socketPath:o})).map(Fe(o)).mapErr(Me(o)))}function Ur(e){return new Promise(r=>{let o=Ue.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function Oe(e){let r=await $r(e);return r.kind==="listening"?Mr(r.server):$e(r.error)}function $r({onConnection:e,socketPath:r}){return new Promise(o=>{let n=Ue.createServer(e);n.once("error",t=>{o({error:t.code==="EADDRINUSE"?{kind:"stale-candidate"}:{kind:"listen-failed",message:t.message},kind:"failed"})}),n.listen(r,()=>{o({kind:"listening",server:n})})})}function Fe(e){return r=>({socketPath:e,close:()=>{r.close(),je(e)}})}function je(e){Fr.rmSync(e,{force:!0})}function Me(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as Nr,randomUUID as jr}from"crypto";function Je(e){let r={attempts:0,consecutiveErrors:0,findings:0,haltedUntil:0,prepared:null,preparing:!1,refreshing:!1},o=O(e,r);return{priority:"p3",next:()=>Qr(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}async function O(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await Br(o);if(n==null)return;r.prepared=n,r.consecutiveErrors=0,r.haltedUntil=0,e.notifyWork()}finally{r.preparing=!1}}}async function Br({fingerprint:e,lockfile:r}){let o=await ae(r);return o==null?null:{exploration:o,fingerprint:e,lockfileHashValue:X(r),strategy:te("even")}}var Be=20,ze=3e5;async function zr(e,r){if(!(r.refreshing||r.preparing||r.prepared==null)){r.refreshing=!0;try{let o=await e.loadLockfile();if(o==null||o.fingerprint===r.prepared.fingerprint)return;l.info("workflow definitions changed, re-preparing exploration"),r.prepared=null,await O(e,r)}finally{r.refreshing=!1}}}function Qr(e,r){zr(e,r);let o=r.prepared;if(o==null||Date.now()<r.haltedUntil)return null;let n=se({lockfileFingerprint:o.fingerprint,lockfileHash:o.lockfileHashValue,prepared:o.exploration,random:Jr,strategy:o.strategy});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${jr()}`,label:t,run:i=>Gr({assign:n,params:e,signal:i,state:r})}}var Qe=2**31;function Jr(){return Nr(Qe)/Qe}async function Gr({assign:e,params:r,signal:o,state:n}){if(!await r.probeApp()){Ge(n,"app-unreachable");return}let t=await r.executeTrail(e,o);if(t.kind!=="aborted"){if(t.kind==="error"){Vr({params:r,reason:t.reason,state:n});return}n.consecutiveErrors=0,n.attempts+=1,t.kind==="finding"&&(n.findings+=1,l.info("exploration finding recorded"))}}function Vr({params:e,reason:r,state:o}){if(r==="lockfile:fingerprint-mismatch"){Kr(e,o);return}Ge(o,r)}function Kr(e,r){r.preparing||(r.prepared=null,O(e,r))}function Ge(e,r){e.consecutiveErrors+=1,l.debug("exploration trail error: %s",r),e.consecutiveErrors>=Be&&(e.haltedUntil=Date.now()+ze,e.consecutiveErrors=0,l.warn("exploration cooling down for %ds after %d consecutive trail errors (last: %s)",ze/1e3,Be,r))}function Xr(e){let{backoffActive:r,exploreEnabled:o,headedActive:n,interactiveActive:t,interactiveQueued:i}=e,{explorationActive:a,exploreConcurrency:s,poolSize:c}=e;if(!o||n||i>0)return{abortCount:a,refillCount:0};if(r)return{abortCount:0,refillCount:0};let d=Math.min(s,c-1,c-t);return{abortCount:0,refillCount:Math.max(0,d-a)}}function Xe(e){let r={active:new Map,backoffUntil:0,cancelBackoffTimer:null,cancelHeartbeat:null,prevInteractiveActive:e.probe().interactiveActive,stopped:!1};return Ye(r,e),{explorationActive:()=>r.active.size,notifyQueueChange:()=>{Yr(r,e)},stop:()=>{r.stopped=!0,r.cancelBackoffTimer?.(),r.cancelBackoffTimer=null,r.cancelHeartbeat?.(),r.cancelHeartbeat=null,Ze(r,r.active.size)}}}function Ye(e,r){e.stopped||(e.cancelHeartbeat=r.setTimer(()=>{I(e,r),Ye(e,r)},15e3))}function I(e,r){if(e.stopped)return;let o=r.probe(),n=Xr({backoffActive:r.now()<e.backoffUntil,explorationActive:e.active.size,exploreConcurrency:r.exploreConcurrency(),exploreEnabled:r.exploreEnabled(),headedActive:o.headedActive>0,interactiveActive:o.interactiveActive,interactiveQueued:o.interactiveQueued,poolSize:o.poolSize});Ze(e,n.abortCount),er({count:n.refillCount,params:r,state:e})}function Ze(e,r){[...e.active.values()].slice(0,r).forEach(({controller:o})=>{o.abort()})}function Yr(e,r){let o=r.probe();o.interactiveActive<e.prevInteractiveActive&&Zr(e,r),e.prevInteractiveActive=o.interactiveActive,I(e,r)}function Zr(e,r){e.backoffUntil=r.now()+3e4,e.cancelBackoffTimer?.(),e.cancelBackoffTimer=r.setTimer(()=>{e.cancelBackoffTimer=null,I(e,r)},3e4)}function er({count:e,params:r,state:o}){if(e<=0)return;let n=eo(r.sources);n!=null&&(ro({params:r,pulled:n,state:o}),er({count:e-1,params:r,state:o}))}function eo(e){return e.reduce((r,o)=>{if(r!=null)return r;let n=o.next();return n==null?null:{job:n,source:o}},null)}function ro({params:e,pulled:r,state:o}){let{job:n,source:t}=r,i=new AbortController;o.active.set(n.id,{controller:i,job:n,source:t}),e.execute({job:n,priority:t.priority,signal:i.signal}).then(()=>{Ke({job:n,outcome:Ve(i.signal,null),params:e,source:t,state:o})}).catch(a=>{Ke({job:n,outcome:Ve(i.signal,{error:a}),params:e,source:t,state:o})})}function Ve(e,r){return e.aborted?{kind:"aborted"}:r==null?{kind:"completed"}:{error:r.error,kind:"error"}}function Ke({job:e,outcome:r,params:o,source:n,state:t}){t.active.delete(e.id),n.onResult(e,r),I(t,o)}function F(e){return{priority:e,next:()=>null,onResult:()=>{}}}function rr({config:e,executor:r,pool:o}){return no({appUrl:e.appUrl,cwd:e.cwd,localExecutor:r==="local",executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function no({appUrl:e,cwd:r,executeTrail:o,localExecutor:n}){let t={concurrency:2,enabled:!1},i={notify:()=>{}},a=to({appUrl:e,cwd:r,executeTrail:o,notifyWork:()=>{i.notify()}}),s=Xe({now:Date.now,probe:io,setTimer:ao,sources:[F("p0"),F("p1"),a],execute:({job:c,priority:d,signal:u})=>E({headed:!1,workClass:so(d),task:()=>c.run(u)}),exploreConcurrency:()=>t.concurrency,exploreEnabled:()=>t.enabled});return _(()=>{s.notifyQueueChange()}),i.notify=()=>{s.notifyQueueChange()},{progress:()=>a.status(),setConcurrency:c=>{t.concurrency=c,s.notifyQueueChange()},setEnabled:c=>{t.enabled=c&&n,s.notifyQueueChange()},status:()=>({explorer:t.enabled?"on":"off",exploring:s.explorationActive(),progress:a.status()}),stop:()=>{s.stop(),_(null),a.stop()}}}function to({appUrl:e,cwd:r,executeTrail:o,notifyWork:n}){return Je({cwd:r,executeTrail:o,notifyWork:n,loadLockfile:async()=>{let{fingerprint:t,result:i}=await v(r);return i.match(a=>({fingerprint:t,lockfile:a}),()=>null)},probeApp:async()=>await oe(e)==null})}function io(){let e=Re();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function ao(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function so(e){switch(e){case"p0":return"p0-ui";case"p1":return"p1-cli";case"p2":return"p2-cover";case"p3":return"p3-explore"}}import{fork as lo}from"child_process";import or from"os";import{CancellationTokenSource as nr,ResponseError as tr}from"vscode-jsonrpc/node";function ir(e,r){return()=>{let o=lo(e,["run-worker"],{cwd:r,stdio:["ignore","inherit","inherit","ipc"]});return{connection:Ee(o),kill:()=>{o.kill("SIGKILL")},onExit:n=>{o.once("exit",n)}}}}function ar(e){let r={closed:!1,lockfileProvider:e.lockfileProvider,nextId:0,size:e.initialSize,spawn:e.spawn,waiters:[],workers:[]};return{close:async()=>{r.closed=!0,await Promise.all([...r.workers].map(o=>M(o,r)))},execute:(o,n)=>uo(o,n,r),exploreTrail:(o,n)=>mo(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(we,{runId:o,span:n})},setSize:o=>{So(o,r)}}}var co=1e4,sr=-32800;async function uo(e,r,o){let n=await lr(o);if(n.runId=e.runId,!n.alive)return T(n,o),{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1};let t=new nr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(be,e,t.token),s=ke.safeParse(a);return s.success?s.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return fo(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),T(n,o)}}async function lr(e){let r=e.workers.find(o=>o.alive&&o.runId===void 0);if(r!=null)return r.runId="pending",r;if(e.workers.length<e.size){let o=po(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function po(e){let r=e.spawn(),o={resolve:()=>{}},n={alive:!0,id:e.nextId,ready:new Promise(t=>{o.resolve=t,r.connection.onNotification(ve,t)}),runId:void 0,worker:r};return e.nextId+=1,r.connection.onRequest(xe,async t=>{let i=ge.safeParse(t);return i.success?e.lockfileProvider(i.data.fingerprint):{unavailable:"bad-lockfile-request"}}),r.onExit(()=>{n.alive=!1,e.workers=e.workers.filter(t=>t!==n),r.connection.dispose(),o.resolve()}),e.workers.push(n),n}function T(e,r){if(e.runId=void 0,!e.alive||r.closed)return;if(r.workers.length>r.size){M(e,r);return}let o=r.waiters.shift();o?.(e)}async function M(e,r){if(r.workers=r.workers.filter(t=>t!==e),!e.alive)return;let o=new Promise(t=>{e.worker.onExit(t)});await e.worker.connection.sendNotification(Pe).catch(()=>{});let n=setTimeout(()=>{e.worker.kill()},co);await o,clearTimeout(n)}function fo(e,r){return e instanceof tr&&e.code===sr?{outcome:{detail:"aborted",kind:"error"},serverNotified:!1}:r.alive?{outcome:{detail:e instanceof Error?e.message:String(e),kind:"error"},serverNotified:!1}:{outcome:{detail:"worker-exit",kind:"error"},serverNotified:!1}}async function mo(e,r,o){let n=await lr(o);if(n.runId="explore",!n.alive)return T(n,o),{kind:"error"};let t=new nr,i=()=>{t.cancel()};r.aborted&&t.cancel(),r.addEventListener("abort",i,{once:!0});try{let a=await n.worker.connection.sendRequest(he,e,t.token),s=ie.safeParse(a);return s.success?s.data:{kind:"error"}}catch(a){return yo(a)}finally{r.removeEventListener("abort",i),t.dispose(),T(n,o)}}function yo(e){return e instanceof tr&&e.code===sr?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function So(e,r){r.size=e,e>or.availableParallelism()&&l.warn({cores:or.availableParallelism(),size:e},"worker pool size exceeds available cores");let o=r.workers.filter(t=>t.alive&&t.runId===void 0),n=r.workers.length-e;o.slice(0,Math.max(0,n)).forEach(t=>{M(t,r)})}import W from"fs";import{graphql as h}from"gql.tada";import{print as U}from"graphql";var go=h(`
23
- query DaemonExploration($devSessionId: String!) {
24
- exploration(devSessionId: $devSessionId) {
25
- active
26
- localWorkers
27
- }
28
- }
29
- `),ko=h(`
30
- subscription WatchExplorationChanged($devSessionId: String!) {
31
- explorationChanged(devSessionId: $devSessionId) {
32
- exploration {
33
- active
34
- localWorkers
35
- }
36
- }
37
- }
38
- `);function dr({config:e,devSessionId:r,machinery:o,sseClient:n}){return vo({config:e,devSessionId:r,machinery:o}),n.subscribe({query:U(ko),variables:{devSessionId:r}},{complete:()=>{},error:t=>{l.error(t,"exploration subscription error")},next:t=>{ur(o,t.data?.explorationChanged.exploration)}})}async function vo({config:e,devSessionId:r,machinery:o}){let n=await k({config:e,document:go,variables:{devSessionId:r}});ur(o,n.exploration)}function ur(e,r){r!=null&&(e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}var bo=h(`
39
- mutation RecordExplorationProgress($devSessionId: String!, $attempts: Int!, $findings: Int!) {
40
- recordExplorationProgress(devSessionId: $devSessionId, attempts: $attempts, findings: $findings)
41
- }
42
- `),cr=3e4;function pr({config:e,devSessionId:r,machinery:o}){let n={attempts:0,findings:0},t=async()=>{let a=o.progress(),s=a.attempts-n.attempts,c=a.findings-n.findings;(s>0||c>0)&&(n.attempts=a.attempts,n.findings=a.findings,await k({config:e,document:bo,variables:{attempts:s,devSessionId:r,findings:c}}).catch(d=>{l.warn({error:d},"exploration progress flush failed")})),i=setTimeout(()=>{t()},cr)},i=setTimeout(()=>{t()},cr);return()=>{clearTimeout(i)}}var xo=h(`
43
- subscription HooksPausedWatch($projectId: String!) {
44
- hooksPausedRequested(projectId: $projectId) {
45
- paused
46
- projectId
47
- }
48
- }
49
- `),ho=h(`
50
- subscription WatchLocalConcurrencyChanged {
51
- myMaxLocalConcurrentRunsChanged
52
- }
53
- `);function fr({pool:e,sseClient:r}){return r.subscribe({query:U(ho)},{complete:()=>{},error:o=>{l.error(o,"localConcurrency subscription error")},next:o=>{let n=o.data?.myMaxLocalConcurrentRunsChanged;n!=null&&(R(n),e.setSize(n))}})}function mr({cwd:e,projectId:r,sseClient:o}){return o.subscribe({query:U(xo),variables:{projectId:r}},{complete:()=>{},error:n=>{l.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&$({cwd:e,paused:t})}})}function $({cwd:e,paused:r}){let o=ce(e);if(r&&!W.existsSync(o)){W.writeFileSync(o,"");return}!r&&W.existsSync(o)&&W.unlinkSync(o)}var Co=6e4,yr=500,Io=15e3,Sr=6e4,To=3,Wo=N(`
54
- mutation HeartbeatDevSessionWatch($id: String!) {
55
- heartbeatDevSession(id: $id) {
56
- __typename
57
- ... on DevSession {
58
- id
59
- }
60
- ... on DevSessionEndedError {
61
- message
62
- }
63
- }
64
- }
65
- `),Ao=N(`
66
- query WatchLocalConcurrency {
67
- currentUser {
68
- id
69
- maxLocalConcurrentRuns
70
- }
71
- }
72
- `),Lo=N(`
73
- mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
74
- endDevSession(projectId: $projectId, cwd: $cwd) {
75
- __typename
76
- ... on DevSession {
77
- id
78
- }
79
- ... on NoActiveDevSessionError {
80
- message
81
- }
82
- }
83
- }
84
- `);async function Rt(e){let{executor:r}=e;Ko();let o=Qo(process.cwd()),n=o.cwd,t=$o(n),i=zo(),a=rr({config:o,executor:r,pool:i.pool}),s={handler:()=>{}},c=jo(),d=qe(),u=Te({config:o,cwd:n,executor:r,explorationStatus:a.status,ready:c.promise,onShutdownRequest:()=>{s.handler()},sseHealth:()=>d.snapshot()}),g=await Bo({cwd:n,ipc:u,releasePid:t}),p=await H(n);p.isErr()&&(process.stderr.write(`ripplo: ${D(p.error)}
85
- `),process.exit(1));let b=p.value,S=await gr(()=>q({config:o,cwd:n,lockfile:b}),{config:o,label:"initial sync"}),w=await Yo(o);$({cwd:n,paused:S.hooksPaused});let f=Ce(n);f!=null&&l.info("watching branch %s in %s",f,n);let m=Po({headers:{Authorization:`Bearer ${o.token}`},retry:He,retryAttempts:1/0,url:`${o.ripploServerUrl}/graphql`}),y=Uo({cwd:n,initialConcurrency:w});i.provide(y);let A=await _o({cwd:n,pool:y}),j=Fo({claim:u.claim,config:o,cwd:n,initialId:S.devSessionId,pool:y,sseClient:m,sseHealth:d}),kr=mr({cwd:n,projectId:o.projectId,sseClient:m}),vr=fr({pool:y,sseClient:m}),br=dr({config:o,devSessionId:S.devSessionId,machinery:a,sseClient:m}),xr=pr({config:o,devSessionId:S.devSessionId,machinery:a}),hr=Oo({config:o,session:j}),wr=Vo(),B=await Ho({config:o,devSessionId:S.devSessionId,executor:r});c.resolve(),qo({devSessionId:S.devSessionId,executor:r,tunnel:B});let Pr=async()=>{hr(),wr(),a.stop(),g.close(),j.stop(),kr(),vr(),br(),xr(),await y.close(),await Do(B),await A.stop().catch(()=>{}),await Promise.race([k({config:o,document:Lo,variables:{cwd:o.cwd,projectId:o.projectId}}).catch(()=>{}),new Promise(Er=>setTimeout(Er,3e3))]),t()},x=()=>{Pr().finally(()=>process.exit(0))};s.handler=x,process.on("SIGINT",x),process.on("SIGTERM",x),process.on("SIGHUP",x),process.on("SIGBREAK",x),await new Promise(()=>{})}async function Ho({config:e,devSessionId:r,executor:o}){if(o==="cloud")return Ae({config:e,devSessionId:r})}async function Do(e){e!=null&&await e.stop()}function _o({cwd:e,pool:r}){return le({localDir:wo.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function qo({devSessionId:e,executor:r,tunnel:o}){process.stdout.write(`${me({devSessionId:e,executor:r,tunnelHostname:o?.hostname,version:G()})}
86
- `)}function Oo({config:e,session:r}){let o=async()=>{try{let t=await k({config:e,document:Wo,variables:{id:r.getId()}});t.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(l.warn("dev session ended server-side (%s); re-registering",t.heartbeatDevSession.message),await r.reregister())}catch(t){l.warn("heartbeat failed: %s",t instanceof Error?t.message:String(t))}},n=setInterval(()=>{o()},Io);return()=>{clearInterval(n)}}function Fo({claim:e,config:r,cwd:o,initialId:n,pool:t,sseClient:i,sseHealth:a}){let s=n,c=null,d=0,u=0,g=f=>{w(f)},p=()=>{let f=De({claim:e,cwd:o,devSessionId:s,onSubscriptionDead:g,pool:t,sseClient:i,sseHealth:a}),m=_e({cwd:o,devSessionId:s,onSubscriptionDead:g,sseClient:i});return()=>{f(),m()}},b=p(),S=async f=>{let m=Date.now();d=m-u>Sr*2?1:d+1,u=m,d>=To&&a.markUnhealthy(f),await Mo(Math.min(1e3*2**(d-1),Sr));let y=await H(o);if(y.isErr()){l.error("re-register: compile failed: %s",D(y.error));return}let A=await gr(()=>q({config:r,cwd:o,lockfile:y.value}),{config:r,label:"re-register sync"});b(),s=A.devSessionId,b=p(),l.info("re-registered dev session as %s",s)},w=f=>(c!=null||(c=S(f).finally(()=>{c=null})),c);return{getId:()=>s,reregister:()=>w("dev session ended server-side"),stop:()=>{b()}}}function Mo(e){return new Promise(r=>setTimeout(r,e))}function Uo({cwd:e,initialConcurrency:r}){return ar({initialSize:r,spawn:ir(Zo(),e),lockfileProvider:async o=>{let n=await v(e);return n.result.isErr()?{unavailable:`daemon-load-failed:${n.result.error.kind}`}:n.fingerprint!==o?{unavailable:"fingerprint-mismatch"}:{lockfileJson:V(K,n.result.value)}}})}function $o(e){try{return re({cwd:e,onCompromised:No})}catch(r){throw r instanceof ee&&(process.stderr.write(`${ye({cwd:r.cwd,pid:r.pid})}
87
- `),process.exit(1)),r}}function No(){l.error("daemon lock compromised; shutting down"),process.stderr.write(`${Se()}
88
- `),process.exit(1)}function jo(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function Bo({cwd:e,ipc:r,releasePid:o}){return(await Ne({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ue(t)}
89
- `),o(),process.exit(1)})}function zo(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function Qo(e){return P(e).match(r=>r,r=>{process.stderr.write(`${Z(r)}
90
- `),process.exit(1)})}function gr(e,{config:r,label:o}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return Eo(async()=>{try{return await e()}catch(t){Jo({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw Go(i)?t:(l.error("%s failed: %s",o,i),new Ro(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 Jo({config:e,error:r}){let o=z(r);o==="UNAUTHENTICATED"&&(process.stderr.write(`ripplo: ${fe()}
91
- `),process.exit(1)),o==="FORBIDDEN"&&(process.stderr.write(`ripplo: ${pe({projectId:e.projectId,serverUrl:e.ripploServerUrl})}
92
- `),process.exit(1))}function Go(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Vo(){L({maxRuns:yr});let e=setInterval(()=>{L({maxRuns:yr})},Co);return()=>{clearInterval(e)}}function Ko(){process.on("unhandledRejection",e=>{l.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{l.error({err:e},"uncaughtException in watch; continuing")})}var Xo=4;async function Yo(e){try{let o=(await k({config:e,document:Ao,variables:void 0})).currentUser?.maxLocalConcurrentRuns;if(o!=null)return R(o),o}catch(r){l.warn({err:r},"failed to fetch local concurrency setting; using default")}return Xo}function Zo(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{Rt as runDaemon};