ripplo 0.6.0 → 0.6.1
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/index.js +170 -169
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ja=Object.create;var
|
|
2
|
+
var ja=Object.create;var vt=Object.defineProperty;var Na=Object.getOwnPropertyDescriptor;var Da=Object.getOwnPropertyNames;var Oa=Object.getPrototypeOf,La=Object.prototype.hasOwnProperty;var _a=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Ua=(e,r)=>{for(var t in r)vt(e,t,{get:r[t],enumerable:!0})},bt=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Da(r))!La.call(e,o)&&o!==t&&vt(e,o,{get:()=>r[o],enumerable:!(n=Na(r,o))||n.enumerable});return e},St=(e,r,t)=>(bt(e,r,"default"),t&&bt(t,r,"default")),kt=(e,r,t)=>(t=e!=null?ja(Oa(e)):{},bt(r||!e||!e.__esModule?vt(t,"default",{value:e,enumerable:!0}):t,e));var $r=_a((Tv,Po)=>{"use strict";var Ql=(function(){function e(t,n){if(typeof t!="function")throw new TypeError("DataLoader must be constructed with a function which accepts "+("Array<key> and returns Promise<Array<value>>, but got: "+t+"."));this._batchLoadFn=t,this._maxBatchSize=tc(n),this._batchScheduleFn=nc(n),this._cacheKeyFn=oc(n),this._cacheMap=ic(n),this._batch=null,this.name=sc(n)}var r=e.prototype;return r.load=function(n){if(n==null)throw new TypeError("The loader.load() function must be called with a value, "+("but got: "+String(n)+"."));var o=ec(this),i=this._cacheMap,s;if(i){s=this._cacheKeyFn(n);var a=i.get(s);if(a){var l=o.cacheHits||(o.cacheHits=[]);return new Promise(function(u){l.push(function(){u(a)})})}}o.keys.push(n);var c=new Promise(function(u,m){o.callbacks.push({resolve:u,reject:m})});return i&&i.set(s,c),c},r.loadMany=function(n){if(!ko(n))throw new TypeError("The loader.loadMany() function must be called with Array<key> "+("but got: "+n+"."));for(var o=[],i=0;i<n.length;i++)o.push(this.load(n[i]).catch(function(s){return s}));return Promise.all(o)},r.clear=function(n){var o=this._cacheMap;if(o){var i=this._cacheKeyFn(n);o.delete(i)}return this},r.clearAll=function(){var n=this._cacheMap;return n&&n.clear(),this},r.prime=function(n,o){var i=this._cacheMap;if(i){var s=this._cacheKeyFn(n);if(i.get(s)===void 0){var a;o instanceof Error?(a=Promise.reject(o),a.catch(function(){})):a=Promise.resolve(o),i.set(s,a)}}return this},e})(),Zl=typeof process=="object"&&typeof process.nextTick=="function"?function(e){Vt||(Vt=Promise.resolve()),Vt.then(function(){process.nextTick(e)})}:typeof setImmediate=="function"?function(e){setImmediate(e)}:function(e){setTimeout(e)},Vt;function ec(e){var r=e._batch;if(r!==null&&!r.hasDispatched&&r.keys.length<e._maxBatchSize)return r;var t={hasDispatched:!1,keys:[],callbacks:[]};return e._batch=t,e._batchScheduleFn(function(){rc(e,t)}),t}function rc(e,r){if(r.hasDispatched=!0,r.keys.length===0){Mt(r);return}var t;try{t=e._batchLoadFn(r.keys)}catch(n){return Ft(e,r,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function "+("errored synchronously: "+String(n)+".")))}if(!t||typeof t.then!="function")return Ft(e,r,new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise: "+String(t)+".")));t.then(function(n){if(!ko(n))throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did "+("not return a Promise of an Array: "+String(n)+"."));if(n.length!==r.keys.length)throw new TypeError("DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys."+(`
|
|
3
3
|
|
|
4
4
|
Keys:
|
|
5
|
-
`+String(
|
|
5
|
+
`+String(r.keys))+(`
|
|
6
6
|
|
|
7
7
|
Values:
|
|
8
|
-
`+String(n)));
|
|
9
|
-
`&&(u(),l="",c=0,
|
|
8
|
+
`+String(n)));Mt(r);for(var o=0;o<r.callbacks.length;o++){var i=n[o];i instanceof Error?r.callbacks[o].reject(i):r.callbacks[o].resolve(i)}}).catch(function(n){Ft(e,r,n)})}function Ft(e,r,t){Mt(r);for(var n=0;n<r.keys.length;n++)e.clear(r.keys[n]),r.callbacks[n].reject(t)}function Mt(e){if(e.cacheHits)for(var r=0;r<e.cacheHits.length;r++)e.cacheHits[r]()}function tc(e){var r=!e||e.batch!==!1;if(!r)return 1;var t=e&&e.maxBatchSize;if(t===void 0)return 1/0;if(typeof t!="number"||t<1)throw new TypeError("maxBatchSize must be a positive number: "+t);return t}function nc(e){var r=e&&e.batchScheduleFn;if(r===void 0)return Zl;if(typeof r!="function")throw new TypeError("batchScheduleFn must be a function: "+r);return r}function oc(e){var r=e&&e.cacheKeyFn;if(r===void 0)return function(t){return t};if(typeof r!="function")throw new TypeError("cacheKeyFn must be a function: "+r);return r}function ic(e){var r=!e||e.cache!==!1;if(!r)return null;var t=e&&e.cacheMap;if(t===void 0)return new Map;if(t!==null){var n=["get","set","delete","clear"],o=n.filter(function(i){return t&&typeof t[i]!="function"});if(o.length!==0)throw new TypeError("Custom cacheMap missing methods: "+o.join(", "))}return t}function sc(e){return e&&e.name?e.name:null}function ko(e){return typeof e=="object"&&e!==null&&typeof e.length=="number"&&(e.length===0||e.length>0&&Object.prototype.hasOwnProperty.call(e,e.length-1))}Po.exports=Ql});import{execFileSync as Va}from"child_process";import Fa from"fs";import Er from"path";function Pt(e){let r=Ha(e);return r??Wn(e)}function Wn(e){let r=Er.dirname(e);return Ma(Er.join(e,".ripplo"))?e:r===e?null:Wn(r)}function Ma(e){try{return Fa.statSync(e).isDirectory()}catch{return!1}}function Ha(e){let r=Ba(["rev-parse","--show-toplevel"],e);if(r==null)return null;let t=r.trim();return t.length===0?null:Er.isAbsolute(t)?t:Er.resolve(e,t)}function Ba(e,r){try{return Va("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return null}}import pl from"path";import{AsyncLocalStorage as Wa}from"async_hooks";import qa from"path";var za=new Wa;function qn(){let e=za.getStore();return e!=null?e.fixturesDir:qa.join(process.cwd(),".ripplo","fixtures")}async function me(e,r,t){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${t} timed out after ${String(r)}ms`))},r)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}var zn=5e3;async function se({awaitPromise:e,expression:r,label:t,session:n,timeoutMs:o}){let i=await me(n.send("Runtime.evaluate",{awaitPromise:e,expression:r,returnByValue:!0}),o??zn,t??"evaluateOnSession");if(i.exceptionDetails==null)return i.result.value}async function Ga({fn:e,label:r,page:t,timeoutMs:n}){let o=n??zn,i=await me(t.context().newCDPSession(t),o,`${r} (newCDPSession)`);try{return await me(e(i),o,r)}finally{await i.detach().catch(()=>{})}}async function sr({awaitPromise:e,expression:r,label:t,page:n,timeoutMs:o}){return Ga({label:t??"evaluateViaCdp",page:n,timeoutMs:o,fn:async i=>{let s=await i.send("Runtime.evaluate",{awaitPromise:e,expression:r,returnByValue:!0});if(s.exceptionDetails==null)return s.result.value}})}var Ka=Object.prototype.toString,Le=Array.isArray||function(r){return Ka.call(r)==="[object Array]"};function xt(e){return typeof e=="function"}function Ja(e){return Le(e)?"array":typeof e}function Rt(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Gn(e,r){return e!=null&&typeof e=="object"&&r in e}function Xa(e,r){return e!=null&&typeof e!="object"&&e.hasOwnProperty&&e.hasOwnProperty(r)}var Ya=RegExp.prototype.test;function Qa(e,r){return Ya.call(e,r)}var Za=/\S/;function el(e){return!Qa(Za,e)}var rl={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function tl(e){return String(e).replace(/[&<>"'`=\/]/g,function(t){return rl[t]})}var nl=/\s*/,ol=/\s+/,Kn=/\s*=/,il=/\s*\}/,sl=/#|\^|\/|>|\{|&|=|!/;function al(e,r){if(!e)return[];var t=!1,n=[],o=[],i=[],s=!1,a=!1,l="",c=0;function u(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var m,y,R;function E(z){if(typeof z=="string"&&(z=z.split(ol,2)),!Le(z)||z.length!==2)throw new Error("Invalid tags: "+z);m=new RegExp(Rt(z[0])+"\\s*"),y=new RegExp("\\s*"+Rt(z[1])),R=new RegExp("\\s*"+Rt("}"+z[1]))}E(r||te.tags);for(var g=new lr(e),O,P,H,Te,De,pe;!g.eos();){if(O=g.pos,H=g.scanUntil(m),H)for(var L=0,J=H.length;L<J;++L)Te=H.charAt(L),el(Te)?(i.push(o.length),l+=Te):(a=!0,t=!0,l+=" "),o.push(["text",Te,O,O+1]),O+=1,Te===`
|
|
9
|
+
`&&(u(),l="",c=0,t=!1);if(!g.scan(m))break;if(s=!0,P=g.scan(sl)||"name",g.scan(nl),P==="="?(H=g.scanUntil(Kn),g.scan(Kn),g.scanUntil(y)):P==="{"?(H=g.scanUntil(R),g.scan(il),g.scanUntil(y),P="&"):H=g.scanUntil(y),!g.scan(y))throw new Error("Unclosed tag at "+g.pos);if(P==">"?De=[P,H,O,g.pos,l,c,t]:De=[P,H,O,g.pos],c++,o.push(De),P==="#"||P==="^")n.push(De);else if(P==="/"){if(pe=n.pop(),!pe)throw new Error('Unopened section "'+H+'" at '+O);if(pe[1]!==H)throw new Error('Unclosed section "'+pe[1]+'" at '+O)}else P==="name"||P==="{"||P==="&"?a=!0:P==="="&&E(H)}if(u(),pe=n.pop(),pe)throw new Error('Unclosed section "'+pe[1]+'" at '+g.pos);return cl(ll(o))}function ll(e){for(var r=[],t,n,o=0,i=e.length;o<i;++o)t=e[o],t&&(t[0]==="text"&&n&&n[0]==="text"?(n[1]+=t[1],n[3]=t[3]):(r.push(t),n=t));return r}function cl(e){for(var r=[],t=r,n=[],o,i,s=0,a=e.length;s<a;++s)switch(o=e[s],o[0]){case"#":case"^":t.push(o),n.push(o),t=o[4]=[];break;case"/":i=n.pop(),i[5]=o[2],t=n.length>0?n[n.length-1][4]:r;break;default:t.push(o)}return r}function lr(e){this.string=e,this.tail=e,this.pos=0}lr.prototype.eos=function(){return this.tail===""};lr.prototype.scan=function(r){var t=this.tail.match(r);if(!t||t.index!==0)return"";var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n};lr.prototype.scanUntil=function(r){var t=this.tail.search(r),n;switch(t){case-1:n=this.tail,this.tail="";break;case 0:n="";break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function Oe(e,r){this.view=e,this.cache={".":this.view},this.parent=r}Oe.prototype.push=function(r){return new Oe(r,this)};Oe.prototype.lookup=function(r){var t=this.cache,n;if(t.hasOwnProperty(r))n=t[r];else{for(var o=this,i,s,a,l=!1;o;){if(r.indexOf(".")>0)for(i=o.view,s=r.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=Gn(i,s[a])||Xa(i,s[a])),i=i[s[a++]];else i=o.view[r],l=Gn(o.view,r);if(l){n=i;break}o=o.parent}t[r]=n}return xt(n)&&(n=n.call(this.view)),n};function X(){this.templateCache={_cache:{},set:function(r,t){this._cache[r]=t},get:function(r){return this._cache[r]},clear:function(){this._cache={}}}}X.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};X.prototype.parse=function(r,t){var n=this.templateCache,o=r+":"+(t||te.tags).join(":"),i=typeof n<"u",s=i?n.get(o):void 0;return s==null&&(s=al(r,t),i&&n.set(o,s)),s};X.prototype.render=function(r,t,n,o){var i=this.getConfigTags(o),s=this.parse(r,i),a=t instanceof Oe?t:new Oe(t,void 0);return this.renderTokens(s,a,n,r,o)};X.prototype.renderTokens=function(r,t,n,o,i){for(var s="",a,l,c,u=0,m=r.length;u<m;++u)c=void 0,a=r[u],l=a[0],l==="#"?c=this.renderSection(a,t,n,o,i):l==="^"?c=this.renderInverted(a,t,n,o,i):l===">"?c=this.renderPartial(a,t,n,i):l==="&"?c=this.unescapedValue(a,t):l==="name"?c=this.escapedValue(a,t,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};X.prototype.renderSection=function(r,t,n,o,i){var s=this,a="",l=t.lookup(r[1]);function c(y){return s.render(y,t,n,i)}if(l){if(Le(l))for(var u=0,m=l.length;u<m;++u)a+=this.renderTokens(r[4],t.push(l[u]),n,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(r[4],t.push(l),n,o,i);else if(xt(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(t.view,o.slice(r[3],r[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(r[4],t,n,o,i);return a}};X.prototype.renderInverted=function(r,t,n,o,i){var s=t.lookup(r[1]);if(!s||Le(s)&&s.length===0)return this.renderTokens(r[4],t,n,o,i)};X.prototype.indentPartial=function(r,t,n){for(var o=t.replace(/[^ \t]/g,""),i=r.split(`
|
|
10
10
|
`),s=0;s<i.length;s++)i[s].length&&(s>0||!n)&&(i[s]=o+i[s]);return i.join(`
|
|
11
|
-
`)};X.prototype.renderPartial=function(t,r,n,o){if(n){var i=this.getConfigTags(o),s=xr(n)?n(t[1]):n[t[1]];if(s!=null){var a=t[6],l=t[5],c=t[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var m=this.parse(u,i);return this.renderTokens(m,r,n,u,o)}}};X.prototype.unescapedValue=function(t,r){var n=r.lookup(t[1]);if(n!=null)return n};X.prototype.escapedValue=function(t,r,n){var o=this.getConfigEscape(n)||re.escape,i=r.lookup(t[1]);if(i!=null)return typeof i=="number"&&o===re.escape?String(i):o(i)};X.prototype.rawValue=function(t){return t[1]};X.prototype.getConfigTags=function(t){return Le(t)?t:t&&typeof t=="object"?t.tags:void 0};X.prototype.getConfigEscape=function(t){if(t&&typeof t=="object"&&!Le(t))return t.escape};var re={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){at.templateCache=e},get templateCache(){return at.templateCache}},at=new X;re.clearCache=function(){return at.clearCache()};re.parse=function(t,r){return at.parse(t,r)};re.render=function(t,r,n,o){if(typeof t!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Ja(t)+'" was given as the first argument for mustache#render(template, view, partials)');return at.render(t,r,n,o)};re.escape=rl;re.Scanner=lt;re.Context=Oe;re.Writer=X;var Jn=re;function Er({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([t,r])=>[t,dl({def:r,name:t})]))}var ul={boolean:!1,number:0,string:""};function dl({def:e,name:t}){if(e.type==="env"){let r=process.env[e.key];if(r==null)throw new Error(`Environment variable "${e.key}" not set for variable "${t}"`);return r}return e.default??ul[e.type]??""}function Ct({ref:e,variables:t}){if(e.type==="static")return e.value;let r=t[e.name];if(r==null||typeof r=="object")throw new Error(`Variable "${e.name}" is not defined`);return r}function Y({ref:e,variables:t}){let r=String(Ct({ref:e,variables:t}));return It({raw:r,variables:t})}function At({ref:e,variables:t}){let r=Ct({ref:e,variables:t});return typeof r=="string"?It({raw:r,variables:t}):r}function It({raw:e,variables:t}){return Jn.render(e,t,{},{escape:r=>r})}function Cr({ref:e,variables:t}){let r=Ct({ref:e,variables:t});if(typeof r=="number")return r;let n=Number(r);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(r)}" to number`);return n}function _e({name:e,store:t,value:r}){return{...t,[e]:r}}function V({locator:e,page:t,variables:r}){switch(e.by){case"testId":return t.getByTestId(Xn(e.value,r));case"role":return t.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Xn(e.name,r)})}}function Xn(e,t){return t==null?e:It({raw:e,variables:t})}async function Yn({node:e,page:t,timeout:r}){await V({locator:e.source,page:t,variables:void 0}).dragTo(V({locator:e.target,page:t,variables:void 0}),{timeout:r})}async function Qn({node:e,page:t,timeout:r}){await V({locator:e.locator,page:t,variables:void 0}).click({button:"right",timeout:r})}function Zn({node:e,page:t,variables:r}){return t.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:r}}async function eo({node:e,page:t,variables:r}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:r}),i=JSON.stringify(o);return await st({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:t,timeoutMs:void 0}),{variables:r}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await st({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:t,timeoutMs:void 0})??"";return{variables:_e({name:e.variable,store:r,value:n})}}async function to({node:e,page:t}){let r=t.context();e.state==="granted"?await r.grantPermissions([e.permission]):await r.clearPermissions()}async function Ar({node:e,page:t,timeout:r,variables:n}){switch(e.type){case"click":return await V({locator:e.locator,page:t,variables:n}).click({modifiers:e.modifier==null?void 0:[e.modifier],timeout:r}),{variables:n};case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return fl({node:e,page:t,timeout:r,variables:n});case"rightClick":return await Qn({node:e,page:t,timeout:r}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await t.goto(o,{timeout:r,waitUntil:"domcontentloaded"}),await t.waitForLoadState("load",{timeout:r}),await t.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:r}),await st({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:t,timeoutMs:void 0}),{variables:n}}case"fill":return yl({node:e,page:t,timeout:r,variables:n});case"select":return hl({node:e,page:t,timeout:r,variables:n});case"type":return wl({node:e,page:t,timeout:r,variables:n});case"press":return await gl({node:e,page:t,timeout:r}),{variables:n};case"drag":return await Yn({node:e,page:t,timeout:r}),{variables:n};case"upload":return bl({node:e,page:t,timeout:r,variables:n});case"extractText":return Sl({node:e,page:t,timeout:r,variables:n});case"setVariable":{let o=At({ref:e.value,variables:n});return{variables:_e({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await t.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Zn({node:e,page:t,variables:n});case"clipboard":return eo({node:e,page:t,variables:n});case"setPermission":return await to({node:e,page:t}),{variables:n}}}var ml={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function fl({node:e,page:t,timeout:r,variables:n}){return await V({locator:e.locator,page:t,variables:n})[ml[e.type]]({timeout:r}),{variables:n}}async function gl({node:e,page:t,timeout:r}){e.locator==null?await t.keyboard.press(e.key):await V({locator:e.locator,page:t,variables:void 0}).press(e.key,{timeout:r})}async function yl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).fill(o,{timeout:r}),{variables:n}}async function hl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).selectOption(o,{timeout:r}),{variables:n}}async function wl({node:e,page:t,timeout:r,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:t,variables:n}).pressSequentially(o,{timeout:r}),{variables:n}}async function bl({node:e,page:t,timeout:r,variables:n}){let o=e.files.map(i=>vl(i));return await V({locator:e.locator,page:t,variables:n}).setInputFiles(o,{timeout:r}),{variables:n}}function vl(e){return pl.join(qn(),e)}async function Sl({node:e,page:t,timeout:r,variables:n}){let o=await V({locator:e.locator,page:t,variables:n}).textContent({timeout:r});if(o==null)throw new Error("extractText: element had no text content");return{variables:_e({name:e.variable,store:n,value:o})}}var G={};Ua(G,{default:()=>kl});Sr(G,Qb);import*as Qb from"playwright/test";import{default as kl}from"playwright/test";async function Ir({expected:e,locator:t,operator:r,timeout:n}){return await ct({expected:e,operator:r,timeout:n,read:async()=>await t.textContent()??""}),ut({expected:e,label:"Text",operator:r,read:async()=>await t.textContent()??""})}async function Tr({expected:e,operator:t,page:r,timeout:n}){return await ct({expected:e,operator:t,timeout:n,read:()=>Promise.resolve(r.url())}),ut({expected:e,label:"URL",operator:t,read:()=>Promise.resolve(r.url())})}async function ro({expected:e,operator:t,page:r,timeout:n}){return await ct({expected:e,operator:t,timeout:n,read:()=>r.title()}),ut({expected:e,label:"Title",operator:t,read:()=>r.title()})}async function $r({expected:e,locator:t,operator:r,timeout:n}){await G.expect.poll(async()=>fo({actual:await t.count(),expected:e,operator:r}),{timeout:n}).toBe(!0).catch(()=>{});let o=await t.count();return mo({actual:o,expected:e,label:"Count",operator:r})}async function jr({expected:e,locator:t,operator:r,timeout:n}){return await ct({expected:e,operator:r,timeout:n,read:()=>t.inputValue()}),ut({expected:e,label:"Value",operator:r,read:()=>t.inputValue()})}async function Nr({locator:e,timeout:t}){return we({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,G.expect)(e).toBeVisible({timeout:t})})}async function Dr({locator:e,timeout:t}){return we({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,G.expect)(e).toBeHidden({timeout:t})})}async function no({attribute:e,expected:t,locator:r,operator:n,timeout:o}){return await ct({expected:t,operator:n,timeout:o,read:async()=>await r.getAttribute(e)??""}),ut({expected:t,label:`Attribute "${e}"`,operator:n,read:async()=>await r.getAttribute(e)??""})}async function oo({locator:e,timeout:t}){return we({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,G.expect)(e).toBeEnabled({timeout:t})})}async function io({locator:e,timeout:t}){return we({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,G.expect)(e).toBeDisabled({timeout:t})})}async function so({locator:e,timeout:t}){return we({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,G.expect)(e).toBeChecked({timeout:t})})}async function ao({locator:e,timeout:t}){return we({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,G.expect)(e).not.toBeChecked({timeout:t})})}async function lo({locator:e,timeout:t}){return we({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,G.expect)(e).toBeFocused({timeout:t})})}async function co({locator:e,timeout:t}){return we({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,G.expect)(e).not.toBeFocused({timeout:t})})}async function we({description:e,failureDetail:t,run:r}){try{return await r(),{description:e,detail:void 0,status:"passed"}}catch{return{description:e,detail:t,status:"failed"}}}async function ct({expected:e,operator:t,read:r,timeout:n}){await G.expect.poll(async()=>{let o=await r().catch(()=>"");return po({actual:o,expected:e,operator:t})},{timeout:n}).toBe(!0).catch(()=>{})}async function ut({expected:e,label:t,operator:r,read:n}){try{let o=await n();return uo({actual:o,expected:e,label:t,operator:r})}catch(o){let i=`${t} ${r} "${e}"`,s=o instanceof Error?o.message:String(o);return{description:i,detail:`Read failed: ${Pl(s)}`,status:"failed"}}}function Pl(e){let t=e.indexOf(`
|
|
12
|
-
`);return
|
|
11
|
+
`)};X.prototype.renderPartial=function(r,t,n,o){if(n){var i=this.getConfigTags(o),s=xt(n)?n(r[1]):n[r[1]];if(s!=null){var a=r[6],l=r[5],c=r[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var m=this.parse(u,i);return this.renderTokens(m,t,n,u,o)}}};X.prototype.unescapedValue=function(r,t){var n=t.lookup(r[1]);if(n!=null)return n};X.prototype.escapedValue=function(r,t,n){var o=this.getConfigEscape(n)||te.escape,i=t.lookup(r[1]);if(i!=null)return typeof i=="number"&&o===te.escape?String(i):o(i)};X.prototype.rawValue=function(r){return r[1]};X.prototype.getConfigTags=function(r){return Le(r)?r:r&&typeof r=="object"?r.tags:void 0};X.prototype.getConfigEscape=function(r){if(r&&typeof r=="object"&&!Le(r))return r.escape};var te={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){ar.templateCache=e},get templateCache(){return ar.templateCache}},ar=new X;te.clearCache=function(){return ar.clearCache()};te.parse=function(r,t){return ar.parse(r,t)};te.render=function(r,t,n,o){if(typeof r!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Ja(r)+'" was given as the first argument for mustache#render(template, view, partials)');return ar.render(r,t,n,o)};te.escape=tl;te.Scanner=lr;te.Context=Oe;te.Writer=X;var Jn=te;function Et({defs:e}){return e==null?{}:Object.fromEntries(Object.entries(e).map(([r,t])=>[r,dl({def:t,name:r})]))}var ul={boolean:!1,number:0,string:""};function dl({def:e,name:r}){if(e.type==="env"){let t=process.env[e.key];if(t==null)throw new Error(`Environment variable "${e.key}" not set for variable "${r}"`);return t}return e.default??ul[e.type]??""}function Cr({ref:e,variables:r}){if(e.type==="static")return e.value;let t=r[e.name];if(t==null||typeof t=="object")throw new Error(`Variable "${e.name}" is not defined`);return t}function Y({ref:e,variables:r}){let t=String(Cr({ref:e,variables:r}));return Ir({raw:t,variables:r})}function Ar({ref:e,variables:r}){let t=Cr({ref:e,variables:r});return typeof t=="string"?Ir({raw:t,variables:r}):t}function Ir({raw:e,variables:r}){return Jn.render(e,r,{},{escape:t=>t})}function Ct({ref:e,variables:r}){let t=Cr({ref:e,variables:r});if(typeof t=="number")return t;let n=Number(t);if(Number.isNaN(n))throw new TypeError(`Cannot convert "${String(t)}" to number`);return n}function _e({name:e,store:r,value:t}){return{...r,[e]:t}}function V({locator:e,page:r,variables:t}){switch(e.by){case"testId":return r.getByTestId(Xn(e.value,t));case"role":return r.getByRole(e.role,{exact:!0,name:e.name==null?void 0:Xn(e.name,t)})}}function Xn(e,r){return r==null?e:Ir({raw:e,variables:r})}async function Yn({node:e,page:r,timeout:t}){await V({locator:e.source,page:r,variables:void 0}).dragTo(V({locator:e.target,page:r,variables:void 0}),{timeout:t})}async function Qn({node:e,page:r,timeout:t}){await V({locator:e.locator,page:r,variables:void 0}).click({button:"right",timeout:t})}function Zn({node:e,page:r,variables:t}){return r.once("dialog",async n=>{e.action==="accept"?await n.accept(e.promptText??void 0):await n.dismiss()}),{variables:t}}async function eo({node:e,page:r,variables:t}){if(e.action==="write"){if(e.value==null)throw new Error("clipboard write requires a value");let o=Y({ref:e.value,variables:t}),i=JSON.stringify(o);return await sr({awaitPromise:!0,expression:`navigator.clipboard.writeText(${i})`,label:"clipboard.writeText",page:r,timeoutMs:void 0}),{variables:t}}if(e.variable==null)throw new Error("clipboard read requires a variable name to store the result");let n=await sr({awaitPromise:!0,expression:"navigator.clipboard.readText()",label:"clipboard.readText",page:r,timeoutMs:void 0})??"";return{variables:_e({name:e.variable,store:t,value:n})}}async function ro({node:e,page:r}){let t=r.context();e.state==="granted"?await t.grantPermissions([e.permission]):await t.clearPermissions()}async function At({node:e,page:r,timeout:t,variables:n}){switch(e.type){case"click":return await V({locator:e.locator,page:r,variables:n}).click({modifiers:e.modifier==null?void 0:[e.modifier],timeout:t}),{variables:n};case"check":case"uncheck":case"clear":case"dblclick":case"focus":case"hover":case"scrollIntoView":return fl({node:e,page:r,timeout:t,variables:n});case"rightClick":return await Qn({node:e,page:r,timeout:t}),{variables:n};case"goto":{let o=Y({ref:e.url,variables:n});return await r.goto(o,{timeout:t,waitUntil:"domcontentloaded"}),await r.waitForLoadState("load",{timeout:t}),await r.waitForFunction("document.body != null && document.body.childElementCount > 0 && (document.body.textContent?.trim().length ?? 0) > 0",void 0,{timeout:t}),await sr({awaitPromise:!0,expression:"new Promise((resolve) => { requestAnimationFrame(() => requestAnimationFrame(() => resolve(undefined))); })",label:"goto raf-settle",page:r,timeoutMs:void 0}),{variables:n}}case"fill":return yl({node:e,page:r,timeout:t,variables:n});case"select":return hl({node:e,page:r,timeout:t,variables:n});case"type":return wl({node:e,page:r,timeout:t,variables:n});case"press":return await gl({node:e,page:r,timeout:t}),{variables:n};case"drag":return await Yn({node:e,page:r,timeout:t}),{variables:n};case"upload":return bl({node:e,page:r,timeout:t,variables:n});case"extractText":return Sl({node:e,page:r,timeout:t,variables:n});case"setVariable":{let o=Ar({ref:e.value,variables:n});return{variables:_e({name:e.variable,store:n,value:o})}}case"fail":throw new Error(e.message);case"setViewport":return await r.setViewportSize({height:e.height,width:e.width}),{variables:n};case"handleDialog":return Zn({node:e,page:r,variables:n});case"clipboard":return eo({node:e,page:r,variables:n});case"setPermission":return await ro({node:e,page:r}),{variables:n}}}var ml={check:"check",clear:"clear",click:"click",dblclick:"dblclick",focus:"focus",hover:"hover",scrollIntoView:"scrollIntoViewIfNeeded",uncheck:"uncheck"};async function fl({node:e,page:r,timeout:t,variables:n}){return await V({locator:e.locator,page:r,variables:n})[ml[e.type]]({timeout:t}),{variables:n}}async function gl({node:e,page:r,timeout:t}){e.locator==null?await r.keyboard.press(e.key):await V({locator:e.locator,page:r,variables:void 0}).press(e.key,{timeout:t})}async function yl({node:e,page:r,timeout:t,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:r,variables:n}).fill(o,{timeout:t}),{variables:n}}async function hl({node:e,page:r,timeout:t,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:r,variables:n}).selectOption(o,{timeout:t}),{variables:n}}async function wl({node:e,page:r,timeout:t,variables:n}){let o=Y({ref:e.value,variables:n});return await V({locator:e.locator,page:r,variables:n}).pressSequentially(o,{timeout:t}),{variables:n}}async function bl({node:e,page:r,timeout:t,variables:n}){let o=e.files.map(i=>vl(i));return await V({locator:e.locator,page:r,variables:n}).setInputFiles(o,{timeout:t}),{variables:n}}function vl(e){return pl.join(qn(),e)}async function Sl({node:e,page:r,timeout:t,variables:n}){let o=await V({locator:e.locator,page:r,variables:n}).textContent({timeout:t});if(o==null)throw new Error("extractText: element had no text content");return{variables:_e({name:e.variable,store:n,value:o})}}var G={};Ua(G,{default:()=>kl});St(G,Qb);import*as Qb from"playwright/test";import{default as kl}from"playwright/test";async function It({expected:e,locator:r,operator:t,timeout:n}){return await cr({expected:e,operator:t,timeout:n,read:async()=>await r.textContent()??""}),ur({expected:e,label:"Text",operator:t,read:async()=>await r.textContent()??""})}async function Tt({expected:e,operator:r,page:t,timeout:n}){return await cr({expected:e,operator:r,timeout:n,read:()=>Promise.resolve(t.url())}),ur({expected:e,label:"URL",operator:r,read:()=>Promise.resolve(t.url())})}async function to({expected:e,operator:r,page:t,timeout:n}){return await cr({expected:e,operator:r,timeout:n,read:()=>t.title()}),ur({expected:e,label:"Title",operator:r,read:()=>t.title()})}async function $t({expected:e,locator:r,operator:t,timeout:n}){await G.expect.poll(async()=>fo({actual:await r.count(),expected:e,operator:t}),{timeout:n}).toBe(!0).catch(()=>{});let o=await r.count();return mo({actual:o,expected:e,label:"Count",operator:t})}async function jt({expected:e,locator:r,operator:t,timeout:n}){return await cr({expected:e,operator:t,timeout:n,read:()=>r.inputValue()}),ur({expected:e,label:"Value",operator:t,read:()=>r.inputValue()})}async function Nt({locator:e,timeout:r}){return we({description:"Element is visible",failureDetail:"Element not visible",run:()=>(0,G.expect)(e).toBeVisible({timeout:r})})}async function Dt({locator:e,timeout:r}){return we({description:"Element is not visible",failureDetail:"Element still visible",run:()=>(0,G.expect)(e).toBeHidden({timeout:r})})}async function no({attribute:e,expected:r,locator:t,operator:n,timeout:o}){return await cr({expected:r,operator:n,timeout:o,read:async()=>await t.getAttribute(e)??""}),ur({expected:r,label:`Attribute "${e}"`,operator:n,read:async()=>await t.getAttribute(e)??""})}async function oo({locator:e,timeout:r}){return we({description:"Element is enabled",failureDetail:"Element is disabled or not found",run:()=>(0,G.expect)(e).toBeEnabled({timeout:r})})}async function io({locator:e,timeout:r}){return we({description:"Element is disabled",failureDetail:"Element is enabled or not found",run:()=>(0,G.expect)(e).toBeDisabled({timeout:r})})}async function so({locator:e,timeout:r}){return we({description:"Element is checked",failureDetail:"Element is not checked",run:()=>(0,G.expect)(e).toBeChecked({timeout:r})})}async function ao({locator:e,timeout:r}){return we({description:"Element is not checked",failureDetail:"Element is checked",run:()=>(0,G.expect)(e).not.toBeChecked({timeout:r})})}async function lo({locator:e,timeout:r}){return we({description:"Element is focused",failureDetail:"Element is not focused",run:()=>(0,G.expect)(e).toBeFocused({timeout:r})})}async function co({locator:e,timeout:r}){return we({description:"Element is not focused",failureDetail:"Element is focused",run:()=>(0,G.expect)(e).not.toBeFocused({timeout:r})})}async function we({description:e,failureDetail:r,run:t}){try{return await t(),{description:e,detail:void 0,status:"passed"}}catch{return{description:e,detail:r,status:"failed"}}}async function cr({expected:e,operator:r,read:t,timeout:n}){await G.expect.poll(async()=>{let o=await t().catch(()=>"");return po({actual:o,expected:e,operator:r})},{timeout:n}).toBe(!0).catch(()=>{})}async function ur({expected:e,label:r,operator:t,read:n}){try{let o=await n();return uo({actual:o,expected:e,label:r,operator:t})}catch(o){let i=`${r} ${t} "${e}"`,s=o instanceof Error?o.message:String(o);return{description:i,detail:`Read failed: ${Pl(s)}`,status:"failed"}}}function Pl(e){let r=e.indexOf(`
|
|
12
|
+
`);return r===-1?e:e.slice(0,r)}function uo(e){let r=`${e.label} ${e.operator} "${e.expected}"`,t=po(e),n=t?void 0:`Got: "${e.actual}"`;return{description:r,detail:n,status:t?"passed":"failed"}}function po({actual:e,expected:r,operator:t}){return t==="equals"?e===r:t==="notEquals"?e!==r:t==="contains"?e.includes(r):t==="startsWith"?e.startsWith(r):t==="endsWith"?e.endsWith(r):new RegExp(r).test(e)}function mo(e){let r=`${e.label} ${e.operator} ${String(e.expected)}`,t=fo(e),n=t?void 0:`Got: ${String(e.actual)}`;return{description:r,detail:n,status:t?"passed":"failed"}}function fo({actual:e,expected:r,operator:t}){return t==="equals"?e===r:t==="notEquals"?e!==r:t==="greaterThan"?e>r:t==="greaterThanOrEqual"?e>=r:t==="lessThan"?e<r:e<=r}import{execFile as xl}from"child_process";import{createRequire as El}from"module";import go from"fs";import yo from"path";import{chromium as ho}from"playwright";import nv from"fs";import iv from"path";import Rl from"pino";var f=Rl({level:process.env.LOG_LEVEL??"info",transport:{options:{ignore:"pid,hostname"},target:"pino-pretty"}});async function Ue({headed:e}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";try{return await ho.launch({headless:!e})}catch(r){throw Cl(r)?new Error(`Playwright browsers are not installed. Run:
|
|
13
13
|
|
|
14
14
|
npx playwright install chromium
|
|
15
|
-
`):
|
|
15
|
+
`):r}}async function Ot(){let e=ho.executablePath();if(go.existsSync(e))return;f.info("Chromium not found. Installing via Playwright...");let r=El(import.meta.url),t=yo.dirname(r.resolve("playwright/package.json")),n=yo.join(t,"cli.js");if(await new Promise((o,i)=>{xl(process.execPath,[n,"install","chromium"],s=>{if(s!=null){i(new Error(`Playwright install failed: ${s.message}`));return}o()})}),!go.existsSync(e))throw new Error(`Playwright browser installation failed. Try running manually:
|
|
16
16
|
|
|
17
17
|
npx playwright install chromium
|
|
18
|
-
`);f.info("\u2713 Chromium installed")}function Cl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as Nl,rm as Dl,stat as Ol}from"fs/promises";import bv from"os";import vo from"path";import{graphql as Ll}from"gql.tada";import{print as Al}from"graphql";var Il=15e3,Ve=class extends Error{errors;constructor(
|
|
18
|
+
`);f.info("\u2713 Chromium installed")}function Cl(e){return e instanceof Error?e.message.includes("Executable doesn't exist"):!1}import{readdir as Nl,rm as Dl,stat as Ol}from"fs/promises";import bv from"os";import vo from"path";import{graphql as Ll}from"gql.tada";import{print as Al}from"graphql";var Il=15e3,Ve=class extends Error{errors;constructor(r){super(r.map(t=>t.message).join(", ")),this.name="GqlRequestError",this.errors=r}};async function h(e){let r=Al(e.document),t=JSON.stringify({query:r,variables:e.variables}),n=`${e.config.ripploServerUrl}/graphql`,o;try{o=await fetch(n,{body:t,headers:{Authorization:`Bearer ${e.config.token}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(Il)})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Failed to connect to Ripplo server at ${e.config.ripploServerUrl}. Check the server is running and reachable. Details: ${a}`)}let i=await Tl({res:o,url:n});if(!$l(i))throw new Error("Invalid GraphQL response");if(jl(i))throw new Ve(i.errors);if(i.data==null)throw new Error("No data returned from server");return i.data}async function Tl({res:e,url:r}){let t=await e.text();if(t.length===0)throw new Error(`Empty response from Ripplo server at ${r} (status ${String(e.status)}). The server may have restarted or the request was rejected before a body was sent.`);try{return JSON.parse(t)}catch{throw new Error(`Non-JSON response from Ripplo server at ${r} (status ${String(e.status)}): ${t.slice(0,200)}`)}}function $l(e){return typeof e=="object"&&e!=null&&("data"in e||"errors"in e)}function jl(e){return Array.isArray(e.errors)&&e.errors.length>0}var wo=vo.join(process.cwd(),".ripplo","debug"),bo=360*60*1e3,Rv=Ll(`
|
|
19
19
|
mutation RevokeCurrentCliToken {
|
|
20
20
|
revokeCurrentCliToken
|
|
21
21
|
}
|
|
22
|
-
`);async function
|
|
23
|
-
`))}async function Hl(e,t){let r=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(_l)}),f.debug("App URL reachability check ok (attempt %d, %dms)",t+1,Math.round(performance.now()-r)),null}catch(n){return f.debug("App URL reachability check attempt %d failed after %dms: %s",t+1,Math.round(performance.now()-r),n instanceof Error?n.message:String(n)),n}}function Bl(e){return new Promise(t=>setTimeout(t,e))}import{Agent as Wl,RetryAgent as ql,setGlobalDispatcher as zl}from"undici";var Gl=1500,Kl=4e3,Jl=3,Xl=50,Yl=100,So=!1;function Ur(){if(So)return;So=!0;let e=new Wl({connections:Yl,keepAliveMaxTimeout:Kl,keepAliveTimeout:Gl}),t=new ql(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:Jl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Xl});zl(t)}var ti=kr($t(),1);import{z as _d}from"zod";import{z as jt}from"zod";var ac=jt.object({__codec:jt.string().min(1),data:jt.unknown(),version:jt.number().int().positive()}),Nt=class extends Error{codec;currentVersion;gotVersion;constructor(t){super(`Unsupported ${t.codec} version ${String(t.gotVersion)} (current ${String(t.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=t.codec,this.currentVersion=t.currentVersion,this.gotVersion=t.gotVersion}},Dt=class extends Error{constructor(t){super(`Codec mismatch: expected "${t.expected}", got "${t.got}"`),this.name="CodecMismatchError"}};function Ot(e){return Ro({legacy:void 0,migrators:[],name:e,schemas:[]})}function Ro(e){return{initial:t=>Hr(t,{...e,schemas:[t]}),legacy:t=>Ro({...e,legacy:t})}}function Hr(e,t){return{build:()=>lc(e,t),legacy:r=>Hr(e,{...t,legacy:r}),upgrade:(r,n)=>{let o=n;return Hr(r,{...t,migrators:[...t.migrators,o],schemas:[...t.schemas,r]})}}}function lc(e,t){let r=t.schemas.length;return{currentVersion:r,name:t.name,decode:n=>cc(e,t,n),encode:n=>({__codec:t.name,data:n,version:r})}}function cc(e,t,r){let{data:n,version:o}=uc(t,r),i=xo(t,n,o);return e.parse(i)}function uc(e,t){let r=ac.safeParse(t);if(r.success){if(r.data.__codec!==e.name)throw new Dt({expected:e.name,got:r.data.__codec});return{data:r.data.data,version:r.data.version}}if(e.legacy!=null&&e.legacy.detect(t))return{data:t,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function xo(e,t,r){let n=e.schemas.length;if(r>n)throw new Nt({codec:e.name,currentVersion:n,gotVersion:r});if(r===n)return t;let o=e.schemas[r-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(r)}; cannot migrate.`);let i=o.parse(t),s=e.migrators[r-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(r)} \u2192 v${String(r+1)}.`);return xo(e,s(i),r+1)}import{z as Io}from"zod";import{z as Fe}from"zod";var Br=Fe.object({depends:Fe.array(Fe.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Fe.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Fe.array(Fe.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as d}from"zod";import{z as be}from"zod";var dc=be.object({by:be.literal("testId"),value:be.string().min(1)}),pc=be.object({by:be.literal("role"),name:be.string().optional(),role:be.string().min(1)}),C=be.discriminatedUnion("by",[dc,pc]);import{z as Eo}from"zod";var ve=Eo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Lt=Eo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var mc=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_t=N.object({name:N.string().min(1),type:N.literal("variable")}),Ut=N.discriminatedUnion("type",[mc,_t]),Q=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),_t]),Vt=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),_t]),Wr=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_t]);import{z as Z}from"zod";var Ft=Z.discriminatedUnion("type",[Z.object({default:Z.string().optional(),type:Z.literal("string")}),Z.object({default:Z.number().optional(),type:Z.literal("number")}),Z.object({default:Z.boolean().optional(),type:Z.literal("boolean")}),Z.object({key:Z.string().min(1),type:Z.literal("env")})]);var v={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Co=500,fc=d.object({...v,type:d.literal("goto"),url:Q}),gc=d.object({...v,locator:C,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),yc=d.object({...v,locator:C,type:d.literal("fill"),value:Q}),hc=d.object({...v,locator:C,type:d.literal("select"),value:Q}),wc=d.object({...v,locator:C,type:d.literal("hover")}),bc=d.object({...v,key:d.string().min(1),locator:C.optional(),type:d.literal("press")}),vc=d.object({...v,locator:C,type:d.literal("check")}),Sc=d.object({...v,locator:C,type:d.literal("uncheck")}),kc=d.object({...v,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Pc=d.object({...v,message:d.string().min(1),type:d.literal("fail")}),Rc=d.object({...v,type:d.literal("setVariable"),value:Ut,variable:d.string().min(1)}),xc=d.object({...v,locator:C,type:d.literal("extractText"),variable:d.string().min(1)}),Ec=d.object({...v,files:d.array(d.string()).min(1),locator:C,type:d.literal("upload")}),Cc=d.object({...v,locator:C,type:d.literal("dblclick")}),Ac=d.object({...v,source:C,target:C,type:d.literal("drag")}),Ic=d.object({...v,locator:C,type:d.literal("scrollIntoView")}),Tc=d.object({...v,locator:C,type:d.literal("type"),value:Q}),$c=d.object({...v,locator:C,type:d.literal("focus")}),jc=d.object({...v,locator:C,type:d.literal("clear")}),Nc=d.object({...v,locator:C,type:d.literal("rightClick")}),Dc=d.object({...v,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Oc=d.object({...v,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:Q.optional(),variable:d.string().min(1).optional()}),Lc=d.object({...v,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),_c=d.object({...v,locator:C,type:d.literal("assertVisible")}),Uc=d.object({...v,locator:C,type:d.literal("assertNotVisible")}),Vc=d.object({...v,expected:Q,locator:C,operator:ve,type:d.literal("assertText")}),Fc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertUrl")}),Mc=d.object({...v,expected:Vt,locator:C,operator:Lt,type:d.literal("assertCount")}),Hc=d.object({...v,expected:Q,locator:C,operator:ve,type:d.literal("assertValue")}),Bc=d.object({...v,attribute:d.string().min(1),expected:Q,locator:C,operator:ve,type:d.literal("assertAttribute")}),Wc=d.object({...v,locator:C,type:d.literal("assertEnabled")}),qc=d.object({...v,locator:C,type:d.literal("assertDisabled")}),zc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertTitle")}),Gc=d.object({...v,locator:C,type:d.literal("assertChecked")}),Kc=d.object({...v,locator:C,type:d.literal("assertNotChecked")}),Jc=d.object({...v,locator:C,type:d.literal("assertFocused")}),Xc=d.object({...v,locator:C,type:d.literal("assertNotFocused")}),Yc=d.object({...v,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Wr),type:d.literal("assertObserver")}),Ao=d.discriminatedUnion("type",[fc,gc,yc,hc,wc,bc,vc,Sc,_c,Uc,Vc,Fc,Mc,Hc,Bc,Wc,qc,kc,Pc,Rc,xc,Ec,Cc,Ac,Ic,Tc,$c,jc,Nc,Dc,Oc,Lc,zc,Gc,Kc,Jc,Xc,Yc]),Mt=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Ao).refine(e=>Object.keys(e).length<=Co,`Workflow has more than ${String(Co)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Ft).optional()});var Qc=Io.record(Io.string().max(200),Br),Zc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},eu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},qr=Ot("workflow-spec").legacy(Zc).initial(Mt).build(),tu=Ot("precondition-map").legacy(eu).initial(Qc).build();import{z as zr}from"zod";var To=["fast","slow","async"],ru=zr.object({budget:zr.enum(To).describe("Polling budget tier: fast | slow | async"),description:zr.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function Ht(e){return e.label??`${e.type} (${e.id})`}import{graphql as ri,readFragment as Ud}from"gql.tada";function jo(){let e,t=!1;function r(o){e=o,t&&$o(o)}async function n(){t||(t=!0,e!=null&&await $o(e))}return{attachContext:r,fire:n,fired:()=>t}}async function $o(e){await e.close().catch(t=>{let r=t instanceof Error?t.message:String(t);f.warn("Failed to close browser context during abort: %s",r)})}import{mkdir as Gr,writeFile as q}from"fs/promises";import B from"path";import{z as ne}from"zod";async function j({fn:e,label:t}){let r=performance.now(),n=await e();return f.debug("%s: %dms",t,Math.round(performance.now()-r)),n}async function Do({cdpSession:e,context:t,page:r,runId:n,stepIndex:o,stepResult:i}){try{let s=B.join(process.cwd(),".ripplo","debug",n,"steps",String(o));await Gr(s,{recursive:!0});let a={assertions:i.assertions,detail:i.detail,duration:i.duration,nodeId:i.nodeId,nodeType:i.nodeType,rrwebIds:i.rrwebIds,snapshotTimestamp:i.snapshotTimestamp,status:i.status,stepIndex:i.stepIndex,title:i.title,url:i.url};await Promise.all([q(B.join(s,"info.json"),JSON.stringify(a,null,2)),iu(au({cdpSession:e,context:t,page:r,stepDir:s}),nu,`capturePageState step ${String(o)}`)])}catch(s){let a=s instanceof Error?s.message:String(s);f.warn("Failed to write step debug data for step %d: %s",o,a)}}var nu=15e3,ou=50;async function iu(e,t,r){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${r} timed out after ${String(t)}ms`))},t)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function su(e){return e.replaceAll(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"<script>/* stripped */</script>").replaceAll(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"<style>/* stripped */</style>")}async function au({cdpSession:e,context:t,stepDir:r}){let[n,o,i,s,a]=await Promise.all([j({label:"captureDom",fn:()=>uu(e)}),j({label:"captureAxTree",fn:()=>mu(e)}),j({label:"captureStorage",fn:()=>bu({cdpSession:e,context:t})}),j({label:"captureScreenshot",fn:()=>hu(e)}),j({label:"captureRrwebElements",fn:()=>cu(e)})]);await j({label:"writeStepFiles",fn:()=>Promise.all([q(B.join(r,"dom.html"),su(n)),q(B.join(r,"accessibility-tree.full.json"),JSON.stringify(o)),q(B.join(r,"accessibility-tree.json"),fu(o)),q(B.join(r,"storage.json"),JSON.stringify(i,null,2)),q(B.join(r,"rrweb-elements.ndjson"),a),q(B.join(r,"screenshot.png"),s)]).then(()=>{})})}var lu=`
|
|
22
|
+
`);async function Tr({maxRuns:e}){try{let t=(await Nl(wo,{withFileTypes:!0})).filter(c=>c.isDirectory()),n=Date.now(),o=await Promise.all(t.map(async c=>{let u=vo.join(wo,c.name),m=await Ol(u);return{dirPath:u,mtime:m.mtimeMs}})),i=o.filter(c=>n-c.mtime>bo),a=o.filter(c=>n-c.mtime<=bo).toSorted((c,u)=>u.mtime-c.mtime).slice(e),l=[...i,...a];if(l.length===0)return;await Promise.allSettled(l.map(c=>Dl(c.dirPath,{force:!0,recursive:!0}))),f.debug("Pruned %d old debug run(s)",l.length)}catch{f.warn("Debug run pruning failed, ignoring")}}var _l=15e3,Ul=2,Vl=250,Fl=3e4,Lt=new Map;function _t({appUrl:e}){let r=Date.now(),t=Lt.get(e);if(t!=null&&t.expiresAt>r)return t.promise;let n=Ml(e).catch(o=>{throw Lt.delete(e),o});return Lt.set(e,{expiresAt:r+Fl,promise:n}),n}async function Ml(e){let r=null,t=0;for(;t<=Ul;){t>0&&await Bl(Vl);let o=await Hl(e,t);if(o==null)return;r=o,t+=1}let n=r instanceof Error?r.message:String(r);throw f.debug("App URL unreachable after retries: %s",n),new Error([`Could not reach your dev server at ${e}.`,"","Troubleshooting:",` 1. Make sure your app is running at ${e}`," 2. Check RIPPLO_APP_URL in the env file declared in .ripplo/project.json"," 3. If you're in a git worktree, RIPPLO_APP_URL and RIPPLO_ENGINE_URL must point at this worktree's dev server port (not main's)"].join(`
|
|
23
|
+
`))}async function Hl(e,r){let t=performance.now();try{return await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(_l)}),f.debug("App URL reachability check ok (attempt %d, %dms)",r+1,Math.round(performance.now()-t)),null}catch(n){return f.debug("App URL reachability check attempt %d failed after %dms: %s",r+1,Math.round(performance.now()-t),n instanceof Error?n.message:String(n)),n}}function Bl(e){return new Promise(r=>setTimeout(r,e))}import{Agent as Wl,RetryAgent as ql,setGlobalDispatcher as zl}from"undici";var Gl=1500,Kl=4e3,Jl=3,Xl=50,Yl=100,So=!1;function Ut(){if(So)return;So=!0;let e=new Wl({connections:Yl,keepAliveMaxTimeout:Kl,keepAliveTimeout:Gl}),r=new ql(e,{errorCodes:["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT","UND_ERR_REQ_CONTENT_LENGTH_MISMATCH","UND_ERR_SOCKET"],maxRetries:Jl,methods:["GET","POST","HEAD","OPTIONS","PUT","DELETE"],minTimeout:Xl});zl(r)}var ri=kt($r(),1);import{z as _d}from"zod";import{z as jr}from"zod";var ac=jr.object({__codec:jr.string().min(1),data:jr.unknown(),version:jr.number().int().positive()}),Nr=class extends Error{codec;currentVersion;gotVersion;constructor(r){super(`Unsupported ${r.codec} version ${String(r.gotVersion)} (current ${String(r.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=r.codec,this.currentVersion=r.currentVersion,this.gotVersion=r.gotVersion}},Dr=class extends Error{constructor(r){super(`Codec mismatch: expected "${r.expected}", got "${r.got}"`),this.name="CodecMismatchError"}};function Or(e){return Ro({legacy:void 0,migrators:[],name:e,schemas:[]})}function Ro(e){return{initial:r=>Ht(r,{...e,schemas:[r]}),legacy:r=>Ro({...e,legacy:r})}}function Ht(e,r){return{build:()=>lc(e,r),legacy:t=>Ht(e,{...r,legacy:t}),upgrade:(t,n)=>{let o=n;return Ht(t,{...r,migrators:[...r.migrators,o],schemas:[...r.schemas,t]})}}}function lc(e,r){let t=r.schemas.length;return{currentVersion:t,name:r.name,decode:n=>cc(e,r,n),encode:n=>({__codec:r.name,data:n,version:t})}}function cc(e,r,t){let{data:n,version:o}=uc(r,t),i=xo(r,n,o);return e.parse(i)}function uc(e,r){let t=ac.safeParse(r);if(t.success){if(t.data.__codec!==e.name)throw new Dr({expected:e.name,got:t.data.__codec});return{data:t.data.data,version:t.data.version}}if(e.legacy!=null&&e.legacy.detect(r))return{data:r,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function xo(e,r,t){let n=e.schemas.length;if(t>n)throw new Nr({codec:e.name,currentVersion:n,gotVersion:t});if(t===n)return r;let o=e.schemas[t-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(t)}; cannot migrate.`);let i=o.parse(r),s=e.migrators[t-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(t)} \u2192 v${String(t+1)}.`);return xo(e,s(i),t+1)}import{z as Io}from"zod";import{z as Fe}from"zod";var Bt=Fe.object({depends:Fe.array(Fe.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Fe.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Fe.array(Fe.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name.");import{z as d}from"zod";import{z as be}from"zod";var dc=be.object({by:be.literal("testId"),value:be.string().min(1)}),pc=be.object({by:be.literal("role"),name:be.string().optional(),role:be.string().min(1)}),C=be.discriminatedUnion("by",[dc,pc]);import{z as Eo}from"zod";var ve=Eo.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),Lr=Eo.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]);import{z as N}from"zod";var mc=N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_r=N.object({name:N.string().min(1),type:N.literal("variable")}),Ur=N.discriminatedUnion("type",[mc,_r]),Q=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.string()}),_r]),Vr=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.number().int().nonnegative()}),_r]),Wt=N.discriminatedUnion("type",[N.object({type:N.literal("static"),value:N.union([N.string(),N.number(),N.boolean()])}),_r]);import{z as Z}from"zod";var Fr=Z.discriminatedUnion("type",[Z.object({default:Z.string().optional(),type:Z.literal("string")}),Z.object({default:Z.number().optional(),type:Z.literal("number")}),Z.object({default:Z.boolean().optional(),type:Z.literal("boolean")}),Z.object({key:Z.string().min(1),type:Z.literal("env")})]);var v={id:d.string().min(1).max(200),label:d.string().max(500).optional(),next:d.string().max(200).optional(),uiOnly:d.boolean().optional()},Co=500,fc=d.object({...v,type:d.literal("goto"),url:Q}),gc=d.object({...v,locator:C,modifier:d.enum(["Alt","Control","Meta","Shift"]).optional(),type:d.literal("click")}),yc=d.object({...v,locator:C,type:d.literal("fill"),value:Q}),hc=d.object({...v,locator:C,type:d.literal("select"),value:Q}),wc=d.object({...v,locator:C,type:d.literal("hover")}),bc=d.object({...v,key:d.string().min(1),locator:C.optional(),type:d.literal("press")}),vc=d.object({...v,locator:C,type:d.literal("check")}),Sc=d.object({...v,locator:C,type:d.literal("uncheck")}),kc=d.object({...v,height:d.number().int().positive(),type:d.literal("setViewport"),width:d.number().int().positive()}),Pc=d.object({...v,message:d.string().min(1),type:d.literal("fail")}),Rc=d.object({...v,type:d.literal("setVariable"),value:Ur,variable:d.string().min(1)}),xc=d.object({...v,locator:C,type:d.literal("extractText"),variable:d.string().min(1)}),Ec=d.object({...v,files:d.array(d.string()).min(1),locator:C,type:d.literal("upload")}),Cc=d.object({...v,locator:C,type:d.literal("dblclick")}),Ac=d.object({...v,source:C,target:C,type:d.literal("drag")}),Ic=d.object({...v,locator:C,type:d.literal("scrollIntoView")}),Tc=d.object({...v,locator:C,type:d.literal("type"),value:Q}),$c=d.object({...v,locator:C,type:d.literal("focus")}),jc=d.object({...v,locator:C,type:d.literal("clear")}),Nc=d.object({...v,locator:C,type:d.literal("rightClick")}),Dc=d.object({...v,action:d.enum(["accept","dismiss"]),promptText:d.string().optional(),type:d.literal("handleDialog")}),Oc=d.object({...v,action:d.enum(["read","write"]),type:d.literal("clipboard"),value:Q.optional(),variable:d.string().min(1).optional()}),Lc=d.object({...v,permission:d.string().min(1),state:d.enum(["granted","prompt"]),type:d.literal("setPermission")}),_c=d.object({...v,locator:C,type:d.literal("assertVisible")}),Uc=d.object({...v,locator:C,type:d.literal("assertNotVisible")}),Vc=d.object({...v,expected:Q,locator:C,operator:ve,type:d.literal("assertText")}),Fc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertUrl")}),Mc=d.object({...v,expected:Vr,locator:C,operator:Lr,type:d.literal("assertCount")}),Hc=d.object({...v,expected:Q,locator:C,operator:ve,type:d.literal("assertValue")}),Bc=d.object({...v,attribute:d.string().min(1),expected:Q,locator:C,operator:ve,type:d.literal("assertAttribute")}),Wc=d.object({...v,locator:C,type:d.literal("assertEnabled")}),qc=d.object({...v,locator:C,type:d.literal("assertDisabled")}),zc=d.object({...v,expected:Q,operator:ve,type:d.literal("assertTitle")}),Gc=d.object({...v,locator:C,type:d.literal("assertChecked")}),Kc=d.object({...v,locator:C,type:d.literal("assertNotChecked")}),Jc=d.object({...v,locator:C,type:d.literal("assertFocused")}),Xc=d.object({...v,locator:C,type:d.literal("assertNotFocused")}),Yc=d.object({...v,budget:d.enum(["fast","slow","async"]),observer:d.string().min(1).max(200),params:d.record(d.string().max(200),Wt),type:d.literal("assertObserver")}),Ao=d.discriminatedUnion("type",[fc,gc,yc,hc,wc,bc,vc,Sc,_c,Uc,Vc,Fc,Mc,Hc,Bc,Wc,qc,kc,Pc,Rc,xc,Ec,Cc,Ac,Ic,Tc,$c,jc,Nc,Dc,Oc,Lc,zc,Gc,Kc,Jc,Xc,Yc]),Mr=d.object({entryNode:d.string().min(1).max(200),nodes:d.record(d.string().max(200),Ao).refine(e=>Object.keys(e).length<=Co,`Workflow has more than ${String(Co)} nodes`),uiOnly:d.boolean().optional(),variableNamespaces:d.record(d.string().max(200),d.string().max(500)).optional(),variables:d.record(d.string().max(200),Fr).optional()});var Qc=Io.record(Io.string().max(200),Bt),Zc={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},eu={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},qt=Or("workflow-spec").legacy(Zc).initial(Mr).build(),ru=Or("precondition-map").legacy(eu).initial(Qc).build();import{z as zt}from"zod";var To=["fast","slow","async"],tu=zt.object({budget:zt.enum(To).describe("Polling budget tier: fast | slow | async"),description:zt.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server.");function Hr(e){return e.label??`${e.type} (${e.id})`}import{graphql as ti,readFragment as Ud}from"gql.tada";function jo(){let e,r=!1;function t(o){e=o,r&&$o(o)}async function n(){r||(r=!0,e!=null&&await $o(e))}return{attachContext:t,fire:n,fired:()=>r}}async function $o(e){await e.close().catch(r=>{let t=r instanceof Error?r.message:String(r);f.warn("Failed to close browser context during abort: %s",t)})}import{mkdir as Gt,writeFile as q}from"fs/promises";import B from"path";import{z as ne}from"zod";async function j({fn:e,label:r}){let t=performance.now(),n=await e();return f.debug("%s: %dms",r,Math.round(performance.now()-t)),n}async function Do({cdpSession:e,context:r,page:t,runId:n,stepIndex:o,stepResult:i}){try{let s=B.join(process.cwd(),".ripplo","debug",n,"steps",String(o));await Gt(s,{recursive:!0});let a={assertions:i.assertions,detail:i.detail,duration:i.duration,nodeId:i.nodeId,nodeType:i.nodeType,rrwebIds:i.rrwebIds,snapshotTimestamp:i.snapshotTimestamp,status:i.status,stepIndex:i.stepIndex,title:i.title,url:i.url};await Promise.all([q(B.join(s,"info.json"),JSON.stringify(a,null,2)),iu(au({cdpSession:e,context:r,page:t,stepDir:s}),nu,`capturePageState step ${String(o)}`)])}catch(s){let a=s instanceof Error?s.message:String(s);f.warn("Failed to write step debug data for step %d: %s",o,a)}}var nu=15e3,ou=50;async function iu(e,r,t){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{s(new Error(`${t} timed out after ${String(r)}ms`))},r)});try{return await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function su(e){return e.replaceAll(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"<script>/* stripped */</script>").replaceAll(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"<style>/* stripped */</style>")}async function au({cdpSession:e,context:r,stepDir:t}){let[n,o,i,s,a]=await Promise.all([j({label:"captureDom",fn:()=>uu(e)}),j({label:"captureAxTree",fn:()=>mu(e)}),j({label:"captureStorage",fn:()=>bu({cdpSession:e,context:r})}),j({label:"captureScreenshot",fn:()=>hu(e)}),j({label:"captureRrwebElements",fn:()=>cu(e)})]);await j({label:"writeStepFiles",fn:()=>Promise.all([q(B.join(t,"dom.html"),su(n)),q(B.join(t,"accessibility-tree.full.json"),JSON.stringify(o)),q(B.join(t,"accessibility-tree.json"),fu(o)),q(B.join(t,"storage.json"),JSON.stringify(i,null,2)),q(B.join(t,"rrweb-elements.ndjson"),a),q(B.join(t,"screenshot.png"),s)]).then(()=>{})})}var lu=`
|
|
24
24
|
(function () {
|
|
25
25
|
try {
|
|
26
26
|
var rrweb = window.rrweb || globalThis.rrweb;
|
|
@@ -84,8 +84,8 @@ Values:
|
|
|
84
84
|
return JSON.stringify({ __ripploError: String(err && err.message ? err.message : err) });
|
|
85
85
|
}
|
|
86
86
|
})()
|
|
87
|
-
`;async function cu(e){return await se({awaitPromise:!1,expression:lu,label:"captureRrwebElements",session:e,timeoutMs:void 0})??""}async function uu(e){return await se({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",session:e,timeoutMs:void 0})??"(unable to capture DOM)"}var
|
|
88
|
-
`)}function gu(e){let
|
|
87
|
+
`;async function cu(e){return await se({awaitPromise:!1,expression:lu,label:"captureRrwebElements",session:e,timeoutMs:void 0})??""}async function uu(e){return await se({awaitPromise:!1,expression:"document.documentElement.outerHTML",label:"captureDom",session:e,timeoutMs:void 0})??"(unable to capture DOM)"}var Br=ne.object({value:ne.unknown()}).partial(),du=ne.object({childIds:ne.array(ne.string()),description:Br,ignored:ne.boolean(),name:Br,nodeId:ne.string(),parentId:ne.string(),properties:ne.array(ne.unknown()),role:Br,value:Br}).partial(),pu=ne.object({nodes:ne.array(du)});async function mu(e){let r=await e.send("Accessibility.getFullAXTree"),t=pu.safeParse(r);return t.success?t.data:{nodes:[]}}function fu(e){return e.nodes.filter(r=>r.ignored!==!0).map(r=>gu(r)).toSorted(yu).map(r=>JSON.stringify(r)).join(`
|
|
88
|
+
`)}function gu(e){let r=e.description?.value,t=e.value?.value;return{childIds:e.childIds??[],name:e.name?.value??"",nodeId:e.nodeId,parentId:e.parentId,properties:e.properties??[],role:e.role?.value??"",...r==null?{}:{description:r},...t==null?{}:{value:t}}}function yu(e,r){return No(e.nodeId)-No(r.nodeId)}function No(e){if(e==null)return Number.MAX_SAFE_INTEGER;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:Number.MAX_SAFE_INTEGER}async function hu(e){let r=await e.send("Page.captureScreenshot",{format:"png",optimizeForSpeed:!0});return Buffer.from(r.data,"base64")}var wu=`(() => {
|
|
89
89
|
function dump(s) {
|
|
90
90
|
var out = {};
|
|
91
91
|
for (var i = 0; i < s.length; i++) {
|
|
@@ -95,23 +95,23 @@ Values:
|
|
|
95
95
|
return out;
|
|
96
96
|
}
|
|
97
97
|
return { localStorage: dump(localStorage), sessionStorage: dump(sessionStorage) };
|
|
98
|
-
})()`;async function bu({cdpSession:e,context:
|
|
99
|
-
`)}function Su(e){return e.map(
|
|
100
|
-
${
|
|
98
|
+
})()`;async function bu({cdpSession:e,context:r}){let[t,n]=await Promise.all([se({awaitPromise:!1,expression:wu,label:"captureStorage",session:e,timeoutMs:void 0}),r.cookies().catch(()=>[])]);return{cookies:n,localStorage:t?.localStorage??{},sessionStorage:t?.sessionStorage??{}}}async function Oo({pageEvents:e,runId:r,steps:t,summary:n}){try{let o=B.join(process.cwd(),".ripplo","debug",r);await Gt(o,{recursive:!0});let i=e.capturePerf(),s=Promise.race([e.drain(),new Promise(a=>setTimeout(a,ou))]);await Promise.all([q(B.join(o,"summary.txt"),Ru({steps:t,summary:n})),q(B.join(o,"manifest.md"),xu({steps:t,summary:n})),q(B.join(o,"console.log"),vu(e.consoleEntries)),q(B.join(o,"page-errors.log"),Su(e.pageErrors)),q(B.join(o,"events.jsonl"),Pu(e.lifecycle)),s.then(()=>q(B.join(o,"network.jsonl"),ku(e.network))),i.then(a=>q(B.join(o,"perf.json"),a==null?"":JSON.stringify(a,null,2)))]),f.info("Debug artifacts written to .ripplo/debug/%s/",r)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write run debug summary: %s",i)}}function vu(e){return e.map(r=>{let t=r.url==null||r.url.length===0?"":` (${r.url})`;return`[${new Date(r.timestamp).toISOString()}] ${r.type.toUpperCase()}${t} ${r.text}`}).join(`
|
|
99
|
+
`)}function Su(e){return e.map(r=>{let t=r.stack==null?"":`
|
|
100
|
+
${r.stack}`;return`[${new Date(r.timestamp).toISOString()}] ${r.message}${t}`}).join(`
|
|
101
101
|
|
|
102
|
-
`)}function ku(e){return e.map(
|
|
103
|
-
`)}function Pu(e){return e.map(
|
|
104
|
-
`)}function Ru({steps:e,summary:
|
|
105
|
-
`)}function xu({steps:e,summary:
|
|
106
|
-
`)}async function Lo({error:e,runId:
|
|
102
|
+
`)}function ku(e){return e.map(r=>JSON.stringify(r)).join(`
|
|
103
|
+
`)}function Pu(e){return e.map(r=>JSON.stringify(r)).join(`
|
|
104
|
+
`)}function Ru({steps:e,summary:r}){return[`Run ID: ${r.runId}`,`Workflow: ${r.workflowName}`,`Status: ${r.status}`,`Duration: ${String(r.duration)}ms`,`Passed: ${String(r.passCount)}`,`Failed: ${String(r.failCount)}`,"","Steps:",...e.map(n=>` [${String(n.stepIndex)}] ${n.status==="passed"?"\u2713":"\u2717"} ${n.title} (${String(n.duration)}ms) \u2014 ${n.detail??"ok"}`)].join(`
|
|
105
|
+
`)}function xu({steps:e,summary:r}){return[`# Run ${r.runId} \u2014 ${r.workflowName}`,"",`Status: **${r.status}** \xB7 ${String(r.passCount)} passed \xB7 ${String(r.failCount)} failed \xB7 ${String(r.duration)}ms`,"","Start here:","- `summary.txt` \u2014 high-level run summary (read first).","- `error.txt` \u2014 present only when the run failed; the failure reason + stack.","- `console.log` \u2014 page console messages captured during the run.","- `page-errors.log` \u2014 uncaught page errors captured during the run.","- `network.jsonl` \u2014 one network response/failure per line, including request/response headers and bodies when available.","- `events.jsonl` \u2014 page lifecycle events (crash, dialog, navigation, popup, download, worker).","- `perf.json` \u2014 Performance API snapshot (navigation, paint, resource entries, memory).","","## Per-step artifacts","","Each `steps/<N>/` directory contains:","","- `info.json` \u2014 step metadata (title, type, duration, assertions).",'- `accessibility-tree.json` \u2014 **compact NDJSON** of the AX tree at snapshot time. One node per line, ignored nodes dropped, provenance arrays stripped. Read directly; line-oriented grep works (e.g. `grep \'"role":"button"\'`).',"- `accessibility-tree.full.json` \u2014 full Chrome DevTools AX tree. Large; slice with `sed`/`grep` if the compact view isn't enough.","- `dom.html` \u2014 full `document.documentElement.outerHTML` at snapshot time. Large; slice with `sed`/`grep`.","- `rrweb-elements.ndjson` \u2014 one JSON object per element with an rrweb mirror id, taken from the live rrweb snapshot. Line-greppable. Fields: `{ rrwebId, tag, attrs?, text? }`. `attrs` only includes referenceable attributes (id, class, role, aria-label, aria-labelledby, name, placeholder, alt, title, type, value, href, data-testid); `text` is the element's *own* text (direct text-node children only), trimmed and capped. Structural tags (html/head/script/style/meta/etc.) are skipped. **Only rrwebId values found in this file are accepted by anchored review comments \u2014 never fabricate one.**","- `screenshot.png` \u2014 PNG, readable as an image (focus rings, contrast, visible state).","- `storage.json` \u2014 cookies + localStorage + sessionStorage.","","## Slicing recipes for large files","","```","wc -c steps/*/dom.html # check sizes","sed -n '1500,1700p' steps/3/dom.html # read a line range","grep -n 'aria-label' steps/3/dom.html | head # locate then narrow",`grep '"role":"navigation"' steps/*/accessibility-tree.json`,"```","","## Steps","",...e.flatMap(t=>[`### steps/${String(t.stepIndex)} \u2014 "${t.title}" (${t.nodeType}, ${t.status}, ${String(t.duration)}ms)`,t.detail==null?"":`> ${t.detail}`,""])].join(`
|
|
106
|
+
`)}async function Lo({error:e,runId:r,stack:t,workflowName:n}){try{let o=B.join(process.cwd(),".ripplo","debug",r);await Gt(o,{recursive:!0});let i=t==null?e:`${e}
|
|
107
107
|
|
|
108
|
-
${
|
|
109
|
-
${
|
|
110
|
-
`),a=[`# Run ${
|
|
111
|
-
`);await Promise.all([q(B.join(o,"error.txt"),i),q(B.join(o,"summary.txt"),s),q(B.join(o,"manifest.md"),a)]),f.info("Debug error artifacts written to .ripplo/debug/%s/",
|
|
108
|
+
${t}`,s=[`Run ID: ${r}`,`Workflow: ${n}`,"Status: failed","",`Error: ${e}`,"",t==null?"":`Stack trace:
|
|
109
|
+
${t}`].join(`
|
|
110
|
+
`),a=[`# Run ${r} \u2014 ${n}`,"","Status: **failed**","","Run aborted before normal completion. Read:","- `error.txt` \u2014 failure reason + stack trace.","- `summary.txt` \u2014 high-level run summary.","- `steps/<N>/info.json` \u2014 per-step metadata for any steps that started before the abort.","","Per-step screenshots / DOM / accessibility-tree may be partial or missing.",""].join(`
|
|
111
|
+
`);await Promise.all([q(B.join(o,"error.txt"),i),q(B.join(o,"summary.txt"),s),q(B.join(o,"manifest.md"),a)]),f.info("Debug error artifacts written to .ripplo/debug/%s/",r)}catch(o){let i=o instanceof Error?o.message:String(o);f.warn("Failed to write error debug artifacts: %s",i)}}import{readFileSync as Eu}from"fs";import{createRequire as Cu}from"module";import _o from"path";import{gzipSync as Au}from"zlib";var Iu=Cu(import.meta.url),Tu=Iu.resolve("rrweb"),$u=_o.join(_o.dirname(Tu),"rrweb.umd.min.cjs"),ju=Eu($u,"utf8"),Nu=[";(function() {"," try {"," if (window.__ripploRrwebLoaded) return;"," window.__ripploRrwebLoaded = true;"," window.__ripploRrwebBuffer = [];"," window.__ripploRrwebDrain = function() {"," var out = window.__ripploRrwebBuffer;"," window.__ripploRrwebBuffer = [];"," return out;"," };"," var r = window.rrweb;"," if (r == null || r.record == null) {"," console.warn('[ripplo] rrweb global not found');"," return;"," }"," function startRecording() {"," if (window.__ripploRrwebStartedAt != null) return;"," window.__ripploRrwebStartedAt = Date.now();"," var stop = r.record({"," emit: function(event) { window.__ripploRrwebBuffer.push(event); },"," recordCanvas: false,"," recordCrossOriginIframes: false,"," });"," window.__ripploRrwebStop = stop;"," window.__ripploRrwebMirror = r.record.mirror;"," }"," window.__ripploRrwebStart = startRecording;"," // Auto-start on every bootstrap run so agent-driven tests (which don't"," // emit a 'first step' signal before navigating) capture from the start."," startRecording();"," } catch (err) {"," console.error('[ripplo] rrweb bootstrap failed', err && err.message ? err.message : err);"," }","})();"].join(`
|
|
112
112
|
`),Du=ju+`
|
|
113
|
-
`+Nu;async function Uo({cdpSession:e,page:
|
|
114
|
-
`),g={body:Au(Buffer.from(R,"utf8")),chunkIndex:n,endTimestamp:m.timestamp-y,eventCount:c.length,startTimestamp:u.timestamp-y};return n+=1,g}async function l(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",session:e,timeoutMs:void 0})}return{currentOffsetMs:s,detach:l,start:i,takeChunk:a}}function Bo({cdpSession:e,page:
|
|
113
|
+
`+Nu;async function Uo({cdpSession:e,page:r}){let t,n=0;async function o(){await r.addScriptTag({content:Du})}await o(),r.on("load",()=>{o().catch(c=>{let u=c instanceof Error?c.message:String(c);f.warn("rrweb re-injection on navigation failed: %s",u)})});async function i(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStart && globalThis.__ripploRrwebStart()",label:"rrweb start",session:e,timeoutMs:void 0});let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStartedAt",label:"rrweb startedAt",session:e,timeoutMs:void 0});typeof c=="number"&&(t??=c)}function s(){if(t!=null)return Date.now()-t}async function a(){let c=await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebDrain ? globalThis.__ripploRrwebDrain() : []",label:"rrweb drain",session:e,timeoutMs:void 0})??[],u=c[0],m=c.at(-1);if(u==null||m==null)return;t??=u.timestamp;let y=t,R=c.map(O=>JSON.stringify(O)).join(`
|
|
114
|
+
`),g={body:Au(Buffer.from(R,"utf8")),chunkIndex:n,endTimestamp:m.timestamp-y,eventCount:c.length,startTimestamp:u.timestamp-y};return n+=1,g}async function l(){await se({awaitPromise:!1,expression:"globalThis.__ripploRrwebStop && globalThis.__ripploRrwebStop()",label:"rrweb stop",session:e,timeoutMs:void 0})}return{currentOffsetMs:s,detach:l,start:i,takeChunk:a}}function Bo({cdpSession:e,page:r}){let t=[],n=[],o=[],i=[],s=[];return Ou(r,t,n),Lu(r,i),_u(r,o,s),{consoleEntries:t,lifecycle:i,network:o,pageErrors:n,capturePerf:()=>Mu(e),drain:async()=>{await Promise.allSettled(s)}}}function Ou(e,r,t){e.on("console",n=>{r.push({text:n.text(),timestamp:Date.now(),type:n.type(),url:n.location().url})}),e.on("pageerror",n=>{t.push({message:n.message,stack:n.stack,timestamp:Date.now()})})}function Lu(e,r){e.on("crash",()=>{r.push({detail:"page crashed",kind:"crash",timestamp:Date.now()})}),e.on("dialog",t=>{r.push({detail:`${t.type()}: ${t.message()}`,kind:"dialog",timestamp:Date.now()})}),e.on("framenavigated",t=>{t===e.mainFrame()&&r.push({detail:t.url(),kind:"navigation",timestamp:Date.now()})}),e.on("popup",t=>{r.push({detail:t.url(),kind:"popup",timestamp:Date.now()})}),e.on("download",t=>{r.push({detail:t.url(),kind:"download",timestamp:Date.now()})}),e.on("worker",t=>{r.push({detail:t.url(),kind:"worker",timestamp:Date.now()})})}function _u(e,r,t){e.on("response",n=>{let o=n.request();if(!Vo.has(o.resourceType()))return;let i=Fo(o,n),s=r.push(i)-1;t.push(Uu({idx:s,network:r,req:o,res:n}))}),e.on("requestfailed",n=>{Vo.has(n.resourceType())&&r.push({...Fo(n),failure:n.failure()?.errorText})})}var Vo=new Set(["fetch","xhr"]);function Fo(e,r){return{failure:void 0,method:e.method(),requestBody:e.postData()??void 0,requestHeaders:void 0,resourceType:e.resourceType(),responseBody:void 0,responseBodyError:void 0,responseHeaders:void 0,status:r?.status(),statusText:r?.statusText(),timestamp:Date.now(),url:e.url()}}async function Uu({idx:e,network:r,req:t,res:n}){let[o,i,s]=await Promise.all([Mo(t.allHeaders()),Mo(n.allHeaders()),Vu(n)]),a=r[e];a!=null&&(r[e]={...a,requestHeaders:o,responseBody:s.text,responseBodyError:s.error,responseHeaders:i})}async function Mo(e){try{return await e}catch{return}}var Ho=1500;async function Vu(e){try{return{error:void 0,text:(await Promise.race([e.body(),new Promise((t,n)=>setTimeout(()=>{n(new Error(`body read timed out after ${String(Ho)}ms`))},Ho))])).toString("utf8")}}catch(r){return{error:r instanceof Error?r.message:String(r),text:void 0}}}var Fu=`(() => {
|
|
115
115
|
const toJSON = (e) => e.toJSON();
|
|
116
116
|
const m = performance.memory;
|
|
117
117
|
const memory = m == null ? null : {
|
|
@@ -125,10 +125,10 @@ ${r}`].join(`
|
|
|
125
125
|
paint: performance.getEntriesByType("paint").map(toJSON),
|
|
126
126
|
resource: performance.getEntriesByType("resource").map(toJSON),
|
|
127
127
|
};
|
|
128
|
-
})()`;async function Mu(e){try{return await se({awaitPromise:!1,expression:Fu,label:"capturePerf",session:e,timeoutMs:void 0})}catch(
|
|
129
|
-
\u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Gu({observer:e,outcome:
|
|
130
|
-
Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:
|
|
131
|
-
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=t.reason,null)}async function Ku({apiUrl:e,observer:t,params:r,webhookSecret:n}){let o=JSON.stringify({observer:t,params:r});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Bu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=zu.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Ju({backoff:e,pollCount:t}){let r=Math.min(t-1,e.length-1);return e[r]??1e3}function zo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Xu(e){return new Promise(t=>setTimeout(t,e))}async function Go(e,t){try{let r=await e.elementHandle({timeout:t});if(r==null)return[];try{let n=await Jo(r);return n==null?[]:[n]}finally{await r.dispose().catch(()=>{})}}catch{return[]}}async function Ko(e){try{let t=await e.all(),n=(await Promise.all(t.map(o=>o.elementHandle({timeout:100}).catch(()=>null)))).filter(o=>o!=null);try{return(await Promise.all(n.map(i=>Jo(i)))).filter(i=>i!=null)}finally{await Promise.all(n.map(o=>o.dispose().catch(()=>{})))}}catch{return[]}}async function Jo(e){try{return await e.evaluate(r=>{let n=globalThis.__ripploRrwebMirror;if(n==null)return null;let o=n.getId(r);return typeof o=="number"&&o>0?o:null})}catch(t){let r=t instanceof Error?t.message:String(t);return f.debug("rrweb mirror lookup failed: %s",r),null}}var Wt=15e3;async function Jr({failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Qu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:t,observerTransport:r,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Yu({onStep:e,steps:t,target:r}){t.forEach(n=>{let o={...n,stepIndex:r.length};r.push(o),e?.(o)})}async function Qu({currentId:e,failFast:t,getRecordingOffsetMs:r,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],u=l,m=e;for(;m!=null;){let y=a.nodes[m];if(y==null)throw new Error(`Node "${m}" not found in spec`);let R=m,E=Ht(y);f.info("Executing node: %s [%s]",E,y.type);let g=await Zu({getRecordingOffsetMs:r,node:y,nodeId:R,observerTransport:n,page:i,runStartTime:s,variables:u});if(Yu({onStep:o,steps:[g],target:c}),u=g.variables,t&&g.status==="failed")break;m=y.next}return{steps:c,variables:u}}async function Zu({getRecordingOffsetMs:e,node:t,nodeId:r,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=Ht(t),u=Wt,m="locator"in t?t.locator:void 0,y=Xo(t),R=await id({isAction:y,locator:m,page:o,timeout:u,variables:s});try{let E=await ed({node:t,observerTransport:n,page:o,timeout:u,variables:s}),g=Math.round(performance.now()-a),O=E.assertions.some(H=>H.status==="failed");R=await sd({failed:O,isAction:y,locator:m,page:o,preActionIds:R,variables:s});let P=e?.();return{assertions:E.assertions,detail:void 0,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:P,recordingStartMs:l,rrwebIds:R,snapshotTimestamp:Math.round(performance.now()-i),status:O?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:E.variables}}catch(E){let g=Math.round(performance.now()-a),O=E instanceof Error?E.message:String(E),P=e?.();return{assertions:[],detail:O,duration:g,nodeId:r,nodeType:t.type,recordingEndMs:P,recordingStartMs:l,rrwebIds:R,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function ed({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(Xo(e)){let s=await Ar({node:e,page:r,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await rd({node:e,observerTransport:t,page:r,timeout:n,variables:o}),variables:o}}function Xo(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function td(e){return e.type.startsWith("assert")}async function rd({node:e,observerTransport:t,page:r,timeout:n,variables:o}){if(!td(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return od({assertNode:i,page:r,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await Ir({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Tr({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await ro({expected:s,operator:i.operator,page:r,timeout:n})]}case"assertCount":{let s=Cr({ref:i.expected,variables:o});return[await $r({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await jr({expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await no({attribute:i.attribute,expected:s,locator:V({locator:i.locator,page:r,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(t==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=At({ref:l,variables:o})}),[await qo({apiUrl:t.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:t.webhookSecret})]}}}var nd={assertChecked:so,assertDisabled:io,assertEnabled:oo,assertFocused:lo,assertNotChecked:ao,assertNotFocused:co,assertNotVisible:Dr,assertVisible:Nr};async function od({assertNode:e,page:t,timeout:r,variables:n}){let o=nd[e.type];return[await o({locator:V({locator:e.locator,page:t,variables:n}),timeout:r})]}async function id({isAction:e,locator:t,page:r,timeout:n,variables:o}){return t==null||!e?[]:Go(V({locator:t,page:r,variables:o}),n)}async function sd({failed:e,isAction:t,locator:r,page:n,preActionIds:o,variables:i}){return r==null||t||e?o:Ko(V({locator:r,page:n,variables:i}))}var ad=5e3,ld=2e3;async function Xr({abort:e,baseUrl:t,browser:r,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let u=await r.newContext({baseURL:t});e.attachContext(u),u.setDefaultTimeout(Wt),u.setDefaultNavigationTimeout(Wt),n.length>0&&await u.addCookies(n);let m=await u.newPage(),y=await u.newCDPSession(m),R=Bo({cdpSession:y,page:m}),E=await Uo({cdpSession:y,page:m});async function g(){let L=await E.takeChunk();L!=null&&s?.(L)}let O=setInterval(()=>{g().catch(L=>{let J=L instanceof Error?L.message:String(L);f.warn("rrweb chunk flush failed: %s",J)})},2e3),P=[],H=!1;function Te(L){a?.(L),H||(H=!0,E.start().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb recorder start failed: %s",z)})),g().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb step-boundary flush failed: %s",z)}),P.push(Do({cdpSession:y,context:u,page:m,runId:l,stepIndex:L.stepIndex,stepResult:L}))}let De=ud(o,c.variableNamespaces),pe={...Er({defs:c.variables}),...De};try{let L=await Jr({failFast:!0,getRecordingOffsetMs:E.currentOffsetMs,observerTransport:i,onStep:Te,page:m,spec:c,variables:pe});clearInterval(O);let J=L.steps.filter(it=>it.status==="passed").length,z=L.steps.filter(it=>it.status==="failed").length,Ta={duration:L.steps.reduce((it,$a)=>it+$a.duration,0),failCount:z,passCount:J,runId:l,status:z>0?"failed":"passed",workflowName:""};return await cd({debugCaptures:P,flushRecording:g,pageEvents:R,recorder:E,runId:l,steps:L.steps,summary:Ta}),L.steps}finally{clearInterval(O),await j({label:"cdpSession.detach",fn:()=>y.detach().catch(()=>{})}),await j({label:"context.close",fn:()=>me(u.close(),ld,"context.close").catch(L=>{let J=L instanceof Error?L.message:String(L);f.warn("Context close failed: %s",J)})})}}async function cd({debugCaptures:e,flushRecording:t,pageEvents:r,recorder:n,runId:o,steps:i,summary:s}){await j({label:"post-run cleanup",fn:()=>me(Promise.allSettled([j({label:"debugCaptures",fn:()=>Promise.allSettled(e)}),j({label:"writeRunDebugSummary",fn:()=>Oo({pageEvents:r,runId:o,steps:i,summary:s})}),j({label:"recorder detach+flush",fn:()=>n.detach().then(t).catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Recorder detach failed: %s",l)})})]),ad,"post-run cleanup").catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Post-run cleanup did not finish in budget: %s",l)})})}function ud(e,t){if(e==null||t==null)return{};let r=new Map;Object.entries(t).forEach(([o,i])=>{r.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=r.get(o);s!=null&&(n[s]={...n[s],...i})}),n}var Zr=kr($t(),1);import{z as S}from"zod";var dd=S.union([S.string(),S.number(),S.boolean()]),pd=S.record(S.string(),S.record(S.string(),dd)),md=S.object({domain:S.string().optional(),expires:S.number().optional(),httpOnly:S.boolean().optional(),name:S.string(),path:S.string().optional(),sameSite:S.enum(["lax","none","strict"]).optional(),secure:S.boolean().optional(),value:S.string()}),fd=S.discriminatedUnion("ok",[S.object({cookies:S.array(md),data:pd,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),gd=S.object({results:S.array(fd)}),yd=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),Yo=3e4;async function en({apiUrl:e,data:t,executed:r,runId:n,webhookSecret:o}){if(r.length!==0)try{await vd({apiUrl:e,webhookSecret:o}).load({data:t,preconditions:r,runId:n})}catch(i){let s=i instanceof Error?i.message:String(i);f.error("Teardown request failed: %s",s)}}async function qt({engineBaseUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){let o=e.length===0?void 0:e;return o==null||t.length===0?{apiUrl:o,cookies:[],data:{},executed:[]}:hd({apiUrl:o,preconditionNames:t,runId:r,webhookSecret:n})}async function hd({apiUrl:e,preconditionNames:t,runId:r,webhookSecret:n}){return{...await wd({apiUrl:e,webhookSecret:n}).load({preconditionNames:t,runId:r}),apiUrl:e}}function tn(){Yr.clear(),Qr.clear()}var Yr=new Map;function wd({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Yr.get(r);if(n!=null)return n;let o=new Zr.default(i=>bd({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Yr.set(r,o),o}async function bd({apiUrl:e,keys:t,webhookSecret:r}){let n=performance.now(),o=JSON.stringify({batch:t.map(u=>({preconditions:[...u.preconditionNames],runId:u.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:r})},method:"PUT",signal:AbortSignal.timeout(Yo)});if(!i.ok){let u=await Pd(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${u}`);return t.map(()=>m)}let s=await i.json(),a=gd.safeParse(s);if(!a.success){let u=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return t.map(()=>u)}let l=new URL(e).hostname,c=new Map(a.data.results.map(u=>[u.runId,u]));return f.debug({batchSize:t.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),t.map(u=>{let m=c.get(u.runId);return m==null?new Error(`execute-preconditions response missing runId ${u.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(y=>Ed({cookie:y,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Qr=new Map;function vd({apiUrl:e,webhookSecret:t}){let r=`${e}::${t}`,n=Qr.get(r);if(n!=null)return n;let o=new Zr.default(i=>Sd({apiUrl:e,keys:i,webhookSecret:t}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Qr.set(r,o),o}async function Sd({apiUrl:e,keys:t,webhookSecret:r}){let n=JSON.stringify({batch:t.map(l=>({data:l.data,preconditions:[...l.preconditions],runId:l.runId}))}),o=await fetch(`${e}/teardown-preconditions`,{body:n,headers:{"Content-Type":"application/json",...Se({body:n,secret:r})},method:"PUT",signal:AbortSignal.timeout(Yo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return t.map(()=>l)}let i=await o.json(),s=yd.safeParse(i);if(!s.success){let l=new Error(`teardown-preconditions response has invalid shape: ${s.error.message}`);return t.map(()=>l)}let a=new Map(s.data.results.map(l=>[l.runId,l]));return t.map(l=>{let c=a.get(l.runId);if(c==null)return new Error(`teardown-preconditions response missing runId ${l.runId}`);if(!c.ok)return new Error(`Teardown failed: ${c.error??"unknown error"}`)})}var kd=S.object({error:S.string()});async function Pd(e){let t=await e.text().catch(()=>"");if(t.length===0)return"no body";let r=Rd(t),n=r==null?null:kd.safeParse(r);return n!=null&&n.success?n.data.error:t.slice(0,500)}function Rd(e){try{return JSON.parse(e)}catch{return null}}var xd={lax:"Lax",none:"None",strict:"Strict"};function Ed({cookie:e,domain:t}){let r={domain:e.domain??t,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(r.sameSite=xd[e.sameSite]??"Lax"),e.expires!=null&&(r.expires=e.expires),r}var dt=kr($t(),1);import{graphql as Me}from"gql.tada";async function nn({config:e,runId:t}){let r=Cd(e);await r.start.load(t);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(r.steps.load({runId:t,step:c})).catch(u=>{f.error(u,"submitRunSteps failed")})}function s(c){o(Td({chunk:c,config:e,runId:t})).catch(u=>{f.error(u,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:u,steps:m,summary:y}){c&&await j({label:"flushSteps",fn:()=>a()});let R=m.filter(P=>P.status==="passed").length,E=m.filter(P=>P.status==="failed").length,g=m.reduce((P,H)=>P+H.duration,0),O=u??(E>0?"failed":"passed");await j({label:"completeRun",fn:()=>r.complete.load({duration:g,failCount:E,passCount:R,runId:t,status:O,summary:y??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:t}}async function on({config:e,reason:t,runId:r}){await h({config:e,document:jd,variables:{reason:t,runId:r}})}var Qo=new Map,rn=new Set;async function sn(){await Promise.allSettled(rn)}function Zo(e){rn.add(e),e.finally(()=>{rn.delete(e)})}function Cd(e){let t=`${e.ripploServerUrl}::${e.token}`,r=Qo.get(t);if(r!=null)return r;let n={artifactsUploaded:new dt.default(async o=>(await zt({config:e,document:$d,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new dt.default(async o=>(await zt({config:e,document:Ld,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new dt.default(async o=>(await zt({config:e,document:Nd,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}}),steps:new dt.default(async o=>(await zt({config:e,document:Dd,opName:"submitRunStepsBatch",size:o.length,variables:{items:Ad(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}})};return Qo.set(t,n),n}async function zt({config:e,document:t,opName:r,size:n,variables:o}){let i=performance.now();await h({config:e,document:t,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:r},"batched op flushed")}function Ad(e){let t=new Map;return e.forEach(({runId:r,step:n})=>{let o=Id(n),i=t.get(r);if(i==null){t.set(r,[o]);return}i.push(o)}),[...t.entries()].map(([r,n])=>({runId:r,steps:n}))}function Id(e){return{assertions:e.assertions.map(t=>({description:t.description,detail:t.detail??null,status:t.status})),detail:e.detail??null,duration:e.duration,nodeType:e.nodeType,recordingEndMs:e.recordingEndMs??null,recordingStartMs:e.recordingStartMs??null,rrwebIds:[...e.rrwebIds],snapshotTimestamp:e.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.url}}async function Td({chunk:e,config:t,runId:r}){await h({config:t,document:Od,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:r,startTimestamp:e.startTimestamp}}})}var $d=Me(`
|
|
128
|
+
})()`;async function Mu(e){try{return await se({awaitPromise:!1,expression:Fu,label:"capturePerf",session:e,timeoutMs:void 0})}catch(r){let t=r instanceof Error?r.message:String(r);f.warn("capturePerf failed: %s",t);return}}import{z as oe}from"zod";import Wo from"crypto";import{Webhook as Hu}from"standardwebhooks";function Se({body:e,secret:r}){let t=new Hu(r),n=`msg_${Wo.randomUUID()}`,o=new Date,i=t.sign(n,o,e),s=Math.floor(o.getTime()/1e3);return{"webhook-id":n,"webhook-signature":i,"webhook-timestamp":String(s)}}function Kt(){return`whsec_${Wo.randomBytes(24).toString("base64")}`}var Bu=15e4,Wu={async:{backoffMs:[500,1e3,2e3,5e3],timeoutMs:12e4},fast:{backoffMs:[100,250,500,1e3],timeoutMs:5e3},slow:{backoffMs:[250,500,1e3,2e3],timeoutMs:3e4}},qu=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("pass")}),oe.object({kind:oe.literal("retry"),reason:oe.string()}),oe.object({kind:oe.literal("fail"),reason:oe.string()})]),zu=oe.object({error:oe.string().optional(),outcome:qu.optional(),success:oe.boolean()});async function qo({apiUrl:e,budget:r,observer:t,params:n,webhookSecret:o}){let i=Wu[r],s=performance.now(),a={lastReason:void 0,pollCount:0};for(;performance.now()-s<i.timeoutMs;){a.pollCount+=1;let l=await Ku({apiUrl:e,observer:t,params:n,webhookSecret:o}),c=Gu({observer:t,outcome:l,start:s,state:a});if(c!=null)return c;let u=i.timeoutMs-(performance.now()-s);if(u<=0)break;let m=Math.min(Ju({backoff:i.backoffMs,pollCount:a.pollCount}),u);await Xu(m)}return{description:`observer "${t}"`,detail:`budget "${r}" exhausted after ${String(a.pollCount)} poll(s) (${zo(s)}); last: ${a.lastReason??"no retry reason"}
|
|
129
|
+
\u2192 /ripplo:debug \u2014 check .ripplo/debug/<runId>/ artifacts`,status:"failed"}}function Gu({observer:e,outcome:r,start:t,state:n}){return r.kind==="transport-error"?{description:`observer "${e}"`,detail:`transport error after ${String(n.pollCount)} poll(s): ${r.reason}
|
|
130
|
+
Load \`/ripplo:setup\` skill for instructions on engine endpoint + webhook secret wiring.`,status:"failed"}:r.kind==="pass"?{description:`observer "${e}"`,detail:n.pollCount>1?`passed after ${String(n.pollCount)} polls (${zo(t)})`:void 0,status:"passed"}:r.kind==="fail"?{description:`observer "${e}"`,detail:`failed (invariant): ${r.reason} (after ${String(n.pollCount)} poll(s)) \u2014 ctx.fail stops polling immediately and is reserved for invariant violations (wrong shape, contradictory/forbidden state). For transient conditions like "not yet committed", "status not yet X", or "row not found", use ctx.retry(reason) so the runtime keeps polling until the budget expires.
|
|
131
|
+
Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=r.reason,null)}async function Ku({apiUrl:e,observer:r,params:t,webhookSecret:n}){let o=JSON.stringify({observer:r,params:t});try{let i=await fetch(`${e}/execute-observer`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:n})},method:"PUT",signal:AbortSignal.timeout(Bu)});if(!i.ok){let l=await i.text().catch(()=>"");return{kind:"transport-error",reason:`status ${String(i.status)}: ${l.slice(0,200)}`}}let s=await i.json(),a=zu.safeParse(s);return a.success?!a.data.success||a.data.outcome==null?{kind:"transport-error",reason:a.data.error??"engine reported failure without outcome"}:a.data.outcome:{kind:"transport-error",reason:`invalid response shape: ${a.error.message}`}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error("observer request failed: %s",s),{kind:"transport-error",reason:s}}}function Ju({backoff:e,pollCount:r}){let t=Math.min(r-1,e.length-1);return e[t]??1e3}function zo(e){return`${String(Math.round(performance.now()-e))}ms`}async function Xu(e){return new Promise(r=>setTimeout(r,e))}async function Go(e,r){try{let t=await e.elementHandle({timeout:r});if(t==null)return[];try{let n=await Jo(t);return n==null?[]:[n]}finally{await t.dispose().catch(()=>{})}}catch{return[]}}async function Ko(e){try{let r=await e.all(),n=(await Promise.all(r.map(o=>o.elementHandle({timeout:100}).catch(()=>null)))).filter(o=>o!=null);try{return(await Promise.all(n.map(i=>Jo(i)))).filter(i=>i!=null)}finally{await Promise.all(n.map(o=>o.dispose().catch(()=>{})))}}catch{return[]}}async function Jo(e){try{return await e.evaluate(t=>{let n=globalThis.__ripploRrwebMirror;if(n==null)return null;let o=n.getId(t);return typeof o=="number"&&o>0?o:null})}catch(r){let t=r instanceof Error?r.message:String(r);return f.debug("rrweb mirror lookup failed: %s",t),null}}var Wr=15e3;async function Jt({failFast:e,getRecordingOffsetMs:r,observerTransport:t,onStep:n,page:o,spec:i,variables:s}){let a=performance.now();return Qu({currentId:i.entryNode,failFast:e,getRecordingOffsetMs:r,observerTransport:t,onStep:n,page:o,runStartTime:a,spec:i,variables:s})}function Yu({onStep:e,steps:r,target:t}){r.forEach(n=>{let o={...n,stepIndex:t.length};t.push(o),e?.(o)})}async function Qu({currentId:e,failFast:r,getRecordingOffsetMs:t,observerTransport:n,onStep:o,page:i,runStartTime:s,spec:a,variables:l}){let c=[],u=l,m=e;for(;m!=null;){let y=a.nodes[m];if(y==null)throw new Error(`Node "${m}" not found in spec`);let R=m,E=Hr(y);f.info("Executing node: %s [%s]",E,y.type);let g=await Zu({getRecordingOffsetMs:t,node:y,nodeId:R,observerTransport:n,page:i,runStartTime:s,variables:u});if(Yu({onStep:o,steps:[g],target:c}),u=g.variables,r&&g.status==="failed")break;m=y.next}return{steps:c,variables:u}}async function Zu({getRecordingOffsetMs:e,node:r,nodeId:t,observerTransport:n,page:o,runStartTime:i,variables:s}){let a=performance.now(),l=e?.(),c=Hr(r),u=Wr,m="locator"in r?r.locator:void 0,y=Xo(r),R=await id({isAction:y,locator:m,page:o,timeout:u,variables:s});try{let E=await ed({node:r,observerTransport:n,page:o,timeout:u,variables:s}),g=Math.round(performance.now()-a),O=E.assertions.some(H=>H.status==="failed");R=await sd({failed:O,isAction:y,locator:m,page:o,preActionIds:R,variables:s});let P=e?.();return{assertions:E.assertions,detail:void 0,duration:g,nodeId:t,nodeType:r.type,recordingEndMs:P,recordingStartMs:l,rrwebIds:R,snapshotTimestamp:Math.round(performance.now()-i),status:O?"failed":"passed",stepIndex:0,title:c,url:o.url(),variables:E.variables}}catch(E){let g=Math.round(performance.now()-a),O=E instanceof Error?E.message:String(E),P=e?.();return{assertions:[],detail:O,duration:g,nodeId:t,nodeType:r.type,recordingEndMs:P,recordingStartMs:l,rrwebIds:R,snapshotTimestamp:Math.round(performance.now()-i),status:"failed",stepIndex:0,title:c,url:o.url(),variables:s}}}async function ed({node:e,observerTransport:r,page:t,timeout:n,variables:o}){if(Xo(e)){let s=await At({node:e,page:t,timeout:n,variables:o});return{assertions:[],variables:s.variables}}return{assertions:await td({node:e,observerTransport:r,page:t,timeout:n,variables:o}),variables:o}}function Xo(e){return["goto","click","dblclick","fill","select","hover","press","check","uncheck","clear","rightClick","handleDialog","clipboard","setPermission","setViewport","fail","setVariable","extractText","upload","drag","scrollIntoView","type","focus"].includes(e.type)}function rd(e){return e.type.startsWith("assert")}async function td({node:e,observerTransport:r,page:t,timeout:n,variables:o}){if(!rd(e))throw new Error(`Unknown node type: ${e.type}`);let i=e;switch(i.type){case"assertVisible":case"assertNotVisible":case"assertEnabled":case"assertDisabled":case"assertChecked":case"assertNotChecked":case"assertFocused":case"assertNotFocused":return od({assertNode:i,page:t,timeout:n,variables:o});case"assertText":{let s=Y({ref:i.expected,variables:o});return[await It({expected:s,locator:V({locator:i.locator,page:t,variables:o}),operator:i.operator,timeout:n})]}case"assertUrl":{let s=Y({ref:i.expected,variables:o});return[await Tt({expected:s,operator:i.operator,page:t,timeout:n})]}case"assertTitle":{let s=Y({ref:i.expected,variables:o});return[await to({expected:s,operator:i.operator,page:t,timeout:n})]}case"assertCount":{let s=Ct({ref:i.expected,variables:o});return[await $t({expected:s,locator:V({locator:i.locator,page:t,variables:o}),operator:i.operator,timeout:n})]}case"assertValue":{let s=Y({ref:i.expected,variables:o});return[await jt({expected:s,locator:V({locator:i.locator,page:t,variables:o}),operator:i.operator,timeout:n})]}case"assertAttribute":{let s=Y({ref:i.expected,variables:o});return[await no({attribute:i.attribute,expected:s,locator:V({locator:i.locator,page:t,variables:o}),operator:i.operator,timeout:n})]}case"assertObserver":{if(r==null)return[{description:`observer "${i.observer}"`,detail:"observer transport not configured \u2014 set engineUrl + webhookSecret in ripplo.config",status:"failed"}];let s={};return Object.entries(i.params).forEach(([a,l])=>{s[a]=Ar({ref:l,variables:o})}),[await qo({apiUrl:r.apiUrl,budget:i.budget,observer:i.observer,params:s,webhookSecret:r.webhookSecret})]}}}var nd={assertChecked:so,assertDisabled:io,assertEnabled:oo,assertFocused:lo,assertNotChecked:ao,assertNotFocused:co,assertNotVisible:Dt,assertVisible:Nt};async function od({assertNode:e,page:r,timeout:t,variables:n}){let o=nd[e.type];return[await o({locator:V({locator:e.locator,page:r,variables:n}),timeout:t})]}async function id({isAction:e,locator:r,page:t,timeout:n,variables:o}){return r==null||!e?[]:Go(V({locator:r,page:t,variables:o}),n)}async function sd({failed:e,isAction:r,locator:t,page:n,preActionIds:o,variables:i}){return t==null||r||e?o:Ko(V({locator:t,page:n,variables:i}))}var ad=5e3,ld=2e3;async function Xt({abort:e,baseUrl:r,browser:t,cookies:n,extraVariables:o,observerTransport:i,onRecordingChunk:s,onStep:a,runId:l,spec:c}){let u=await t.newContext({baseURL:r});e.attachContext(u),u.setDefaultTimeout(Wr),u.setDefaultNavigationTimeout(Wr),n.length>0&&await u.addCookies(n);let m=await u.newPage(),y=await u.newCDPSession(m),R=Bo({cdpSession:y,page:m}),E=await Uo({cdpSession:y,page:m});async function g(){let L=await E.takeChunk();L!=null&&s?.(L)}let O=setInterval(()=>{g().catch(L=>{let J=L instanceof Error?L.message:String(L);f.warn("rrweb chunk flush failed: %s",J)})},2e3),P=[],H=!1;function Te(L){a?.(L),H||(H=!0,E.start().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb recorder start failed: %s",z)})),g().catch(J=>{let z=J instanceof Error?J.message:String(J);f.warn("rrweb step-boundary flush failed: %s",z)}),P.push(Do({cdpSession:y,context:u,page:m,runId:l,stepIndex:L.stepIndex,stepResult:L}))}let De=ud(o,c.variableNamespaces),pe={...Et({defs:c.variables}),...De};try{let L=await Jt({failFast:!0,getRecordingOffsetMs:E.currentOffsetMs,observerTransport:i,onStep:Te,page:m,spec:c,variables:pe});clearInterval(O);let J=L.steps.filter(ir=>ir.status==="passed").length,z=L.steps.filter(ir=>ir.status==="failed").length,Ta={duration:L.steps.reduce((ir,$a)=>ir+$a.duration,0),failCount:z,passCount:J,runId:l,status:z>0?"failed":"passed",workflowName:""};return await cd({debugCaptures:P,flushRecording:g,pageEvents:R,recorder:E,runId:l,steps:L.steps,summary:Ta}),L.steps}finally{clearInterval(O),await j({label:"cdpSession.detach",fn:()=>y.detach().catch(()=>{})}),await j({label:"context.close",fn:()=>me(u.close(),ld,"context.close").catch(L=>{let J=L instanceof Error?L.message:String(L);f.warn("Context close failed: %s",J)})})}}async function cd({debugCaptures:e,flushRecording:r,pageEvents:t,recorder:n,runId:o,steps:i,summary:s}){await j({label:"post-run cleanup",fn:()=>me(Promise.allSettled([j({label:"debugCaptures",fn:()=>Promise.allSettled(e)}),j({label:"writeRunDebugSummary",fn:()=>Oo({pageEvents:t,runId:o,steps:i,summary:s})}),j({label:"recorder detach+flush",fn:()=>n.detach().then(r).catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Recorder detach failed: %s",l)})})]),ad,"post-run cleanup").catch(a=>{let l=a instanceof Error?a.message:String(a);f.warn("Post-run cleanup did not finish in budget: %s",l)})})}function ud(e,r){if(e==null||r==null)return{};let t=new Map;Object.entries(r).forEach(([o,i])=>{t.set(i,o)});let n={};return Object.entries(e).forEach(([o,i])=>{let s=t.get(o);s!=null&&(n[s]={...n[s],...i})}),n}var Zt=kt($r(),1);import{z as S}from"zod";var dd=S.union([S.string(),S.number(),S.boolean()]),pd=S.record(S.string(),S.record(S.string(),dd)),md=S.object({domain:S.string().optional(),expires:S.number().optional(),httpOnly:S.boolean().optional(),name:S.string(),path:S.string().optional(),sameSite:S.enum(["lax","none","strict"]).optional(),secure:S.boolean().optional(),value:S.string()}),fd=S.discriminatedUnion("ok",[S.object({cookies:S.array(md),data:pd,executed:S.array(S.string()),ok:S.literal(!0),runId:S.string()}),S.object({error:S.string(),ok:S.literal(!1),runId:S.string()})]),gd=S.object({results:S.array(fd)}),yd=S.object({results:S.array(S.object({error:S.string().optional(),ok:S.boolean(),runId:S.string()}))}),Yo=3e4;async function en({apiUrl:e,data:r,executed:t,runId:n,webhookSecret:o}){if(t.length!==0)try{await vd({apiUrl:e,webhookSecret:o}).load({data:r,preconditions:t,runId:n})}catch(i){let s=i instanceof Error?i.message:String(i);f.error("Teardown request failed: %s",s)}}async function qr({engineBaseUrl:e,preconditionNames:r,runId:t,webhookSecret:n}){let o=e.length===0?void 0:e;return o==null||r.length===0?{apiUrl:o,cookies:[],data:{},executed:[]}:hd({apiUrl:o,preconditionNames:r,runId:t,webhookSecret:n})}async function hd({apiUrl:e,preconditionNames:r,runId:t,webhookSecret:n}){return{...await wd({apiUrl:e,webhookSecret:n}).load({preconditionNames:r,runId:t}),apiUrl:e}}function rn(){Yt.clear(),Qt.clear()}var Yt=new Map;function wd({apiUrl:e,webhookSecret:r}){let t=`${e}::${r}`,n=Yt.get(t);if(n!=null)return n;let o=new Zt.default(i=>bd({apiUrl:e,keys:i,webhookSecret:r}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Yt.set(t,o),o}async function bd({apiUrl:e,keys:r,webhookSecret:t}){let n=performance.now(),o=JSON.stringify({batch:r.map(u=>({preconditions:[...u.preconditionNames],runId:u.runId}))}),i=await fetch(`${e}/execute-preconditions`,{body:o,headers:{"Content-Type":"application/json",...Se({body:o,secret:t})},method:"PUT",signal:AbortSignal.timeout(Yo)});if(!i.ok){let u=await Pd(i),m=new Error(`execute-preconditions returned ${String(i.status)}: ${u}`);return r.map(()=>m)}let s=await i.json(),a=gd.safeParse(s);if(!a.success){let u=new Error(`execute-preconditions response has invalid shape: ${a.error.message}`);return r.map(()=>u)}let l=new URL(e).hostname,c=new Map(a.data.results.map(u=>[u.runId,u]));return f.debug({batchSize:r.length,elapsedMs:Math.round(performance.now()-n),op:"execute-preconditions"},"batched op flushed"),r.map(u=>{let m=c.get(u.runId);return m==null?new Error(`execute-preconditions response missing runId ${u.runId}`):m.ok?(f.info("Preconditions resolved: %s",m.executed.join(", ")),{cookies:m.cookies.map(y=>Ed({cookie:y,domain:l})),data:m.data,executed:m.executed}):new Error(`Precondition batch failed: ${m.error}`)})}var Qt=new Map;function vd({apiUrl:e,webhookSecret:r}){let t=`${e}::${r}`,n=Qt.get(t);if(n!=null)return n;let o=new Zt.default(i=>Sd({apiUrl:e,keys:i,webhookSecret:r}),{cache:!1,batchScheduleFn:i=>{setTimeout(i,100)},cacheKeyFn:i=>i.runId});return Qt.set(t,o),o}async function Sd({apiUrl:e,keys:r,webhookSecret:t}){let n=JSON.stringify({batch:r.map(l=>({data:l.data,preconditions:[...l.preconditions],runId:l.runId}))}),o=await fetch(`${e}/teardown-preconditions`,{body:n,headers:{"Content-Type":"application/json",...Se({body:n,secret:t})},method:"PUT",signal:AbortSignal.timeout(Yo)});if(!o.ok){let l=new Error(`teardown-preconditions returned ${String(o.status)}`);return r.map(()=>l)}let i=await o.json(),s=yd.safeParse(i);if(!s.success){let l=new Error(`teardown-preconditions response has invalid shape: ${s.error.message}`);return r.map(()=>l)}let a=new Map(s.data.results.map(l=>[l.runId,l]));return r.map(l=>{let c=a.get(l.runId);if(c==null)return new Error(`teardown-preconditions response missing runId ${l.runId}`);if(!c.ok)return new Error(`Teardown failed: ${c.error??"unknown error"}`)})}var kd=S.object({error:S.string()});async function Pd(e){let r=await e.text().catch(()=>"");if(r.length===0)return"no body";let t=Rd(r),n=t==null?null:kd.safeParse(t);return n!=null&&n.success?n.data.error:r.slice(0,500)}function Rd(e){try{return JSON.parse(e)}catch{return null}}var xd={lax:"Lax",none:"None",strict:"Strict"};function Ed({cookie:e,domain:r}){let t={domain:e.domain??r,httpOnly:e.httpOnly??!1,name:e.name,path:e.path??"/",secure:e.secure??!1,value:e.value};return e.sameSite!=null&&(t.sameSite=xd[e.sameSite]??"Lax"),e.expires!=null&&(t.expires=e.expires),t}var dr=kt($r(),1);import{graphql as Me}from"gql.tada";async function nn({config:e,runId:r}){let t=Cd(e);await t.start.load(r);let n=[];function o(c){return n.push(c.catch(()=>{})),c}function i(c){o(t.steps.load({runId:r,step:c})).catch(u=>{f.error(u,"submitRunSteps failed")})}function s(c){o(Td({chunk:c,config:e,runId:r})).catch(u=>{f.error(u,"submitRunRecordingChunk failed")})}async function a(){for(;n.length>0;){let c=n.splice(0);await Promise.all(c)}}async function l({flush:c,statusOverride:u,steps:m,summary:y}){c&&await j({label:"flushSteps",fn:()=>a()});let R=m.filter(P=>P.status==="passed").length,E=m.filter(P=>P.status==="failed").length,g=m.reduce((P,H)=>P+H.duration,0),O=u??(E>0?"failed":"passed");await j({label:"completeRun",fn:()=>t.complete.load({duration:g,failCount:E,passCount:R,runId:r,status:O,summary:y??null,warnCount:0})})}return{complete:l,enqueueRecordingChunk:s,enqueueStep:i,flushSteps:a,runId:r}}async function on({config:e,reason:r,runId:t}){await h({config:e,document:jd,variables:{reason:r,runId:t}})}var Qo=new Map,tn=new Set;async function sn(){await Promise.allSettled(tn)}function Zo(e){tn.add(e),e.finally(()=>{tn.delete(e)})}function Cd(e){let r=`${e.ripploServerUrl}::${e.token}`,t=Qo.get(r);if(t!=null)return t;let n={artifactsUploaded:new dr.default(async o=>(await zr({config:e,document:$d,opName:"markRunArtifactsUploadedBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1}),complete:new dr.default(async o=>(await zr({config:e,document:Ld,opName:"completeRunsBatch",size:o.length,variables:{items:[...o]}}),o.map(()=>!0)),{cache:!1}),start:new dr.default(async o=>(await zr({config:e,document:Nd,opName:"startRunsBatch",size:o.length,variables:{runIds:[...o]}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}}),steps:new dr.default(async o=>(await zr({config:e,document:Dd,opName:"submitRunStepsBatch",size:o.length,variables:{items:Ad(o)}}),o.map(()=>!0)),{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}})};return Qo.set(r,n),n}async function zr({config:e,document:r,opName:t,size:n,variables:o}){let i=performance.now();await h({config:e,document:r,variables:o}),f.debug({batchSize:n,elapsedMs:Math.round(performance.now()-i),op:t},"batched op flushed")}function Ad(e){let r=new Map;return e.forEach(({runId:t,step:n})=>{let o=Id(n),i=r.get(t);if(i==null){r.set(t,[o]);return}i.push(o)}),[...r.entries()].map(([t,n])=>({runId:t,steps:n}))}function Id(e){return{assertions:e.assertions.map(r=>({description:r.description,detail:r.detail??null,status:r.status})),detail:e.detail??null,duration:e.duration,nodeType:e.nodeType,recordingEndMs:e.recordingEndMs??null,recordingStartMs:e.recordingStartMs??null,rrwebIds:[...e.rrwebIds],snapshotTimestamp:e.snapshotTimestamp,status:e.status,stepIndex:e.stepIndex,title:e.title,url:e.url}}async function Td({chunk:e,config:r,runId:t}){await h({config:r,document:Od,variables:{input:{bodyBase64:e.body.toString("base64"),chunkIndex:e.chunkIndex,endTimestamp:e.endTimestamp,eventCount:e.eventCount,runId:t,startTimestamp:e.startTimestamp}}})}var $d=Me(`
|
|
132
132
|
mutation MarkRunArtifactsUploadedBatchCLI($runIds: [String!]!) {
|
|
133
133
|
markRunArtifactsUploadedBatch(runIds: $runIds)
|
|
134
134
|
}
|
|
@@ -157,7 +157,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
157
157
|
status
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
-
`);var Vd=12e4,Fd=15e3,ni=
|
|
160
|
+
`);var Vd=12e4,Fd=15e3,ni=ti(`
|
|
161
161
|
fragment WorkflowRun on Workflow {
|
|
162
162
|
id
|
|
163
163
|
slug
|
|
@@ -169,7 +169,7 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
169
169
|
preconditionName
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
|
-
`),Md=
|
|
172
|
+
`),Md=ti(`
|
|
173
173
|
query RunsByIdsWorkflowSpec($ids: [String!]!) {
|
|
174
174
|
runsByIds(ids: $ids) {
|
|
175
175
|
id
|
|
@@ -182,10 +182,10 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
182
182
|
}
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
|
-
`,[ni]);async function an({baseUrl:e,browser:
|
|
186
|
-
`,1)[0]??e}async function Kd({preconditionResult:e,runId:
|
|
187
|
-
`),
|
|
188
|
-
`,{mode:384})}function pn(){let e=ke("token");return
|
|
185
|
+
`,[ni]);async function an({baseUrl:e,browser:r,config:t,headed:n,preconditionNames:o,runId:i,webhookSecret:s}){let a="unknown",l,c,u=!1,m=jo(),y=performance.now();try{u=r==null,c=Hd({externalBrowser:r,headed:n});let R=o==null?void 0:qr({engineBaseUrl:t.engineUrl,preconditionNames:o,runId:i,webhookSecret:s}),[{engineBaseUrl:E,workflow:g},O]=await Promise.all([j({label:"Run context resolved",fn:()=>Jd({config:t,runId:i})}),j({label:"Streaming run started",fn:()=>nn({config:t,runId:i})}),_t({appUrl:e})]);a=g.name,l=O;let P=Xd(g.spec);f.info("Executing workflow: %s",g.name),await Zd(Wd({abort:m,baseUrl:e,browserPromise:c,engineBaseUrl:E,preconditionPromise:R,runId:i,specData:P,streaming:l,webhookSecret:s,workflow:g}),Qd(),m)}catch(R){throw ep(R)?R:(await me(Bd({browserPromise:c,config:t,error:R,ownsBrowser:u,runId:i,streaming:l,workflowName:a}),Fd,"post-deadline cleanup").catch(E=>{let g=E instanceof Error?E.message:String(E);f.warn("Post-deadline cleanup did not finish in budget: %s",g)}),new Gr(R))}finally{f.debug({elapsedMs:Math.round(performance.now()-y),runId:i},"run finished (totalMs=%d)",Math.round(performance.now()-y))}}var Gr=class extends Error{cause;constructor(r){let t=r instanceof Error?r.message:String(r);super(t),this.name="RunReportedError",this.cause=r}};function Hd({externalBrowser:e,headed:r}){return e!=null?Promise.resolve(e):j({label:"Browser launched",fn:()=>Ue({headed:r})})}async function Bd({browserPromise:e,config:r,error:t,ownsBrowser:n,runId:o,streaming:i,workflowName:s}){let a=t instanceof Error?t.message:String(t),l=t instanceof Error?t.stack:void 0;await Lo({error:a,runId:o,stack:l,workflowName:s}),i==null?await on({config:r,reason:a,runId:o}).catch(()=>{}):await i.complete({flush:!1,statusOverride:"failed",steps:[],summary:a}).catch(()=>{}),n&&e!=null&&await(await e.catch(()=>{}))?.close()}async function Wd({abort:e,baseUrl:r,browserPromise:t,engineBaseUrl:n,preconditionPromise:o,runId:i,specData:s,streaming:a,webhookSecret:l,workflow:c}){let u=o??qr({engineBaseUrl:n,preconditionNames:c.preconditions,runId:i,webhookSecret:l}),[m,y]=await Promise.all([u,t]);await qd({abort:e,baseUrl:r,browser:y,preconditionResult:m,runId:i,specData:s,streaming:a,webhookSecret:l})}async function qd({abort:e,baseUrl:r,browser:t,preconditionResult:n,runId:o,specData:i,streaming:s,webhookSecret:a}){let l=await j({label:"Spec executed",fn:()=>Xt({abort:e,baseUrl:r,browser:t,cookies:n.cookies,extraVariables:n.data,observerTransport:n.apiUrl==null?void 0:{apiUrl:n.apiUrl,webhookSecret:a},onRecordingChunk:s.enqueueRecordingChunk,onStep:s.enqueueStep,runId:o,spec:i})});Kd({preconditionResult:n,runId:o,webhookSecret:a}).catch(y=>{let R=y instanceof Error?y.message:String(y);f.warn("Precondition teardown failed: %s",R)});let c=s.complete({flush:!0,statusOverride:void 0,steps:l,summary:zd(l)}).catch(y=>{let R=y instanceof Error?y.message:String(y);f.warn("streaming.complete failed: %s",R)});Zo(c);let u=l.filter(y=>y.status==="passed").length,m=l.filter(y=>y.status==="failed").length;f.info("Run complete: %d passed, %d failed",u,m)}function zd(e){let r=e.find(o=>o.status==="failed");if(r==null)return;let n=r.assertions.find(o=>o.status==="failed")?.detail??r.detail;return n==null||n.length===0?r.title:`${r.title} \u2014 ${Gd(n)}`}function Gd(e){return e.split(`
|
|
186
|
+
`,1)[0]??e}async function Kd({preconditionResult:e,runId:r,webhookSecret:t}){e.apiUrl!=null&&await en({apiUrl:e.apiUrl,data:e.data,executed:e.executed,runId:r,webhookSecret:t})}async function Jd({config:e,runId:r}){let t=await rp(e).load(r);if(t.workflow==null)throw new Error(`Run ${r} not found`);let n=Ud(ni,t.workflow),o=t.workflow.project?.engineBaseUrl??"";return{engineBaseUrl:e.engineUrl.length>0?e.engineUrl:o,workflow:n}}function Xd(e){if(e==null)throw new Error("Workflow has no spec");return qt.decode(e)}var Yd=_d.coerce.number().int().positive().catch(Vd);function Qd(){return Yd.parse(process.env.RIPPLO_RUN_TIMEOUT_MS)}async function Zd(e,r,t){let n,o=new Promise((i,s)=>{n=setTimeout(()=>{t.fire(),s(new Error(`Run timed out after ${String(r)}ms`))},r)});try{await Promise.race([e,o])}finally{n!=null&&clearTimeout(n)}}function ep(e){return e instanceof Ve?e.errors.some(r=>r.extensions?.code==="THROTTLED"):!1}var ei=new Map;function rp(e){let r=`${e.ripploServerUrl}::${e.token}`,t=ei.get(r);if(t!=null)return t;let n=new ri.default(async o=>{let i=performance.now(),s=await h({config:e,document:Md,variables:{ids:[...o]}}),a=new Map(s.runsByIds?.map(l=>[l.id,l])??[]);return f.debug({batchSize:o.length,elapsedMs:Math.round(performance.now()-i),op:"runsByIds"},"batched op flushed"),o.map(l=>a.get(l)??new Error(`Run ${l} not found`))},{cache:!1,batchScheduleFn:o=>{setTimeout(o,100)}});return ei.set(r,n),n}import gr from"fs";import je from"fs";import tp from"os";import pr from"path";var np=".local",op=".ripplo";function ln(e){return pr.join(e,".ripplo",np)}function mr(e){let r=ln(e);je.existsSync(r)||je.mkdirSync(r,{recursive:!0});let t=pr.join(r,".gitignore");return je.existsSync(t)||je.writeFileSync(t,`*
|
|
187
|
+
`),r}function fr(e,r){return pr.join(ln(e),r)}function cn(){return pr.join(tp.homedir(),op)}function un(){let e=cn();return je.existsSync(e)?je.chmodSync(e,448):je.mkdirSync(e,{mode:448,recursive:!0}),e}function ke(e){return pr.join(cn(),e)}function ie(){let e=process.env.RIPPLO_TOKEN;if(e!=null&&e.trim().length>0)return e.trim();let r=ke("token");if(!gr.existsSync(r))return null;let t=gr.readFileSync(r,"utf8").trim();return t.length===0?null:t}function dn(e){un(),gr.writeFileSync(ke("token"),e+`
|
|
188
|
+
`,{mode:384})}function pn(){let e=ke("token");return gr.existsSync(e)?(gr.unlinkSync(e),!0):!1}import{graphql as yr}from"gql.tada";var Zk=yr(`
|
|
189
189
|
query AgentReviewContextWorker($reviewId: String!) {
|
|
190
190
|
agentReview(id: $reviewId) {
|
|
191
191
|
id
|
|
@@ -199,11 +199,11 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
199
199
|
}
|
|
200
200
|
}
|
|
201
201
|
}
|
|
202
|
-
`);var eP=
|
|
202
|
+
`);var eP=yr(`
|
|
203
203
|
mutation StartAgentReviewWorker($reviewId: String!) {
|
|
204
204
|
startAgentReview(reviewId: $reviewId)
|
|
205
205
|
}
|
|
206
|
-
`);var
|
|
206
|
+
`);var rP=yr(`
|
|
207
207
|
mutation CompleteAgentReviewWorker(
|
|
208
208
|
$reviewId: String!
|
|
209
209
|
$markdown: String!
|
|
@@ -217,78 +217,79 @@ Load \`/ripplo:create\` skill for instructions.`,status:"failed"}:(n.lastReason=
|
|
|
217
217
|
comments: $comments
|
|
218
218
|
)
|
|
219
219
|
}
|
|
220
|
-
`);var
|
|
220
|
+
`);var tP=yr(`
|
|
221
221
|
mutation UpdateAgentReviewProgressWorker($reviewId: String!, $text: String!) {
|
|
222
222
|
updateAgentReviewProgress(reviewId: $reviewId, text: $text)
|
|
223
223
|
}
|
|
224
|
-
`);var nP=
|
|
224
|
+
`);var nP=yr(`
|
|
225
225
|
mutation FailAgentReviewWorker($reviewId: String!, $reason: String!) {
|
|
226
226
|
failAgentReview(reviewId: $reviewId, reason: $reason)
|
|
227
227
|
}
|
|
228
|
-
`);import si from"fs";import
|
|
229
|
-
`)}function sp(e){return e.length!==mn.length?!1:e.every((t
|
|
228
|
+
`);import si from"fs";import Xr from"path";import{config as ap}from"dotenv";import{z as Jr}from"zod";import hr from"fs";import fn from"path";import{z as Kr}from"zod";var oi=fn.join(".ripplo","project.json"),mn=[".env",".env.local"],ip=Kr.object({envFiles:Kr.array(Kr.string().min(1)).optional(),projectId:Kr.string().min(1)});function gn(e){return fn.join(e,oi)}function yn(e){let r=gn(e);if(!hr.existsSync(r))throw new Error(`ripplo: missing ${oi}. Run \`ripplo init\` to create it.`);let t=JSON.parse(hr.readFileSync(r,"utf8")),n=ip.parse(t);return{envFiles:n.envFiles??mn,projectId:n.projectId}}function hn(e){let r=gn(e);if(hr.existsSync(r))try{return yn(e)}catch{return}}function ii({cwd:e,envFiles:r,projectId:t}){let n=gn(e);hr.mkdirSync(fn.dirname(n),{recursive:!0});let o={projectId:t};r!=null&&!sp(r)&&(o.envFiles=[...r]),hr.writeFileSync(n,JSON.stringify(o,null,2)+`
|
|
229
|
+
`)}function sp(e){return e.length!==mn.length?!1:e.every((r,t)=>r===mn[t])}function Yr(e){let t=hn(e)?.envFiles??[".env",".env.local"],n=Xr.join(e,".ripplo");t.forEach(o=>{let i=Xr.resolve(n,o);si.existsSync(i)&&ap({override:!0,path:i,quiet:!0})}),wn=void 0}var lp=Jr.object({RIPPLO_APP_URL:Jr.url(),RIPPLO_ENGINE_URL:Jr.url(),RIPPLO_WEBHOOK_SECRET:Jr.string().min(1)}),wn;function He(){return wn??=cp(),wn}function cp(){let e=lp.safeParse(process.env);if(!e.success){let t=e.error.issues.map(s=>` ${s.path.join(".")}: ${s.message}`).join(`
|
|
230
230
|
`),n=bn(process.cwd()),o=n.map(s=>` ${s}`).join(`
|
|
231
231
|
`),i=n.length>0?`
|
|
232
232
|
|
|
233
233
|
Declared env file(s) not found at this path:
|
|
234
234
|
${o}
|
|
235
235
|
If you're in a git worktree, the env file may not have been copied from the main checkout \u2014 recreate it (or symlink to a shared file outside the working tree).`:"";throw new Error(`ripplo: env config invalid:
|
|
236
|
-
${
|
|
236
|
+
${t}
|
|
237
237
|
|
|
238
|
-
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let
|
|
238
|
+
Add missing values to the env file(s) declared in .ripplo/project.json.${i}`)}let r=e.data;return{appUrl:r.RIPPLO_APP_URL,engineUrl:r.RIPPLO_ENGINE_URL,webhookSecret:r.RIPPLO_WEBHOOK_SECRET}}function bn(e){let t=hn(e)?.envFiles??[],n=Xr.join(e,".ripplo");return t.map(o=>Xr.resolve(n,o)).filter(o=>!si.existsSync(o))}import gb from"yargs";import{hideBin as yb}from"yargs/helpers";import{graphql as Rp}from"gql.tada";import{exec as fp}from"child_process";import{createAuthClient as up}from"better-auth/client";import{deviceAuthorizationClient as dp}from"better-auth/client/plugins";function ai({baseURL:e}){return up({baseURL:e,fetchOptions:{headers:{"User-Agent":"Ripplo CLI"}},plugins:[dp()]})}import{z as vn}from"zod";var pp="https://ripplo.ai";function ee(){return Qr().RIPPLO_SERVER_URL}function ci(){return Qr().RIPPLO_PROJECT_ID}var mp=vn.object({RIPPLO_PROJECT_ID:vn.string().min(1).optional(),RIPPLO_SERVER_URL:vn.string().min(1).default(pp)}),li;function Qr(){return li??=mp.parse(process.env),li}var gp=5e3,ui="ripplo-cli";async function di({onDeviceCode:e,url:r}){let t=r??Qr().RIPPLO_SERVER_URL,n=ai({baseURL:t}),o=await n.device.code({client_id:ui});if(o.error!=null)throw new Error(`Failed to request device code: ${o.error.error_description}`);let{device_code:i,user_code:s,verification_uri_complete:a}=o.data;e({userCode:s,verificationUrl:a}),Sp(a);let l=await yp({authClient:n,deviceCode:i});return dn(l),l}async function yp({authClient:e,deviceCode:r}){for(;;){await bp(gp);let t=await e.device.token({client_id:ui,device_code:r,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(t.data?.access_token!=null)return t.data.access_token;if(t.error==null)continue;if(!wp(t.error.error))throw new Error(`Authorization failed: ${t.error.error_description}`)}}var hp=new Set(["authorization_pending","slow_down"]);function wp(e){return hp.has(e)}function bp(e){return new Promise(r=>{setTimeout(r,e)})}function vp(){return process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open"}function Sp(e){let r=vp();fp(`${r} "${e}"`,()=>{})}function Pe({serverUrl:e,token:r}){return{appUrl:"",cwd:process.cwd(),engineUrl:"",projectId:"",ripploServerUrl:e,token:r,webhookSecret:""}}import kp from"fs";import Pp from"path";function A(e){return kp.existsSync(Pp.join(e,".ripplo"))}var xp=Rp(`
|
|
239
239
|
query AuthViewer {
|
|
240
240
|
currentUser {
|
|
241
241
|
name
|
|
242
242
|
email
|
|
243
243
|
}
|
|
244
244
|
}
|
|
245
|
-
`);async function pi(){let e=ee(),
|
|
245
|
+
`);async function pi(){let e=ee(),r=ie();if(r!=null){let s=await Sn({serverUrl:e,token:r});if(s!=null){process.stdout.write(`Already signed in as ${s.email}. Run \`ripplo auth logout\` to switch.
|
|
246
246
|
`);return}process.stdout.write(`Your saved session expired \u2014 let's sign you back in.
|
|
247
247
|
|
|
248
|
-
`)}let
|
|
248
|
+
`)}let t=await di({url:e,onDeviceCode:s=>{process.stdout.write(`Opening your browser to finish sign-in.
|
|
249
249
|
`),process.stdout.write(`If it didn't open, visit: ${s.verificationUrl}
|
|
250
250
|
`),process.stdout.write(`Verification code: ${s.userCode}
|
|
251
251
|
|
|
252
252
|
`),process.stdout.write(`Waiting for you to approve...
|
|
253
|
-
`)}}),n=await Sn({serverUrl:e,token:
|
|
253
|
+
`)}}),n=await Sn({serverUrl:e,token:t}),o=A(process.cwd()),i=o?"Welcome back":"Welcome to Ripplo";process.stdout.write(`
|
|
254
254
|
`),process.stdout.write(n==null?`${i}.
|
|
255
255
|
`:`${i}, ${Ep(n)}.
|
|
256
256
|
`),process.stdout.write(`Session saved to ${ke("token")}.
|
|
257
|
-
`),o||(process.stdout.write("\nNext: run `/ripplo:setup` in Claude Code to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}function Ep(e){let
|
|
257
|
+
`),o||(process.stdout.write("\nNext: run `/ripplo:setup` in Claude Code to wire Ripplo into this project,\n"),process.stdout.write("or `npx ripplo init` to set it up by hand.\n"))}function Ep(e){let r=e.name.trim().split(/\s+/)[0];return r!=null&&r.length>0?r:e.email}async function Sn({serverUrl:e,token:r}){try{let n=(await h({config:Pe({serverUrl:e,token:r}),document:xp,variables:void 0})).currentUser;return n==null?null:{email:n.email,name:n.name}}catch{return null}}async function mi(){let e=ie();e==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login`.\n"),process.exit(1));let r=ee(),t=await Sn({serverUrl:r,token:e});t==null&&(process.stdout.write("Token rejected. Run `ripplo auth login` to re-authenticate.\n"),process.stdout.write(`(Claude Code: run this yourself as a background process \u2014 device-code flow, the user only approves in the browser.)
|
|
258
|
+
`),process.exit(1)),process.stdout.write(`Authenticated as ${t.name} <${t.email}> (${r})
|
|
258
259
|
`)}function fi(){if(!pn()){process.stdout.write(`No token to remove.
|
|
259
260
|
`);return}process.stdout.write(`Removed ${ke("token")}
|
|
260
|
-
`)}import{createHash as Cp}from"crypto";import
|
|
261
|
-
`}async function tr({cwd:e}){let t=We.join(e,le),r=await Fm(t);return r==null?null:$p(Ei,r)}var hi=10*1024*1024,wi=50*1024*1024;async function ce({cwd:e,result:t}){let r=await Ai({cwd:e,result:t}),n=Ci(r),o=We.join(e,le);await wt.mkdir(We.dirname(o),{recursive:!0}),await wt.writeFile(o,Rn(n),"utf8")}async function Ai({cwd:e,result:t}){let r=Vm(t);if(r.size===0)return{...t,fixtures:{}};let n=We.join(e,jm),o=[...r].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Um({fixturesRoot:n,name:a});if(l.size>hi)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(hi)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>wi)throw new Error(`Total fixtures size exceeds limit of ${String(wi)} bytes`);return{...t,fixtures:Object.fromEntries(i)}}async function Um({fixturesRoot:e,name:t}){let r=t;if(typeof r!="string"||r.length===0)throw new Error(`Internal error: upload step produced a non-string fixture name (got ${r===null?"null":typeof r}). This usually means a test passed a non-Fixture value to upload() \u2014 wrap the filename with fixture("file.png").`);if(t.includes("..")||We.isAbsolute(t))throw new Error(`Invalid fixture name "${t}": must be a path under .ripplo/fixtures/`);let n=We.join(e,t),o=await wt.lstat(n).catch(a=>{throw Ii(a)&&a.code==="ENOENT"?new Error(`Fixture "${t}" not found at ${n}`):a});if(o.isSymbolicLink())throw new Error(`Fixture "${t}" is a symlink; symlinks are not allowed`);if(!o.isFile())throw new Error(`Fixture "${t}" is not a regular file`);let i=await wt.readFile(n);return{sha256:Cp("sha256").update(i).digest("hex"),size:i.byteLength}}function Vm(e){let t=new Set;return e.tests.forEach(r=>{Object.entries(r.spec.nodes).forEach(([n,o])=>{o.type==="upload"&&o.files.forEach((i,s)=>{let a=i;if(typeof a!="string"||a.length===0)throw new Error(`Test "${r.slug}" step "${n}" upload files[${String(s)}] is not a non-empty string (got ${a===null?"null":typeof a}). Wrap filenames with fixture(): upload(loc, fixture("file.png")).`);t.add(a)})})}),t}async function rr({compiled:e,cwd:t,existing:r}){if(r==null)return"missing";let n=await Ai({cwd:t,result:e}),o=Rn(Ci(n)),i=Rn(r);return o===i?"match":"stale"}async function Fm(e){try{return await wt.readFile(e,"utf8")}catch(t){if(Ii(t)&&t.code==="ENOENT")return null;throw t}}function Ii(e){return e instanceof Error&&"code"in e}function Mm(e){return function(r,n){return n===e||!Hm(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Hm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import vt from"fs";import ir from"path";var Cn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],xe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function Ti(e){return e.data}function $i(e){return{as(t){return{data:{label:t,node:e}}}}}function nr(e){let t=e.getPreconditions(),r=e.getObservers(),n=e.getTests();Bm(n);let o={};t.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};r.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>Wm(a,t));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Bm(e){let t=new Map;e.forEach(r=>{let n=t.get(r.id);if(n!=null)throw new Error(`Duplicate test id "${r.id}" used by "${n}" and "${r.name}"`);t.set(r.id,r.name)})}function Wm(e,t){let r=e.id,{accessedKeys:n,vars:o}=zm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[qm(i),...s],l=Gm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let m=Jm(e.requires,t);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:r,sourcePath:e.sourcePath,spec:l,warnings:c}}function qm(e){return $i({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function zm(e){let t=new Set,r={};return Object.keys(e).forEach(n=>{r[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return t.add(s),`{{${s}}}`}}})}),{accessedKeys:t,vars:r}}function Gm(e,t,r,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,u=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Km(a,c,u)});let i={};t.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...r};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function Km(e,t,r){let{label:n,node:o}=Ti(e);return{...o,id:t,label:n,next:r}}function Jm(e,t){let r=new Map(t.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),r.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as WR,WebhookVerificationError as qR}from"standardwebhooks";import{z as _}from"zod";var ji=_.union([_.string(),_.number(),_.boolean()]),Xm=_.record(_.string(),_.record(_.string(),ji)),GR=_.object({batch:_.array(_.object({preconditions:_.array(_.string().min(1)),runId:_.string().min(1)})).min(1)}),KR=_.object({batch:_.array(_.object({data:Xm,preconditions:_.array(_.string().min(1)),runId:_.string().min(1)})).min(1)}),JR=_.object({observer:_.string().min(1).max(200),params:_.record(_.string().max(200),ji)});function qe(e){let t=[];return e.tests.forEach(r=>{let n=Ym(r),o=i=>{t.push({...i,test:r.slug})};Sf.forEach(i=>{i(n,r,o)})}),{diagnostics:t}}function Ym(e){let t=[],r=e.spec.entryNode,n=new Set;for(;r!=null&&!n.has(r);){n.add(r);let o=e.spec.nodes[r];if(o==null)break;t.push(o),r=o.next}return t}function Qm(e,t,r){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&r({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function Zm(e,t,r){Object.keys(t.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Di(o.value)){let i=o.value.value;!Oi(i)&&af(i)&&r({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function ef(e,t,r){if(Object.keys(t.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||r({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function tf(e,t,r){e.forEach(n=>{(n.label==null||n.label.length===0)&&r({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function rf(e,t,r){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):r({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function nf(e,t,r){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(ze(o)){n=0;return}n++,n===3&&r({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function of(e,t,r){if(e.length===0)return;let n=e.at(-1);n!=null&&!ze(n)&&r({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function sf(e,t,r){t.implemented&&e.length===0&&r({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Di(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Oi(e){return e.includes("{{")}function af(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function ze(e){return e.type.startsWith("assert")}var lf=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function cf(e){return lf.has(e.type)}function uf(e,t,r){!t.implemented||e.length===0||e.some(n=>ze(n))||r({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function df(e,t,r){if(!t.implemented||e.length<=3)return;let n=e.filter(i=>ze(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);r({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function An(e){if(!("locator"in e)||e.locator==null)return;let t=e.locator;return t.by==="role"?`role:${t.role}:${t.name??""}`:`testId:${t.value}`}function pf(e,t,r){e.forEach((n,o)=>{if(n.type!=="click")return;let i=An(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&An(c)===i)==null||s.some(c=>cf(c)||ze(c)&&An(c)!==i)||r({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var mf=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function In(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=3&&!mf.has(t))}function ff(e){let t=e.label==null?[]:In(e.label);if(!("locator"in e)||e.locator==null)return t;let r=e.locator,n=r.by==="role"?r.name??"":r.value;return[...t,...In(n)]}function gf(e,t,r){if(!t.implemented||e.length===0)return;let n=new Set(In(t.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>ze(s));if(o.length===0)return;o.some(s=>ff(s).some(a=>n.has(a)))||r({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var yf=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Ni(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let t=e.locator,r=t.by==="role"?t.name??"":t.value;return yf.test(r)}function hf(e,t,r){!t.implemented||t.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Ni(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(u=>Ni(u)),a=s===-1?i.length:s;i.slice(0,a).some(u=>u.type==="assertObserver")||r({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function wf(e,t,r){Object.keys(t.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>Di(a)&&Oi(a.value))||r({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function bf(e,t,r){e.forEach(n=>{n.type==="upload"&&n.files.forEach(o=>{if(o.length===0){r({message:`upload "${n.label??n.id}" references an empty fixture name`,rule:"upload-fixture-name",step:n.label??n.id});return}(o.includes("..")||o.startsWith("/"))&&r({message:`upload "${n.label??n.id}" references "${o}" \u2014 fixture names must be relative paths under .ripplo/fixtures/, no ".." or absolute paths`,rule:"upload-fixture-name",step:n.label??n.id})})})}function vf(e,t,r){let n=new Set(Object.keys(t.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),u=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");r({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${u} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Sf=[Qm,Zm,vf,ef,tf,rf,nf,of,sf,uf,df,pf,gf,hf,wf,bf];import zf from"picomatch";import{execFileSync as kf,spawnSync as Pf}from"child_process";function K(e,t){return kf("git",[...e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Li(e,t){let r=Pf("git",["show",e],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(r.status===0)return r.stdout;if(r.status===128)return null;throw new Error(`git show ${e} failed (${String(r.status)}): ${r.stderr}`)}import b from"typescript";import*as _i from"remeda";var Ui=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],Rf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),xf=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function or({filePath:e,source:t}){let r=b.createSourceFile(e,t,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return r.statements.flatMap(n=>Ef({filePath:e,sf:r,stmt:n}))}function Ef({filePath:e,sf:t,stmt:r}){let n=Af(r);if(n==null||Cf(n))return[];let o=Vi(r,t).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return _i.uniqueBy(o,i=>i.id)}function Cf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Af(e){if(b.isExportAssignment(e))return If(e.expression);if(!Tf(e))return null;if(b.isFunctionDeclaration(e)||b.isClassDeclaration(e))return e.name?.text??null;if(b.isVariableStatement(e)){let t=e.declarationList.declarations[0];return t!=null&&b.isIdentifier(t.name)?t.name.text:null}return null}function If(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Tf(e){if(!b.canHaveModifiers(e))return!1;let t=b.getModifiers(e);return t!=null&&t.some(r=>r.kind===b.SyntaxKind.ExportKeyword)}function Vi(e,t){let r=$f(e,t),n=e.getChildren(t).flatMap(o=>Vi(o,t));return r==null?n:[r,...n]}function $f(e,t){let r=jf(e);if(r==null)return null;let n=Nf(r);if(n==null)return null;let o=Uf(r,n);return o==null?null:{kind:n,label:o,line:qf(t,e.getStart(t))}}function jf(e){return b.isJsxSelfClosingElement(e)&&b.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:b.isJsxElement(e)&&b.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Nf({attrs:e,tag:t}){let r=ue(e,"role");return r!=null?Rf.get(r)??null:Of(t,e)??Lf(t)??_f(e)}var Df=new Map([["button",()=>"click"],["a",e=>ue(e,"href")==null?null:"navigate"],["input",e=>ue(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Of(e,t){return Df.get(e)?.(t)??null}function Lf(e){return/^[A-Z]/.test(e)?xf.find(([t])=>t.test(e))?.[1]??null:null}function _f(e){return Ui.find(([t])=>Mf(e,t))?.[1]??null}function Uf({attrs:e,children:t,tag:r},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(Vf(r)?void 0:Wf(t))??Ff(e,n)}function Vf(e){return e==="input"||e==="textarea"||e==="select"}function Ff(e,t){let r=Ui.find(([,o])=>o===t)?.[0];if(r==null)return;let n=Hf(e,r);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return Fi(n.body)}}function Fi(e){if(b.isCallExpression(e)){let t=e.expression;return b.isIdentifier(t)?t.text:b.isPropertyAccessExpression(t)?t.name.text:void 0}return b.forEachChild(e,Fi)}function Mf(e,t){return e.properties.some(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function Mi(e,t){return e.properties.find(r=>b.isJsxAttribute(r)&&b.isIdentifier(r.name)&&r.name.text===t)}function ue(e,t){let r=Mi(e,t);return r==null?void 0:Bf(r.initializer)}function Hf(e,t){let r=Mi(e,t);if(!(r?.initializer==null||!b.isJsxExpression(r.initializer)))return r.initializer.expression}function Bf(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Bi(e.expression)}function Wf(e){let t=e.flatMap(r=>Hi(r)).join(" ").trim();return t.length===0?void 0:t}function Hi(e){if(b.isJsxText(e)){let t=e.text.trim();return t.length===0?[]:[t]}if(b.isJsxExpression(e)){let t=Bi(e.expression);return t==null?[]:[t]}return b.isJsxElement(e)?e.children.flatMap(t=>Hi(t)):[]}function Bi(e){if(e!=null){if(b.isStringLiteral(e)||b.isNoSubstitutionTemplateLiteral(e))return e.text;if(b.isCallExpression(e)&&e.arguments.length===1){let t=e.arguments[0];if(t!=null&&(b.isStringLiteral(t)||b.isNoSubstitutionTemplateLiteral(t)))return t.text}}}function qf(e,t){return e.getLineAndCharacterOfPosition(t).line+1}var Gf=ir.join(".ripplo","coverage.d.ts");function Ge({cwd:e}){Kf({cwd:e,ignorePaths:xe})}function Kf({cwd:e,ignorePaths:t}){let r=Ke({cwd:e,ignorePaths:t});Yf({content:Xf(r),cwd:e})}function Ke({cwd:e,ignorePaths:t}){let n=Jf({cwd:e,ignorePaths:t}).flatMap(o=>Tn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Jf({cwd:e,ignorePaths:t}){let r=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=zf([...t]);return r.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>vt.existsSync(ir.join(e,o)))}function Tn({cwd:e,file:t}){let r=vt.readFileSync(ir.join(e,t),"utf8");return or({filePath:t,source:r}).map(n=>n.id)}function Xf(e){let t=`// GENERATED \u2014 do not edit
|
|
261
|
+
`)}import{createHash as Cp}from"crypto";import wr from"fs/promises";import We from"path";import{z as Zr}from"zod";import{z as gi}from"zod";import{z as Be}from"zod";import{z as p}from"zod";import{z as Re}from"zod";import{z as Si}from"zod";import{z as D}from"zod";import{z as re}from"zod";import{z as kn}from"zod";import{z as T}from"zod";var Ap=Zr.object({__codec:Zr.string().min(1),data:Zr.unknown(),version:Zr.number().int().positive()}),Ip=class extends Error{codec;currentVersion;gotVersion;constructor(e){super(`Unsupported ${e.codec} version ${String(e.gotVersion)} (current ${String(e.currentVersion)}). Upgrade Ripplo or rebuild with a compatible CLI.`),this.name="CodecVersionError",this.codec=e.codec,this.currentVersion=e.currentVersion,this.gotVersion=e.gotVersion}},Tp=class extends Error{constructor(e){super(`Codec mismatch: expected "${e.expected}", got "${e.got}"`),this.name="CodecMismatchError"}};function xn(e){return bi({legacy:void 0,migrators:[],name:e,schemas:[]})}function $p(e,r){let t=JSON.parse(r);return e.decode(t)}function bi(e){return{initial:r=>Pn(r,{...e,schemas:[r]}),legacy:r=>bi({...e,legacy:r})}}function Pn(e,r){return{build:()=>jp(e,r),legacy:t=>Pn(e,{...r,legacy:t}),upgrade:(t,n)=>{let o=n;return Pn(t,{...r,migrators:[...r.migrators,o],schemas:[...r.schemas,t]})}}}function jp(e,r){let t=r.schemas.length;return{currentVersion:t,name:r.name,decode:n=>Np(e,r,n),encode:n=>({__codec:r.name,data:n,version:t})}}function Np(e,r,t){let{data:n,version:o}=Dp(r,t),i=vi(r,n,o);return e.parse(i)}function Dp(e,r){let t=Ap.safeParse(r);if(t.success){if(t.data.__codec!==e.name)throw new Tp({expected:e.name,got:t.data.__codec});return{data:t.data.data,version:t.data.version}}if(e.legacy!=null&&e.legacy.detect(r))return{data:r,version:e.legacy.assumedVersion};throw new Error(`Cannot decode "${e.name}": value is not a codec envelope and no legacy detector matched.`)}function vi(e,r,t){let n=e.schemas.length;if(t>n)throw new Ip({codec:e.name,currentVersion:n,gotVersion:t});if(t===n)return r;let o=e.schemas[t-1];if(o==null)throw new Error(`Codec "${e.name}" missing schema for v${String(t)}; cannot migrate.`);let i=o.parse(r),s=e.migrators[t-1];if(s==null)throw new Error(`Codec "${e.name}" missing migrator v${String(t)} \u2192 v${String(t+1)}.`);return vi(e,s(i),t+1)}var En=Be.object({depends:Be.array(Be.string().min(1)).optional().describe("Names of other preconditions that must be satisfied first. Resolved via topological sort; cycles are rejected at validation time."),description:Be.string().min(1).describe("Human-readable description of what this precondition ensures"),returns:Be.array(Be.string().min(1)).optional().describe("Keys that the execute response's data field will contain. e.g. ['projectId', 'workflowId']. These are used for route param interpolation ({{projectId}}) and workflow variables. Declared here so generated types are strongly typed per precondition.")}).describe("A named precondition declared at the graph level. States reference these by name."),Op=Re.object({by:Re.literal("testId"),value:Re.string().min(1)}),Lp=Re.object({by:Re.literal("role"),name:Re.string().optional(),role:Re.string().min(1)}),$=Re.discriminatedUnion("by",[Op,Lp]),br=Si.enum(["equals","notEquals","contains","startsWith","endsWith","matches"]),_p=Si.enum(["equals","notEquals","greaterThan","greaterThanOrEqual","lessThan","lessThanOrEqual"]),Up=D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),et=D.object({name:D.string().min(1),type:D.literal("variable")}),Vp=D.discriminatedUnion("type",[Up,et]),ae=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.string()}),et]),Fp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.number().int().nonnegative()}),et]),Mp=D.discriminatedUnion("type",[D.object({type:D.literal("static"),value:D.union([D.string(),D.number(),D.boolean()])}),et]),Hp=re.discriminatedUnion("type",[re.object({default:re.string().optional(),type:re.literal("string")}),re.object({default:re.number().optional(),type:re.literal("number")}),re.object({default:re.boolean().optional(),type:re.literal("boolean")}),re.object({key:re.string().min(1),type:re.literal("env")})]),k={id:p.string().min(1).max(200),label:p.string().max(500).optional(),next:p.string().max(200).optional(),uiOnly:p.boolean().optional()},yi=500,Bp=p.object({...k,type:p.literal("goto"),url:ae}),Wp=p.object({...k,locator:$,modifier:p.enum(["Alt","Control","Meta","Shift"]).optional(),type:p.literal("click")}),qp=p.object({...k,locator:$,type:p.literal("fill"),value:ae}),zp=p.object({...k,locator:$,type:p.literal("select"),value:ae}),Gp=p.object({...k,locator:$,type:p.literal("hover")}),Kp=p.object({...k,key:p.string().min(1),locator:$.optional(),type:p.literal("press")}),Jp=p.object({...k,locator:$,type:p.literal("check")}),Xp=p.object({...k,locator:$,type:p.literal("uncheck")}),Yp=p.object({...k,height:p.number().int().positive(),type:p.literal("setViewport"),width:p.number().int().positive()}),Qp=p.object({...k,message:p.string().min(1),type:p.literal("fail")}),Zp=p.object({...k,type:p.literal("setVariable"),value:Vp,variable:p.string().min(1)}),em=p.object({...k,locator:$,type:p.literal("extractText"),variable:p.string().min(1)}),rm=p.object({...k,files:p.array(p.string()).min(1),locator:$,type:p.literal("upload")}),tm=p.object({...k,locator:$,type:p.literal("dblclick")}),nm=p.object({...k,source:$,target:$,type:p.literal("drag")}),om=p.object({...k,locator:$,type:p.literal("scrollIntoView")}),im=p.object({...k,locator:$,type:p.literal("type"),value:ae}),sm=p.object({...k,locator:$,type:p.literal("focus")}),am=p.object({...k,locator:$,type:p.literal("clear")}),lm=p.object({...k,locator:$,type:p.literal("rightClick")}),cm=p.object({...k,action:p.enum(["accept","dismiss"]),promptText:p.string().optional(),type:p.literal("handleDialog")}),um=p.object({...k,action:p.enum(["read","write"]),type:p.literal("clipboard"),value:ae.optional(),variable:p.string().min(1).optional()}),dm=p.object({...k,permission:p.string().min(1),state:p.enum(["granted","prompt"]),type:p.literal("setPermission")}),pm=p.object({...k,locator:$,type:p.literal("assertVisible")}),mm=p.object({...k,locator:$,type:p.literal("assertNotVisible")}),fm=p.object({...k,expected:ae,locator:$,operator:br,type:p.literal("assertText")}),gm=p.object({...k,expected:ae,operator:br,type:p.literal("assertUrl")}),ym=p.object({...k,expected:Fp,locator:$,operator:_p,type:p.literal("assertCount")}),hm=p.object({...k,expected:ae,locator:$,operator:br,type:p.literal("assertValue")}),wm=p.object({...k,attribute:p.string().min(1),expected:ae,locator:$,operator:br,type:p.literal("assertAttribute")}),bm=p.object({...k,locator:$,type:p.literal("assertEnabled")}),vm=p.object({...k,locator:$,type:p.literal("assertDisabled")}),Sm=p.object({...k,expected:ae,operator:br,type:p.literal("assertTitle")}),km=p.object({...k,locator:$,type:p.literal("assertChecked")}),Pm=p.object({...k,locator:$,type:p.literal("assertNotChecked")}),Rm=p.object({...k,locator:$,type:p.literal("assertFocused")}),xm=p.object({...k,locator:$,type:p.literal("assertNotFocused")}),Em=p.object({...k,budget:p.enum(["fast","slow","async"]),observer:p.string().min(1).max(200),params:p.record(p.string().max(200),Mp),type:p.literal("assertObserver")}),Cm=p.discriminatedUnion("type",[Bp,Wp,qp,zp,Gp,Kp,Jp,Xp,pm,mm,fm,gm,ym,hm,wm,bm,vm,Yp,Qp,Zp,em,rm,tm,nm,om,im,sm,am,lm,cm,um,dm,Sm,km,Pm,Rm,xm,Em]),ki=p.object({entryNode:p.string().min(1).max(200),nodes:p.record(p.string().max(200),Cm).refine(e=>Object.keys(e).length<=yi,`Workflow has more than ${String(yi)} nodes`),uiOnly:p.boolean().optional(),variableNamespaces:p.record(p.string().max(200),p.string().max(500)).optional(),variables:p.record(p.string().max(200),Hp).optional()}),Am=gi.record(gi.string().max(200),En),Im={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&"entryNode"in e&&"nodes"in e},Tm={assumedVersion:1,detect:e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&!("__codec"in e)},jR=xn("workflow-spec").legacy(Im).initial(ki).build(),NR=xn("precondition-map").legacy(Tm).initial(Am).build(),$m=["fast","slow","async"],Pi=kn.object({budget:kn.enum($m).describe("Polling budget tier: fast | slow | async"),description:kn.string().min(1).describe("Human-readable description of what this observer checks")}).describe("A named backend state observer. Tests assert against it with assert.backend(observer, params). Implementation lives on the user's server."),le=".ripplo/ripplo.lock",jm=".ripplo/fixtures",Ri=5e3,Nm=T.record(T.string().max(200),T.string().max(200)),xi=T.object({coverage:T.array(T.string().max(500)).max(2e3).default([]),expectedOutcome:T.string().max(2e3),name:T.string().max(200),preconditions:T.array(T.string().max(200)).max(1e3),requiresKeys:Nm,slug:T.string().max(200),sourcePath:T.string().max(500).optional(),spec:ki}),Dm=T.object({sha256:T.string().regex(/^[0-9a-f]{64}$/u),size:T.number().int().nonnegative()}),Om=T.record(T.string().min(1).max(500),Dm),Lm=T.object({observers:T.record(T.string().max(200),Pi),preconditions:T.record(T.string().max(200),En),tests:T.array(xi).max(Ri)}),_m=T.object({fixtures:Om,observers:T.record(T.string().max(200),Pi),preconditions:T.record(T.string().max(200),En),tests:T.array(xi).max(Ri)}),Ei=xn("ripplo-lockfile").initial(Lm).upgrade(_m,e=>({...e,fixtures:{}})).build();function Ci(e){return{fixtures:{...e.fixtures},observers:e.observers,preconditions:e.preconditions,tests:e.tests.filter(r=>r.implemented).map(r=>({coverage:[...r.coverage],expectedOutcome:r.expectedOutcome,name:r.name,preconditions:[...r.preconditions],requiresKeys:{...r.requiresKeys},slug:r.slug,sourcePath:r.sourcePath,spec:r.spec}))}}function Rn(e){let r=Ei.encode(e);return`${JSON.stringify(r,Mm(r),2)}
|
|
262
|
+
`}async function rt({cwd:e}){let r=We.join(e,le),t=await Fm(r);return t==null?null:$p(Ei,t)}var hi=10*1024*1024,wi=50*1024*1024;async function ce({cwd:e,result:r}){let t=await Ai({cwd:e,result:r}),n=Ci(t),o=We.join(e,le);await wr.mkdir(We.dirname(o),{recursive:!0}),await wr.writeFile(o,Rn(n),"utf8")}async function Ai({cwd:e,result:r}){let t=Vm(r);if(t.size===0)return{...r,fixtures:{}};let n=We.join(e,jm),o=[...t].toSorted((a,l)=>a.localeCompare(l)),i=await Promise.all(o.map(async a=>{let l=await Um({fixturesRoot:n,name:a});if(l.size>hi)throw new Error(`Fixture "${a}" is ${String(l.size)} bytes; exceeds per-file limit of ${String(hi)} bytes`);return[a,l]}));if(i.reduce((a,[,l])=>a+l.size,0)>wi)throw new Error(`Total fixtures size exceeds limit of ${String(wi)} bytes`);return{...r,fixtures:Object.fromEntries(i)}}async function Um({fixturesRoot:e,name:r}){let t=r;if(typeof t!="string"||t.length===0)throw new Error(`Internal error: upload step produced a non-string fixture name (got ${t===null?"null":typeof t}). This usually means a test passed a non-Fixture value to upload() \u2014 wrap the filename with fixture("file.png").`);if(r.includes("..")||We.isAbsolute(r))throw new Error(`Invalid fixture name "${r}": must be a path under .ripplo/fixtures/`);let n=We.join(e,r),o=await wr.lstat(n).catch(a=>{throw Ii(a)&&a.code==="ENOENT"?new Error(`Fixture "${r}" not found at ${n}`):a});if(o.isSymbolicLink())throw new Error(`Fixture "${r}" is a symlink; symlinks are not allowed`);if(!o.isFile())throw new Error(`Fixture "${r}" is not a regular file`);let i=await wr.readFile(n);return{sha256:Cp("sha256").update(i).digest("hex"),size:i.byteLength}}function Vm(e){let r=new Set;return e.tests.forEach(t=>{Object.entries(t.spec.nodes).forEach(([n,o])=>{o.type==="upload"&&o.files.forEach((i,s)=>{let a=i;if(typeof a!="string"||a.length===0)throw new Error(`Test "${t.slug}" step "${n}" upload files[${String(s)}] is not a non-empty string (got ${a===null?"null":typeof a}). Wrap filenames with fixture(): upload(loc, fixture("file.png")).`);r.add(a)})})}),r}async function tt({compiled:e,cwd:r,existing:t}){if(t==null)return"missing";let n=await Ai({cwd:r,result:e}),o=Rn(Ci(n)),i=Rn(t);return o===i?"match":"stale"}async function Fm(e){try{return await wr.readFile(e,"utf8")}catch(r){if(Ii(r)&&r.code==="ENOENT")return null;throw r}}function Ii(e){return e instanceof Error&&"code"in e}function Mm(e){return function(t,n){return n===e||!Hm(n)?n:Object.fromEntries(Object.entries(n).toSorted(([o],[i])=>o.localeCompare(i)))}}function Hm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import vr from"fs";import it from"path";var Cn=["**/src/**","**/app/**","**/apps/**","**/pages/**","**/routes/**","**/components/**","**/server/**","**/api/**","**/backend/**","**/features/**","**/modules/**","**/views/**","**/ui/**","**/hooks/**","**/contexts/**","**/providers/**","**/controllers/**","**/handlers/**","**/resolvers/**","**/services/**","**/middleware/**","**/lib/**"],xe=["**/*.gen.*","**/generated/**","**/*.d.ts","**/*.test.*","**/*.spec.*","**/node_modules/**","**/dist/**","**/build/**",".ripplo/**","**/*.md","**/.next/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/.nuxt/**","**/.astro/**","**/coverage/**","**/storybook-static/**","**/*.stories.*","**/*.story.*","**/cli/**","**/scripts/**","**/tools/**","**/__tests__/**","**/__mocks__/**","**/__fixtures__/**","**/*.config.*","**/*.setup.*","**/public/**","**/static/**","**/assets/**","**/migrations/**","**/prisma/migrations/**","**/scripts/**"];function Ti(e){return e.data}function $i(e){return{as(r){return{data:{label:r,node:e}}}}}function nt(e){let r=e.getPreconditions(),t=e.getObservers(),n=e.getTests();Bm(n);let o={};r.forEach(a=>{o[a.name]={depends:[...a.dependsOn],description:a.description,returns:[...a.returns]}});let i={};t.forEach(a=>{i[a.name]={budget:a.budget,description:a.description}});let s=n.map(a=>Wm(a,r));return{fixtures:{},observers:i,preconditions:o,tests:s}}function Bm(e){let r=new Map;e.forEach(t=>{let n=r.get(t.id);if(n!=null)throw new Error(`Duplicate test id "${t.id}" used by "${n}" and "${t.name}"`);r.set(t.id,t.name)})}function Wm(e,r){let t=e.id,{accessedKeys:n,vars:o}=zm(e.requiresKeys),i=e.startsAtFn==null?void 0:e.startsAtFn(o),s=e.stepsFn==null?[]:e.stepsFn(o),a=i==null?s:[qm(i),...s],l=Gm(a,n,e.requiresKeys,e.uiOnly),c=[];Object.keys(e.requiresKeys).length>0&&n.size===0&&e.implemented&&c.push("Test requires preconditions but never references their data \u2014 destructure and use precondition data in steps()");let m=Jm(e.requires,r);return{additionalChecks:[],coverage:e.coverage,description:e.description,expectedOutcome:e.expectedOutcome,implemented:e.implemented,name:e.name,preconditions:m,requiresKeys:{...e.requiresKeys},slug:t,sourcePath:e.sourcePath,spec:l,warnings:c}}function qm(e){return $i({type:"goto",url:{type:"static",value:e}}).as(`navigate to ${e}`)}function zm(e){let r=new Set,t={};return Object.keys(e).forEach(n=>{t[n]=new Proxy({},{get(o,i){if(typeof i=="string"){let s=`${n}.${i}`;return r.add(s),`{{${s}}}`}}})}),{accessedKeys:r,vars:t}}function Gm(e,r,t,n){let o={};e.forEach((a,l)=>{let c=`step-${String(l)}`,u=l<e.length-1?`step-${String(l+1)}`:void 0;o[c]=Km(a,c,u)});let i={};r.forEach(a=>{i[a]={default:`test-${a}`,type:"string"}});let s={...t};return{entryNode:"step-0",nodes:o,uiOnly:n,variableNamespaces:s,variables:i}}function Km(e,r,t){let{label:n,node:o}=Ti(e);return{...o,id:r,label:n,next:t}}function Jm(e,r){let t=new Map(r.map(s=>[s.name,s])),n=[],o=new Set;function i(s){o.has(s)||(o.add(s),t.get(s)?.dependsOn.forEach(a=>{i(a)}),n.push(s))}return e.forEach(s=>{i(s)}),n}import{Webhook as WR,WebhookVerificationError as qR}from"standardwebhooks";import{z as _}from"zod";var ji=_.union([_.string(),_.number(),_.boolean()]),Xm=_.record(_.string(),_.record(_.string(),ji)),GR=_.object({batch:_.array(_.object({preconditions:_.array(_.string().min(1)),runId:_.string().min(1)})).min(1)}),KR=_.object({batch:_.array(_.object({data:Xm,preconditions:_.array(_.string().min(1)),runId:_.string().min(1)})).min(1)}),JR=_.object({observer:_.string().min(1).max(200),params:_.record(_.string().max(200),ji)});function qe(e){let r=[];return e.tests.forEach(t=>{let n=Ym(t),o=i=>{r.push({...i,test:t.slug})};Sf.forEach(i=>{i(n,t,o)})}),{diagnostics:r}}function Ym(e){let r=[],t=e.spec.entryNode,n=new Set;for(;t!=null&&!n.has(t);){n.add(t);let o=e.spec.nodes[t];if(o==null)break;r.push(o),t=o.next}return r}function Qm(e,r,t){e.forEach(n=>{n.type==="assertText"&&"operator"in n&&n.operator!=="equals"&&t({message:`${n.type} uses operator "${n.operator}" \u2014 only "equals" is allowed for determinism`,rule:"exact-text-match",step:n.label??n.id})})}function Zm(e,r,t){Object.keys(r.spec.variables??{}).length>0&&e.forEach(o=>{if(o.type==="fill"&&Di(o.value)){let i=o.value.value;!Oi(i)&&af(i)&&t({message:`fill() uses hardcoded value "${i}" \u2014 consider using precondition data via {{namespace.key}}`,rule:"no-hardcoded-data",step:o.label??o.id})}})}function ef(e,r,t){if(Object.keys(r.spec.variables??{}).length===0)return;e.some(i=>JSON.stringify(i).includes("{{"))||t({message:"Test requires preconditions but steps() never references precondition data \u2014 destructure and use it",rule:"prefer-precondition-data",step:void 0})}function rf(e,r,t){e.forEach(n=>{(n.label==null||n.label.length===0)&&t({message:`Step "${n.id}" lacks .as("...") label \u2014 every step must be labeled`,rule:"missing-label",step:n.id})})}function tf(e,r,t){let n=new Map;e.forEach(o=>{if(o.label==null)return;let i=n.get(o.label);i==null?n.set(o.label,o.id):t({message:`Duplicate label "${o.label}" \u2014 also used by ${i}`,rule:"no-duplicate-labels",step:o.label})})}function nf(e,r,t){let n=0;e.forEach((o,i)=>{if(!(i===0&&o.type==="goto")){if(ze(o)){n=0;return}n++,n===3&&t({message:"3+ consecutive actions without an assertion \u2014 add verification between actions",rule:"assert-after-action",step:o.label??o.id})}})}function of(e,r,t){if(e.length===0)return;let n=e.at(-1);n!=null&&!ze(n)&&t({message:"Last step is an action, not an assertion \u2014 expectedOutcome should be verified by assertions at the end",rule:"assert-matches-outcome",step:n.label??n.id})}function sf(e,r,t){r.implemented&&e.length===0&&t({message:"Test has zero steps",rule:"no-empty-steps",step:void 0})}function Di(e){return!(typeof e!="object"||e==null||!("type"in e)||e.type!=="static"||!("value"in e)||typeof e.value!="string")}function Oi(e){return e.includes("{{")}function af(e){return e.includes("@")||/\b[a-f0-9]{8,}\b/.test(e)||/^(test|ripplo|example|sample|demo)/i.test(e)}function ze(e){return e.type.startsWith("assert")}var lf=new Set(["assertText","assertValue","assertCount","assertUrl","assertNotVisible","assertChecked","assertNotChecked","assertAttribute","assertDisabled","assertEnabled"]);function cf(e){return lf.has(e.type)}function uf(e,r,t){!r.implemented||e.length===0||e.some(n=>ze(n))||t({message:"Test has zero assertion steps \u2014 cannot verify expectedOutcome. Add assert.* steps.",rule:"no-assertions",step:void 0})}function df(e,r,t){if(!r.implemented||e.length<=3)return;let n=e.filter(i=>ze(i)).length;if(n===0)return;let o=n/e.length;if(o<.15){let i=Math.round(o*100);t({message:`Only ${String(n)}/${String(e.length)} steps are assertions (${String(i)}%) \u2014 add more verification between actions`,rule:"low-assertion-ratio",step:void 0})}}function An(e){if(!("locator"in e)||e.locator==null)return;let r=e.locator;return r.by==="role"?`role:${r.role}:${r.name??""}`:`testId:${r.value}`}function pf(e,r,t){e.forEach((n,o)=>{if(n.type!=="click")return;let i=An(n);if(i==null)return;let s=e.slice(o+1,o+4);s.find(c=>c.type==="assertVisible"&&An(c)===i)==null||s.some(c=>cf(c)||ze(c)&&An(c)!==i)||t({message:`click "${n.label??n.id}" is followed only by assert.visible on the same locator \u2014 verifies nothing about the click's effect`,rule:"tautological-post-click-assert",step:n.label??n.id})})}var mf=new Set(["the","is","a","an","and","or","of","to","in","on","at","for","that","this","with","be","are","was","were","it","its","as","by","from","after","before","should","will","can","still","but","not","no","so","if","then","than","user","users","page","view","shows","show","see","click","clicks","clicked","clickable","visible","appears","appear","displayed","stays","remains"]);function In(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>=3&&!mf.has(r))}function ff(e){let r=e.label==null?[]:In(e.label);if(!("locator"in e)||e.locator==null)return r;let t=e.locator,n=t.by==="role"?t.name??"":t.value;return[...r,...In(n)]}function gf(e,r,t){if(!r.implemented||e.length===0)return;let n=new Set(In(r.expectedOutcome));if(n.size===0)return;let o=e.filter(s=>ze(s));if(o.length===0)return;o.some(s=>ff(s).some(a=>n.has(a)))||t({message:`No assertion references any keyword from expectedOutcome (${[...n].join(", ")}) \u2014 the outcome may not actually be verified`,rule:"expected-outcome-keyword-coverage",step:void 0})}var yf=/save|submit|create|delete|remove|send|invite|update|confirm|publish|apply|pay|subscribe|upgrade|cancel|archive|rename/i;function Ni(e){if(e.type==="upload")return!0;if(e.type!=="click")return!1;let r=e.locator,t=r.by==="role"?r.name??"":r.value;return yf.test(t)}function hf(e,r,t){!r.implemented||r.spec.uiOnly===!0||e.forEach((n,o)=>{if(!Ni(n)||"uiOnly"in n&&n.uiOnly===!0)return;let i=e.slice(o+1),s=i.findIndex(u=>Ni(u)),a=s===-1?i.length:s;i.slice(0,a).some(u=>u.type==="assertObserver")||t({message:`"${n.label??n.id}" looks like it mutates backend state but no assert.backend(...) observer verifies it \u2014 the test can pass while the server is broken. You need to add an observer that checks the persisted result (see .ripplo/observers/ for examples). Only if this action truly does NOT change any server state (pure client-side interaction, presentation toggle, etc.) should you fall back to marking the step { uiOnly: true } to silence this rule.`,rule:"mutation-without-observer-coverage",step:n.label??n.id})})}function wf(e,r,t){Object.keys(r.spec.variables??{}).length!==0&&e.forEach(o=>{if(o.type!=="assertObserver")return;let i=Object.entries(o.params);i.length===0||i.some(([,a])=>Di(a)&&Oi(a.value))||t({message:`assert.backend "${o.label??o.id}" passes only hardcoded params while the test defines precondition variables \u2014 observer assertions should reference {{namespace.key}} so they match the actual precondition data`,rule:"observer-params-reference-variables",step:o.label??o.id})})}function bf(e,r,t){e.forEach(n=>{n.type==="upload"&&n.files.forEach(o=>{if(o.length===0){t({message:`upload "${n.label??n.id}" references an empty fixture name`,rule:"upload-fixture-name",step:n.label??n.id});return}(o.includes("..")||o.startsWith("/"))&&t({message:`upload "${n.label??n.id}" references "${o}" \u2014 fixture names must be relative paths under .ripplo/fixtures/, no ".." or absolute paths`,rule:"upload-fixture-name",step:n.label??n.id})})})}function vf(e,r,t){let n=new Set(Object.keys(r.spec.variables??{})),o=/\{\{([^{}]+?)\}\}/g;e.forEach(i=>{let a=[...JSON.stringify(i).matchAll(o)],l=[...new Set(a.map(m=>m[1]).filter(m=>m!=null&&!n.has(m)))];if(l.length===0)return;let c=l.map(m=>`{{${m}}}`).join(", "),u=[...new Set(l.map(m=>m.split(".")[0]??m))].join(", ");t({message:`"${i.label??i.id}" contains literal template string(s) ${c} \u2014 destructure the proxy in .steps(({ ${u} }) => \u2026) and pass the proxy value (e.g. \`${l[0]??""}\`) directly. Writing the template as a string bypasses type-checking and silently accepts typos.`,rule:"no-literal-template-strings",step:i.label??i.id})})}var Sf=[Qm,Zm,vf,ef,rf,tf,nf,of,sf,uf,df,pf,gf,hf,wf,bf];import zf from"picomatch";import{execFileSync as kf,spawnSync as Pf}from"child_process";function K(e,r){return kf("git",[...e],{cwd:r,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}function Li(e,r){let t=Pf("git",["show",e],{cwd:r,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(t.status===0)return t.stdout;if(t.status===128)return null;throw new Error(`git show ${e} failed (${String(t.status)}): ${t.stderr}`)}import b from"typescript";import*as _i from"remeda";var Ui=[["onClick","click"],["onContextMenu","click"],["onKeyDown","click"],["onKeyPress","click"],["onKeyUp","click"],["onSelect","click"],["onOpenChange","click"],["onPress","click"],["onActivate","click"],["onToggle","click"],["onOpen","click"],["onClose","click"],["onDismiss","click"],["onConfirm","click"],["onCancel","click"],["onApply","click"],["onClear","click"],["onSubmit","submit"],["onReset","submit"],["onDrop","drag"],["onDragEnd","drag"],["onDragEnter","drag"],["onDragLeave","drag"],["onDragOver","drag"],["onDragStart","drag"],["onValueChange","select"],["onSelectionChange","select"],["onChange","input"],["onCheckedChange","input"],["onInput","input"]],Rf=new Map([["button","click"],["link","navigate"],["textbox","input"],["searchbox","input"],["combobox","select"],["listbox","select"]]),xf=[[/(?:^|[a-z])Button$/,"click"],[/(?:^|[a-z])(?:Link|NavLink|Anchor)$/,"navigate"],[/(?:^|[a-z])(?:Textarea|TextArea|Input|Field|SearchBox)$/,"input"],[/(?:^|[a-z])(?:Select|Combobox|ComboBox|Dropdown)$/,"select"],[/(?:^|[a-z])Form$/,"submit"]];function ot({filePath:e,source:r}){let t=b.createSourceFile(e,r,b.ScriptTarget.Latest,!0,b.ScriptKind.TSX);return t.statements.flatMap(n=>Ef({filePath:e,sf:t,stmt:n}))}function Ef({filePath:e,sf:r,stmt:t}){let n=Af(t);if(n==null||Cf(n))return[];let o=Vi(t,r).map(i=>({id:`${e}#${n}.${i.kind}[${i.label}]`,line:i.line}));return _i.uniqueBy(o,i=>i.id)}function Cf(e){return e.endsWith("Fragment")||e.endsWith("Skeleton")||/^use[A-Z]/.test(e)||/^[A-Z][A-Z0-9_]*$/.test(e)}function Af(e){if(b.isExportAssignment(e))return If(e.expression);if(!Tf(e))return null;if(b.isFunctionDeclaration(e)||b.isClassDeclaration(e))return e.name?.text??null;if(b.isVariableStatement(e)){let r=e.declarationList.declarations[0];return r!=null&&b.isIdentifier(r.name)?r.name.text:null}return null}function If(e){return b.isIdentifier(e)?e.text:(b.isFunctionExpression(e)||b.isClassExpression(e))&&e.name!=null?e.name.text:"default"}function Tf(e){if(!b.canHaveModifiers(e))return!1;let r=b.getModifiers(e);return r!=null&&r.some(t=>t.kind===b.SyntaxKind.ExportKeyword)}function Vi(e,r){let t=$f(e,r),n=e.getChildren(r).flatMap(o=>Vi(o,r));return t==null?n:[t,...n]}function $f(e,r){let t=jf(e);if(t==null)return null;let n=Nf(t);if(n==null)return null;let o=Uf(t,n);return o==null?null:{kind:n,label:o,line:qf(r,e.getStart(r))}}function jf(e){return b.isJsxSelfClosingElement(e)&&b.isIdentifier(e.tagName)?{attrs:e.attributes,children:[],tag:e.tagName.text}:b.isJsxElement(e)&&b.isIdentifier(e.openingElement.tagName)?{attrs:e.openingElement.attributes,children:e.children,tag:e.openingElement.tagName.text}:null}function Nf({attrs:e,tag:r}){let t=ue(e,"role");return t!=null?Rf.get(t)??null:Of(r,e)??Lf(r)??_f(e)}var Df=new Map([["button",()=>"click"],["a",e=>ue(e,"href")==null?null:"navigate"],["input",e=>ue(e,"type")==="file"?"upload":"input"],["textarea",()=>"input"],["select",()=>"select"],["form",()=>"submit"]]);function Of(e,r){return Df.get(e)?.(r)??null}function Lf(e){return/^[A-Z]/.test(e)?xf.find(([r])=>r.test(e))?.[1]??null:null}function _f(e){return Ui.find(([r])=>Mf(e,r))?.[1]??null}function Uf({attrs:e,children:r,tag:t},n){return n==="navigate"?ue(e,"href")??ue(e,"to"):ue(e,"aria-label")??ue(e,"label")??ue(e,"title")??ue(e,"name")??ue(e,"placeholder")??(Vf(t)?void 0:Wf(r))??Ff(e,n)}function Vf(e){return e==="input"||e==="textarea"||e==="select"}function Ff(e,r){let t=Ui.find(([,o])=>o===r)?.[0];if(t==null)return;let n=Hf(e,t);if(n!=null){if(b.isIdentifier(n))return n.text;if(b.isArrowFunction(n)||b.isFunctionExpression(n))return Fi(n.body)}}function Fi(e){if(b.isCallExpression(e)){let r=e.expression;return b.isIdentifier(r)?r.text:b.isPropertyAccessExpression(r)?r.name.text:void 0}return b.forEachChild(e,Fi)}function Mf(e,r){return e.properties.some(t=>b.isJsxAttribute(t)&&b.isIdentifier(t.name)&&t.name.text===r)}function Mi(e,r){return e.properties.find(t=>b.isJsxAttribute(t)&&b.isIdentifier(t.name)&&t.name.text===r)}function ue(e,r){let t=Mi(e,r);return t==null?void 0:Bf(t.initializer)}function Hf(e,r){let t=Mi(e,r);if(!(t?.initializer==null||!b.isJsxExpression(t.initializer)))return t.initializer.expression}function Bf(e){if(e==null)return"";if(b.isStringLiteral(e))return e.text;if(b.isJsxExpression(e))return Bi(e.expression)}function Wf(e){let r=e.flatMap(t=>Hi(t)).join(" ").trim();return r.length===0?void 0:r}function Hi(e){if(b.isJsxText(e)){let r=e.text.trim();return r.length===0?[]:[r]}if(b.isJsxExpression(e)){let r=Bi(e.expression);return r==null?[]:[r]}return b.isJsxElement(e)?e.children.flatMap(r=>Hi(r)):[]}function Bi(e){if(e!=null){if(b.isStringLiteral(e)||b.isNoSubstitutionTemplateLiteral(e))return e.text;if(b.isCallExpression(e)&&e.arguments.length===1){let r=e.arguments[0];if(r!=null&&(b.isStringLiteral(r)||b.isNoSubstitutionTemplateLiteral(r)))return r.text}}}function qf(e,r){return e.getLineAndCharacterOfPosition(r).line+1}var Gf=it.join(".ripplo","coverage.d.ts");function Ge({cwd:e}){Kf({cwd:e,ignorePaths:xe})}function Kf({cwd:e,ignorePaths:r}){let t=Ke({cwd:e,ignorePaths:r});Yf({content:Xf(t),cwd:e})}function Ke({cwd:e,ignorePaths:r}){let n=Jf({cwd:e,ignorePaths:r}).flatMap(o=>Tn({cwd:e,file:o}));return[...new Set(n)].sort((o,i)=>o.localeCompare(i))}function Jf({cwd:e,ignorePaths:r}){let t=K(["ls-files","--cached","--others","--exclude-standard","-z"],e),n=zf([...r]);return t.split("\0").filter(o=>o.length>0&&/\.(tsx|jsx)$/.test(o)).filter(o=>!n(o)).filter(o=>vr.existsSync(it.join(e,o)))}function Tn({cwd:e,file:r}){let t=vr.readFileSync(it.join(e,r),"utf8");return ot({filePath:r,source:t}).map(n=>n.id)}function Xf(e){let r=`// GENERATED \u2014 do not edit
|
|
262
263
|
import "@ripplo/testing";
|
|
263
264
|
|
|
264
265
|
declare module "@ripplo/testing" {
|
|
265
266
|
interface CoverageRegistry {
|
|
266
|
-
`,
|
|
267
|
-
`);return e.length===0?`${
|
|
267
|
+
`,t=e.map(o=>` ${JSON.stringify(o)}: true;`).join(`
|
|
268
|
+
`);return e.length===0?`${r} }
|
|
268
269
|
}
|
|
269
|
-
`:`${
|
|
270
|
+
`:`${r}${t}
|
|
270
271
|
}
|
|
271
272
|
}
|
|
272
|
-
`}function Yf({content:e,cwd:
|
|
273
|
+
`}function Yf({content:e,cwd:r}){let t=it.join(r,Gf);vr.existsSync(t)&&vr.readFileSync(t,"utf8")===e||vr.writeFileSync(t,e)}import{readdir as tg,stat as ng}from"fs/promises";import kr from"path";import{createJiti as og}from"jiti";import Qf from"fs";import Sr from"path";import Je from"typescript";function Wi(e){let r=Sr.join(e,"index.ts"),t=rg(e);Qf.mkdirSync(Sr.dirname(t.tsBuildInfoFile??""),{recursive:!0});let n=Je.createIncrementalCompilerHost(t),o=Je.createIncrementalProgram({host:n,options:t,rootNames:[r]}),i=[...o.getSyntacticDiagnostics(),...o.getSemanticDiagnostics()];o.emit();let s=i.filter(c=>Zf(c,e));if(s.length===0)return{diagnostics:[],ok:!0};let a={getCanonicalFileName:c=>c,getCurrentDirectory:()=>Sr.dirname(e),getNewLine:()=>`
|
|
273
274
|
`};return{diagnostics:Je.formatDiagnosticsWithColorAndContext(s,a).split(`
|
|
274
|
-
`).filter(c=>c.length>0),ok:!1}}function Zf(e,
|
|
275
|
-
`),ok:!1};try{let o=await og(import.meta.url,{fsCache:!1,moduleCache:!1,sourceMaps:!0}).import(e),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;return sg(i)?{builder:i,ok:!0,result:
|
|
276
|
-
`)}async function zi(e,t
|
|
277
|
-
`).map(a=>dg.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(
|
|
275
|
+
`).filter(c=>c.length>0),ok:!1}}function Zf(e,r){let t=e.file?.fileName;return t==null?!0:t.startsWith(r)}var eg=Sr.join(".local","tsbuildinfo");function rg(e){return{allowImportingTsExtensions:!0,allowJs:!1,esModuleInterop:!0,incremental:!0,module:Je.ModuleKind.Preserve,moduleResolution:Je.ModuleResolutionKind.Bundler,noEmit:!0,resolveJsonModule:!0,skipLibCheck:!0,strict:!1,target:Je.ScriptTarget.ES2022,tsBuildInfoFile:Sr.join(e,eg)}}var ig=["getObservers","getPreconditions","getTests","getUnimplemented"];function sg(e){return e==null||typeof e!="object"?!1:ig.every(r=>typeof Reflect.get(e,r)=="function")}function ag(e){return e===null?"null":Array.isArray(e)?"array":typeof e}var lg=new Set(["debug",".local"]),qi=new Map;async function x(e){let r=kr.join(e,".ripplo","index.ts"),t=kr.join(e,".ripplo"),n=await ug(t),o=qi.get(e);if(o!=null&&o.fingerprint===n)return o.result;let i=await cg(r,t);return qi.set(e,{fingerprint:n,result:i}),i}async function cg(e,r){let t=Wi(r);if(!t.ok)return{error:["TypeScript errors in .ripplo/:",...t.diagnostics].join(`
|
|
276
|
+
`),ok:!1};try{let o=await og(import.meta.url,{fsCache:!1,moduleCache:!1,sourceMaps:!0}).import(e),i=o!=null&&typeof o=="object"&&"default"in o?Reflect.get(o,"default"):o;return sg(i)?{builder:i,ok:!0,result:nt(i)}:{error:`${e} must default-export a RipploBuilder (got ${ag(i)})`,ok:!1}}catch(n){return{error:pg(n,r),ok:!1}}}async function ug(e){let r=[];return await zi(e,e,r),r.sort((t,n)=>t.localeCompare(n)),r.join(`
|
|
277
|
+
`)}async function zi(e,r,t){let n=await tg(r,{withFileTypes:!0}).catch(()=>[]);await Promise.all(n.map(async o=>{if(o.isDirectory()){if(lg.has(o.name))return;await zi(e,kr.join(r,o.name),t);return}let i=kr.join(r,o.name),s=await ng(i).catch(()=>{});s!=null&&t.push(`${kr.relative(e,i)}:${String(s.mtimeMs)}:${String(s.size)}`)}))}var dg=/\(?([^\s()]{1,500}\.ts):(\d{1,10}):(\d{1,10})\)?$/;function pg(e,r){if(!(e instanceof Error))return String(e);let t=mg(e.stack,r);return t==null?e.message:`${t} \u2014 ${e.message}`}function mg(e,r){if(e==null)return;let n=e.split(`
|
|
278
|
+
`).map(a=>dg.exec(a)).find(a=>a!=null&&a[1]!=null&&a[2]!=null&&a[3]!=null&&a[1].startsWith(r));if(n==null)return;let[,o,i,s]=n;return`${o??""}:${i??""}:${s??""}`}function w(e,r){return r==null?`Load \`/ripplo:${e}\` skill for instructions.`:`Load \`/ripplo:${e}\` skill for instructions on ${r}.`}function Gi(e){return e.length===1?w(e[0]):`REQUIRED before proceeding: load ${e.map(t=>`\`/ripplo:${t}\``).join(" AND ")} skills (load every one \u2014 each carries rules the others don't).`}function $n(e){process.stderr.write(`Compilation failed: ${e}
|
|
278
279
|
`),process.stderr.write(`${w("create","DSL authoring + lint rules")}
|
|
279
|
-
`),process.exit(1)}function Ki(e){return e instanceof Error?e.message:String(e)}async function Ji(e){let
|
|
280
|
+
`),process.exit(1)}function Ki(e){return e instanceof Error?e.message:String(e)}async function Ji(e){let r=process.cwd(),t=await x(r);if(t.ok||$n(t.error),e.check){let n=await rt({cwd:r}),o=await tt({compiled:t.result,cwd:r,existing:n}).catch(s=>$n(Ki(s)));if(o==="match"){process.stdout.write(`${le} is up to date
|
|
280
281
|
`);return}let i=o==="missing"?"missing":"out of date";process.stderr.write(`${le} is ${i} \u2014 run \`ripplo compile\` and commit the result
|
|
281
282
|
`),process.stderr.write(`${w("setup")}
|
|
282
|
-
`),process.exit(1)}try{await ce({cwd:
|
|
283
|
-
`)}import fe from"process";import fg from"fs";import gg from"path";import yg from"picomatch";function Xi({compileResult:e,cwd:
|
|
284
|
-
`),fe.exit(1));let
|
|
283
|
+
`),process.exit(1)}try{await ce({cwd:r,result:t.result})}catch(n){$n(Ki(n))}Ge({cwd:r}),process.stdout.write(`wrote ${le}
|
|
284
|
+
`)}import fe from"process";import fg from"fs";import gg from"path";import yg from"picomatch";function Xi({compileResult:e,cwd:r,ignorePaths:t}){let n=new Set(Ke({cwd:r,ignorePaths:t})),o=Zi(e),i=hg({cwd:r,ignorePaths:t});return Qi({acknowledged:o,allStatements:n,unacked:i})}function Yi({compileResult:e,cwd:r,ignorePaths:t}){let n=new Set(Ke({cwd:r,ignorePaths:t})),o=Zi(e);return Qi({acknowledged:o,allStatements:n,unacked:n})}function Qi({acknowledged:e,allStatements:r,unacked:t}){let n=[...t].filter(i=>!e.has(i)).map(i=>({id:i,kind:"unacknowledged"})),o=[...e].filter(i=>!r.has(i)).map(i=>({id:i,kind:"stale"}));return[...n,...o]}function Zi(e){return new Set(e.tests.flatMap(r=>r.coverage))}function hg({cwd:e,ignorePaths:r}){let t=wg({cwd:e,ignorePaths:r}),n=new Set(t.flatMap(i=>bg({cwd:e,file:i}))),o=new Set(t.flatMap(i=>vg({cwd:e,file:i})?Tn({cwd:e,file:i}):[]));return new Set([...o].filter(i=>!n.has(i)))}function wg({cwd:e,ignorePaths:r}){let t=K(["diff","--name-only","HEAD","-z"],e),n=K(["ls-files","--others","--exclude-standard","-z"],e),o=yg([...r]);return[...new Set([...t.split("\0"),...n.split("\0")])].filter(i=>i.length>0&&/\.(tsx|jsx)$/.test(i)).filter(i=>!o(i))}function bg({cwd:e,file:r}){let t=Li(`HEAD:${r}`,e);return t==null?[]:ot({filePath:r,source:t}).map(n=>n.id)}function vg({cwd:e,file:r}){return fg.existsSync(gg.join(e,r))}async function es(){let e=fe.cwd(),r=await x(e);r.ok||(fe.stderr.write(`Compilation failed: ${r.error}
|
|
285
|
+
`),fe.exit(1));let t=Ke({cwd:e,ignorePaths:xe}),n=Yi({compileResult:r.result,cwd:e,ignorePaths:xe}),o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=t.length-o.length;fe.stdout.write(`Coverage: ${String(s)}/${String(t.length)} statements acknowledged
|
|
285
286
|
`),o.length>0&&(fe.stdout.write(`
|
|
286
287
|
Unacknowledged (${String(o.length)}):
|
|
287
288
|
`),o.forEach(a=>fe.stdout.write(` ${a.id}
|
|
288
289
|
`))),i.length>0&&(fe.stdout.write(`
|
|
289
290
|
Stale claims (${String(i.length)}):
|
|
290
291
|
`),i.forEach(a=>fe.stdout.write(` ${a.id}
|
|
291
|
-
`))),n.length>0&&fe.exit(1)}import{graphql as Ag}from"gql.tada";import
|
|
292
|
+
`))),n.length>0&&fe.exit(1)}import{graphql as Ag}from"gql.tada";import rs from"fs";import jn from"path";function ts(e){let r=rs.realpathSync(e),t=r,n=jn.dirname(t);for(;n!==t;){if(rs.existsSync(jn.join(t,".git")))return t;t=n,n=jn.dirname(t)}return r}function W(e){let r=yn(e),t=He(),n=ie();if(n==null)throw new Error("ripplo: not authenticated. Run `ripplo auth login`.");return{appUrl:t.appUrl,cwd:ts(e),engineUrl:t.engineUrl,projectId:ci()??r.projectId,ripploServerUrl:ee(),token:n,webhookSecret:t.webhookSecret}}import ge from"fs";var Sg="dev.pid";function os(e){return fr(e,Sg)}function Ye(e){let r=os(e);if(!ge.existsSync(r))return!1;let t=ge.readFileSync(r,"utf8").trim(),n=Number.parseInt(t,10);if(!Number.isFinite(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch{return!1}}var Xe=class extends Error{pid;cwd;constructor({cwd:r,pid:t}){super(`ripplo watch already running (pid ${String(t)})`),this.name="DevLockHeldError",this.pid=t,this.cwd=r}};function is(e){mr(e);let r=os(e);kg({cwd:e,path:r});let t=!1;return()=>{if(!t){t=!0;try{let n=ge.readFileSync(r,"utf8").trim();Number.parseInt(n,10)===process.pid&&ge.unlinkSync(r)}catch{}}}}function kg({cwd:e,path:r}){let t=()=>{try{let o=ge.openSync(r,"wx");return ge.writeSync(o,String(process.pid)),ge.closeSync(o),"ok"}catch(o){if(!Pg(o))throw o;let i=ns(r);if(i!=null&&Rg(i))throw new Xe({cwd:e,pid:i});return ge.unlinkSync(r),"retry"}};if(t()==="ok"||t()==="ok")return;let n=ns(r);throw n!=null?new Xe({cwd:e,pid:n}):new Error("failed to acquire dev lock")}function Pg(e){if(!(e instanceof Error)||!("code"in e))return!1;let{code:r}=e;return r==="EEXIST"}function ns(e){try{let r=ge.readFileSync(e,"utf8").trim(),t=Number.parseInt(r,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Rg(e){try{return process.kill(e,0),!0}catch{return!1}}import xg from"fs";import Nn from"path";var Eg=["MERGE_HEAD","rebase-merge","rebase-apply","CHERRY_PICK_HEAD","REVERT_HEAD"];function st(e){let r=Cg(e);return r==null?!1:Eg.some(t=>xg.existsSync(Nn.join(r,t)))}function Cg(e){try{let r=K(["rev-parse","--git-dir"],e).trim();return r.length===0?null:Nn.isAbsolute(r)?r:Nn.resolve(e,r)}catch{return null}}var Ig=Ag(`
|
|
292
293
|
query DevSessionCheckHealth($projectId: String!, $cwd: String!) {
|
|
293
294
|
project(id: $projectId) {
|
|
294
295
|
id
|
|
@@ -297,25 +298,25 @@ Stale claims (${String(i.length)}):
|
|
|
297
298
|
}
|
|
298
299
|
}
|
|
299
300
|
}
|
|
300
|
-
`);function ss(e){switch(e.status){case"active":return e.gitMidOperation?"\u2713 Dev session: ripplo watch is live (hooks auto-paused \u2014 git is mid-merge/rebase/cherry-pick; resumes when the operation completes or aborts)":"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function as(e){let
|
|
301
|
-
${e.missing.map(
|
|
301
|
+
`);function ss(e){switch(e.status){case"active":return e.gitMidOperation?"\u2713 Dev session: ripplo watch is live (hooks auto-paused \u2014 git is mid-merge/rebase/cherry-pick; resumes when the operation completes or aborts)":"\u2713 Dev session: ripplo watch is live for this directory";case"starting":return"! Dev session: `ripplo watch` is running locally but hasn't registered with the server yet. Wait a few seconds and re-run `npx ripplo doctor`. If it persists, check the watch process output for auth/network errors.";case"missing":return"\u2717 Dev session: no active ripplo watch. Start `npx ripplo watch` as a background process (separate from your app's dev server). Without it, `ripplo run` will refuse to dispatch and scope/coverage hooks won't arm."}}async function as(e){let r=Ye(e),t=st(e),n;try{n=W(e)}catch{return{gitMidOperation:t,status:r?"starting":"missing",type:"dev-session"}}return(await h({config:n,document:Ig,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null))?.project?.devSession!=null?{gitMidOperation:t,status:"active",type:"dev-session"}:{gitMidOperation:t,status:r?"starting":"missing",type:"dev-session"}}function ls(e){switch(e.type){case"settings":return Ng(e);case"env-files":return Dg(e);case"token":return Og(e);case"dev-server":return Lg(e);case"dev-session":return ss(e);case"preconditions":return Vg(e);case"webhook-verification":return _g(e);case"preconditions-validation":return Fg(e);case"workflows":return Mg(e);case"browser":return Ug(e);case"engine-endpoint":return e.reachable?`\u2713 Engine endpoint: ${e.url} is reachable`:`\u2717 Engine endpoint: ${e.url} is not reachable`;case"adapter-enabled":return Tg(e);case"lockfile":return $g(e);case"pre-commit-hook":return jg(e)}}function Tg(e){switch(e.status){case"enabled":return`\u2713 Adapter: enabled at ${e.url}`;case"disabled":return"\u2717 Adapter: disabled (handler returned 404). Set ENABLE_RIPPLO_TESTING=true in your app's env (e.g. apps/<app>/.env.local for Next.js) and restart the dev server.";case"bad-secret":return"\u2717 Adapter: webhook signature rejected. RIPPLO_WEBHOOK_SECRET seen by your dev server does not match the one in your env file.";case"unreachable":return`\u2717 Adapter: ${e.url} could not be reached for signed probe.`;case"no-secret":return"\u2717 Adapter: RIPPLO_WEBHOOK_SECRET is not set in your env file (declared in .ripplo/project.json)."}}function $g(e){switch(e.status){case"match":return`\u2713 Lockfile: ${le} is up to date`;case"missing":return`\u2717 Lockfile: ${le} is missing \u2014 run \`ripplo compile\` and commit it`;case"stale":return`\u2717 Lockfile: ${le} is out of date \u2014 run \`ripplo compile\` and commit it`}}function jg(e){return e.installed?"\u2713 Pre-commit hook: .git/hooks/pre-commit runs `ripplo compile --check`":"! Pre-commit hook: .git/hooks/pre-commit does not run `ripplo compile --check` \u2014 see the setup skill for the snippet"}function Ng(e){return e.valid?"\u2713 Settings: Project configured":`\u2717 Settings: Missing fields: ${e.missingFields.join(", ")}`}function Dg(e){return e.missing.length===0?"\u2713 Env files: declared files present":`\u2717 Env files: declared in .ripplo/project.json but missing:
|
|
302
|
+
${e.missing.map(t=>` ${t}`).join(`
|
|
302
303
|
`)}
|
|
303
|
-
If you're in a git worktree, copy the env file from the main checkout (or symlink to a shared file outside the working tree).`}function Og(e){switch(e.status){case"valid":return`\u2713 Auth: Signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: No token found. Run `ripplo` to authenticate.";case"invalid":return"\u2717 Auth: Saved token rejected by server. Run `ripplo auth login` to re-authenticate.";case"unreachable":return`! Auth: Could not reach ${ee()} to validate token.`}}function Lg(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Make sure your dev server is running.`}function _g(e){return e.rejectsUnsigned?"\u2713 Webhook verification: Unsigned requests are correctly rejected":"\u2717 Webhook verification: Endpoint accepted an unsigned request \u2014 webhook signature verification may be missing or misconfigured."}function Ug(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Vg(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function Fg(e){if(!e.found)return"\u2717 State graph: DSL compilation failed";if(e.valid)return"\u2713 State graph: Valid";let
|
|
304
|
-
${
|
|
305
|
-
`)}`}function Mg(e){if(e.total===0)return"! Tests: No tests defined";if(e.invalidNames.length===0)return`\u2713 Tests: ${String(e.total)} valid`;let
|
|
306
|
-
${
|
|
307
|
-
`)}`}function Hg(e){let
|
|
308
|
-
`+
|
|
309
|
-
`)}import On from"fs";import Kg from"path";import{chromium as Jg}from"playwright";import Bg from"fs";import Wg from"path";async function cs(e){let
|
|
304
|
+
If you're in a git worktree, copy the env file from the main checkout (or symlink to a shared file outside the working tree).`}function Og(e){switch(e.status){case"valid":return`\u2713 Auth: Signed in as ${e.email??"unknown"}`;case"missing":return"\u2717 Auth: No token found. Run `ripplo auth login` to authenticate.\n (Claude Code: run this yourself as a background process \u2014 it's a device-code flow, the user only needs to approve in the browser.)";case"invalid":return"\u2717 Auth: Saved token rejected by server. Run `ripplo auth login` to re-authenticate.\n (Claude Code: run this yourself as a background process \u2014 it's a device-code flow, the user only needs to approve in the browser.)";case"unreachable":return`! Auth: Could not reach ${ee()} to validate token.`}}function Lg(e){return e.reachable?`\u2713 Dev server: ${e.appUrl} is reachable`:`\u2717 Dev server: ${e.appUrl} is not responding. Make sure your dev server is running.`}function _g(e){return e.rejectsUnsigned?"\u2713 Webhook verification: Unsigned requests are correctly rejected":"\u2717 Webhook verification: Endpoint accepted an unsigned request \u2014 webhook signature verification may be missing or misconfigured."}function Ug(e){return e.installed?"\u2713 Browser: Chromium installed":"\u2717 Browser: Chromium not installed. Run: npx playwright install chromium"}function Vg(e){return e.count===0?"! Preconditions: None defined":e.configured?e.endpointReachable===void 0?`! Preconditions: ${String(e.count)} defined (could not verify endpoint)`:`\u2713 Preconditions: ${String(e.count)} defined, endpoint configured`:`\u2717 Preconditions: ${String(e.count)} defined but RIPPLO_ENGINE_URL is not set in your env file`}function Fg(e){if(!e.found)return"\u2717 State graph: DSL compilation failed";if(e.valid)return"\u2713 State graph: Valid";let r=e.errors.map(t=>` - ${t.path===""?"":t.path+": "}${t.message}`);return`\u2717 State graph: ${String(e.errorCount)} validation error${e.errorCount===1?"":"s"}
|
|
305
|
+
${r.join(`
|
|
306
|
+
`)}`}function Mg(e){if(e.total===0)return"! Tests: No tests defined";if(e.invalidNames.length===0)return`\u2713 Tests: ${String(e.total)} valid`;let r=e.invalidWorkflows.map(t=>Hg(t));return`\u2717 Tests: ${String(e.invalidNames.length)} invalid
|
|
307
|
+
${r.join(`
|
|
308
|
+
`)}`}function Hg(e){let r=e.errors.map(t=>" - "+(t.path===""?"":t.path+": ")+t.message);return" "+e.name+`:
|
|
309
|
+
`+r.join(`
|
|
310
|
+
`)}import On from"fs";import Kg from"path";import{chromium as Jg}from"playwright";import Bg from"fs";import Wg from"path";async function cs(e){let r=Wg.join(e,".ripplo","index.ts");if(!Bg.existsSync(r))return{appUrl:void 0,engineUrl:void 0,errors:[{message:".ripplo/index.ts not found",path:""}],valid:!1,warnings:[]};let t=await x(e);if(!t.ok)return{appUrl:void 0,engineUrl:void 0,errors:[{message:t.error,path:".ripplo/"}],valid:!1,warnings:[]};try{let n=He();return{appUrl:n.appUrl,engineUrl:n.engineUrl,errors:[],valid:!0,warnings:[]}}catch(n){return{appUrl:void 0,engineUrl:void 0,errors:[{message:n instanceof Error?n.message:String(n),path:""}],valid:!1,warnings:[]}}}async function Dn(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 us({appUrl:e,engineUrl:r}){let t=r.startsWith("http://")||r.startsWith("https://")?r:`${e}${r}`;try{return(await fetch(`${t}/execute-preconditions`,{body:JSON.stringify({preconditions:[]}),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{graphql as qg}from"gql.tada";var zg=qg(`
|
|
310
311
|
query DoctorAuthViewer {
|
|
311
312
|
currentUser {
|
|
312
313
|
name
|
|
313
314
|
email
|
|
314
315
|
}
|
|
315
316
|
}
|
|
316
|
-
`),Gg="Failed to connect to Ripplo server";async function ds({serverUrl:e,token:
|
|
317
|
+
`),Gg="Failed to connect to Ripplo server";async function ds({serverUrl:e,token:r}){try{let t=await h({config:Pe({serverUrl:e,token:r}),document:zg,variables:void 0});return t.currentUser==null?{kind:"invalid"}:{email:t.currentUser.email,kind:"valid"}}catch(t){return(t instanceof Error?t.message:String(t)).startsWith(Gg)?{kind:"unreachable"}:{kind:"invalid"}}}function ps(e){switch(e.type){case"settings":return!e.valid;case"env-files":return e.missing.length>0;case"token":return e.status==="missing"||e.status==="invalid";case"dev-server":return!e.reachable;case"dev-session":return e.status!=="active";case"preconditions":return e.count>0&&!e.configured;case"engine-endpoint":return!e.reachable;case"adapter-enabled":return e.status!=="enabled";case"webhook-verification":return!e.rejectsUnsigned;case"preconditions-validation":return!e.valid;case"workflows":return e.invalidNames.length>0;case"browser":return!e.installed;case"lockfile":return e.status!=="match";case"pre-commit-hook":return!e.installed}}async function ms(e){let r=await Qg(e),t={missing:bn(e),type:"env-files"},n=await Zg(),o=ey(),i=await x(e),s=ry(i),a=oy(i),l=await Xg(e,i),c=Yg(e),u=await iy(r,i);return[r,t,n,...u,s,a,l,c,o]}async function Xg(e,r){if(!r.ok)return{status:"missing",type:"lockfile"};let t=await rt({cwd:e});return{status:await tt({compiled:r.result,cwd:e,existing:t}),type:"lockfile"}}function Yg(e){let r=Kg.join(e,".git","hooks","pre-commit");return On.existsSync(r)?{installed:On.readFileSync(r,"utf8").includes("ripplo compile --check"),type:"pre-commit-hook"}:{installed:!1,type:"pre-commit-hook"}}async function Qg(e){let r=await cs(e);return r.valid?{missingFields:[],type:"settings",valid:!0}:{missingFields:r.errors.map(n=>n.path).filter(n=>n.length>0),type:"settings",valid:!1}}async function Zg(){let e=ie();if(e==null||e.length===0)return{email:void 0,status:"missing",type:"token"};let r=await ds({serverUrl:ee(),token:e});return r.kind==="valid"?{email:r.email,status:"valid",type:"token"}:{email:void 0,status:r.kind,type:"token"}}function ey(){let e=Jg.executablePath();return{installed:On.existsSync(e),type:"browser"}}function ry(e){if(!e.ok)return{errorCount:1,errors:[{message:e.error,path:""}],found:!1,type:"preconditions-validation",valid:!1};let r=ty(e.result.preconditions,e.result.tests);return{errorCount:r.length,errors:r,found:!0,type:"preconditions-validation",valid:r.length===0}}function ty(e,r){let t=[],n=new Set(Object.keys(e));return Object.entries(e).forEach(([o,i])=>{(i.depends??[]).forEach(s=>{n.has(s)||t.push({message:`Depends on non-existent precondition "${s}"`,path:`preconditions.${o}.depends`})})}),r.forEach(o=>{Object.entries(o.requiresKeys).forEach(([i,s])=>{n.has(s)||t.push({message:`Test "${o.slug}" requires non-existent precondition "${s}" (as ${i})`,path:`tests.${o.slug}.requiresKeys.${i}`})})}),ny(e).forEach(o=>{t.push({message:o,path:"preconditions"})}),t}function ny(e){let r=new Set,t=new Set,n=[];function o(i){if(t.has(i)){n.push(`Precondition "${i}" has a circular dependency`);return}r.has(i)||(r.add(i),t.add(i),(e[i]?.depends??[]).forEach(s=>{o(s)}),t.delete(i))}return Object.keys(e).forEach(i=>{o(i)}),n}function oy(e){if(!e.ok)return{invalidNames:[],invalidWorkflows:[],total:0,type:"workflows",valid:0};let r=e.result.tests.length;return{invalidNames:[],invalidWorkflows:[],total:r,type:"workflows",valid:r}}async function iy(e,r){if(!e.valid||!r.ok)return[];let t;try{let a=He();t={appUrl:a.appUrl,engineUrl:a.engineUrl,webhookSecret:a.webhookSecret}}catch{return[]}let n=[],o=await Dn(t.appUrl)==null;n.push({appUrl:t.appUrl,reachable:o,type:"dev-server"});let i=await as(process.cwd());n.push(i);let s=await sy(t,r);return n.push(...s),n}async function sy(e,r){let t=r.ok?Object.keys(r.result.preconditions).length:0,n=e.engineUrl.length>0,o={configured:n,count:t,endpointReachable:void 0,type:"preconditions"};if(t===0||!n)return[o];let i=ly(e.appUrl,e.engineUrl);if(i==null)return[o];let s=await Dn(i)==null,a=[];if(a.push({configured:!0,count:t,endpointReachable:s,type:"preconditions"}),fs(e.engineUrl)&&a.push({reachable:s,type:"engine-endpoint",url:i}),!s)return a;let l=await us({appUrl:e.appUrl,engineUrl:e.engineUrl});a.push({rejectsUnsigned:l==null,type:"webhook-verification"});let c=await ay({engineUrl:i,webhookSecret:e.webhookSecret});return a.push({status:c,type:"adapter-enabled",url:i}),a}async function ay({engineUrl:e,webhookSecret:r}){if(r.length===0)return"no-secret";let t=JSON.stringify({preconditions:[]});try{let n=await fetch(`${e}/execute-preconditions`,{body:t,headers:{"Content-Type":"application/json",...Se({body:t,secret:r})},method:"PUT",signal:AbortSignal.timeout(5e3)});return n.status===404?"disabled":n.status===401||n.status===403?"bad-secret":"enabled"}catch{return"unreachable"}}function fs(e){return e.startsWith("http://")||e.startsWith("https://")}function ly(e,r){return fs(r)?r:`${e}${r}`}async function gs(){let e=process.cwd(),r=await ms(e),t=r.map(o=>ls(o));process.stdout.write(t.join(`
|
|
317
318
|
`)+`
|
|
318
|
-
`);let n=
|
|
319
|
+
`);let n=r.some(o=>ps(o));process.exit(n?1:0)}import uy from"crypto";import{graphql as dy}from"gql.tada";import Ln from"fs";import _n from"path";function at(e){try{let r=_n.join(cy(e),"HEAD"),t=Ln.readFileSync(r,"utf8").trim(),n="ref: refs/heads/";return t.startsWith(n)?t.slice(n.length):t.length===0?void 0:t.slice(0,7)}catch{return}}function cy(e){let r=_n.join(e,".git");if(Ln.statSync(r).isDirectory())return r;let n=Ln.readFileSync(r,"utf8").trim(),o="gitdir:";if(!n.startsWith(o))throw new Error(`unrecognized .git file at ${r}`);let i=n.slice(o.length).trim();if(i.length===0)throw new Error(`empty gitdir pointer at ${r}`);return _n.resolve(e,i)}var py=dy(`
|
|
319
320
|
mutation SyncDevSession(
|
|
320
321
|
$projectId: String!
|
|
321
322
|
$cwd: String!
|
|
@@ -334,13 +335,13 @@ ${t.join(`
|
|
|
334
335
|
hooksPaused
|
|
335
336
|
}
|
|
336
337
|
}
|
|
337
|
-
`);async function Qe(e){let
|
|
338
|
-
`).filter(n=>n.length>0).filter(n=>wy.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{
|
|
338
|
+
`);async function Qe(e){let r=my(e.compiled);return gy({config:e.config,cwd:e.cwd,payload:r})}async function ye(e,r){let t=await x(e);if(!t.ok)throw new Error(`DSL compilation failed: ${t.error}`);let n=await Qe({compiled:t.result,config:r,cwd:e});return{compiled:t.result,devSessionId:n.devSessionId}}function my(e){return{preconditions:Object.entries(e.preconditions).map(([r,t])=>({depends:[...t.depends??[]],description:t.description,name:r,returns:[...t.returns??[]]})),workflows:e.tests.map(r=>({expectedOutcome:r.expectedOutcome,name:r.name,preconditions:[...r.preconditions],requiresKeys:Object.entries(r.requiresKeys).map(([t,n])=>({namespace:t,preconditionName:n})),slug:r.slug,sourcePath:r.sourcePath??null,spec:r.implemented?JSON.stringify(r.spec):null}))}}function fy(e){return uy.createHash("sha256").update(JSON.stringify(e)).digest("hex")}async function gy({config:e,cwd:r,payload:t}){let n=fy(t),o=at(r),i=await h({config:e,document:py,variables:{branch:o??null,cwd:r,preconditions:t.preconditions.map(s=>({depends:[...s.depends],description:s.description,name:s.name,returns:[...s.returns]})),projectId:e.projectId,workflows:t.workflows.map(s=>({expectedOutcome:s.expectedOutcome,name:s.name,preconditions:[...s.preconditions],requiresKeys:s.requiresKeys.map(a=>({namespace:a.namespace,preconditionName:a.preconditionName})),slug:s.slug,sourcePath:s.sourcePath,spec:s.spec??null}))}});if(i.syncDevSession==null)throw new Error("syncDevSession returned null");return{devSessionId:i.syncDevSession.id,hash:n,hooksPaused:i.syncDevSession.hooksPaused}}import{graphql as Pr,readFragment as vy}from"gql.tada";import{createHash as ys}from"crypto";import{mkdirSync as yy,readFileSync as Un,writeFileSync as hy}from"fs";import lt from"path";var wy=[".ts",".tsx",".js",".jsx"];function Ee(e){let r=ys("sha256");return r.update(K(["rev-parse","HEAD"],e)),r.update("\0"),r.update(K(["diff","HEAD"],e)),r.update("\0"),K(["ls-files","--others","--exclude-standard"],e).split(`
|
|
339
|
+
`).filter(n=>n.length>0).filter(n=>wy.some(o=>n.endsWith(o))).toSorted((n,o)=>n.localeCompare(o)).forEach(n=>{r.update(n),r.update("\0"),r.update(by(lt.join(e,n))),r.update("\0")}),r.digest("hex")}function hs(e){let r=lt.join(e,".ripplo","ripplo.lock");try{let t=Un(r);return ys("sha256").update(t).digest("hex")}catch{return null}}function Ze(e,r){try{return Un(ws(e,r),"utf8").trim()}catch{return null}}function er(e,r,t){let n=ws(e,r);yy(lt.dirname(n),{recursive:!0}),hy(n,t)}function ws(e,r){return lt.join(e,".ripplo",".local",`${r}.hash`)}function by(e){try{return Un(e)}catch{return Buffer.alloc(0)}}import bs from"figures";var Ne={cross:bs.cross,tick:bs.tick};var Ss=Pr(`
|
|
339
340
|
fragment WorkflowIdMCP on Workflow {
|
|
340
341
|
id
|
|
341
342
|
slug
|
|
342
343
|
}
|
|
343
|
-
`),Sy=
|
|
344
|
+
`),Sy=Pr(`
|
|
344
345
|
query ProjectWorkflowIdsMCP($projectId: String!, $cwd: String!) {
|
|
345
346
|
project(id: $projectId) {
|
|
346
347
|
id
|
|
@@ -352,13 +353,13 @@ ${t.join(`
|
|
|
352
353
|
}
|
|
353
354
|
}
|
|
354
355
|
}
|
|
355
|
-
`,[Ss]),ky=
|
|
356
|
+
`,[Ss]),ky=Pr(`
|
|
356
357
|
mutation SetProjectViewCLI($projectId: String!, $devSessionId: String!) {
|
|
357
358
|
setProjectView(projectId: $projectId, devSessionId: $devSessionId) {
|
|
358
359
|
id
|
|
359
360
|
}
|
|
360
361
|
}
|
|
361
|
-
`),Py=
|
|
362
|
+
`),Py=Pr(`
|
|
362
363
|
mutation CreateRunMCP($workflowId: String!, $lockfileHash: String, $repoHash: String) {
|
|
363
364
|
createRun(workflowId: $workflowId, lockfileHash: $lockfileHash, repoHash: $repoHash) {
|
|
364
365
|
__typename
|
|
@@ -381,7 +382,7 @@ ${t.join(`
|
|
|
381
382
|
}
|
|
382
383
|
}
|
|
383
384
|
}
|
|
384
|
-
`),Ry=
|
|
385
|
+
`),Ry=Pr(`
|
|
385
386
|
query RunStatusMCP($id: String!) {
|
|
386
387
|
run(id: $id) {
|
|
387
388
|
id
|
|
@@ -408,7 +409,7 @@ ${t.join(`
|
|
|
408
409
|
}
|
|
409
410
|
}
|
|
410
411
|
}
|
|
411
|
-
`);async function
|
|
412
|
+
`);async function ct({config:e,ids:r,presynced:t}){let n=await xy({config:e,ids:r,presynced:t}),o=await Promise.all(n.map(async a=>{try{let l=await Ty({config:e,workflowId:a.workflowId});return{entry:a,ok:!0,runId:l}}catch(l){let c=l instanceof Error?l.message:String(l);return{entry:a,message:c,ok:!1}}})),i=await Promise.all(o.map(async a=>{if(!a.ok)return{id:a.entry.id,runId:"",summary:`ERROR creating run: ${a.message}
|
|
412
413
|
${w("setup","check auth + config")}`};let{entry:l,runId:c}=a;try{let u=await Ny({config:e,runId:c}),m=Iy({config:e,id:l.id,runId:c}),y=`.ripplo/debug/${c}/`;return{id:l.id,runId:c,summary:`View run: ${m}
|
|
413
414
|
Debug artifacts: ${y}
|
|
414
415
|
${w("debug","read summary.txt, accessibility-tree, network.jsonl before guessing")}
|
|
@@ -419,10 +420,10 @@ ${a.summary}`).join(`
|
|
|
419
420
|
|
|
420
421
|
---
|
|
421
422
|
|
|
422
|
-
`);return{results:i,summary:s}}async function xy({config:e,ids:
|
|
423
|
-
Did you mean: ${
|
|
424
|
-
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Cy({compiledSlugs:e,limit:
|
|
425
|
-
`)}function Oy(e){if(e.caughtKind==null)return null;let
|
|
423
|
+
`);return{results:i,summary:s}}async function xy({config:e,ids:r,presynced:t}){let n=t??await ye(e.cwd,e),o=await h({config:e,document:Sy,variables:{cwd:e.cwd,projectId:e.projectId}});if(o.project==null)throw new Error("Project not found");let i=o.project.devSession;if(i==null)throw new Error("No active dev session. Start one by running `ripplo` (or `npx ripplo`) in your terminal, then try again.");await h({config:e,document:ky,variables:{devSessionId:i.id,projectId:e.projectId}});let s=(i.workflows??[]).map(l=>vy(Ss,l));if(r.length===0)return s.map(l=>({id:l.slug,workflowId:l.id}));let a=n.compiled.tests.map(l=>l.slug);return r.map(l=>{let c=s.find(u=>u.slug===l);if(c==null)throw new Error(Ey({compiledSlugs:a,slug:l}));return{id:l,workflowId:c.id}})}function Ey({compiledSlugs:e,slug:r}){if(e.includes(r))return`Test "${r}" was synced from .ripplo/ but the server didn't return it. This is likely a server-state bug \u2014 check the server logs for the SyncDevSession mutation.`;let t=Cy({compiledSlugs:e,limit:3,slug:r}),n=t.length>0?`
|
|
424
|
+
Did you mean: ${t.join(", ")}?`:"";return`Test "${r}" is not registered in this dev session.${n}
|
|
425
|
+
Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on demand \u2014 restarting the dev server will not help.)`}function Cy({compiledSlugs:e,limit:r,slug:t}){let n=new Set(t.split("-"));return e.map(i=>({candidate:i,score:Ay(n,i)})).filter(i=>i.score>0).toSorted((i,s)=>s.score-i.score).slice(0,r).map(i=>i.candidate)}function Ay(e,r){return r.split("-").filter(t=>e.has(t)).length}function Iy({config:e,id:r,runId:t}){let n=e.ripploServerUrl.replace(/:3000\b/,":3001"),o=new URL(n.endsWith("/")?n:`${n}/`);return new URL(`projects/${e.projectId}/workflows/${r}/runs/${t}`,o).toString()}async function Ty({config:e,workflowId:r}){let n=(await h({config:e,document:Py,variables:{lockfileHash:hs(e.cwd),repoHash:$y(e.cwd),workflowId:r}})).createRun;if(n==null)throw new Error("Failed to create run");if(n.__typename!=="Run")throw new Error(`Cannot create run: ${n.message}`);return n.id}function $y(e){try{return Ee(e)}catch{return null}}var jy=2e3,vs=150;async function Ny({config:e,runId:r}){let t=0;for(;t<vs;){await Ly(jy),t+=1;let o=(await h({config:e,document:Ry,variables:{id:r}})).run;if(o==null)throw new Error(`Run ${r} not found`);if(!(o.status==="pending"||o.status==="running"))return Dy({run:o,runId:r})}return`Run ${r} timed out after polling ${String(vs)} times.`}function Dy({run:e,runId:r}){let t=[`Run ${r}: ${e.status.toUpperCase()}`],n=Oy(e);return n!=null&&t.push(n),t.push(` ${e.status}: ${String(e.passCount)} passed, ${String(e.failCount)} failed (${String(e.duration??0)}ms)`),e.summary!=null&&t.push(` Summary: ${e.summary}`),e.traceEntries.forEach(o=>{let i=o.status==="passed"?Ne.tick:Ne.cross,s=o.detail==null?"":` \u2014 ${o.detail}`;t.push(` ${i} ${o.title} (${String(o.duration??0)}ms)${s}`),o.assertions.forEach(a=>{let l=a.status==="passed"?Ne.tick:Ne.cross,c=a.detail==null?"":` \u2014 ${a.detail}`;t.push(` ${l} ${a.description}${c}`)})}),t.join(`
|
|
426
|
+
`)}function Oy(e){if(e.caughtKind==null)return null;let r=e.workflow?.slug??"workflow";return e.caughtKind==="new_test"?` ${Ne.tick} ripplo caught a bug \u2014 new test "${r}" surfaced an issue in your app code`:` ${Ne.tick} ripplo caught a regression in "${r}"`}function Ly(e){return new Promise(r=>{setTimeout(r,e)})}import{graphql as _y}from"gql.tada";var Uy=_y(`
|
|
426
427
|
query DevSessionCheckPreflight($projectId: String!, $cwd: String!) {
|
|
427
428
|
project(id: $projectId) {
|
|
428
429
|
id
|
|
@@ -431,29 +432,29 @@ Tests must be exported from .ripplo/tests/index.ts. (ripplo run already syncs on
|
|
|
431
432
|
}
|
|
432
433
|
}
|
|
433
434
|
}
|
|
434
|
-
`);function de(){try{return W(process.cwd())}catch(e){let
|
|
435
|
+
`);function de(){try{return W(process.cwd())}catch(e){let r=e instanceof Error?e.message:String(e);process.stderr.write(`${r}
|
|
435
436
|
`),process.stderr.write(`${w("setup")}
|
|
436
437
|
`),process.exit(1)}}async function he(e){(await h({config:e,document:Uy,variables:{cwd:e.cwd,projectId:e.projectId}})).project?.devSession==null&&(process.stderr.write("No active dev session. Start `npx ripplo watch` as a background process (your app's dev server must also be running), then retry. Or run `/ripplo:start` in Claude Code.\n"),process.stderr.write(`${w("setup")}
|
|
437
|
-
`),process.exit(1))}async function ks({id:e,runs:
|
|
438
|
-
`);let n=await ye(
|
|
439
|
-
`).find(y=>y.includes("FAILED")||y.includes("ERROR"))??"unknown failure";a.set(m,(a.get(m)??0)+1)}else i++});let l=
|
|
438
|
+
`),process.exit(1))}async function ks({id:e,runs:r}){let t=de();await he(t),process.stdout.write(`flake-detect "${e}" x${String(r)}...
|
|
439
|
+
`);let n=await ye(t.cwd,t),o=await Promise.allSettled(Array.from({length:r},()=>ct({config:t,ids:[e],presynced:n}))),i=0,s=0,a=new Map;o.forEach(c=>{if(c.status==="rejected"){s++;let m=c.reason instanceof Error?c.reason.message:"unknown error";a.set(m,(a.get(m)??0)+1);return}let u=c.value.results[0];if(u==null){s++;return}if(u.summary.includes("FAILED")||u.summary.includes("ERROR")){s++;let m=u.summary.split(`
|
|
440
|
+
`).find(y=>y.includes("FAILED")||y.includes("ERROR"))??"unknown failure";a.set(m,(a.get(m)??0)+1)}else i++});let l=r>0?s/r*100:0;process.stdout.write(`${String(i)} passed / ${String(s)} failed (${l.toFixed(1)}% flake)
|
|
440
441
|
`),a.size>0&&a.forEach((c,u)=>{process.stdout.write(` ${String(c)}x: ${u}
|
|
441
442
|
`)}),s>0&&process.stderr.write(`${w("flake-detect","parallel safety + race conditions")}
|
|
442
|
-
`),process.exit(s>0?1:0)}import
|
|
443
|
+
`),process.exit(s>0?1:0)}import ut from"fs";import{graphql as Fy}from"gql.tada";import Vy from"fs";function Ce(e){return fr(e,"hooks-paused")}function F(e){return Vy.existsSync(Ce(e))||st(e)?!1:Ye(e)}var My=Fy(`
|
|
443
444
|
mutation CliSetHooksPaused($projectId: String!, $paused: Boolean!) {
|
|
444
445
|
setHooksPaused(projectId: $projectId, paused: $paused) {
|
|
445
446
|
id
|
|
446
447
|
}
|
|
447
448
|
}
|
|
448
|
-
`);async function Ps(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();
|
|
449
|
-
`);return}
|
|
450
|
-
`)}async function xs(e,
|
|
451
|
-
`)[0]??
|
|
449
|
+
`);async function Ps(){process.stdin.isTTY||(process.stderr.write("`ripplo hooks pause` must be invoked interactively from a terminal \u2014 refusing non-TTY invocation. Bypassing the gate is a human decision, not an agent decision.\n"),process.exit(1));let e=process.cwd();mr(e);let r=Ce(e);if(ut.existsSync(r)){process.stdout.write("Hooks already paused. Run `ripplo hooks resume` to re-enable.\n");return}ut.writeFileSync(r,""),await xs(e,!0),process.stdout.write("Hooks paused. Pre-edit gates and stop enforcement are off until you run `ripplo hooks resume`.\n")}async function Rs(){let e=process.cwd(),r=Ce(e);if(!ut.existsSync(r)){process.stdout.write(`Hooks already active.
|
|
450
|
+
`);return}ut.unlinkSync(r),await xs(e,!1),process.stdout.write(`Hooks resumed.
|
|
451
|
+
`)}async function xs(e,r){let t;try{t=W(e)}catch{return}await h({config:t,document:My,variables:{paused:r,projectId:t.projectId}}).catch(()=>null)}import rr from"fs";import tr from"path";import{input as As,select as Is}from"@inquirer/prompts";import{graphql as ch}from"gql.tada";import{exec as Hy}from"child_process";import U from"fs";import M from"path";import{promisify as By}from"util";var Wy=["@ripplo/testing"],Es=".ripplo/ripplo.lock linguist-generated=true",qy=[".ripplo/debug/",".ripplo/.local/"],zy=By(Hy);async function Cs({cwd:e,onStep:r}){r("Scaffolding project files..."),th({cwd:e}),r("Updating .gitignore..."),nh(e),r("Marking ripplo.lock as generated..."),Jy(e),r("Installing dependencies...");let t=await Gy(e),n=[];if(t.ok||n.push({manualCommand:t.cmd,message:`Couldn't auto-install dev dependencies (${t.reason}). Run the command below, then run \`ripplo lint\` to compile the lockfile.`}),t.ok){r("Compiling initial lockfile...");let o=await Ky(e);o!=null&&n.push({manualCommand:void 0,message:o})}return r("Setting up browser..."),await Ot(),n}async function Gy(e){let r=Xy({cwd:e,pm:rh(e)});f.info("Installing dependencies: %s",r);try{return await zy(r,{cwd:e}),{ok:!0}}catch(t){let n=t instanceof Error?t.message.split(`
|
|
452
|
+
`)[0]??t.message:String(t);return f.warn("Install failed (%s): %s",r,n),{cmd:r,ok:!1,reason:n}}}async function Ky(e){try{let r=await x(e);if(!r.ok)return;await ce({cwd:e,result:r.result});return}catch(r){return`Couldn't compile initial lockfile: ${r instanceof Error?r.message:String(r)}.`}}function Jy(e){let r=M.join(e,".gitattributes"),t=U.existsSync(r)?U.readFileSync(r,"utf8"):"";if(t.includes(Es))return;let n=t.length===0||t.endsWith(`
|
|
452
453
|
`)?"":`
|
|
453
|
-
`;U.writeFileSync(
|
|
454
|
-
`)}function Xy({cwd:e,pm:
|
|
454
|
+
`;U.writeFileSync(r,`${t}${n}${Es}
|
|
455
|
+
`)}function Xy({cwd:e,pm:r}){let t=Wy.join(" ");return r==="pnpm"?Zy(e)?`pnpm add -wD ${t}`:`pnpm add -D ${t}`:r==="yarn"?Yy({cwd:e,deps:t}):r==="bun"?`bun add -d ${t}`:`npm install -D ${t}`}function Yy({cwd:e,deps:r}){return Qy(e)?`yarn add -D ${r}`:eh(e)?`yarn add -WD ${r}`:`yarn add -D ${r}`}function Qy(e){if(U.existsSync(M.join(e,".yarnrc.yml"))||U.existsSync(M.join(e,".pnp.cjs"))||U.existsSync(M.join(e,".pnp.js")))return!0;let r=M.join(e,"package.json");if(!U.existsSync(r))return!1;try{let t=JSON.parse(U.readFileSync(r,"utf8"));if(t==null||typeof t!="object"||!("packageManager"in t))return!1;let n=t.packageManager;if(typeof n!="string")return!1;let o=/^yarn@(\d+)/.exec(n);return o!=null&&Number(o[1])>=2}catch{return!1}}function Zy(e){return U.existsSync(M.join(e,"pnpm-workspace.yaml"))||U.existsSync(M.join(e,"pnpm-workspace.yml"))}function eh(e){let r=M.join(e,"package.json");if(!U.existsSync(r))return!1;try{let t=JSON.parse(U.readFileSync(r,"utf8"));if(t==null||typeof t!="object"||!("workspaces"in t))return!1;let n=t.workspaces;return Array.isArray(n)||n!=null&&typeof n=="object"}catch{return!1}}function rh(e){return U.existsSync(M.join(e,"pnpm-lock.yaml"))?"pnpm":U.existsSync(M.join(e,"yarn.lock"))?"yarn":U.existsSync(M.join(e,"bun.lockb"))||U.existsSync(M.join(e,"bun.lock"))?"bun":"npm"}function th({cwd:e}){let r=M.join(e,".ripplo"),t=M.join(r,"tests"),n=M.join(r,"preconditions"),o=M.join(r,"observers");U.mkdirSync(t,{recursive:!0}),U.mkdirSync(n,{recursive:!0}),U.mkdirSync(o,{recursive:!0}),Rr(M.join(r,"index.ts"),oh),Rr(M.join(n,"index.ts"),ih),Rr(M.join(o,"index.ts"),sh),Rr(M.join(t,"index.ts"),ah),Rr(M.join(r,"tsconfig.json"),lh)}function Rr(e,r){U.existsSync(e)||U.writeFileSync(e,r)}function nh(e){let r=M.join(e,".gitignore");if(!U.existsSync(r))return;let t=U.readFileSync(r,"utf8"),n=qy.filter(i=>!t.includes(i));if(n.length===0)return;let o=t.endsWith(`
|
|
455
456
|
`)?"":`
|
|
456
|
-
`;U.writeFileSync(t
|
|
457
|
+
`;U.writeFileSync(r,t+o+n.join(`
|
|
457
458
|
`)+`
|
|
458
459
|
`)}var oh=`import { createRipplo } from "@ripplo/testing";
|
|
459
460
|
import { preconditions } from "./preconditions/index";
|
|
@@ -520,20 +521,20 @@ export const tests = [] as const;
|
|
|
520
521
|
name
|
|
521
522
|
}
|
|
522
523
|
}
|
|
523
|
-
`),Vn=["../.env.local","../.env"];async function Ts(e=mh()){let
|
|
524
|
-
`),process.exit(1));let o=await ph({serverUrl:n,token:
|
|
524
|
+
`),Vn=["../.env.local","../.env"];async function Ts(e=mh()){let r=process.cwd(),t=ie();t==null&&(process.stdout.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let n=ee();dh(r)&&(process.stdout.write(`\`.ripplo/index.ts\` already exists at ${r}. Delete it first if you want to re-init.
|
|
525
|
+
`),process.exit(1));let o=await ph({serverUrl:n,token:t});o.length===0&&(process.stdout.write("No projects found. Create one in the dashboard first, then re-run `ripplo init`.\n"),process.exit(1));let i=await gh(o,e.projectId),s=await yh(r,e.envFile),a=await hh(e.appUrl),l=fh(a,e.engineUrl),c=tr.resolve(tr.join(r,".ripplo"),s);ii({cwd:r,envFiles:[s],projectId:i}),vh({appUrl:a,engineUrl:l,filePath:c});let u=await Cs({cwd:r,onStep:m=>{process.stdout.write(` ${m}
|
|
525
526
|
`)}});if(u.length>0){process.stdout.write(`Done with warnings:
|
|
526
527
|
`),u.forEach(m=>{process.stdout.write(` - ${m.message}
|
|
527
528
|
`),m.manualCommand!=null&&process.stdout.write(` run: ${m.manualCommand}
|
|
528
|
-
`)});return}process.stdout.write("Ready. Start `npx ripplo watch` as a background process (or run `/ripplo:start` in Claude Code), then write tests in `.ripplo/tests/`.\n")}function dh(e){return
|
|
529
|
-
`),process.exit(1)}return
|
|
530
|
-
`),process.exit(1)),process.stdout.write(`Using project: ${
|
|
531
|
-
`),
|
|
532
|
-
`),
|
|
533
|
-
`),process.exit(1)),
|
|
534
|
-
`),process.exit(1)}return e}return bh()}async function wh(e){let
|
|
529
|
+
`)});return}process.stdout.write("Ready. Start `npx ripplo watch` as a background process (or run `/ripplo:start` in Claude Code), then write tests in `.ripplo/tests/`.\n")}function dh(e){return rr.existsSync(tr.join(e,".ripplo","index.ts"))}async function ph({serverUrl:e,token:r}){return((await h({config:Pe({serverUrl:e,token:r}),document:uh,variables:void 0})).projects??[]).map(n=>({id:n.id,name:n.name}))}function mh(){return{appUrl:void 0,engineUrl:void 0,envFile:void 0,projectId:void 0}}function fh(e,r){if(r!=null){try{new URL(r)}catch{process.stdout.write(`--engine-url is not a valid URL: ${r}
|
|
530
|
+
`),process.exit(1)}return r}return`${e.replace(/\/$/,"")}/ripplo`}async function gh(e,r){if(r!=null){let t=e.find(n=>n.id===r);return t==null&&(process.stdout.write(`Unknown project id: ${r}
|
|
531
|
+
`),process.exit(1)),process.stdout.write(`Using project: ${t.name} (${t.id})
|
|
532
|
+
`),t.id}if(e.length===1){let t=e[0];if(t==null)throw new Error("unreachable");return process.stdout.write(`Using project: ${t.name} (${t.id})
|
|
533
|
+
`),t.id}return Is({choices:e.map(t=>({name:t.name,value:t.id})),message:"Select a project"})}async function yh(e,r){return r!=null?(r.trim().length===0&&(process.stdout.write(`--env must not be empty
|
|
534
|
+
`),process.exit(1)),r):wh(e)}async function hh(e){if(e!=null){try{new URL(e)}catch{process.stdout.write(`--app-url is not a valid URL: ${e}
|
|
535
|
+
`),process.exit(1)}return e}return bh()}async function wh(e){let r=tr.join(e,".ripplo"),t=Vn.find(o=>rr.existsSync(tr.resolve(r,o))),n=await Is({choices:[...Vn.map(o=>({name:t===o?`${o} (detected)`:o,value:o})),{name:"custom path",value:"__custom__"}],default:t??Vn[0],message:"Which env file should ripplo write RIPPLO_APP_URL, RIPPLO_ENGINE_URL, RIPPLO_WEBHOOK_SECRET, and ENABLE_RIPPLO_TESTING to?"});return n!=="__custom__"?n:As({message:"Path to env file (relative to .ripplo/, e.g. ../apps/server/.env)",validate:o=>o.trim().length>0?!0:"required"})}async function bh(){return As({default:"http://localhost:3000",message:"Where does your dev server run? (RIPPLO_APP_URL)",validate:e=>{try{return new URL(e),!0}catch{return"must be a valid URL"}}})}function vh({appUrl:e,engineUrl:r,filePath:t}){rr.mkdirSync(tr.dirname(t),{recursive:!0});let n=rr.existsSync(t)?rr.readFileSync(t,"utf8"):"",o=[];if(/^RIPPLO_APP_URL=/m.test(n)||o.push(`RIPPLO_APP_URL=${e}`),/^RIPPLO_ENGINE_URL=/m.test(n)||o.push(`RIPPLO_ENGINE_URL=${r}`),/^RIPPLO_WEBHOOK_SECRET=/m.test(n)||o.push(`RIPPLO_WEBHOOK_SECRET=${Kt()}`),/^ENABLE_RIPPLO_TESTING=/m.test(n)||o.push("ENABLE_RIPPLO_TESTING=true"),o.length===0)return;let i=n.length===0||n.endsWith(`
|
|
535
536
|
`)?"":`
|
|
536
|
-
`;
|
|
537
|
+
`;rr.writeFileSync(t,`${n}${i}${o.join(`
|
|
537
538
|
`)}
|
|
538
539
|
`)}import Fn from"fs";import js from"path";import*as Ds from"remeda";import{graphql as Sh}from"gql.tada";var kh=Sh(`
|
|
539
540
|
mutation AutoScopeAddDirty($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
@@ -546,14 +547,14 @@ export const tests = [] as const;
|
|
|
546
547
|
}
|
|
547
548
|
}
|
|
548
549
|
}
|
|
549
|
-
`);async function
|
|
550
|
-
`).map(
|
|
550
|
+
`);async function nr({compileResult:e,cwd:r}){if(!F(r))return{addedSlugs:[]};let t=Rh(r);if(t.length===0)return{addedSlugs:[]};let n=new Set(t),o=e.result.tests.filter(l=>l.sourcePath!=null&&n.has(l.sourcePath)).map(l=>l.slug);if(o.length===0)return{addedSlugs:[]};let i;try{i=W(r)}catch{return{addedSlugs:[]}}return await Qe({compiled:e.result,config:i,cwd:r}).catch(l=>(f.warn("auto-sync failed: %s",l instanceof Error?l.message:String(l)),null))==null?{addedSlugs:[]}:{addedSlugs:await Ph({cfg:i,slugs:o})?o:[]}}async function Ph({cfg:e,slugs:r}){let n=(await h({config:e,document:kh,variables:{cwd:e.cwd,projectId:e.projectId,workflowSlugs:[...r]}}).catch(o=>(f.warn("auto-scope failed: %s",o instanceof Error?o.message:String(o)),null)))?.addDirtyTestsToScope;return n?.__typename!=="MutationAddDirtyTestsToScopeSuccess"?!1:n.data.length>0}var $s=".ripplo/tests/";function Rh(e){let r;try{r=K(["status","--porcelain","--",".ripplo/tests"],e)}catch{return[]}return r.split(`
|
|
551
|
+
`).map(t=>t.slice(3).trim()).filter(t=>t.startsWith($s)&&t.endsWith(".ts")).map(t=>t.slice($s.length)).filter(t=>t!=="index.ts"&&!t.endsWith("/index.ts"))}function Ns(e){process.stderr.write(`Compilation failed: ${e}
|
|
551
552
|
`),process.stderr.write(`${w("create","DSL authoring + lint rules")}
|
|
552
|
-
`),process.exit(1)}async function Os(e){let{ids:
|
|
553
|
+
`),process.exit(1)}async function Os(e){let{ids:r,requireImplemented:t}=e,n=process.cwd(),o=await x(n);o.ok||Ns(o.error),await ce({cwd:n,result:o.result}).catch(g=>{Ns(g instanceof Error?g.message:String(g))});let i=qe(o.result),s=r.length===0?i.diagnostics:i.diagnostics.filter(g=>r.includes(g.test)),a=Ds.groupBy(s,g=>g.test);Object.entries(a).forEach(([g,O])=>{process.stderr.write(`
|
|
553
554
|
${g}
|
|
554
555
|
`),O.forEach(P=>{let H=P.step==null?"":` at "${P.step}"`;process.stderr.write(` [${P.rule}]${H}
|
|
555
556
|
`),process.stderr.write(` ${P.message}
|
|
556
|
-
`)})});let l=new Set(o.builder.getUnimplemented().tests),c=
|
|
557
|
+
`)})});let l=new Set(o.builder.getUnimplemented().tests),c=t.filter(g=>l.has(g));c.length>0&&(process.stderr.write(`
|
|
557
558
|
not-implemented
|
|
558
559
|
`),c.forEach(g=>{process.stderr.write(` ${g} is still marked .notImplemented()
|
|
559
560
|
`)}));let u=Ah(n);u.length>0&&(process.stderr.write(`
|
|
@@ -562,18 +563,18 @@ export const tests = [] as const;
|
|
|
562
563
|
`),process.stderr.write(` ${g.message}
|
|
563
564
|
`)}));let m=s.length+c.length+u.length;m>0&&(process.stderr.write(`
|
|
564
565
|
${String(m)} error(s)
|
|
565
|
-
`),xh({diagnostics:s,hardcodeWarnings:u,stillStubbed:c}),process.exit(1));let y=o.result.tests.length,R=
|
|
566
|
-
`);let{addedSlugs:E}=await
|
|
567
|
-
`)}function xh({diagnostics:e,hardcodeWarnings:
|
|
568
|
-
`))}var Eh=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,Ch=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Ah(e){let
|
|
566
|
+
`),xh({diagnostics:s,hardcodeWarnings:u,stillStubbed:c}),process.exit(1));let y=o.result.tests.length,R=r.length===0?"all tests":`${String(r.length)} test(s)`;process.stdout.write(`\u2713 ripplo lint: ${R} passed (${String(y)} compiled, lockfile written)
|
|
567
|
+
`);let{addedSlugs:E}=await nr({compileResult:o,cwd:n});E.length>0&&process.stdout.write(`\u2713 Auto-scoped ${E.join(", ")} (dirty tests).
|
|
568
|
+
`)}function xh({diagnostics:e,hardcodeWarnings:r,stillStubbed:t}){let n=new Set;(e.length>0||t.length>0)&&n.add("create"),r.length>0&&n.add("explore"),n.forEach(o=>process.stderr.write(`${w(o)}
|
|
569
|
+
`))}var Eh=/['"`][\w.+-]+@[\w.-]+\.[a-z]{2,}['"`]/i,Ch=/['"`][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}['"`]/i;function Ah(e){let r=js.join(e,".ripplo","preconditions");return Fn.existsSync(r)?Fn.readdirSync(r).filter(n=>n.endsWith(".ts")).flatMap(n=>Ih(js.join(r,n))):[]}function Ih(e){let r=Fn.readFileSync(e,"utf8"),t=r.includes("ctx.uniqueEmail")||r.includes("ctx.uniqueId"),n=[],o=Eh.exec(r);o!=null&&!t&&n.push({file:e,message:`hardcoded email literal ${o[0]} \u2014 use ctx.uniqueEmail() so parallel runs don't collide`});let i=Ch.exec(r);return i!=null&&!t&&n.push({file:e,message:`hardcoded UUID-like literal ${i[0]} \u2014 use ctx.uniqueId() so parallel runs don't collide`}),n}import{graphql as Th}from"gql.tada";var $h=Th(`
|
|
569
570
|
query ProjectsList {
|
|
570
571
|
projects {
|
|
571
572
|
id
|
|
572
573
|
name
|
|
573
574
|
}
|
|
574
575
|
}
|
|
575
|
-
`);async function Ls(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let
|
|
576
|
-
`)}import{graphql as jh}from"gql.tada";var
|
|
576
|
+
`);async function Ls(){let e=ie();e==null&&(process.stderr.write("Not authenticated. Run `ripplo auth login` first.\n"),process.exit(1));let r=ee(),n=((await h({config:Pe({serverUrl:r,token:e}),document:$h,variables:void 0})).projects??[]).map(o=>({id:o.id,name:o.name}));process.stdout.write(`${JSON.stringify({projects:n},null,2)}
|
|
577
|
+
`)}import{graphql as jh}from"gql.tada";var dt=jh(`
|
|
577
578
|
query ScopeStatus($projectId: String!, $cwd: String!) {
|
|
578
579
|
project(id: $projectId) {
|
|
579
580
|
id
|
|
@@ -593,17 +594,17 @@ ${String(m)} error(s)
|
|
|
593
594
|
}
|
|
594
595
|
}
|
|
595
596
|
}
|
|
596
|
-
`);async function _s({all:e,ids:
|
|
597
|
-
`),process.exit(1));let
|
|
597
|
+
`);async function _s({all:e,ids:r}){e&&r.length>0&&(process.stderr.write(`Pass either --all or test ids, not both.
|
|
598
|
+
`),process.exit(1));let t=de();await he(t);let n=await Nh({all:e,cwd:t.cwd,ids:r});n==null&&process.exit(1);let{results:o,summary:i}=await ct({config:t,ids:n,presynced:void 0});process.stdout.write(`${i}
|
|
598
599
|
`);let s=o.filter(l=>l.summary.includes("FAILED")||l.summary.includes("ERROR")),a=s.map(l=>l.runId).filter(l=>l.length>0);if(a.length>0){let l=a.map(c=>`.ripplo/debug/${c}/`).join(", ");process.stderr.write(`Artifacts in ${l} \u2014 read before re-running.
|
|
599
600
|
`),process.stderr.write(`${w("debug")}
|
|
600
|
-
`)}process.exit(s.length>0?1:0)}async function Nh({all:e,cwd:
|
|
601
|
-
`)}let o=(await h({config:
|
|
601
|
+
`)}process.exit(s.length>0?1:0)}async function Nh({all:e,cwd:r,ids:t}){return t.length>0?t:e?[]:Dh(r)}async function Dh(e){let r=de(),t=await x(e);if(t.ok){let{addedSlugs:a}=await nr({compileResult:t,cwd:e});a.length>0&&process.stdout.write(`Auto-scoped ${a.join(", ")} (dirty tests).
|
|
602
|
+
`)}let o=(await h({config:r,document:dt,variables:{cwd:r.cwd,projectId:r.projectId}})).project?.devSession?.scopeItems??[],i=o.flatMap(a=>a.workflow!=null&&a.workflow.spec!=null?[a.workflow.slug]:[]),s=o.flatMap(a=>a.workflow==null?[`[intent] ${a.label??"(no label)"}`]:a.workflow.spec==null?[`[stub] ${a.workflow.slug}`]:[]);return s.length>0&&process.stdout.write(`Skipped non-runnable scope items: ${s.join(", ")}
|
|
602
603
|
`),i.length===0?(process.stderr.write("No runnable tests in scope. Add tests with `ripplo scope add <id>`, or run the full suite with `ripplo run --all`.\n"),process.stderr.write(`${w("scope")}
|
|
603
|
-
`),null):i}async function Us(){let e=process.cwd(),
|
|
604
|
-
`)}catch(
|
|
604
|
+
`),null):i}async function Us(){let e=process.cwd(),r=W(e);try{let t=await ye(r.cwd,r),n=t.compiled.tests.length,o=Object.keys(t.compiled.preconditions).length;process.stdout.write(`synced ${String(n)} tests, ${String(o)} preconditions to dev session ${t.devSessionId}
|
|
605
|
+
`)}catch(t){let n=t instanceof Error?t.message:String(t);process.stderr.write(`ripplo sync failed: ${n}
|
|
605
606
|
`),process.stderr.write(`${w("setup","verify auth + server reachability")}
|
|
606
|
-
`),process.exit(1)}}import
|
|
607
|
+
`),process.exit(1)}}import pt from"fs";import{createClient as Fh}from"graphql-sse";import Mh,{AbortError as Hh}from"p-retry";import{graphql as or}from"gql.tada";import{print as Hn}from"graphql";import Oh from"p-limit";var Lh=4,Vs=Oh(Lh),xr=new Set;function Mn(e){!Number.isFinite(e)||e<1||(Vs.concurrency=Math.floor(e),f.debug({concurrency:e},"Local executor concurrency set to %d",e))}var Ae;async function Fs(e){if(!xr.has(e.runId)){xr.add(e.runId),f.debug({inflight:xr.size,runId:e.runId},"run dispatched (inflight=%d)",xr.size);try{await Vs(()=>Uh(e))}finally{xr.delete(e.runId)}}}async function Ms(){if(Ae==null)return;let e=await Ae.catch(()=>{});Ae=void 0,e!=null&&e.isConnected()&&await e.close().catch(()=>{})}async function _h(){Ae??=Ue({headed:!1});let e=Ae,r=await e;return r.isConnected()?r:(Ae===e&&(Ae=Ue({headed:!1})),Ae)}async function Uh({config:e,cwd:r,runId:t,workflowSlug:n}){try{let o=await j({label:"getSharedBrowser",fn:()=>_h()}),i=await j({label:"resolvePreconditionNames",fn:async()=>{if(!(r==null||n==null))return Vh({cwd:r,workflowSlug:n})}});await an({baseUrl:e.appUrl,browser:o,config:e,headed:!1,preconditionNames:i,runId:t,webhookSecret:e.webhookSecret})}catch(o){f.error(o,"Runner error")}}async function Vh({cwd:e,workflowSlug:r}){let t=await x(e);if(!t.ok)return;let n=t.result.tests.find(o=>o.slug===r);if(n!=null)return n.preconditions}var Bh=6e4,Hs=100,Wh=15e3,qh=or(`
|
|
607
608
|
subscription RunRequestedWatch($devSessionId: String!) {
|
|
608
609
|
runRequested(devSessionId: $devSessionId) {
|
|
609
610
|
runId
|
|
@@ -611,14 +612,14 @@ ${String(m)} error(s)
|
|
|
611
612
|
workflowSlug
|
|
612
613
|
}
|
|
613
614
|
}
|
|
614
|
-
`),zh=
|
|
615
|
+
`),zh=or(`
|
|
615
616
|
subscription HooksPausedWatch($projectId: String!) {
|
|
616
617
|
hooksPausedRequested(projectId: $projectId) {
|
|
617
618
|
paused
|
|
618
619
|
projectId
|
|
619
620
|
}
|
|
620
621
|
}
|
|
621
|
-
`),Gh=
|
|
622
|
+
`),Gh=or(`
|
|
622
623
|
mutation HeartbeatDevSessionWatch($id: String!) {
|
|
623
624
|
heartbeatDevSession(id: $id) {
|
|
624
625
|
__typename
|
|
@@ -630,18 +631,18 @@ ${String(m)} error(s)
|
|
|
630
631
|
}
|
|
631
632
|
}
|
|
632
633
|
}
|
|
633
|
-
`),Kh=
|
|
634
|
+
`),Kh=or(`
|
|
634
635
|
query WatchLocalConcurrency {
|
|
635
636
|
currentUser {
|
|
636
637
|
id
|
|
637
638
|
maxLocalConcurrentRuns
|
|
638
639
|
}
|
|
639
640
|
}
|
|
640
|
-
`),Jh=
|
|
641
|
+
`),Jh=or(`
|
|
641
642
|
subscription WatchLocalConcurrencyChanged {
|
|
642
643
|
myMaxLocalConcurrentRunsChanged
|
|
643
644
|
}
|
|
644
|
-
`),Xh=
|
|
645
|
+
`),Xh=or(`
|
|
645
646
|
mutation EndDevSessionWatch($projectId: String!, $cwd: String!) {
|
|
646
647
|
endDevSession(projectId: $projectId, cwd: $cwd) {
|
|
647
648
|
__typename
|
|
@@ -653,12 +654,12 @@ ${String(m)} error(s)
|
|
|
653
654
|
}
|
|
654
655
|
}
|
|
655
656
|
}
|
|
656
|
-
`);async function Bs(){sw();let e=nw(process.cwd()),
|
|
657
|
-
`),process.exit(1));let o=await qs(()=>Qe({compiled:n.result,config:e,cwd:
|
|
658
|
-
`);let y=async()=>{u(),m(),a.stop(),l(),c(),await Promise.race([h({config:e,document:Xh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(E=>setTimeout(E,3e3))]),await sn(),await Ms(),
|
|
659
|
-
`);let s;try{
|
|
660
|
-
`),process.exit(1)),
|
|
661
|
-
`),process.exit(1)}}function qs(e,{config:
|
|
657
|
+
`);async function Bs(){sw();let e=nw(process.cwd()),r=e.cwd,t=tw(r),n=await x(r);n.ok||(process.stderr.write(`ripplo: DSL compilation failed: ${n.error}
|
|
658
|
+
`),process.exit(1));let o=await qs(()=>Qe({compiled:n.result,config:e,cwd:r}),{config:e,label:"initial sync"});await aw(e),Ws({cwd:r,paused:o.hooksPaused});let i=at(r);i!=null&&f.info("watching branch %s in %s",i,r);let s=Fh({headers:{Authorization:`Bearer ${e.token}`},retryAttempts:1/0,url:`${e.ripploServerUrl}/graphql`}),a=rw({config:e,cwd:r,initialId:o.devSessionId,sseClient:s}),l=Zh({cwd:r,projectId:e.projectId,sseClient:s}),c=Qh({sseClient:s}),u=ew({config:e,session:a}),m=iw();process.stdout.write(`ripplo watch: ready as local executor for session ${o.devSessionId} (sync happens on each \`ripplo run\`; Ctrl-C to stop)
|
|
659
|
+
`);let y=async()=>{u(),m(),a.stop(),l(),c(),await Promise.race([h({config:e,document:Xh,variables:{cwd:e.cwd,projectId:e.projectId}}).catch(()=>{}),new Promise(E=>setTimeout(E,3e3))]),await sn(),await Ms(),rn(),t()},R=()=>{y().finally(()=>process.exit(0))};process.on("SIGINT",R),process.on("SIGTERM",R),process.on("SIGHUP",R),process.on("SIGBREAK",R),await new Promise(()=>{})}function Yh({cwd:e,devSessionId:r,onReconnecting:t,sseClient:n}){return n.subscribe({query:Hn(qh),variables:{devSessionId:r}},{complete:()=>{},error:o=>{f.warn("runRequested SSE retries exhausted: %s",o instanceof Error?o.message:String(o))},next:o=>{let i=o.data?.runRequested;if(i==null)return;process.stdout.write(`ripplo: run ${i.workflowSlug}
|
|
660
|
+
`);let s;try{Yr(e),s=W(e)}catch(a){f.error({err:a,runId:i.runId},"failed to load env for run dispatch; skipping");return}Fs({config:s,cwd:e,runId:i.runId,workflowId:i.workflowId,workflowSlug:i.workflowSlug}).catch(a=>{f.error({err:a,runId:i.runId,workflowSlug:i.workflowSlug},"run execution failed; watch continuing")})}},{connecting:o=>{o&&t()}})}function Ws({cwd:e,paused:r}){let t=Ce(e);if(r&&!pt.existsSync(t)){pt.writeFileSync(t,"");return}!r&&pt.existsSync(t)&&pt.unlinkSync(t)}function Qh({sseClient:e}){return e.subscribe({query:Hn(Jh)},{complete:()=>{},error:r=>{f.error(r,"localConcurrency subscription error")},next:r=>{let t=r.data?.myMaxLocalConcurrentRunsChanged;t!=null&&Mn(t)}})}function Zh({cwd:e,projectId:r,sseClient:t}){return t.subscribe({query:Hn(zh),variables:{projectId:r}},{complete:()=>{},error:n=>{f.error(n,"hooksPaused subscription error")},next:n=>{let o=n.data?.hooksPausedRequested?.paused;o!=null&&Ws({cwd:e,paused:o})}})}function ew({config:e,session:r}){let t=async()=>{try{let o=await h({config:e,document:Gh,variables:{id:r.getId()}});o.heartbeatDevSession?.__typename==="DevSessionEndedError"&&(f.warn("dev session ended server-side (%s); re-registering",o.heartbeatDevSession.message),await r.reregister())}catch(o){f.warn("heartbeat failed: %s",o instanceof Error?o.message:String(o))}},n=setInterval(()=>{t()},Wh);return()=>{clearInterval(n)}}function rw({config:e,cwd:r,initialId:t,sseClient:n}){let o=t,i=null,s=()=>{f.warn("runRequested SSE reconnecting; re-registering session"),u()},a=()=>Yh({cwd:r,devSessionId:o,onReconnecting:s,sseClient:n}),l=a(),c=async()=>{let m=await x(r);if(!m.ok){f.error("re-register: DSL compile failed: %s",m.error);return}let y=await qs(()=>Qe({compiled:m.result,config:e,cwd:r}),{config:e,label:"re-register sync"});l(),o=y.devSessionId,l=a(),f.info("re-registered dev session as %s",o)},u=()=>(i!=null||(i=c().finally(()=>{i=null})),i);return{reregister:u,getId:()=>o,stop:()=>{l()}}}function tw(e){try{return is(e)}catch(r){throw r instanceof Xe&&(process.stderr.write(`ripplo watch: another watcher is already running for this project (pid ${String(r.pid)}, cwd ${r.cwd}).
|
|
661
|
+
`),process.exit(1)),r}}function nw(e){try{return W(e)}catch(r){let t=r instanceof Error?r.message:String(r);process.stderr.write(`${t}
|
|
662
|
+
`),process.exit(1)}}function qs(e,{config:r,label:t}){let n=r.ripploServerUrl.includes("localhost")||r.ripploServerUrl.includes("127.0.0.1");return Mh(async()=>{try{return await e()}catch(o){let i=o instanceof Error?o.message:String(o);throw ow(i)?o:(f.error("%s failed: %s",t,i),new Hh(i))}},{factor:2,maxTimeout:n?2e3:1e4,minTimeout:n?100:1e3,retries:1/0,onFailedAttempt:({attemptNumber:o,error:i})=>{f.warn("%s attempt %d failed; retrying: %s",t,o,i.message)}})}function ow(e){return e.includes("status 502")||e.includes("ECONNREFUSED")||e.includes("Failed to connect")||e.includes("fetch failed")}function iw(){Tr({maxRuns:Hs});let e=setInterval(()=>{Tr({maxRuns:Hs})},Bh);return()=>{clearInterval(e)}}function sw(){process.on("unhandledRejection",e=>{f.error({err:e},"unhandledRejection in watch; continuing")}),process.on("uncaughtException",e=>{f.error({err:e},"uncaughtException in watch; continuing")})}async function aw(e){try{let t=(await h({config:e,document:Kh,variables:void 0})).currentUser?.maxLocalConcurrentRuns;t!=null&&Mn(t)}catch(r){f.warn({err:r},"failed to fetch local concurrency setting; using default")}}import{graphql as mt}from"gql.tada";var lw=mt(`
|
|
662
663
|
query ScopeWorkflowBySlug($projectId: String!, $cwd: String!, $slug: String!) {
|
|
663
664
|
project(id: $projectId) {
|
|
664
665
|
id
|
|
@@ -671,7 +672,7 @@ ${String(m)} error(s)
|
|
|
671
672
|
}
|
|
672
673
|
}
|
|
673
674
|
}
|
|
674
|
-
`),cw=
|
|
675
|
+
`),cw=mt(`
|
|
675
676
|
mutation ScopeAddDirtyTests($projectId: String!, $cwd: String!, $workflowSlugs: [String!]!) {
|
|
676
677
|
addDirtyTestsToScope(projectId: $projectId, cwd: $cwd, workflowSlugs: $workflowSlugs) {
|
|
677
678
|
__typename
|
|
@@ -689,36 +690,36 @@ ${String(m)} error(s)
|
|
|
689
690
|
}
|
|
690
691
|
}
|
|
691
692
|
}
|
|
692
|
-
`),uw=
|
|
693
|
+
`),uw=mt(`
|
|
693
694
|
mutation ScopeLink($id: ID!, $workflowId: String!) {
|
|
694
695
|
linkScopeItem(id: $id, workflowId: $workflowId) {
|
|
695
696
|
id
|
|
696
697
|
}
|
|
697
698
|
}
|
|
698
|
-
`),dw=
|
|
699
|
+
`),dw=mt(`
|
|
699
700
|
mutation ScopeRemoveMany($ids: [ID!]!) {
|
|
700
701
|
removeScopeItems(ids: $ids)
|
|
701
702
|
}
|
|
702
|
-
`);async function zs(e){let
|
|
703
|
+
`);async function zs(e){let r=de();await he(r);let n=(await h({config:r,document:dt,variables:{cwd:r.cwd,projectId:r.projectId}})).project?.devSession?.scopeItems??[];if(e.format==="json"){process.stdout.write(`${JSON.stringify(n,null,2)}
|
|
703
704
|
`);return}if(n.length===0){process.stdout.write("No scope items. Add via `ripplo scope add <test-ids..>` (variadic) or from the dashboard.\n");return}n.forEach(o=>{let i=o.workflow;if(i==null){process.stdout.write(` [intent] (${o.id}) ${o.label??""}
|
|
704
705
|
`);return}let s=i.spec==null?"stub":"implemented";process.stdout.write(` [${s}] (${o.id}) ${i.slug} \u2014 ${i.name}
|
|
705
|
-
`)})}async function Gs({testIds:e}){let
|
|
706
|
+
`)})}async function Gs({testIds:e}){let r=de();await he(r),await ye(r.cwd,r);let n=(await h({config:r,document:cw,variables:{cwd:r.cwd,projectId:r.projectId,workflowSlugs:[...e]}})).addDirtyTestsToScope;n?.__typename==="NoActiveDevSessionError"&&(process.stderr.write(`${n.message}
|
|
706
707
|
`),process.exit(1));let o=n?.__typename==="MutationAddDirtyTestsToScopeSuccess"?n.data:[];if(o.length===0){process.stdout.write(`No scope items added.
|
|
707
708
|
`);return}let i=o.map(s=>s.workflow?.slug??"?").join(", ");process.stdout.write(`Added ${String(o.length)} scope item(s): ${i}
|
|
708
|
-
`)}async function Ks({id:e,testId:
|
|
709
|
-
`)}async function Js({ids:e}){let
|
|
710
|
-
`)}async function pw({cfg:e,slug:
|
|
709
|
+
`)}async function Ks({id:e,testId:r}){let t=de();await he(t),await ye(t.cwd,t);let n=await pw({cfg:t,slug:r});await h({config:t,document:uw,variables:{id:e,workflowId:n}}),process.stdout.write(`Linked scope item ${e} to ${r}
|
|
710
|
+
`)}async function Js({ids:e}){let r=de();await he(r);let n=(await h({config:r,document:dw,variables:{ids:[...e]}})).removeScopeItems??0;process.stdout.write(`Removed ${String(n)} scope item(s)
|
|
711
|
+
`)}async function pw({cfg:e,slug:r}){let n=(await h({config:e,document:lw,variables:{cwd:e.cwd,projectId:e.projectId,slug:r}})).project?.devSession?.workflows?.[0];return n==null&&(process.stderr.write(`No workflow found with id "${r}". Create a stub first via the testing DSL.
|
|
711
712
|
`),process.stderr.write(`${w("create")}
|
|
712
|
-
`),process.exit(1)),n.id}async function Xs(e){let
|
|
713
|
-
`),process.exit(1));let{tests:n}=
|
|
713
|
+
`),process.exit(1)),n.id}async function Xs(e){let r=process.cwd(),t=await x(r);t.ok||(process.stderr.write(`Compilation failed: ${t.error}
|
|
714
|
+
`),process.exit(1));let{tests:n}=t.builder.getUnimplemented();if(e.format==="summary"){n.length>0&&process.stdout.write(`tests: ${n.join(", ")}
|
|
714
715
|
`);return}let o={tests:n.map(i=>({id:i,implemented:!1}))};process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
715
|
-
`)}import{z as mw}from"zod";function I(e,
|
|
716
|
-
`).filter(
|
|
717
|
-
`).filter(
|
|
718
|
-
`),hookEventName:"UserPromptSubmit"}}});import hw from"path";import na from"picomatch";import{z as oa}from"zod";var ww=oa.looseObject({file_path:oa.string()}),ia=I("PostToolUse",async e=>{let
|
|
719
|
-
${w("create","DSL authoring + lint rules")}`}});async function vw({compileResult:e,cwd:
|
|
716
|
+
`)}import{z as mw}from"zod";function I(e,r){let t=mw.custom(n=>typeof n=="object"&&n!==null&&"hook_event_name"in n&&n.hook_event_name===e);return{event:e,run:async n=>await r(t.parse(n))??void 0}}import{createHash as RI}from"crypto";import Ys from"picomatch";function fw(e){return K(["diff","--name-only","HEAD"],e).split(`
|
|
717
|
+
`).filter(r=>r.length>0)}function Qs({cwd:e,ignoreGlobs:r,watchGlobs:t}){let n=Ys([...t]),o=Ys([...r]);return fw(e).filter(i=>n(i)&&!o(i))}function ft(e,...r){return K(["diff","--name-only","HEAD","--",...r],e).split(`
|
|
718
|
+
`).filter(t=>t.length>0)}function Ie(){return{ignorePaths:xe,watchPaths:Cn}}var Zs=I("UserPromptSubmit",e=>{let{cwd:r}=e;if(!A(r)||!F(r))return;let t=Ee(r);if(Ze(r,"coverage-nudge")===t)return;let{ignorePaths:n,watchPaths:o}=Ie(),i=Qs({cwd:r,ignoreGlobs:n,watchGlobs:o});if(er(r,"coverage-nudge",t),!(i.length===0||ft(r,".ripplo/tests",".ripplo/preconditions",".ripplo/observers").length>0))return{hookSpecificOutput:{additionalContext:`SCOPE DRIFT: ${String(i.length)} app file(s) changed without .ripplo/tests updates. ${w("scope")}`,hookEventName:"UserPromptSubmit"}}});import gt from"fs";import gw from"os";import ea from"path";var ra=I("PreToolUse",e=>{if(e.tool_name!=="ExitPlanMode"||!F(e.cwd))return;let r=yw();if(r==null)return;let t=gt.readFileSync(r,"utf8");if(!/\.ripplo\/tests|Tests to implement|No e2e coverage needed/.test(t))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Plan must cite ripplo test stubs. Add a "Tests to implement" section listing .ripplo/tests/<id>.ts per affected flow, OR add "No e2e coverage needed: <reason>" if this plan touches no user-facing behavior. ${w("explore")}`}}});function yw(){let e=ea.join(gw.homedir(),".claude","plans");return gt.existsSync(e)?gt.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>ea.join(e,t)).map(t=>({full:t,mtime:gt.statSync(t).mtimeMs})).sort((t,n)=>n.mtime-t.mtime)[0]?.full??null:null}var ta=I("UserPromptSubmit",async e=>{if(e.permission_mode!=="plan"||!A(e.cwd)||!F(e.cwd))return;let r=await x(e.cwd);if(!r.ok)return;let{tests:t}=r.builder.getUnimplemented(),n=['Plan must include "Tests to implement" with .ripplo/tests/<id>.ts per affected flow (ExitPlanMode blocks otherwise).'];return t.length>0&&n.push(`Existing stubs: ${t.join(", ")}`),{hookSpecificOutput:{additionalContext:n.join(`
|
|
719
|
+
`),hookEventName:"UserPromptSubmit"}}});import hw from"path";import na from"picomatch";import{z as oa}from"zod";var ww=oa.looseObject({file_path:oa.string()}),ia=I("PostToolUse",async e=>{let r=ww.safeParse(e.tool_input);if(!r.success)return;let t=r.data.file_path,{cwd:n}=e;if(!A(n)||!F(n))return;let o=hw.relative(n,t);if(o.startsWith(".."))return;let{ignorePaths:i,watchPaths:s}=Ie(),a=na([...s]),l=na([...i]);if(!a(o)||l(o))return;let c=await x(n);if(!c.ok)return;let{tests:u}=c.builder.getUnimplemented();if(u.length!==0)return{hookSpecificOutput:{additionalContext:`Reminder: .notImplemented() stubs still present \u2014 tests: ${u.join(", ")}`,hookEventName:"PostToolUse"}}});import{z as sa}from"zod";var bw=sa.looseObject({file_path:sa.string()}),aa=I("PostToolUse",async e=>{let r=bw.safeParse(e.tool_input);if(!r.success)return;let t=r.data.file_path;if(!/\/\.ripplo\/.*\.ts$/.test(t))return;let{cwd:n}=e;if(!A(n))return;if(!F(n))return{hookSpecificOutput:{additionalContext:"Ripplo hooks are paused \u2014 DSL lint, lockfile sync, and coverage codegen did not run for this edit. Resume with `npx ripplo hooks resume` when ready.",hookEventName:"PostToolUse"}};let o=await x(n);return o.ok?(await ce({cwd:n,result:o.result}),Ge({cwd:n}),await vw({compileResult:o,cwd:n})):{decision:"block",reason:`Compilation failed: ${o.error}
|
|
720
|
+
${w("create","DSL authoring + lint rules")}`}});async function vw({compileResult:e,cwd:r}){let{diagnostics:t}=qe(e.result);if(t.length>0)return{decision:"block",reason:`${t.map(i=>{let s=i.step==null?"":` at "${i.step}"`;return` [${i.rule}]${s} ${i.test}: ${i.message}`}).join(`
|
|
720
721
|
`)}
|
|
721
|
-
${w("create")}`};let{addedSlugs:n}=await
|
|
722
|
+
${w("create")}`};let{addedSlugs:n}=await nr({compileResult:e,cwd:r});if(n.length!==0)return{hookSpecificOutput:{additionalContext:`Auto-scoped ${n.join(", ")} (dirty tests).`,hookEventName:"PostToolUse"}}}import{z as la}from"zod";var Sw=la.looseObject({command:la.string()}),kw=/\bripplo\s+hooks\s+pause\b/,ca=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let r=Sw.safeParse(e.tool_input);if(!r.success||!kw.test(r.data.command))return;let{cwd:t}=e;if(A(t))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"`ripplo hooks pause` is a human-only escape hatch \u2014 agents can't bypass Ripplo guardrails on their own. If watch genuinely can't start (auth, server down, intentional offline work), surface the blocker to the user and ask them to run `npx ripplo hooks pause` themselves from their terminal."}}});import{parse as Cw}from"shell-quote";import{z as da}from"zod";import{existsSync as Pw,mkdirSync as Rw,rmSync as ST,writeFileSync as xw}from"fs";import Bn from"path";function yt(e,r,t){let n=ua(e,r,t);Rw(Bn.dirname(n),{recursive:!0}),xw(n,"")}function ht(e,r,t){return Pw(ua(e,r,t))}function Ew(e,r){return Bn.join(e,".ripplo",".local","skills-loaded",r)}function ua(e,r,t){return Bn.join(Ew(e,r),t)}var Aw=da.looseObject({command:da.string()}),Iw="debug",Tw=new Set(["tail","head","less","more","wc","sort","uniq","awk","sed","grep"]),ma=I("PreToolUse",e=>{if(e.tool_name!=="Bash")return;let r=Aw.safeParse(e.tool_input);if(!r.success)return;let t=$w(r.data.command);if(!jw(t))return;let{cwd:n}=e;if(!A(n)||!F(n))return;if(!ht(n,e.session_id,Iw))return pa("Running `ripplo run` requires the `/ripplo:debug` skill loaded first. Load `/ripplo:debug` then retry \u2014 it carries the artifact-read order and the no-grep-piping guidance for run failures.");let i=Dw(t);if(i!=null)return pa(`Don't pipe \`ripplo run\` through \`${i}\` \u2014 buffering filters hold all stdout until EOF, hiding live progress; if you kill the pipeline mid-run the run is orphaned on the server. Redirect to a file instead: \`ripplo run <id> > /tmp/run.log 2>&1\` and Read the file, or use \`run_in_background: true\`.`)});function $w(e){try{return Cw(e)}catch{return[]}}function jw(e){return e.some((r,t)=>r==="ripplo"&&e[t+1]==="run")}function Nw(e){return typeof e=="object"&&"op"in e&&e.op==="|"}function Dw(e){let r=e.find((t,n)=>{let o=e[n-1];return o!=null&&Nw(o)&&typeof t=="string"&&Tw.has(t)});return typeof r=="string"?r:null}function pa(e){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}}}import Ow from"path";import{z as fa}from"zod";var Lw=new Set(["Edit","Write","NotebookEdit"]),_w=fa.looseObject({file_path:fa.string()}),Uw="create",ga=I("PreToolUse",e=>{if(!Lw.has(e.tool_name))return;let r=_w.safeParse(e.tool_input);if(!r.success)return;let{cwd:t}=e;if(!A(t)||!F(t))return;let n=Ow.relative(t,r.data.file_path);if(!(n.startsWith("..")||n!==".ripplo"&&!n.startsWith(".ripplo/"))&&!ht(t,e.session_id,Uw))return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Editing \`.ripplo/\` files (${n}) requires the \`/ripplo:create\` skill loaded first. Load \`/ripplo:create\` then retry \u2014 it carries the DSL builder shape, lint rules, and the parallelization guidance you'll need.`}}});import Vw from"path";import ya from"picomatch";import{graphql as Fw}from"gql.tada";import{z as ha}from"zod";var Mw=new Set(["Edit","Write","NotebookEdit"]),Hw=ha.looseObject({file_path:ha.string()}),Bw=Fw(`
|
|
722
723
|
query PreEditScopeGate($projectId: String!, $cwd: String!) {
|
|
723
724
|
project(id: $projectId) {
|
|
724
725
|
id
|
|
@@ -730,9 +731,9 @@ ${w("create")}`};let{addedSlugs:n}=await nt({compileResult:e,cwd:t});if(n.length
|
|
|
730
731
|
}
|
|
731
732
|
}
|
|
732
733
|
}
|
|
733
|
-
`),wa=I("PreToolUse",async e=>{if(!Mw.has(e.tool_name))return;let
|
|
734
|
+
`),wa=I("PreToolUse",async e=>{if(!Mw.has(e.tool_name))return;let r=Hw.safeParse(e.tool_input);if(!r.success)return;let{cwd:t}=e;if(!A(t)||!F(t))return;let n=Vw.relative(t,r.data.file_path);if(n.startsWith("..")||n===".ripplo"||n.startsWith(".ripplo/")||!Ww(n))return;let o=await qw(t);return o.populated?o.degradedReason!=null?{hookSpecificOutput:{additionalContext:`Scope check skipped (${o.degradedReason}) \u2014 edit allowed through, but the scope guardrail isn't enforcing on this edit.`,hookEventName:"PreToolUse"}}:void 0:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Scope empty; edit touches app code (${n}). Stub a test or \`scope add\` an existing one before proceeding \u2014 or acknowledge "no user-facing behavior" if pure refactor. Hook re-fires until scope is populated (or hooks paused via the web UI). ${Gi(["scope","create"])}`}}});function Ww(e){let{ignorePaths:r,watchPaths:t}=Ie(),n=ya([...t]),o=ya([...r]);return n(e)&&!o(e)}async function qw(e){let r;try{r=W(e)}catch{return{degradedReason:"no project config \u2014 `ripplo init` not run here",populated:!0}}let t=await h({config:r,document:Bw,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null);return t==null?{degradedReason:"server unreachable",populated:!0}:{degradedReason:null,populated:(t.project?.devSession?.scopeItems??[]).length>0}}import zw from"fs";import Gw from"path";import{z as ba}from"zod";var Kw=new Set(["Edit","Write","NotebookEdit"]),Jw=ba.looseObject({file_path:ba.string()}),va=I("PreToolUse",async e=>{if(!Kw.has(e.tool_name))return;let r=Xw(e);if(r==null)return;let{cwd:t}=e;if(zw.existsSync(Ce(t))||Ye(t))return;let n=await x(t);return n.ok?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`\`ripplo watch\` is not running, so this edit to \`${r}\` won't sync to the server and dev-mode guardrails won't fire. Run \`/ripplo:start\` (or spawn \`npx ripplo watch\` directly via Bash with run_in_background), then retry. The app's dev server also needs to be running \u2014 \`npx ripplo doctor\` reports both. If watch can't start (auth, server down, intentional offline work), the user can run \`npx ripplo hooks pause\` to bypass this gate; \`npx ripplo hooks resume\` re-enables it. ${w("start")}`}}:{hookSpecificOutput:{additionalContext:`\`ripplo watch\` isn't running and the DSL is currently failing to compile, so the watch gate is letting this edit through \u2014 fix the compile error before relying on dev-mode guardrails. Compile error:
|
|
734
735
|
${n.error}
|
|
735
|
-
${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function Xw(e){let
|
|
736
|
+
${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});function Xw(e){let r=Jw.safeParse(e.tool_input);if(!r.success||!A(e.cwd))return null;let t=Gw.relative(e.cwd,r.data.file_path);return t.startsWith("..")||t!==".ripplo"&&!t.startsWith(".ripplo/")?null:t}import{graphql as Yw}from"gql.tada";var Qw=Yw(`
|
|
736
737
|
query ScopeReminder($projectId: String!, $cwd: String!) {
|
|
737
738
|
project(id: $projectId) {
|
|
738
739
|
id
|
|
@@ -749,9 +750,9 @@ ${w("create","DSL authoring + lint rules")}`,hookEventName:"PreToolUse"}}});func
|
|
|
749
750
|
}
|
|
750
751
|
}
|
|
751
752
|
}
|
|
752
|
-
`),Sa=I("UserPromptSubmit",async e=>{let{cwd:
|
|
753
|
+
`),Sa=I("UserPromptSubmit",async e=>{let{cwd:r}=e;if(!A(r)||!F(r))return;let t=Ee(r);if(Ze(r,"scope-reminder")===t)return;let n;try{n=W(r)}catch{return}let o=await h({config:n,document:Qw,variables:{cwd:n.cwd,projectId:n.projectId}}).catch(()=>null);if(o==null)return;er(r,"scope-reminder",t);let i=o.project?.devSession?.scopeItems??[];return{hookSpecificOutput:{additionalContext:i.length===0?`RIPPLO SCOPE: empty. ${w("scope")}`:`RIPPLO SCOPE (${String(i.length)}):
|
|
753
754
|
${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}`:` [${l.spec==null?"stub":"implemented"}] (${a.id}) ${l.slug}`}).join(`
|
|
754
|
-
`)}`,hookEventName:"UserPromptSubmit"}}});var Zw="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",ka=I("SessionStart",e=>{if(A(e.cwd))return{hookSpecificOutput:{additionalContext:Zw,hookEventName:"SessionStart"}}});import{execFileSync as eb}from"child_process";import
|
|
755
|
+
`)}`,hookEventName:"UserPromptSubmit"}}});var Zw="# Ripplo \u2014 always-on session context\n\nEvery user-facing change in this repo ships with a deterministic, backend-aware test that proves it works end-to-end.\n\n## Load the right skill before acting \u2014 this is critical\n\nThe skills below carry the procedural detail you need to do Ripplo work correctly: precondition isolation, observer budget tiers, coverage IDs, scope discipline, artifact-read order on failures, parallelization patterns. **None of that is reproduced in this preamble** \u2014 only the always-on guardrails are. If you act on a Ripplo task without loading the matching skill, you will skip rules that exist to prevent specific past failure modes (cross-run data leakage, \"passing\" tests that never asserted backend state, cleared coverage gates without proof, etc.).\n\nMatch the task to a skill from the triage table; if unsure between two, load both. If completely unsure, load `/ripplo:explore` or `/ripplo:create`. Loading is cheap; acting under-informed is not.\n\n## Skill triage\n\n- Load `/ripplo:setup` skill for instructions on initializing Ripplo in a project; `ripplo doctor` reports the engine endpoint missing.\n- Load `/ripplo:explore` skill for instructions on planning/stubbing test coverage for a new project or new feature area.\n- Load `/ripplo:scope` skill for instructions on managing the working set of tests this session is responsible for.\n- Load `/ripplo:create` skill for instructions on authoring a single test spec for a user flow.\n- Load `/ripplo:run` skill for instructions on executing existing tests.\n- Load `/ripplo:debug` skill for instructions on a failed run; read artifacts in `.ripplo/debug/<runId>/` before re-running.\n- Load `/ripplo:flake-detect` skill for instructions on intermittent failures; parallelizes N runs (only use with evidence of flake).\n\n## Universal rules\n\n- **Two background processes must be running before feature work.** (1) The app's dev server, so the app is reachable; (2) `npx ripplo watch` (run `/ripplo:start` to spawn it, or invoke it directly via Bash with `run_in_background`), so the dev session is live. Without watch, scope/coverage hooks don't arm and `ripplo run` refuses to dispatch. Without the dev server, runs fail when they try to hit the app. `npx ripplo doctor` reports both.\n- **Two funnels.** Definitions \u2192 `createRipplo({ preconditions, observers, tests })` in `.ripplo/index.ts`. Implementations \u2192 `createEngine(ripplo, { preconditions, observers })` in your app server's `test/engine.ts`. Never call either elsewhere. TS enforces exhaustiveness across both.\n- **\"Done\" = app code delivers the behavior AND a passing test proves it.** Both halves. Shipping without a test isn't done; writing a test against broken UI/API isn't done.\n- **Scope is your job.** For any non-trivial change, enumerate every flow it could affect and either `scope add` existing tests or stub `.notImplemented()` tests. Don't wait to be told.\n- **`scope remove` is never for size/effort.** Valid only when an item is genuinely out of scope (wrong flow, duplicate, user said \"not this session,\" feature cut). \"Too many stubs\" \u2192 parallelize with subagents. Don't present \"implement vs. remove\" as a neutral A/B.\n- **Stub gates are not a question.** When `stop-enforce` blocks on `.notImplemented()` stubs, implement them \u2014 don't ask the user \"implement or defer?\", don't propose pausing hooks as option B. The fix isn't done until the test is. New scaffolding (precondition, observer, engine impl) is in-scope work, not follow-up.\n- **`uiOnly: true` is not a stub.** Observer wiring is in-scope for mutation flows; don't use it to silence observer lint.\n- **Never weaken a test to make it pass.** No `contains`/regex for exact text, no removed assertions, no fabricated locators. App lacks an accessible name \u2192 add one to the app, don't fall back to `testId()`. App bug \u2192 report with evidence.\n- **Artifacts first, re-run last.** Failed runs produce DOM, a11y tree, console, network, screenshots under `.ripplo/debug/<runId>/`. Read them. Never pipe `ripplo run` through `grep`/`tail`/`head`. Form a hypothesis citing an artifact line, make ONE change, re-run once.\n- **`.ripplo/ripplo.lock` is committed, never hand-edited.** `ripplo lint` / `ripplo compile` regenerates it. Pre-commit runs `ripplo compile --check`.\n- **Scratch files live in `.ripplo/.local/`.** Never loose in `.ripplo/`.\n- **Worktrees are self-contained.** Each worktree has its own `.ripplo/` checkout, DevSession, scope, and debug artifacts. Auth and projectId are shared globally. Env files (typically gitignored) won't carry over to a fresh worktree \u2014 copy from main or point at a shared file. **If sibling worktrees run dev servers on different ports, the worktree's env file MUST update both `RIPPLO_APP_URL` and `RIPPLO_ENGINE_URL` to match the port that worktree's dev server is bound to** (e.g. main on `:3000`, this worktree on `:3001` \u2192 set `RIPPLO_APP_URL=http://localhost:3001` and `RIPPLO_ENGINE_URL=http://localhost:3001/ripplo` in the worktree's env file). Mismatched ports = `npx ripplo watch` (whether started via `/ripplo:start` or manually) talks to the wrong server, runs silently fail or hit the sibling worktree's app.\n- **DSL locators are semantic.** No `css` / `placeholder` / `waitFor` / `group`.\n- **New backend assertion?** Declare in `.ripplo/observers/index.ts`, implement in your app server's `engine.ts` (TS flags the missing impl).\n\n## Key files\n\n- `.ripplo/index.ts` \u2014 `createRipplo` call.\n- `.ripplo/{preconditions,observers,tests}/index.ts` \u2014 registry aggregators.\n- `.ripplo/project.json` \u2014 project id + env-file pointers.\n- `<app>/src/test/engine.ts` \u2014 single impl funnel via `createEngine`.\n- `packages/testing/README.md` (or the npm page for `@ripplo/testing`) \u2014 DSL reference.\n",ka=I("SessionStart",e=>{if(A(e.cwd))return{hookSpecificOutput:{additionalContext:Zw,hookEventName:"SessionStart"}}});import{execFileSync as eb}from"child_process";import rb from"path";import Pa from"process";import{graphql as tb}from"gql.tada";import{z as wt}from"zod";var nb=tb(`
|
|
755
756
|
query ScopeEnforce($projectId: String!, $cwd: String!) {
|
|
756
757
|
project(id: $projectId) {
|
|
757
758
|
id
|
|
@@ -770,14 +771,14 @@ ${i.map(a=>{let l=a.workflow;return l==null?` [intent] (${a.id}) ${a.label??""}
|
|
|
770
771
|
}
|
|
771
772
|
}
|
|
772
773
|
}
|
|
773
|
-
`),xa=I("Stop",async e=>{let{cwd:
|
|
774
|
+
`),xa=I("Stop",async e=>{let{cwd:r}=e;if(!A(r)||!F(r))return;let t=Ee(r),n=Ze(r,"stop-enforce")===t;if(n&&!e.stop_hook_active)return;let o=ob(r),i=await ib(r,o);if(er(r,"stop-enforce",t),i.length!==0)return n&&e.stop_hook_active?{continue:!1,stopReason:`Stop-enforce: same repo state across consecutive stop attempts; agent appears stuck. Errors:
|
|
774
775
|
${i.join(`
|
|
775
776
|
|
|
776
777
|
`)}`}:{decision:"block",reason:i.join(`
|
|
777
778
|
|
|
778
|
-
`)}});function ob(e){return
|
|
779
|
-
${
|
|
780
|
-
${w("create")}`];await ce({cwd:e,result:
|
|
779
|
+
`)}});function ob(e){return ft(e,".ripplo/tests").filter(r=>r.endsWith(".ts")).map(r=>rb.basename(r,".ts")).filter(r=>r!=="index")}async function ib(e,r){let t=await x(e);if(!t.ok)return[`--- Compilation failed ---
|
|
780
|
+
${t.error}
|
|
781
|
+
${w("create")}`];await ce({cwd:e,result:t.result}),Ge({cwd:e});let n=await ab(e),o=lb(t,r),i=cb(t),s=sb(e,t),l=r.length>0||n.hasRunnable?ub(e):null;return[o,i,s,l,n.error].filter(c=>c!=null)}function sb(e,r){let{ignorePaths:t}=Ie(),n=Xi({compileResult:r.result,cwd:e,ignorePaths:t});if(n.length===0)return null;let o=n.filter(a=>a.kind==="unacknowledged"),i=n.filter(a=>a.kind==="stale"),s=[];if(o.length>0){let a=o.map(l=>` ${l.id}`).join(`
|
|
781
782
|
`);s.push(`Unacknowledged interactions (add to a test's .coverage(...)):
|
|
782
783
|
${a}`)}if(i.length>0){let a=i.map(l=>` ${l.id}`).join(`
|
|
783
784
|
`);s.push(`Stale .coverage(...) claims (id no longer exists in source):
|
|
@@ -785,22 +786,22 @@ ${a}`)}return`--- Exhaustiveness ---
|
|
|
785
786
|
${s.join(`
|
|
786
787
|
|
|
787
788
|
`)}
|
|
788
|
-
${w("create")}`}async function ab(e){let
|
|
789
|
+
${w("create")}`}async function ab(e){let r;try{r=W(e)}catch{return{error:null,hasRunnable:!1}}let n=(await h({config:r,document:nb,variables:{cwd:r.cwd,projectId:r.projectId}}).catch(()=>null))?.project?.devSession?.scopeItems??[],o=n.flatMap(a=>{let l=a.workflow;return l==null?[` [intent] ${a.label??"(no label)"} \u2014 stub a test for this flow`]:l.spec==null?[` [stub] ${l.slug} \u2014 implement \`${l.name}\``]:[]}),i=n.some(a=>a.workflow?.spec!=null);return{error:o.length===0?null:`--- Testing Scope ---
|
|
789
790
|
${o.join(`
|
|
790
791
|
`)}
|
|
791
|
-
${w("create")}`,hasRunnable:i}}function lb(e,
|
|
792
|
+
${w("create")}`,hasRunnable:i}}function lb(e,r){let{diagnostics:t}=qe(e.result),n=new Set(e.builder.getUnimplemented().tests),o=r.filter(a=>n.has(a));if(t.length===0&&o.length===0)return null;let i=t.map(a=>{let l=a.step==null?"":` at "${a.step}"`;return` [${a.rule}]${l} ${a.test}: ${a.message}`}),s=o.map(a=>` [not-implemented] ${a} is still marked .notImplemented()`);return`--- Ripplo Lint ---
|
|
792
793
|
${[...i,...s].join(`
|
|
793
794
|
`)}
|
|
794
|
-
${w("create")}`}function cb(e){let{tests:
|
|
795
|
-
${
|
|
795
|
+
${w("create")}`}function cb(e){let{tests:r}=e.builder.getUnimplemented();return r.length===0?null:`--- Unimplemented stubs ---
|
|
796
|
+
${r.join(", ")}
|
|
796
797
|
Implement the stub now. Do not ask the user "implement or defer?" \u2014 that framing is forbidden by /ripplo:create. New scaffolding (precondition, observer, engine impl) is in-scope, not follow-up.
|
|
797
|
-
${w("create")}`}function ub(e){let
|
|
798
|
+
${w("create")}`}function ub(e){let r=pb(["run"],e);if(r.code===0)return null;let t=r.output.split(`
|
|
798
799
|
`).filter(n=>/FAILED/.test(n)).join(`
|
|
799
|
-
`);return
|
|
800
|
-
${
|
|
801
|
-
Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var db=
|
|
802
|
-
`),process.exit(1));let
|
|
803
|
-
`),process.exit(1)});function vb(e){return e.command("status","Print the current scope",
|
|
800
|
+
`);return t.length===0?null:`--- Ripplo Run Failures (scope) ---
|
|
801
|
+
${t}
|
|
802
|
+
Artifacts: .ripplo/debug/<runId>/. ${w("debug")}`}var db=wt.object({status:wt.number().nullish(),stderr:wt.unknown().optional(),stdout:wt.unknown().optional()});function Ra(e){return e instanceof Buffer?e.toString("utf8"):typeof e=="string"?e:""}function pb(e,r){let t=Pa.argv[1];if(t==null)return{code:1,output:""};try{return{code:0,output:eb(Pa.execPath,[t,...e],{cwd:r,encoding:"utf8",stdio:["ignore","pipe","pipe"]})}}catch(n){let o=db.safeParse(n);if(!o.success)return{code:1,output:""};let i=`${Ra(o.data.stdout)}${Ra(o.data.stderr)}`;return{code:o.data.status??1,output:i}}}import{z as Ea}from"zod";var mb=Ea.looseObject({skill:Ea.string()}),Ca=I("PostToolUse",e=>{if(e.tool_name!=="Skill")return;let r=mb.safeParse(e.tool_input);if(!r.success)return;let t=/^ripplo:(.+)$/.exec(r.data.skill);if(t==null)return;let n=t[1];n!=null&&A(e.cwd)&&yt(e.cwd,e.session_id,n)});var fb=/(?:^|\s)\/ripplo:([a-z][a-z0-9-]*)\b/gi,Aa=I("UserPromptSubmit",e=>{A(e.cwd)&&[...e.prompt.matchAll(fb)].map(r=>r[1]).filter(r=>r!=null).forEach(r=>{yt(e.cwd,e.session_id,r)})});Rb();Yr(process.cwd());Ut();var Ia={"coverage-nudge":Zs,"exit-plan-gate":ra,"plan-reminder":ta,"post-edit-flag-stubs":ia,"post-edit-lint":aa,"pre-bash-hooks-pause-gate":ca,"pre-bash-run-gate":ma,"pre-edit-ripplo-skill-gate":ga,"pre-edit-scope-gate":wa,"pre-edit-watch-gate":va,"scope-reminder":Sa,"session-preamble":ka,"stop-enforce":xa,"track-skill-load":Ca,"track-skill-prompt":Aa};async function hb(){await gb(yb(process.argv)).scriptName("ripplo").version("0.6.1").command("watch","Watch for run requests and execute locally",()=>{},()=>Bs()).command("auth <subcommand>","Manage authentication",Pb).command("projects <subcommand>","Inspect Ripplo projects",kb).command("hooks <subcommand>","Pause or resume Ripplo hooks",Sb).command("init","Scaffold .ripplo/ in this project",e=>e.option("project",{type:"string"}).option("env",{type:"string"}).option("app-url",{type:"string"}).option("engine-url",{type:"string"}),e=>Ts({appUrl:e["app-url"],engineUrl:e["engine-url"],envFile:e.env,projectId:e.project})).command("run [ids..]","Run tests (defaults to scope; auto-adds dirty tests)",e=>{let r=[];return e.positional("ids",{array:!0,default:r,describe:"Test ids to run (defaults to dev-session scope)",type:"string"}).option("all",{default:!1,describe:"Run every test in the dev session (expensive)",type:"boolean"})},e=>_s({all:e.all,ids:e.ids})).command("lint [ids..]","Compile and lint tests (all or specific ids)",e=>{let r=[];return e.positional("ids",{array:!0,default:r,describe:"Test ids to lint (all if omitted)",type:"string"}).option("require-implemented",{array:!0,default:r,describe:"Test ids that must not be .notImplemented() \u2014 fails if any still are",type:"string"})},e=>Os({ids:e.ids,requireImplemented:e["require-implemented"]})).command("flake-detect <id>","Run N times to detect flakiness",e=>e.positional("id",{demandOption:!0,type:"string"}).option("runs",{default:10,type:"number"}),e=>ks({id:e.id,runs:e.runs})).command("sync","Push the compiled .ripplo/ resources to the server (no run)",()=>{},()=>Us()).command("compile","Compile the DSL and write .ripplo/ripplo.lock",e=>e.option("check",{default:!1,describe:"Exit non-zero if the lockfile is missing or stale (does not write)",type:"boolean"}),e=>Ji({check:e.check})).command("cover","Audit all coverage statements",()=>{},()=>es()).command("doctor","Check project health",()=>{},()=>gs()).command("status","Report unimplemented tests and preconditions",e=>e.option("format",{choices:["json","summary"],default:"json",describe:"Output format"}),e=>Xs({format:e.format})).command("scope <subcommand>","Manage testing scope",vb).command("hook <name>","Internal: run a Claude Code plugin hook",e=>e.positional("name",{choices:Object.keys(Ia),demandOption:!0,type:"string"}),e=>wb(e.name)).strict().help().parse()}async function wb(e){let r=Ia[e];r==null&&(process.stderr.write(`Unknown hook: ${e}
|
|
803
|
+
`),process.exit(1));let t=await bb(),n=t.trim()===""?{}:JSON.parse(t),o=await r.run(n);o!=null&&process.stdout.write(JSON.stringify(o))}function bb(){return new Promise((e,r)=>{if(process.stdin.isTTY){e("");return}let t=[];process.stdin.on("data",n=>t.push(n)),process.stdin.on("end",()=>{e(Buffer.concat(t).toString("utf8"))}),process.stdin.on("error",r)})}hb().catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
804
|
+
`),process.exit(1)});function vb(e){return e.command("status","Print the current scope",r=>r.option("format",{choices:["json","text"],default:"text",describe:"Output format"}),r=>zs({format:r.format})).command("add <test-ids..>","Bind one or more existing tests (stubs or implemented) to scope as agent intent",r=>{let t=[];return r.positional("test-ids",{array:!0,default:t,demandOption:!0,describe:"Slugs of existing workflows",type:"string"})},r=>Gs({testIds:r["test-ids"]})).command("link <id> <test-id>","Link an existing scope item to a test",r=>r.positional("id",{demandOption:!0,describe:"Scope item id",type:"string"}).positional("test-id",{demandOption:!0,describe:"Slug of the workflow to link",type:"string"}),r=>Ks({id:r.id,testId:r["test-id"]})).command("remove <ids..>","Remove one or more scope items by id",r=>{let t=[];return r.positional("ids",{array:!0,default:t,demandOption:!0,describe:"Scope item ids",type:"string"})},r=>Js({ids:r.ids})).demandCommand(1)}function Sb(e){return e.command("pause","Disable all Ripplo pre-edit gates and stop enforcement until resumed",()=>{},()=>Ps()).command("resume","Re-enable Ripplo hooks paused via `ripplo hooks pause`",()=>{},()=>Rs()).demandCommand(1)}function kb(e){return e.command("list","List projects you have access to (JSON)",()=>{},()=>Ls()).demandCommand(1)}function Pb(e){return e.command("login","Authenticate via device flow",()=>{},()=>pi()).command("status","Show authentication status",()=>{},()=>mi()).command("logout","Remove the saved token",()=>{},()=>{fi()}).demandCommand(1)}function Rb(){let e=process.cwd(),r=Pt(e);r!=null&&r!==e&&(process.chdir(r),process.stderr.write(`ripplo: resolved .ripplo/ at ${r}
|
|
804
805
|
`))}export{hb as main};
|
|
805
806
|
/*! Bundled license information:
|
|
806
807
|
|