@webority/sandbox-gate 0.170.0 → 0.171.0

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/process.d.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  export declare const shellLine: (command: string, args?: string[]) => string;
2
2
  export declare function exitAfterOutput(code: number): Promise<void>;
3
+ /** A helper command the gate runs failed to start or exited non-zero. */
4
+ export declare class GateCommandError extends Error {
5
+ name: string;
6
+ }
7
+ /** Run a helper command hidden, to completion; throws GateCommandError when it cannot start or exits non-zero. */
8
+ export declare function runChecked(command: string, args: string[], okStatuses?: number[]): string;
9
+ /** Kill `pid` (and on Windows its tree); a kill that fails while the process is still alive throws. */
10
+ export declare function killPidHard(pid: string): void;
3
11
  export declare const secs: (ms: number) => string;
4
12
  export declare function reachable(url: string): Promise<boolean>;
5
13
  /** Kill the process listening on a port, and its descendants. */
@@ -1,14 +1,14 @@
1
1
  import{spawn as e,spawnSync as t}from"node:child_process";import{existsSync as n,mkdtempSync as r,openSync as i,readFileSync as a,readdirSync as o,rmSync as s}from"node:fs";import{tmpdir as c}from"node:os";import{join as l,resolve as u}from"node:path";import{createHash as d}from"node:crypto";async function f(e,t={}){return p(await e.locator(t.selector??`body`).ariaSnapshot())}function p(e){let t=[];for(let n of e.split(`
2
- `)){let e=n.trimStart();if(!e.startsWith(`- `))continue;let r=(n.length-e.length)/2,i=e.slice(2).trimEnd();if(i.startsWith(`/`))continue;i.endsWith(`:`)&&(i=i.slice(0,-1));let a=[];for(;i.endsWith(`]`);){let e=i.lastIndexOf(` [`);if(e===-1)break;a.unshift(i.slice(e+2,-1)),i=i.slice(0,e)}let o=i,s=``,c=i.indexOf(` `),l=i.indexOf(`:`);l!==-1&&(c===-1||l<c)?(o=i.slice(0,l),s=m(i.slice(l+1).trim())):c!==-1&&(o=i.slice(0,c),s=m(i.slice(c+1).trim())),t.push({depth:r,role:o,name:s,states:a})}return t}function m(e){return e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}var h=`webority-ui-gate-chrome`,g=RegExp(`${h}[=-](\\d+)`);function _(){let e=Number(process.env.WEBORITY_UI_GATE_PID);return Number.isFinite(e)&&e>0?e:process.pid}function v(){return r(l(c(),`${h}-${_()}-`))}function y(){return[`--${h}=${_()}`]}function b(e){try{return process.kill(e,0),!0}catch{return!1}}function x(){return process.platform===`win32`?(t(`powershell`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.CommandLine }`],{encoding:`utf8`}).stdout||``).split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(` `);return t<0?null:{pid:e.slice(0,t).trim(),commandLine:e.slice(t+1)}}).filter(e=>e!==null):(t(`ps`,[`-A`,`-o`,`pid=,args=`],{encoding:`utf8`}).stdout||``).split(`
3
- `).map(e=>e.trim()).filter(e=>/(?:^|[/\s])(chrome|chromium)(?:\s|$|\.exe)/i.test(e)).map(e=>{let t=e.match(/^(\d+)\s+(.*)$/);if(!t)return null;let[,n,r]=t;return n===void 0||r===void 0?null:{pid:n,commandLine:r}}).filter(e=>e!==null)}function S(e){process.platform===`win32`?t(`taskkill`,[`/PID`,e,`/T`,`/F`],{stdio:`ignore`}):t(`kill`,[`-9`,e],{stdio:`ignore`})}function C(){let e=[];for(let{pid:t,commandLine:n}of x()){if(!n?.includes(`webority-ui-gate-chrome`))continue;let r=n.match(g);if(!r)continue;let i=Number(r[1]);!Number.isFinite(i)||i<=0||i!==process.pid&&(b(i)||e.push(t))}for(let t of e)S(t);return T(),e.length}function w(e=process.pid){let t=[];for(let{pid:n,commandLine:r}of x()){let i=r?.match(g);i&&Number(i[1])===e&&t.push(n)}for(let e of t)S(e);return t.length}function T(){let e=RegExp(`^${h}-(\\d+)-`),t;try{t=o(c())}catch{return}for(let n of t){let t=n.match(e);if(!t)continue;let r=Number(t[1]);if(!(r===process.pid||b(r)))try{s(l(c(),n),{recursive:!0,force:!0})}catch(e){if((e instanceof Error&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}}var E=`--blink-settings=preferredColorScheme=1`;function D(e){process.stdout.write(`${e}\n`)}var O=(e,t=[])=>[e,...t].join(` `);async function ee(e){await new Promise(e=>process.stdout.write(``,()=>e())),await new Promise(e=>process.stderr.write(``,()=>e())),process.exit(e)}var k=e=>`${(e/1e3).toFixed(1)}s`;async function A(e){try{return(await fetch(e)).ok}catch{return!1}}var j=/* @__PURE__ */ new Map;function M(e){if(process.platform===`win32`){let n=t(`netstat`,[`-ano`],{encoding:`utf8`}).stdout||``,r=new Set(n.split(`
4
- `).filter(e=>e.includes(`LISTENING`)).filter(t=>t.trim().split(/\s+/)[1]?.endsWith(`:${e}`)).map(e=>e.trim().split(/\s+/).pop()).filter(e=>!!e&&e!==`0`));for(let e of r)t(`taskkill`,[`/PID`,e,`/T`,`/F`],{stdio:`ignore`});return r.size>0&&j.set(e,performance.now()),r.size>0}let n=(t(`lsof`,[`-ti`,`tcp:${e}`,`-sTCP:LISTEN`],{encoding:`utf8`}).stdout||``).split(`
5
- `).filter(Boolean);for(let e of n)t(`kill`,[`-9`,e],{stdio:`ignore`});return n.length>0&&j.set(e,performance.now()),n.length>0}function te(e,t){let n=j.get(e);return n!==void 0&&n>=t}function ne(){let e=process.platform===`win32`?t(`powershell`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.ParentProcessId }`],{encoding:`utf8`}):t(`ps`,[`-A`,`-o`,`pid=,ppid=`],{encoding:`utf8`});if(e.status!==0)throw Error(`Listing processes failed (exit ${e.status}): ${e.stderr}`);let n=/* @__PURE__ */ new Map;for(let t of e.stdout.split(/\r?\n/)){let e=t.trim().match(/^(\d+)\s+(\d+)$/);e&&n.set(Number(e[1]),Number(e[2]))}return n}function N(e,t){let n=[],r=[t];for(;r.length>0;){let i=[];for(let[a,o]of e)r.includes(o)&&a!==t&&!n.includes(a)&&(n.push(a),i.push(a));r=i}return n}var re=2**30;function ie(e){return typeof e==`object`&&!!e&&`ProcessId`in e&&typeof e.ProcessId==`number`&&`ParentProcessId`in e&&typeof e.ParentProcessId==`number`&&`WorkingSetSize`in e&&typeof e.WorkingSetSize==`number`}function ae(){let e=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;if(process.platform===`win32`){let r=t(`powershell`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | Select ProcessId,ParentProcessId,WorkingSetSize | ConvertTo-Json -Compress`],{encoding:`utf8`,windowsHide:!0});if(r.status!==0)throw Error(`powershell failed (exit ${r.status}): ${r.error?.message??r.stderr}`);let i=JSON.parse(r.stdout),a=Array.isArray(i)?i:[i];for(let t of a){if(!ie(t))throw Error(`powershell returned a process row of an unknown shape: ${JSON.stringify(t)}`);e.set(t.ProcessId,t.ParentProcessId),n.set(t.ProcessId,t.WorkingSetSize)}return{parentOf:e,bytesOf:n}}let r=t(`ps`,[`-A`,`-o`,`pid=,ppid=,rss=`],{encoding:`utf8`,windowsHide:!0});if(r.status!==0)throw Error(`ps failed (exit ${r.status}): ${r.error?.message??r.stderr}`);for(let t of r.stdout.split(/\r?\n/)){if(t.trim()===``)continue;let r=t.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/);if(!r)throw Error(`ps returned a line of an unknown shape: ${t}`);e.set(Number(r[1]),Number(r[2])),n.set(Number(r[1]),Number(r[3])*1024)}return{parentOf:e,bytesOf:n}}var oe=250,P;function F(e){let t=performance.now();(P===void 0||t-P.atMs>oe)&&(P={atMs:t,table:ae()});let{parentOf:n,bytesOf:r}=P.table;if(!r.has(e))return null;let i=0;for(let t of[e,...N(n,e)])i+=r.get(t)??0;return i/re}function I(e=process.pid){let t=0;for(let n=0;n<3;n+=1){let n=N(ne(),e);if(n.length===0)return t;for(let e of n.reverse())try{process.kill(e,`SIGKILL`),t+=1}catch(e){if(L(e)!==`ESRCH`)throw e}}return t}function L(e){return e instanceof Error&&`code`in e?e.code:void 0}function R(e){try{process.kill(e,`SIGKILL`)}catch(t){let n=L(t);if(n===`ESRCH`||n===`EPERM`&&e<0)return;throw t}}function z(e){I(e),R(e),process.platform!==`win32`&&R(-e)}var se=[`react`,`razor`,`phoneWeb`],ce=/Port \d+ is already in use|address already in use|EADDRINUSE/i;function B({log:e,retriesLeft:t,killed:n}){return!n&&t>0&&ce.test(e)}function V(t){let{which:r,ports:o,origins:l,readyUrls:d={},reactFilter:f=`@webority/react-sandbox`,razorProject:p=`samples/Razor.Sandbox`,phoneWebDir:m=`samples/mobile-sandbox-web`,tag:h,env:g={}}=t,_=e=>{let t=o[e];if(t===void 0)throw Error(`bootSandboxes: no port for "${e}"`);return t},v=e=>{let t=l[e];if(t===void 0)throw Error(`bootSandboxes: no origin for "${e}"`);return t};for(let e of r){if(!se.includes(e))throw Error(`bootSandboxes: unknown sandbox "${e}"`);_(e),v(e)}let y=e=>{switch(e){case`react`:return[`corepack`,[`pnpm`,`--filter`,f,`dev`,`--port`,String(_(`react`)),`--strictPort`]];case`razor`:return[`dotnet`,[`run`,`--project`,p,`--no-build`,`--`,`--urls`,v(`razor`)]];case`phoneWeb`:return[`corepack`,[`pnpm`,`--dir`,m,`exec`,`vite`,`--port`,String(_(`phoneWeb`)),`--strictPort`]]}},b=e=>u(c(),`webority-gate-${h?`${e}-${h}`:e}-sandbox-${process.pid}.log`),x={};for(let e of r)x[e]=b(e);let S=[];D(`\nStarting the sandboxes (${r.join(`, `)})... (output: ${r.map(e=>b(e)).join(`, `)})`);let C=[],w=(t,r,o)=>{let[s,c]=y(t),l=b(t);M(_(t));let u=i(l,`w`),d=e(O(s,c),{stdio:[`ignore`,u,u],shell:!0,env:{...process.env,...g,WEBORITY_GATE_SANDBOX:`1`}}),f=performance.now();return d.on(`exit`,(e,i)=>{B({log:n(l)?a(l,`utf8`):``,retriesLeft:o,killed:d.killed})?(D(`\nThe ${t} sandbox's port ${_(t)} was taken; freeing it and starting the sandbox once more.`),C[r]=w(t,r,o-1)):d.killed||S.push({name:t,port:_(t),code:e,signal:i,log:l,stoppedByGate:te(_(t),f)})}),d};r.forEach((e,t)=>{C[t]=w(e,t,1)});let T=r.map(e=>d[e]??v(e));async function E(){for(let e of T)if(!await A(e))return!1;return!0}return{children:C,logs:x,deaths:()=>[...S],async waitReady({attempts:e=600,intervalMs:t=300}={}){for(let n=0;n<e;n+=1){if(await E())return!0;await new Promise(e=>setTimeout(e,t))}return!1},finish(e){if(e===0)for(let e of Object.values(x))e!==void 0&&s(e,{force:!0});else for(let[e,t]of Object.entries(x)){if(t===void 0||!n(t))continue;let r=a(t,`utf8`).trimEnd().split(`
6
- `),i=r.findIndex(e=>/Exception: |^\s*Error: /.test(e));i!==-1&&i<r.length-25&&D(`\n──── ${e} sandbox log, first error (${t}:${i+1}) ────\n${r.slice(i,i+3).join(`
7
- `)}`),D(`\n──── ${e} sandbox log, last 25 lines (${t}) ────\n${r.slice(-25).join(`
8
- `)}`)}}}}function H({ports:e=[],children:t=[]}={}){for(let e of t)e.kill();for(let t of e)M(t);return w()}function U({name:e,port:t,code:n,signal:r,log:i,stoppedByGate:a}){let o=r?`signal ${r}`:`exit ${n}`,s=r===`SIGKILL`||n===137;return`The ${e} sandbox ended before the run did (${o}): ${s&&a?`the gate itself ended it when it freed port ${t}, while the sandbox was still in use`:s?`the system killed it, usually for lack of memory`:`it stopped on its own`}. This is an infrastructure failure, not a test failure: rerun the gate. Log: ${i}`}var W=process.env.WUI_REACT_ORIGIN||`http://localhost:5173`,le=process.env.WUI_RAZOR_ORIGIN||`http://localhost:5299`,ue=process.env.WUI_PHONE_WEB_ORIGIN||`http://localhost:5174`,de={first:7e3,end:1e4},fe=[7e3,7474,7687,8e3,8008,8080,8081,8443,8888,9e3,9090,9092,9200,9229,9300],G=12;function pe(e,t=2){if(!Number.isInteger(t)||t<1||t>12)throw RangeError(`derivePorts: count must be 1 to 12, got ${t}`);let{first:n,end:r}=de,i=(r-n)/G,a=d(`sha1`).update(e).digest().readUInt16BE(0)%i;for(let e=0;e<i;e++){let r=n+(a+e)%i*G;if(!fe.some(e=>e>=r&&e<r+G))return Array.from({length:t},(e,t)=>r+t)}throw Error(`derivePorts: no free port slot`)}var me=124,he=3,ge=5e3,K=/* @__PURE__ */ new Set,q=!1;function J(e){return e instanceof Error&&`code`in e&&(e.code===`ESRCH`||e.code===`EPERM`)}function Y(e){if(!(Number.isFinite(e.limitMs)&&e.limitMs>0))throw Error(`${e.label}: limitMs must be a positive number of milliseconds, not ${e.limitMs}. Every gate task states its limit.`)}function X(t,n={},r){Y(t);let{command:i,args:a,label:o,limitMs:s}=t;return new Promise(t=>{let c=performance.now(),l=[],u=!1,d=!1,f=!1,p,m,h,g,_,v,y=e(O(i,a),{shell:!0,env:{...process.env,...n},detached:process.platform!==`win32`,windowsHide:!0});y.pid!==void 0&&(K.add(y.pid),q||(q=!0,process.on(`exit`,()=>{if(process.platform!==`win32`)for(let e of K)try{process.kill(-e,`SIGKILL`)}catch(e){if(!J(e))throw e}})));let b=e=>{if(f)return;f=!0,clearTimeout(h),clearTimeout(g),clearTimeout(_),clearInterval(v),y.pid!==void 0&&K.delete(y.pid);let n=Math.round(performance.now()-c),r=Buffer.concat(l).toString(),i=[];m!==void 0&&i.push(`MEMORY SAMPLE FAILED: ${m}`),u&&i.push(`HUNG: ${o} was still running at ${k(s*3)}, 3 times its limit of ${k(s)}; its process tree was ended.`);let a=i.length===0?r:`${r}${r.endsWith(`
2
+ `)){let e=n.trimStart();if(!e.startsWith(`- `))continue;let r=(n.length-e.length)/2,i=e.slice(2).trimEnd();if(i.startsWith(`/`))continue;i.endsWith(`:`)&&(i=i.slice(0,-1));let a=[];for(;i.endsWith(`]`);){let e=i.lastIndexOf(` [`);if(e===-1)break;a.unshift(i.slice(e+2,-1)),i=i.slice(0,e)}let o=i,s=``,c=i.indexOf(` `),l=i.indexOf(`:`);l!==-1&&(c===-1||l<c)?(o=i.slice(0,l),s=m(i.slice(l+1).trim())):c!==-1&&(o=i.slice(0,c),s=m(i.slice(c+1).trim())),t.push({depth:r,role:o,name:s,states:a})}return t}function m(e){return e.length>=2&&e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e}var h=(e,t=[])=>[e,...t].join(` `);async function g(e){await new Promise(e=>process.stdout.write(``,()=>e())),await new Promise(e=>process.stderr.write(``,()=>e())),process.exit(e)}var _=class extends Error{name=`GateCommandError`};function v(e,n,r=[0]){let i=t(e,n,{encoding:`utf8`,windowsHide:!0});if(i.error)throw new _(`${e} failed to start: ${i.error.message}`);if(i.status===null||!r.includes(i.status))throw new _(`${e} ${n.join(` `)} failed (exit ${i.status??i.signal}): ${i.stderr.trim()}`);return i.stdout}function y(e){try{return process.kill(Number(e),0),!0}catch(e){let t=e instanceof Error&&`code`in e?e.code:void 0;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}function b(e){let[n,r]=process.platform===`win32`?[`taskkill`,[`/PID`,e,`/T`,`/F`]]:[`kill`,[`-9`,e]],i=t(n,r,{encoding:`utf8`,windowsHide:!0});if(i.error)throw new _(`${n} failed to start: ${i.error.message}`);if(i.status!==0&&y(e))throw new _(`${n} ${r.join(` `)} failed (exit ${i.status}): ${i.stderr.trim()}`)}var x=e=>`${(e/1e3).toFixed(1)}s`;async function S(e){try{return(await fetch(e)).ok}catch{return!1}}var C=/* @__PURE__ */ new Map;function w(e){if(process.platform===`win32`){let t=v(`netstat`,[`-ano`]),n=new Set(t.split(`
3
+ `).filter(e=>e.includes(`LISTENING`)).filter(t=>t.trim().split(/\s+/)[1]?.endsWith(`:${e}`)).map(e=>e.trim().split(/\s+/).pop()).filter(e=>!!e&&e!==`0`));for(let e of n)b(e);return n.size>0&&C.set(e,performance.now()),n.size>0}let t=v(`lsof`,[`-ti`,`tcp:${e}`,`-sTCP:LISTEN`],[0,1]).split(`
4
+ `).filter(Boolean);for(let e of t)b(e);return t.length>0&&C.set(e,performance.now()),t.length>0}function ee(e,t){let n=C.get(e);return n!==void 0&&n>=t}function T(){let e=process.platform===`win32`?v(`powershell`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.ParentProcessId }`]):v(`ps`,[`-A`,`-o`,`pid=,ppid=`]),t=/* @__PURE__ */ new Map;for(let n of e.split(/\r?\n/)){let e=n.trim().match(/^(\d+)\s+(\d+)$/);e&&t.set(Number(e[1]),Number(e[2]))}return t}function E(e,t){let n=[],r=[t];for(;r.length>0;){let i=[];for(let[a,o]of e)r.includes(o)&&a!==t&&!n.includes(a)&&(n.push(a),i.push(a));r=i}return n}var D=2**30;function O(e){return typeof e==`object`&&!!e&&`ProcessId`in e&&typeof e.ProcessId==`number`&&`ParentProcessId`in e&&typeof e.ParentProcessId==`number`&&`WorkingSetSize`in e&&typeof e.WorkingSetSize==`number`}function k(){let e=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;if(process.platform===`win32`){let r=t(`powershell`,[`-NoProfile`,`-NonInteractive`,`-Command`,`Get-CimInstance Win32_Process | Select ProcessId,ParentProcessId,WorkingSetSize | ConvertTo-Json -Compress`],{encoding:`utf8`,windowsHide:!0});if(r.status!==0)throw new _(`powershell failed (exit ${r.status}): ${r.error?.message??r.stderr}`);let i=JSON.parse(r.stdout),a=Array.isArray(i)?i:[i];for(let t of a){if(!O(t))throw Error(`powershell returned a process row of an unknown shape: ${JSON.stringify(t)}`);e.set(t.ProcessId,t.ParentProcessId),n.set(t.ProcessId,t.WorkingSetSize)}return{parentOf:e,bytesOf:n}}let r=t(`ps`,[`-A`,`-o`,`pid=,ppid=,rss=`],{encoding:`utf8`,windowsHide:!0});if(r.status!==0)throw new _(`ps failed (exit ${r.status}): ${r.error?.message??r.stderr}`);for(let t of r.stdout.split(/\r?\n/)){if(t.trim()===``)continue;let r=t.trim().match(/^(\d+)\s+(\d+)\s+(\d+)$/);if(!r)throw Error(`ps returned a line of an unknown shape: ${t}`);e.set(Number(r[1]),Number(r[2])),n.set(Number(r[1]),Number(r[3])*1024)}return{parentOf:e,bytesOf:n}}var te=250,A;function j(e){let t=performance.now();(A===void 0||t-A.atMs>te)&&(A={atMs:t,table:k()});let{parentOf:n,bytesOf:r}=A.table;if(!r.has(e))return null;let i=0;for(let t of[e,...E(n,e)])i+=r.get(t)??0;return i/D}function M(e=process.pid){let t=0;for(let n=0;n<3;n+=1){let n=E(T(),e);if(n.length===0)return t;for(let e of n.reverse())try{process.kill(e,`SIGKILL`),t+=1}catch(e){if(N(e)!==`ESRCH`)throw e}}return t}function N(e){return e instanceof Error&&`code`in e?e.code:void 0}function P(e){try{process.kill(e,`SIGKILL`)}catch(t){let n=N(t);if(n===`ESRCH`||n===`EPERM`&&e<0)return;throw t}}function F(e){M(e),P(e),process.platform!==`win32`&&P(-e)}var I=`webority-ui-gate-chrome`,L=RegExp(`${I}[=-](\\d+)`);function R(){let e=Number(process.env.WEBORITY_UI_GATE_PID);return Number.isFinite(e)&&e>0?e:process.pid}function ne(){return r(l(c(),`${I}-${R()}-`))}function re(){return[`--${I}=${R()}`]}function z(e){try{return process.kill(e,0),!0}catch{return!1}}function B(){return process.platform===`win32`?v(`powershell`,[`-NoProfile`,`-Command`,`Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.CommandLine }`]).split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(` `);return t<0?null:{pid:e.slice(0,t).trim(),commandLine:e.slice(t+1)}}).filter(e=>e!==null):v(`ps`,[`-A`,`-o`,`pid=,args=`]).split(`
5
+ `).map(e=>e.trim()).filter(e=>/(?:^|[/\s])(chrome|chromium)(?:\s|$|\.exe)/i.test(e)).map(e=>{let t=e.match(/^(\d+)\s+(.*)$/);if(!t)return null;let[,n,r]=t;return n===void 0||r===void 0?null:{pid:n,commandLine:r}}).filter(e=>e!==null)}function ie(){let e=[];for(let{pid:t,commandLine:n}of B()){if(!n?.includes(`webority-ui-gate-chrome`))continue;let r=n.match(L);if(!r)continue;let i=Number(r[1]);!Number.isFinite(i)||i<=0||i!==process.pid&&(z(i)||e.push(t))}for(let t of e)b(t);return ae(),e.length}function V(e=process.pid){let t=[];for(let{pid:n,commandLine:r}of B()){let i=r?.match(L);i&&Number(i[1])===e&&t.push(n)}for(let e of t)b(e);return t.length}function ae(){let e=RegExp(`^${I}-(\\d+)-`),t;try{t=o(c())}catch{return}for(let n of t){let t=n.match(e);if(!t)continue;let r=Number(t[1]);if(!(r===process.pid||z(r)))try{s(l(c(),n),{recursive:!0,force:!0})}catch(e){if((e instanceof Error&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}}var oe=`--blink-settings=preferredColorScheme=1`;function H(e){process.stdout.write(`${e}\n`)}var se=[`react`,`razor`,`phoneWeb`],ce=/Port \d+ is already in use|address already in use|EADDRINUSE/i;function U({log:e,retriesLeft:t,killed:n}){return!n&&t>0&&ce.test(e)}function W(t){let{which:r,ports:o,origins:l,readyUrls:d={},reactFilter:f=`@webority/react-sandbox`,razorProject:p=`samples/Razor.Sandbox`,phoneWebDir:m=`samples/mobile-sandbox-web`,tag:g,env:_={}}=t,v=e=>{let t=o[e];if(t===void 0)throw Error(`bootSandboxes: no port for "${e}"`);return t},y=e=>{let t=l[e];if(t===void 0)throw Error(`bootSandboxes: no origin for "${e}"`);return t};for(let e of r){if(!se.includes(e))throw Error(`bootSandboxes: unknown sandbox "${e}"`);v(e),y(e)}let b=e=>{switch(e){case`react`:return[`corepack`,[`pnpm`,`--filter`,f,`dev`,`--port`,String(v(`react`)),`--strictPort`]];case`razor`:return[`dotnet`,[`run`,`--project`,p,`--no-build`,`--`,`--urls`,y(`razor`)]];case`phoneWeb`:return[`corepack`,[`pnpm`,`--dir`,m,`exec`,`vite`,`--port`,String(v(`phoneWeb`)),`--strictPort`]]}},x=e=>u(c(),`webority-gate-${g?`${e}-${g}`:e}-sandbox-${process.pid}.log`),C={};for(let e of r)C[e]=x(e);let T=[];H(`\nStarting the sandboxes (${r.join(`, `)})... (output: ${r.map(e=>x(e)).join(`, `)})`);let E=[],D=(t,r,o)=>{let[s,c]=b(t),l=x(t);w(v(t));let u=i(l,`w`),d=e(h(s,c),{stdio:[`ignore`,u,u],shell:!0,windowsHide:!0,env:{...process.env,..._,WEBORITY_GATE_SANDBOX:`1`}}),f=performance.now();return d.on(`exit`,(e,i)=>{U({log:n(l)?a(l,`utf8`):``,retriesLeft:o,killed:d.killed})?(H(`\nThe ${t} sandbox's port ${v(t)} was taken; freeing it and starting the sandbox once more.`),E[r]=D(t,r,o-1)):d.killed||T.push({name:t,port:v(t),code:e,signal:i,log:l,stoppedByGate:ee(v(t),f)})}),d};r.forEach((e,t)=>{E[t]=D(e,t,1)});let O=r.map(e=>d[e]??y(e));async function k(){for(let e of O)if(!await S(e))return!1;return!0}return{children:E,logs:C,deaths:()=>[...T],async waitReady({attempts:e=600,intervalMs:t=300}={}){for(let n=0;n<e;n+=1){if(await k())return!0;await new Promise(e=>setTimeout(e,t))}return!1},finish(e){if(e===0)for(let e of Object.values(C))e!==void 0&&s(e,{force:!0});else for(let[e,t]of Object.entries(C)){if(t===void 0||!n(t))continue;let r=a(t,`utf8`).trimEnd().split(`
6
+ `),i=r.findIndex(e=>/Exception: |^\s*Error: /.test(e));i!==-1&&i<r.length-25&&H(`\n──── ${e} sandbox log, first error (${t}:${i+1}) ────\n${r.slice(i,i+3).join(`
7
+ `)}`),H(`\n──── ${e} sandbox log, last 25 lines (${t}) ────\n${r.slice(-25).join(`
8
+ `)}`)}}}}function le({ports:e=[],children:t=[]}={}){for(let e of t)e.kill();for(let t of e)w(t);return V()}function ue({name:e,port:t,code:n,signal:r,log:i,stoppedByGate:a}){let o=r?`signal ${r}`:`exit ${n}`,s=r===`SIGKILL`||n===137;return`The ${e} sandbox ended before the run did (${o}): ${s&&a?`the gate itself ended it when it freed port ${t}, while the sandbox was still in use`:s?`the system killed it, usually for lack of memory`:`it stopped on its own`}. This is an infrastructure failure, not a test failure: rerun the gate. Log: ${i}`}var de=process.env.WUI_REACT_ORIGIN||`http://localhost:5173`,fe=process.env.WUI_RAZOR_ORIGIN||`http://localhost:5299`,pe=process.env.WUI_PHONE_WEB_ORIGIN||`http://localhost:5174`,me={first:7e3,end:1e4},he=[7e3,7474,7687,8e3,8008,8080,8081,8443,8888,9e3,9090,9092,9200,9229,9300],G=12;function ge(e,t=2){if(!Number.isInteger(t)||t<1||t>12)throw RangeError(`derivePorts: count must be 1 to 12, got ${t}`);let{first:n,end:r}=me,i=(r-n)/G,a=d(`sha1`).update(e).digest().readUInt16BE(0)%i;for(let e=0;e<i;e++){let r=n+(a+e)%i*G;if(!he.some(e=>e>=r&&e<r+G))return Array.from({length:t},(e,t)=>r+t)}throw Error(`derivePorts: no free port slot`)}var _e=124,ve=3,ye=5e3,K=/* @__PURE__ */ new Set,q=!1;function be(e){return e instanceof Error&&`code`in e&&(e.code===`ESRCH`||e.code===`EPERM`)}function J(e){if(!(Number.isFinite(e.limitMs)&&e.limitMs>0))throw Error(`${e.label}: limitMs must be a positive number of milliseconds, not ${e.limitMs}. Every gate task states its limit.`)}function Y(t,n={},r){J(t);let{command:i,args:a,label:o,limitMs:s}=t;return new Promise(t=>{let c=performance.now(),l=[],u=!1,d=!1,f=!1,p,m,g,_,v,y,b=e(h(i,a),{shell:!0,env:{...process.env,...n},detached:process.platform!==`win32`,windowsHide:!0});b.pid!==void 0&&(K.add(b.pid),q||(q=!0,process.on(`exit`,()=>{if(process.platform!==`win32`)for(let e of K)try{process.kill(-e,`SIGKILL`)}catch(e){if(!be(e))throw e}})));let S=e=>{if(f)return;f=!0,clearTimeout(g),clearTimeout(_),clearTimeout(v),clearInterval(y),b.pid!==void 0&&K.delete(b.pid);let n=Math.round(performance.now()-c),r=Buffer.concat(l).toString(),i=[];m!==void 0&&i.push(`MEMORY SAMPLE FAILED: ${m}`),u&&i.push(`HUNG: ${o} was still running at ${x(s*3)}, 3 times its limit of ${x(s)}; its process tree was ended.`);let a=i.length===0?r:`${r}${r.endsWith(`
9
9
  `)?``:`
10
10
  `}${i.join(`
11
- `)}`,b=p===void 0?{}:{peakMemoryGiB:p};t(u?{label:o,code:124,hung:!0,output:a,ms:n,...b}:{label:o,code:e,output:a,ms:n,...d?{slow:!0}:{},...b})};y.stdout.on(`data`,e=>l.push(e)),y.stderr.on(`data`,e=>l.push(e)),y.on(`close`,e=>b(e??1));let x=y.pid;r!==void 0&&x!==void 0&&(v=setInterval(()=>{try{let e=r.sample(x);e!==null&&(p===void 0||e>p)&&(p=e)}catch(e){m=e instanceof Error?e.message:String(e),clearInterval(v)}},r.everyMs)),h=setTimeout(()=>{d=!0,D(`SLOW: ${o} passed its limit of ${k(s)}; it keeps running and is ended as hung at ${k(s*3)}.`)},s),g=setTimeout(()=>{u=!0,y.pid!==void 0&&z(y.pid),_=setTimeout(()=>{y.stdout.destroy(),y.stderr.destroy(),b(124)},ge)},s*3)})}var _e=/\[vitest-pool\]: Failed to start \w+ worker|\[vitest-pool-runner\]: Timeout waiting for worker to respond/,ve=/^\s*(Test Files|Tests)\s.*\b\d+ failed/m;async function ye(e,t,n){let r=await X(e,t,n);if(r.hung||r.code===0||!e.retryArgs||!_e.test(r.output)||ve.test(r.output))return r;D(`\n──── RETRY ${e.label}: the vitest worker pool did not start in time (machine load, ${k(r.ms)}); running it once more with half the workers ────`);let i=await X({...e,args:e.retryArgs},t,n),a=r.slow||i.slow,o=[r.peakMemoryGiB,i.peakMemoryGiB].filter(e=>e!==void 0);return{...i,ms:r.ms+i.ms,output:`${r.output}\n──── retry ────\n${i.output}`,...a&&!i.hung?{slow:!0}:{},...o.length>0?{peakMemoryGiB:Math.max(...o)}:{}}}async function be(e,t={}){if(e.length===0)return[];let{env:n={},heartbeatMs:r=6e4,maxParallel:i,admit:a,sampleMemory:o=F,memorySampleMs:s=process.platform===`win32`?5e3:1e3}=t;if(i!==void 0&&!(Number.isInteger(i)&&i>=1))throw Error(`runTasks: maxParallel must be a whole number of at least 1, not ${i}.`);if(!(Number.isFinite(s)&&s>0))throw Error(`runTasks: memorySampleMs must be a positive number of milliseconds, not ${s}.`);let c={sample:o,everyMs:s};for(let t of e)Y(t);let l=i??1/0,u=[],d=()=>l>0?(--l,Promise.resolve()):new Promise(e=>u.push(e)),f=()=>{let e=u.shift();e===void 0?l+=1:e()};D(`\n──── running in parallel${i!==void 0&&i<e.length?`, ${i} at a time`:``}: ${e.map(e=>e.label).join(` · `)} ────`);let p=performance.now(),m=/* @__PURE__ */ new Set,h=0,g=setInterval(()=>{let t=e.map(e=>e.label).filter(e=>!m.has(e));D(`still running after ${Math.round((performance.now()-p)/1e3)} s: ${t.join(`, `)}`)},r),_=/* @__PURE__ */ new Map,v;try{v=await Promise.all(e.map(e=>{let t=(async()=>{await null,e.after&&_.has(e.after)&&await _.get(e.after),await d(),await a?.(e,()=>h),D(`\n──── start ${e.label} (limit ${k(e.limitMs)}) ────`);let t;h+=1;try{t=await ye(e,n,c)}finally{--h,f()}m.add(t.label);let r=t.peakMemoryGiB===void 0?``:`, peak ${t.peakMemoryGiB.toFixed(1)} GiB`;return D(`\n──── ${t.hung?`${t.label} → HUNG (${k(t.ms)}${r}, limit ${k(e.limitMs)})`:`${t.label} → ${t.code===0?`ok`:`FAIL`}${t.slow?`, SLOW`:``} (${k(t.ms)}${r}${t.slow?`, limit ${k(e.limitMs)}`:``})`} ────`),process.stdout.write(t.output.endsWith(`
12
- `)?t.output:`${t.output}\n`),{label:t.label,code:t.code,ms:t.ms,...t.hung?{hung:!0}:{},...t.slow?{slow:!0}:{},...t.peakMemoryGiB===void 0?{}:{peakMemoryGiB:t.peakMemoryGiB}}})();return _.set(e.label,t),t}))}finally{clearInterval(g)}return D(`──── group wall time: ${k(Math.round(performance.now()-p))} ────`),v}function Z(e,n){let r=t(`git`,n,{cwd:e,encoding:`utf8`});return r.status===0?r.stdout.split(`
13
- `).filter(Boolean):null}function xe(e,t=process.env.GATE_BASE||null){let n=t?Z(e,[`diff`,`--name-only`,`--no-renames`,t,`HEAD`]):Z(e,[`diff`,`--name-only`,`--no-renames`,`origin/development...HEAD`]);if(n===null)return null;let r=Z(e,[`diff`,`--name-only`,`--no-renames`,`HEAD`])??[],i=Z(e,[`ls-files`,`--others`,`--exclude-standard`])??[];return[.../* @__PURE__ */ new Set([...n,...r,...i])].sort()}function Q(e,t){return t||Z(e,[`merge-base`,`origin/development`,`HEAD`])?.[0]||null}function $(e,t){let n=Z(e,[`show`,`${t}:version.json`]);if(n===null)return null;try{let e=JSON.parse(n.join(`
14
- `)),t=typeof e==`object`&&e&&`Version`in e?e.Version:void 0;return typeof t==`string`?t:null}catch{return null}}function Se(e,t,n){let r=Q(e,n);if(!r)return!1;let i=$(e,r),a=$(e,`HEAD`);if(i===null||a===null||i===a)return!1;let o=Z(e,[`status`,`--porcelain`,`--`,t]);if(o===null||o.length>0)return!1;let s=Z(e,[`diff`,`-U0`,`--no-renames`,r,`HEAD`,`--`,t]);if(s===null)return!1;let c=[];for(let e of s){let t=c.at(-1);e.startsWith(`@@`)?c.push({removed:[],added:[]}):t&&e.startsWith(`-`)?t.removed.push(e.slice(1)):t&&e.startsWith(`+`)&&t.added.push(e.slice(1))}return c.length!==0&&c.every(({removed:e,added:t})=>e.length===t.length&&e.every((e,n)=>e.split(i).join(a)===t[n]))}export{h as GATE_CHROME_MARKER,me as HUNG_EXIT_CODE,he as HUNG_LIMIT_MULTIPLIER,E as LIGHT_SCHEME_ARG,ue as PHONE_WEB_ORIGIN,le as RAZOR_ORIGIN,W as REACT_ORIGIN,f as accessibilityTree,Q as baseCommitOf,V as bootSandboxes,xe as changedFiles,pe as derivePorts,N as descendantsOf,U as describeSandboxDeath,I as endDescendants,z as endProcessTree,ee as exitAfterOutput,_ as gateOwnerPid,Z as gitLines,M as killPort,p as parseAriaSnapshot,y as playwrightGateArgs,v as profileDir,A as reachable,C as reapOrphanGateChrome,w as reapOwnGateChrome,X as runBuffered,be as runTasks,k as secs,O as shellLine,H as stopAll,F as treeMemoryGiB,Se as versionStampOnly};
11
+ `)}`,h=p===void 0?{}:{peakMemoryGiB:p};t(u?{label:o,code:124,hung:!0,output:a,ms:n,...h}:{label:o,code:e,output:a,ms:n,...d?{slow:!0}:{},...h})};b.stdout.on(`data`,e=>l.push(e)),b.stderr.on(`data`,e=>l.push(e)),b.on(`close`,e=>S(e??1));let C=b.pid;r!==void 0&&C!==void 0&&(y=setInterval(()=>{try{let e=r.sample(C);e!==null&&(p===void 0||e>p)&&(p=e)}catch(e){m=e instanceof Error?e.message:String(e),clearInterval(y)}},r.everyMs)),g=setTimeout(()=>{d=!0,H(`SLOW: ${o} passed its limit of ${x(s)}; it keeps running and is ended as hung at ${x(s*3)}.`)},s),_=setTimeout(()=>{u=!0,b.pid!==void 0&&F(b.pid),v=setTimeout(()=>{b.stdout.destroy(),b.stderr.destroy(),S(124)},ye)},s*3)})}var xe=/\[vitest-pool\]: Failed to start \w+ worker|\[vitest-pool-runner\]: Timeout waiting for worker to respond/,X=/^\s*(Test Files|Tests)\s.*\b\d+ failed/m;async function Se(e,t,n){let r=await Y(e,t,n);if(r.hung||r.code===0||!e.retryArgs||!xe.test(r.output)||X.test(r.output))return r;H(`\n──── RETRY ${e.label}: the vitest worker pool did not start in time (machine load, ${x(r.ms)}); running it once more with half the workers ────`);let i=await Y({...e,args:e.retryArgs},t,n),a=r.slow||i.slow,o=[r.peakMemoryGiB,i.peakMemoryGiB].filter(e=>e!==void 0);return{...i,ms:r.ms+i.ms,output:`${r.output}\n──── retry ────\n${i.output}`,...a&&!i.hung?{slow:!0}:{},...o.length>0?{peakMemoryGiB:Math.max(...o)}:{}}}async function Ce(e,t={}){if(e.length===0)return[];let{env:n={},heartbeatMs:r=6e4,maxParallel:i,admit:a,sampleMemory:o=j,memorySampleMs:s=process.platform===`win32`?5e3:1e3}=t;if(i!==void 0&&!(Number.isInteger(i)&&i>=1))throw Error(`runTasks: maxParallel must be a whole number of at least 1, not ${i}.`);if(!(Number.isFinite(s)&&s>0))throw Error(`runTasks: memorySampleMs must be a positive number of milliseconds, not ${s}.`);let c={sample:o,everyMs:s};for(let t of e)J(t);let l=i??1/0,u=[],d=()=>l>0?(--l,Promise.resolve()):new Promise(e=>u.push(e)),f=()=>{let e=u.shift();e===void 0?l+=1:e()};H(`\n──── running in parallel${i!==void 0&&i<e.length?`, ${i} at a time`:``}: ${e.map(e=>e.label).join(` · `)} ────`);let p=performance.now(),m=/* @__PURE__ */ new Set,h=0,g=setInterval(()=>{let t=e.map(e=>e.label).filter(e=>!m.has(e));H(`still running after ${Math.round((performance.now()-p)/1e3)} s: ${t.join(`, `)}`)},r),_=/* @__PURE__ */ new Map,v;try{v=await Promise.all(e.map(e=>{let t=(async()=>{await null,e.after&&_.has(e.after)&&await _.get(e.after),await d(),await a?.(e,()=>h),H(`\n──── start ${e.label} (limit ${x(e.limitMs)}) ────`);let t;h+=1;try{t=await Se(e,n,c)}finally{--h,f()}m.add(t.label);let r=t.peakMemoryGiB===void 0?``:`, peak ${t.peakMemoryGiB.toFixed(1)} GiB`;return H(`\n──── ${t.hung?`${t.label} → HUNG (${x(t.ms)}${r}, limit ${x(e.limitMs)})`:`${t.label} → ${t.code===0?`ok`:`FAIL`}${t.slow?`, SLOW`:``} (${x(t.ms)}${r}${t.slow?`, limit ${x(e.limitMs)}`:``})`} ────`),process.stdout.write(t.output.endsWith(`
12
+ `)?t.output:`${t.output}\n`),{label:t.label,code:t.code,ms:t.ms,...t.hung?{hung:!0}:{},...t.slow?{slow:!0}:{},...t.peakMemoryGiB===void 0?{}:{peakMemoryGiB:t.peakMemoryGiB}}})();return _.set(e.label,t),t}))}finally{clearInterval(g)}return H(`──── group wall time: ${x(Math.round(performance.now()-p))} ────`),v}function Z(e,n){let r=t(`git`,n,{cwd:e,encoding:`utf8`,windowsHide:!0});if(r.error)throw new _(`git failed to start: ${r.error.message}`);return r.status===0?r.stdout.split(`
13
+ `).filter(Boolean):null}function we(e,t=process.env.GATE_BASE||null){let n=t?Z(e,[`diff`,`--name-only`,`--no-renames`,t,`HEAD`]):Z(e,[`diff`,`--name-only`,`--no-renames`,`origin/development...HEAD`]);if(n===null)return null;let r=Z(e,[`diff`,`--name-only`,`--no-renames`,`HEAD`])??[],i=Z(e,[`ls-files`,`--others`,`--exclude-standard`])??[];return[.../* @__PURE__ */ new Set([...n,...r,...i])].sort()}function Q(e,t){return t||Z(e,[`merge-base`,`origin/development`,`HEAD`])?.[0]||null}function $(e,t){let n=Z(e,[`show`,`${t}:version.json`]);if(n===null)return null;try{let e=JSON.parse(n.join(`
14
+ `)),t=typeof e==`object`&&e&&`Version`in e?e.Version:void 0;return typeof t==`string`?t:null}catch{return null}}function Te(e,t,n){let r=Q(e,n);if(!r)return!1;let i=$(e,r),a=$(e,`HEAD`);if(i===null||a===null||i===a)return!1;let o=Z(e,[`status`,`--porcelain`,`--`,t]);if(o===null||o.length>0)return!1;let s=Z(e,[`diff`,`-U0`,`--no-renames`,r,`HEAD`,`--`,t]);if(s===null)return!1;let c=[];for(let e of s){let t=c.at(-1);e.startsWith(`@@`)?c.push({removed:[],added:[]}):t&&e.startsWith(`-`)?t.removed.push(e.slice(1)):t&&e.startsWith(`+`)&&t.added.push(e.slice(1))}return c.length!==0&&c.every(({removed:e,added:t})=>e.length===t.length&&e.every((e,n)=>e.split(i).join(a)===t[n]))}export{I as GATE_CHROME_MARKER,_e as HUNG_EXIT_CODE,ve as HUNG_LIMIT_MULTIPLIER,oe as LIGHT_SCHEME_ARG,pe as PHONE_WEB_ORIGIN,fe as RAZOR_ORIGIN,de as REACT_ORIGIN,f as accessibilityTree,Q as baseCommitOf,W as bootSandboxes,we as changedFiles,ge as derivePorts,E as descendantsOf,ue as describeSandboxDeath,M as endDescendants,F as endProcessTree,g as exitAfterOutput,R as gateOwnerPid,Z as gitLines,w as killPort,p as parseAriaSnapshot,re as playwrightGateArgs,ne as profileDir,S as reachable,ie as reapOrphanGateChrome,V as reapOwnGateChrome,Y as runBuffered,Ce as runTasks,x as secs,h as shellLine,le as stopAll,j as treeMemoryGiB,Te as versionStampOnly};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/sandbox-gate",
3
- "version": "0.170.0",
3
+ "version": "0.171.0",
4
4
  "description": "The gate runner Webority repos share: sandbox boot on ports derived from the checkout, a buffered parallel task runner, headless Chrome ownership and orphan reaping, accessibility trees from Playwright, and changed-file helpers for a quick scope. Node only.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/node": "^24.0.0",
28
- "@webority/biome-config": "0.170.0",
28
+ "@webority/biome-config": "0.171.0",
29
29
  "typescript": "^7.0.2",
30
30
  "vite": "^8.3.6"
31
31
  },