ripplo 0.7.28 → 0.7.30

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 we,X as be,Y as xe,Z as he,_ 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 L,ia as Ie,ja as We,l as H,la as C,oa as Te,q as Z,t as P,v as ee,w as re}from"./chunk-RJNO37CR.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-UODLSLH7.js";import{b as Ae}from"./chunk-RLXQYG7H.js";import{c as z,d as k,e as l,f as D,g as Q}from"./chunk-5VRJXHWH.js";import"./chunk-IHSHBPJY.js";import"./chunk-7UWDMECF.js";import Eo from"path";import{createClient as Ro}from"graphql-sse";import Co,{AbortError as Io}from"p-retry";import{graphql as $}from"gql.tada";import{graphql as Cr}from"gql.tada";import{print as Ir}from"graphql";async function De({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 Wr=6e4,Tr=Cr(`
3
- subscription RunRequestedWatch($devSessionId: String!) {
4
- runRequested(devSessionId: $devSessionId) {
5
- runId
6
- testSlug
7
- workflowId
8
- workflowSlug
9
- }
10
- }
11
- `);async function Le(e){let r=Math.min(1e3*2**e,Wr)+Lr();await new Promise(o=>setTimeout(o,r))}function He({claim:e,cwd:r,devSessionId:o,onSubscriptionDead:n,pool:t,sseClient:i,sseHealth:a}){let s=new Set;return i.subscribe({query:Ir(Tr),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=Dr(e(o.runId),o);a.started(),De({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 Dr(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 Lr(){return Math.floor(Math.random()*2700)+300}import{graphql as Hr}from"gql.tada";import{print as _r}from"graphql";var qr=Hr(`
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=>{Fr({cwd:e,event:a.data?.teleportRequested,running:t})}});return()=>{t.forEach(a=>{a.abort()}),t.clear(),i()}}function Fr({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
- `),Te({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 Mr from"fs";import Ne from"net";import{err as Ue,ok as Or}from"neverthrow";async function $e({cwd:e,onConnection:r}){Q(e);let o=de(e),n=await Fe({onConnection:r,socketPath:o});return n.isOk()||n.error.kind!=="stale-candidate"?n.map(Me(o)).mapErr(Oe(o)):await Nr(o)?Ue({kind:"already-running",socketPath:o}):(je(o),(await Fe({onConnection:r,socketPath:o})).map(Me(o)).mapErr(Oe(o)))}function Nr(e){return new Promise(r=>{let o=Ne.connect(e);o.once("connect",()=>{o.destroy(),r(!0)}),o.once("error",()=>{r(!1)})})}async function Fe(e){let r=await Ur(e);return r.kind==="listening"?Or(r.server):Ue(r.error)}function Ur({onConnection:e,socketPath:r}){return new Promise(o=>{let n=Ne.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 Me(e){return r=>({socketPath:e,close:()=>{r.close(),je(e)}})}function je(e){Mr.rmSync(e,{force:!0})}function Oe(e){return r=>r.kind==="stale-candidate"?{kind:"already-running",socketPath:e}:{kind:"bind-failed",message:r.message}}import{randomInt as $r,randomUUID as jr}from"crypto";function Je(e){let r={attempts:0,consecutiveErrors:0,findings:0,haltedUntil:0,prepared:null,preparing:!1,refreshing:!1,windowAttempts:0,windowFindings:0,windowStartMs:Date.now()},o=F(e,r);return{priority:"p3",next:()=>Jr(e,r),onResult:()=>{},ready:()=>o,status:()=>({attempts:r.attempts,findings:r.findings}),stop:()=>Promise.resolve()}}var Br=12;async function F(e,r){if(!r.preparing){r.preparing=!0;try{let o=await e.loadLockfile(),n=o==null?null:await zr(o);if(n==null)return;r.prepared=n,r.consecutiveErrors=0,r.haltedUntil=0,e.notifyWork()}finally{r.preparing=!1}}}async function zr({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 Qr(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 F(e,r)}finally{r.refreshing=!1}}}function Jr(e,r){Qr(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:Gr,strategy:o.strategy});if(n==null)return null;let t=n.baseStateTest.name;return{id:`explore:${jr()}`,label:t,run:i=>Vr({assign:n,params:e,signal:i,state:r})}}var Qe=2**31;function Gr(){return $r(Qe)/Qe}async function Vr({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"){Xr({params:r,reason:t.reason,state:n});return}n.consecutiveErrors=0,n.attempts+=1,n.windowAttempts+=1,t.kind==="finding"&&(n.findings+=1,n.windowFindings+=1,l.info("exploration finding recorded")),n.windowAttempts>=Br&&Kr(n)}}function Kr(e){let r=Date.now()-e.windowStartMs;l.info({attempts:e.windowAttempts,avgTrailMs:Math.round(r/e.windowAttempts),findings:e.windowFindings,windowMs:r,yield:Number((e.windowFindings/e.windowAttempts).toFixed(3))},"explore window"),e.windowAttempts=0,e.windowFindings=0,e.windowStartMs=Date.now()}function Xr({params:e,reason:r,state:o}){if(r==="lockfile:fingerprint-mismatch"){Yr(e,o);return}Ge(o,r)}function Yr(e,r){r.preparing||(r.prepared=null,F(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 Zr(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:()=>{eo(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=Zr({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 eo(e,r){let o=r.probe();o.interactiveActive<e.prevInteractiveActive&&ro(e,r),e.prevInteractiveActive=o.interactiveActive,I(e,r)}function ro(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=oo(r.sources);n!=null&&(no({params:r,pulled:n,state:o}),er({count:e-1,params:r,state:o}))}function oo(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 no({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 M(e){return{priority:e,next:()=>null,onResult:()=>{}}}function rr({config:e,executor:r,pool:o}){return io({appUrl:e.appUrl,cwd:e.cwd,localExecutor:r==="local",executeTrail:async(n,t)=>(await o).exploreTrail(n,t)})}function io({appUrl:e,cwd:r,executeTrail:o,localExecutor:n}){let t={concurrency:2,enabled:!1},i={notify:()=>{}},a=ao({appUrl:e,cwd:r,executeTrail:o,notifyWork:()=>{i.notify()}}),s=Xe({now:Date.now,probe:so,setTimer:lo,sources:[M("p0"),M("p1"),a],execute:({job:c,priority:d,signal:u})=>E({headed:!1,workClass:co(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 ao({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 so(){let e=Re();return{headedActive:e.headedActive,interactiveActive:e.active,interactiveQueued:e.queued,poolSize:e.poolSize}}function lo(e,r){let o=setTimeout(e,r);return()=>{clearTimeout(o)}}function co(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 uo}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=uo(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=>O(o,r)))},execute:(o,n)=>fo(o,n,r),exploreTrail:(o,n)=>So(o,n,r),routeSpan:(o,n)=>{let t=r.workers.find(i=>i.runId===o);t?.worker.connection.sendNotification(he,{runId:o,span:n})},setSize:o=>{ko(o,r)}}}var po=1e4,sr=-32800;async function fo(e,r,o){let n=await lr(o);if(n.runId=e.runId,!n.alive)return W(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(we,e,t.token),s=ke.safeParse(a);return s.success?s.data:{outcome:{detail:"bad-outcome-frame",kind:"error"},serverNotified:!1}}catch(a){return yo(a,n)}finally{r.removeEventListener("abort",i),t.dispose(),W(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=mo(e);return o.runId="pending",await o.ready,o}return new Promise(o=>{e.waiters.push(n=>{n.runId="pending",o(n)})})}function mo(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(be,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 W(e,r){if(e.runId=void 0,!e.alive||r.closed)return;if(r.workers.length>r.size){O(e,r);return}let o=r.waiters.shift();o?.(e)}async function O(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()},po);await o,clearTimeout(n)}function yo(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 So(e,r,o){let n=await lr(o);if(n.runId="explore",!n.alive)return W(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(xe,e,t.token),s=ie.safeParse(a);return s.success?s.data:{kind:"error"}}catch(a){return go(a)}finally{r.removeEventListener("abort",i),t.dispose(),W(n,o)}}function go(e){return e instanceof tr&&e.code===sr?{kind:"aborted"}:{kind:"error",reason:`transport:${e instanceof Error?e.message.slice(0,120):"unknown"}`}}function ko(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=>{O(t,r)})}import T from"fs";import{graphql as x}from"gql.tada";import{print as N}from"graphql";var vo=x(`
23
- query DaemonExploration($devSessionId: String!) {
24
- exploration(devSessionId: $devSessionId) {
25
- active
26
- localWorkers
27
- }
28
- }
29
- `),wo=x(`
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}){let t={localWorkers:-1};return bo({config:e,devSessionId:r,machinery:o,prev:t}),n.subscribe({query:N(wo),variables:{devSessionId:r}},{complete:()=>{},error:i=>{l.error(i,"exploration subscription error")},next:i=>{ur(o,i.data?.explorationChanged.exploration,t)}})}async function bo({config:e,devSessionId:r,machinery:o,prev:n}){let t=await k({config:e,document:vo,variables:{devSessionId:r}});ur(o,t.exploration,n)}function ur(e,r,o){r!=null&&(r.localWorkers!==o.localWorkers&&(l.info({workers:r.localWorkers},"explore local worker count changed"),o.localWorkers=r.localWorkers),e.setConcurrency(r.localWorkers),e.setEnabled(r.active))}var xo=x(`
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:xo,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 ho=x(`
43
- subscription HooksPausedWatch($projectId: String!) {
44
- hooksPausedRequested(projectId: $projectId) {
45
- paused
46
- projectId
47
- }
48
- }
49
- `),Po=x(`
50
- subscription WatchLocalConcurrencyChanged {
51
- myMaxLocalConcurrentRunsChanged
52
- }
53
- `);function fr({pool:e,sseClient:r}){return r.subscribe({query:N(Po)},{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:N(ho),variables:{projectId:r}},{complete:()=>{},error:n=>{l.error(n,"hooksPaused subscription error")},next:n=>{let t=n.data?.hooksPausedRequested?.paused;t!=null&&U({cwd:e,paused:t})}})}function U({cwd:e,paused:r}){let o=ce(e);if(r&&!T.existsSync(o)){T.writeFileSync(o,"");return}!r&&T.existsSync(o)&&T.unlinkSync(o)}var Wo=6e4,yr=500,To=15e3,Sr=6e4,Ao=3,Do=$(`
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
- `),Lo=$(`
66
- query WatchLocalConcurrency {
67
- currentUser {
68
- id
69
- maxLocalConcurrentRuns
70
- }
71
- }
72
- `),Ho=$(`
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 It(e){let{executor:r}=e;Yo();let o=Go(process.cwd()),n=o.cwd,t=jo(n),i=Jo(),a=rr({config:o,executor:r,pool:i.pool}),s={handler:()=>{}},c=zo(),d=qe(),u=We({config:o,cwd:n,executor:r,explorationStatus:a.status,ready:c.promise,onShutdownRequest:()=>{s.handler()},sseHealth:()=>d.snapshot()}),g=await Qo({cwd:n,ipc:u,releasePid:t}),p=await L(n);p.isErr()&&(process.stderr.write(`ripplo: ${H(p.error)}
85
- `),process.exit(1));let w=p.value,S=await gr(()=>q({config:o,cwd:n,lockfile:w}),{config:o,label:"initial sync"}),h=await en(o);U({cwd:n,paused:S.hooksPaused});let f=Ce(n);f!=null&&l.info("watching branch %s in %s",f,n);let m=Ro({headers:{Authorization:`Bearer ${o.token}`},retry:Le,retryAttempts:1/0,url:`${o.ripploServerUrl}/graphql`}),y=$o({cwd:n,initialConcurrency:h});i.provide(y);let A=await Fo({cwd:n,pool:y}),j=No({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}),wr=dr({config:o,devSessionId:S.devSessionId,machinery:a,sseClient:m}),br=pr({config:o,devSessionId:S.devSessionId,machinery:a}),xr=Oo({config:o,session:j}),hr=Xo(),B=await _o({config:o,devSessionId:S.devSessionId,executor:r});c.resolve(),Mo({devSessionId:S.devSessionId,executor:r,tunnel:B});let Pr=async()=>{xr(),hr(),a.stop(),g.close(),j.stop(),kr(),vr(),wr(),br(),await y.close(),await qo(B),await A.stop().catch(()=>{}),await Promise.race([k({config:o,document:Ho,variables:{cwd:o.cwd,projectId:o.projectId}}).catch(()=>{}),new Promise(Er=>setTimeout(Er,3e3))]),t()},b=()=>{Pr().finally(()=>process.exit(0))};s.handler=b,process.on("SIGINT",b),process.on("SIGTERM",b),process.on("SIGHUP",b),process.on("SIGBREAK",b),await new Promise(()=>{})}async function _o({config:e,devSessionId:r,executor:o}){if(o==="cloud")return Ae({config:e,devSessionId:r})}async function qo(e){e!=null&&await e.stop()}function Fo({cwd:e,pool:r}){return le({localDir:Eo.join(e,".ripplo",".local"),writePortFile:!0,onRrwebBatch:()=>{},onSpan:o=>{let n=o.attributes["ripplo.run"];n!=null&&r.routeSpan(n,o)}})}function Mo({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:Do,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()},To);return()=>{clearInterval(n)}}function No({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=>{h(f)},p=()=>{let f=He({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()}},w=p(),S=async f=>{let m=Date.now();d=m-u>Sr*2?1:d+1,u=m,d>=Ao&&a.markUnhealthy(f),await Uo(Math.min(1e3*2**(d-1),Sr));let y=await L(o);if(y.isErr()){l.error("re-register: compile failed: %s",H(y.error));return}let A=await gr(()=>q({config:r,cwd:o,lockfile:y.value}),{config:r,label:"re-register sync"});w(),s=A.devSessionId,w=p(),l.info("re-registered dev session as %s",s)},h=f=>(c!=null||(c=S(f).finally(()=>{c=null})),c);return{getId:()=>s,reregister:()=>h("dev session ended server-side"),stop:()=>{w()}}}function Uo(e){return new Promise(r=>setTimeout(r,e))}function $o({cwd:e,initialConcurrency:r}){return ar({initialSize:r,spawn:ir(rn(),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 jo(e){try{return re({cwd:e,onCompromised:Bo})}catch(r){throw r instanceof ee&&(process.stderr.write(`${ye({cwd:r.cwd,pid:r.pid})}
87
- `),process.exit(1)),r}}function Bo(){l.error("daemon lock compromised; shutting down"),process.stderr.write(`${Se()}
88
- `),process.exit(1)}function zo(){let e={handler:()=>{}};return{promise:new Promise(o=>{e.handler=o}),resolve:()=>{e.handler()}}}async function Qo({cwd:e,ipc:r,releasePid:o}){return(await $e({cwd:e,onConnection:r.handleConnection})).match(t=>t,t=>{process.stderr.write(`${ue(t)}
89
- `),o(),process.exit(1)})}function Jo(){let e={provide:()=>{}};return{pool:new Promise(o=>{e.provide=o}),provide:o=>{e.provide(o)}}}function Go(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 Co(async()=>{try{return await e()}catch(t){Vo({config:r,error:t});let i=t instanceof Error?t.message:String(t);throw Ko(i)?t:(l.error("%s failed: %s",o,i),new Io(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 Vo({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 Ko(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function Xo(){D({maxRuns:yr});let e=setInterval(()=>{D({maxRuns:yr})},Wo);return()=>{clearInterval(e)}}function Yo(){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 Zo=4;async function en(e){try{let o=(await k({config:e,document:Lo,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 Zo}function rn(){let e=process.argv[1];if(e==null)throw new Error("cli entry unavailable");return e}export{It as runDaemon};