@opencoredev/sandbox-sdk1.2.016.9 kB
import{w,m,N}from"./chunk-1mzegrft.js";import{n}from"./chunk-2ts3evzh.js";import{G}from"./chunk-b761qx9j.js";import{t,r,e,D,s}from"./chunk-dat243tf.js";import{posix as T,resolve as I,relative as we}from"node:path";import{tmpdir as Q}from"node:os";import{execFile as ge}from"node:child_process";import{promisify as he}from"node:util";import{promises as P}from"node:fs";function ye(d,a,x){let b=(k)=>k?k.replace(/\n$/,"").split(`
`):[],C=b(a),c=b(x),A=(k,R)=>R&&!k?.endsWith(`
`)?`\\ No newline at end of file
`:"";return[`--- ${a===void 0?"/dev/null":`a/${d}`}
`,`+++ ${x===void 0?"/dev/null":`b/${d}`}
`,`@@ -${C.length?1:0},${C.length} +${c.length?1:0},${c.length} @@
`,...C.map((k)=>`-${k}
`),A(a,C.length),...c.map((k)=>`+${k}
`),A(x,c.length)].join("")}async function ee(d,a){try{await d.remove(a)}catch(x){if(D(x))return;if(x instanceof e&&x.code==="provider"&&!await d.exists(a))return;throw x}}function Z(d){return t(d)||d instanceof Uint8Array}var re=(d)=>d.split(/(\*\*\/|\*\*|\*|\?)/);function te(d,a){let x=re(a).map((b)=>b==="**/"?"(?:.*/)?":b==="**"?".*":b==="*"?"[^/]*":b==="?"?".":b.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")).join("");return new RegExp(`^${x}$`).test(d)||!a.includes("/")&&new RegExp(`^${x}$`).test(T.basename(d))}function be(d){let x=(b)=>Array.from({length:b.length},(C,c)=>`\\u${b.charCodeAt(c).toString(16).padStart(4,"0")}`).join("");return re(d).map((b)=>b==="**/"?"(?:[^\\n\\r\\u2028\\u2029]*/)?":b==="**"?"[^\\n\\r\\u2028\\u2029]*":b==="*"?"[^/]*":b==="?"?"[^\\n\\r\\u2028\\u2029]":x(b)).join("")}var ke=`import json,os,stat,sys
try:
a=json.loads(os.environ.get("SANDBOX_SDK_INPUT") or sys.stdin.buffer.read());p=os.path.realpath(a["path"]);f=a["find"].encode();r=a["replace"].encode();w=a["write"]
s=os.stat(p)
if not stat.S_ISREG(s.st_mode) or (w!="in-place" and s.st_nlink>1):sys.exit(70)
with open(p,"rb") as h:d=h.read()
except Exception:sys.exit(70)
m=[];n=1;q=0;i=d.find(f)
while i>=0:n+=d.count(b"\\n",q,i);q=i;m.append(n);i=d.find(f,i+1)
if len(m)!=1:print(" ".join(map(str,m)));sys.exit(3)
i=d.find(f);o=d[:i]+r+d[i+len(f):]
def put(fd,b):
os.lseek(fd,0,0);v=memoryview(b)
while v:v=v[os.write(fd,v):]
os.ftruncate(fd,len(b))
if w=="in-place":
try:fd=os.open(p,os.O_WRONLY)
except Exception:sys.exit(70)
try:put(fd,o)
except Exception:
try:put(fd,d)
except Exception:sys.exit(71)
sys.exit(70)
sys.exit(0)
t="%s/.%s.%s.sdk-edit"%(os.path.dirname(p),os.path.basename(p),os.urandom(6).hex())
try:fd=os.open(t,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
except Exception:sys.exit(70)
try:
with os.fdopen(fd,"wb") as h:h.write(o)
if (s.st_uid,s.st_gid)!=(os.geteuid(),os.getegid()):os.chown(t,s.st_uid,s.st_gid)
os.chmod(t,stat.S_IMODE(s.st_mode));os.rename(t,p)
except Exception:
os.unlink(t);sys.exit(70)`,$e=`import base64,json,os,re,stat,sys
def u(s):
if all(c<="\\uffff" for c in s):return s
b=s.encode("utf-16-le","surrogatepass");return "".join(chr(int.from_bytes(b[i:i+2],"little")) for i in range(0,len(b),2))
files=[]
def walk(d,rel):
names=os.listdir(d)
for b in sorted(names) if order=="name" else names:
p=os.path.join(d,b);s=os.lstat(p);name=b.decode("utf-8","replace");r=rel+name
if stat.S_ISREG(s.st_mode) and (g is None or g.fullmatch(u(r)) or (base and g.fullmatch(u(name)))):files.append((p,os.path.join(root,r)))
elif stat.S_ISDIR(s.st_mode):walk(p,r+"/")
try:
a=json.loads(os.environ.get("SANDBOX_SDK_INPUT") or sys.stdin.buffer.read())
root=a["root"];q=a["query"].encode();g=re.compile(a["pattern"]) if a["pattern"] else None;base=a["base"]is True;mx=int(a["max"]);order=a["order"]
walk(os.fsencode(root),"");n=0
for p,shown in files:
with open(p,"rb") as h:lines=h.read().split(b"\\n")
for i,line in enumerate(lines):
if q in line:
print(json.dumps([shown,i+1,base64.b64encode(line).decode()]));n+=1
if n>=mx:sys.exit(0)
except Exception:sys.exit(70)`,ne=(d)=>!/\p{Cs}|[\uFEFF\uFFFD]/u.test(d),X=(d)=>!/\p{Cs}/u.test(d),Se=(d)=>`python3 -I -S -c ${n(d)}`,_e=new Set(["auth","invalid_argument","unsupported","quota","not_found"]),Ce=(d)=>G(d)||d instanceof e&&_e.has(d.code),ie=(d,a)=>new e(`Edit failed at ${d}. ${a.length?`Matches on lines ${a.join(", ")}`:"Text not found"}. Supply a unique exact match.`,{code:a.length?"edit_not_unique":"edit_not_found"});function Pe(d){return Array.isArray(d)&&d.length===3&&t(d[0])&&Number.isSafeInteger(d[1])&&t(d[2])}var se=new WeakMap;function xe(d,a,x){let b=se.get(d);return b?b(a,x):d.read(a,{as:"bytes"})}function fe(d,a,x,b=()=>{},C=async()=>{}){let c=d.files,A=new Set,k=he(ge);async function R(i){if((await d.exec(a,{command:i,cwd:"/workspace",env:w,timeoutMs:120000,onChunk(){}})).exitCode!==0)throw new e("File transfer failed. The remote archive command failed. Ensure tar is installed and paths are accessible.",{code:"provider"})}let q=d.name!=="memory";async function z(i,o,l){if(!q)return{exitCode:70,stdout:""};let u="",f=JSON.stringify(o),p=Buffer.byteLength(f)<=32768,h=await c.guestInput?.(a)??"stdin";if(h==="none"||h==="env"&&!p)return{exitCode:70,stdout:""};let g;try{g=await d.exec(a,{command:Se(i),cwd:"/",env:{...w,SANDBOX_SDK_INPUT:p?f:""},stdin:p?void 0:f,timeoutMs:120000,onChunk(y){if(y.stream==="stdout")u+=y.text}})}catch(y){if(!l||Ce(y))throw y;throw new e("File edit outcome unknown. The guest command may have run before the call failed. Read the file to check its state before retrying.",{code:"outcome_unknown",provider:d.name,sandboxId:a,cause:x.error(y,d.name,a)})}if(g.timedOut||g.exitCode===null||g.exitCode>=128){if(!l)return{exitCode:70,stdout:""};throw new e("File edit outcome unknown. The guest command was stopped before it reported. Read the file to check its state before retrying.",{code:"outcome_unknown"})}if(g.exitCode===126||g.exitCode===127)q=!1;return{exitCode:g.exitCode,stdout:u}}let E=async(i)=>{try{return b(),await C().finally(b),await i()}catch(o){throw x.error(o,d.name,a)}};async function W(i=".",o={}){let l=m(i),u=[];async function f(p){for(let h of await c.list(a,p)){if(!o.glob||te(T.relative(l,h.path),o.glob))u.push(h);if(o.recursive&&h.type==="directory")await f(h.path)}}return await f(l),u}async function L(i,o){let l=await E(()=>c.read(a,m(i)));return o?.as==="bytes"?l:new TextDecoder().decode(l)}async function j(i,o,l){let u=t(i),f=u?[[i,Z(o)?o:""]]:Object.entries(i),p=(u?l:Z(o)?void 0:o)??{},{mode:h}=p,g=new Set;await E(async()=>{if(h!==void 0&&(!Number.isSafeInteger(h)||h<0||h>4095))s("mode must be an integer from 0 to 0o7777, such as 0o600");let y=[];for(let[O,F]of f){let _=m(O),v=T.dirname(_);if(!c.writeCreatesParents&&!g.has(v))await c.mkdir(a,v),g.add(v);await c.write(a,_,t(F)?new TextEncoder().encode(F):F,p),y.push(_)}if(h===void 0||c.writeSupportsMode||!y.length)return;let S=await d.exec(a,{command:`chmod ${h.toString(8)} ${y.map(n).join(" ")}`,cwd:"/workspace",env:w,timeoutMs:30000,onChunk(){}});if(S.timedOut||S.exitCode!==0)throw new e(`File mode not applied. chmod ${S.timedOut?"timed out":`exited with ${S.exitCode}`}; the files were written with default permissions. Check that the paths are writable and retry.`,{code:"provider"})})}let U="/tmp/.sandbox-sdk/changes.git";async function M(i,o){let l="";if((await d.exec(a,{command:`git --git-dir=${n(U)} --work-tree=/workspace ${i}`,cwd:"/workspace",env:{...w,GIT_INDEX_FILE:`${U}/sdk.index`},stdin:o,timeoutMs:120000,onChunk(f){if(f.stream==="stdout")l+=f.text}})).exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return l}async function J(i){let o=["-name .git",...(c.internal??[]).map((p)=>`-path ${n(`./${T.relative("/workspace",m(p))}`)}`)].join(" -o "),l=`command -v git >/dev/null 2>&1 || exit 69
command -v find >/dev/null 2>&1 || exit 78
g=${n(U)}
# A fresh index per call: a killed attempt leaves no index.lock to block later checkpoints.
export GIT_INDEX_FILE="$g/tree.$$.index"; paths="$g/tree.$$.paths"; trap 'rm -f "$GIT_INDEX_FILE" "$GIT_INDEX_FILE.lock" "$paths"' EXIT
[ -d "$g" ] || git init -q --bare "$g" >/dev/null || exit 69
cd /workspace && find . \\( ${o} \\) -prune -o ! -type d -print0 > "$paths" || exit 1
git --git-dir="$g" --work-tree=/workspace read-tree --empty || exit 1
git --git-dir="$g" --work-tree=/workspace update-index --add --remove -z --stdin < "$paths" || exit 1
tree=$(git --git-dir="$g" --work-tree=/workspace write-tree) || exit 1
${i?`mkdir -p ${n(T.dirname(i))} && printf '%s' "$tree" > ${n(i)} || exit 1
`:""}printf '%s\\n' "$tree"`,u="",f=await d.exec(a,{command:l,cwd:"/workspace",env:w,timeoutMs:120000,onChunk(p){if(p.stream==="stdout")u+=p.text}});if(f.exitCode===78){let p=await ce();if(i)await j(i,p);return p}if(f.exitCode===69)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"});if(f.exitCode!==0)throw new e("File checkpoint failed. Git could not update the hidden index. Ensure git is installed and /workspace is readable.",{code:"provider"});return u.trim()}async function ce(){if(!await K(U)){if((await d.exec(a,{command:`git init --bare ${n(U)}`,cwd:"/workspace",env:w,timeoutMs:1e4,onChunk(){}})).exitCode!==0)throw new e("File checkpoint failed. Git is unavailable. Install git in the sandbox image.",{code:"unsupported"})}let i=[],o=new Set((c.internal??[]).map((u)=>m(u)));async function l(u){for(let f of await c.list(a,u)){if(T.basename(f.path)===".git"||o.has(f.path))continue;if(f.type==="directory")await l(f.path);else i.push(T.relative("/workspace",f.path))}}if(await l("/workspace"),await M("read-tree --empty"),i.length)await M("update-index --add --remove -z --stdin",i.join("\x00")+"\x00");return(await M("write-tree")).trim()}async function K(i){try{return await c.stat(a,i),!0}catch(o){if(D(o))return!1;throw o}}async function Y(){let i={};for(let o of await W(".",{recursive:!0}))if(o.type==="file")i[o.path]=Buffer.from(await c.read(a,o.path)).toString("base64");return i}let B=(i)=>`/tmp/.sandbox-sdk/marks/${encodeURIComponent(i)}.json`;async function de(i){let o=JSON.parse(new TextDecoder().decode(await c.read(a,B(i))));if(!r(o)||Array.isArray(o))s("Invalid file checkpoint");let l={};for(let[u,f]of Object.entries(o)){if(!t(f))s("Invalid file checkpoint content");l[u]=f}return l}async function V(i,o){try{return await o()}catch(l){if((i??"start")==="start"&&!await K(B("start")).catch(()=>!0))throw new e("No start checkpoint. createSandbox records one only with trackChanges: true. Pass trackChanges: true or call files.mark() and changes({ since }).",{code:"invalid_argument"});throw l}}let le=(i)=>V(i,()=>L(B(i??"start"))),H={[Symbol.dispose](){for(let i of A)i()},read:L,write:j,list:(i,o)=>E(()=>W(i,o)),stat:(i)=>E(()=>c.stat(a,m(i))),exists:(i)=>E(async()=>{try{return await c.stat(a,m(i)),!0}catch(o){if(D(o))return!1;throw o}}),remove:(i,o)=>E(()=>c.remove(a,m(i),{recursive:o?.recursive??!1})),edit:(i,{find:o,replace:l})=>E(async()=>{if(!o)s("find cannot be empty");let u=m(i);if(c.editInGuest&&ne(o)&&X(l)&&X(u)){let{exitCode:g,stdout:y}=await z(ke,{path:u,find:o,replace:l,write:c.editInGuest},!0);if(g===0)return;if(g===3)throw ie(i,y.trim()?y.trim().split(" ").map(Number):[]);if(g===71)throw new e(`File edit outcome unknown at ${i}. Writing the file failed and its original contents could not be restored. Read the file to check its state before retrying.`,{code:"outcome_unknown"})}let f=await L(i),p=[],h=f.indexOf(o);while(h!==-1)p.push(f.slice(0,h).split(`
`).length),h=f.indexOf(o,h+1);if(p.length!==1)throw ie(i,p);await c.write(a,u,new TextEncoder().encode(f.replace(o,()=>l)))}),upload:(i,o,l)=>E(async()=>{let u=I(i);if(c.transfer!=="files"&&(await P.lstat(u)).isDirectory()){let p=await P.mkdtemp(I(Q(),"sandbox-sdk-upload-")),h=`/tmp/.sandbox-sdk/upload-${crypto.randomUUID()}.tar`;try{let g=I(p,"files.tar");await k("tar",["-cf",g,"-C",u,...(l?.ignore??[]).flatMap((y)=>["--exclude",y]),"."],{timeout:120000}),await j(h,new Uint8Array(await P.readFile(g))),await c.mkdir(a,m(o)),await R(`tar -xf ${n(h)} -C ${n(m(o))} --no-same-owner`)}finally{await P.rm(p,{recursive:!0,force:!0}),await c.remove(a,h,{recursive:!1}).catch(()=>{})}return}async function f(p,h){let g=await P.lstat(p);if(g.isSymbolicLink())s("Uploading symlinks is unsupported");if(g.isDirectory()){await c.mkdir(a,m(h));for(let y of await P.readdir(p))if(!l?.ignore?.some((S)=>te(we(u,I(p,y)),S)||S===y))await f(I(p,y),T.join(h,y))}else await j(h,new Uint8Array(await P.readFile(p)))}await f(u,o)}),download:(i,o)=>E(async()=>{if(c.transfer!=="files"&&(await c.stat(a,m(i))).type==="directory"){let u=await P.mkdtemp(I(Q(),"sandbox-sdk-download-")),f=`/tmp/.sandbox-sdk/download-${crypto.randomUUID()}.tar`;try{await R(`mkdir -p ${n(T.dirname(f))} && tar -cf ${n(f)} -C ${n(m(i))} .`);let p=I(u,"files.tar");await P.writeFile(p,await c.read(a,f)),await P.mkdir(I(o),{recursive:!0}),await k("tar",["-xf",p,"-C",I(o),"--no-same-owner","--no-same-permissions"],{timeout:120000})}finally{await P.rm(u,{recursive:!0,force:!0}),await c.remove(a,f,{recursive:!1}).catch(()=>{})}return}async function l(u,f){let p=await c.stat(a,u);if(p.type==="symlink")s("Downloading symlinks is unsupported");if(p.type==="directory"){await P.mkdir(f,{recursive:!0});for(let h of await c.list(a,u))await l(h.path,I(f,T.basename(h.path)))}else await P.mkdir(I(f,".."),{recursive:!0}),await P.writeFile(f,await c.read(a,u))}await l(m(i),I(o))}),search:(i,o={})=>E(async()=>{let l=[],u=o.maxMatches??200;if(!Number.isSafeInteger(u)||u<1)s("maxMatches must be positive");let f=m(o.path);if(c.listOrder&&i&&!i.includes(`
`)&&ne(i)&&X(f)){let p=o.glob??"",{exitCode:h,stdout:g}=await z($e,{root:f,query:i,pattern:p&&be(p),base:p!==""&&!p.includes("/"),max:u,order:c.listOrder},!1);if(h===0){for(let y of g.split(`
`)){if(!y)continue;let S=JSON.parse(y);if(!Pe(S)){l.length=0;break}let O=new TextDecoder("utf-8",{ignoreBOM:S[1]!==1}).decode(Buffer.from(S[2],"base64"));if(!O.includes(i)){l.length=0;break}l.push({path:S[0],line:S[1],text:x.text(O)})}if(l.length||!g)return l}}for(let p of await W(o.path,{recursive:!0,glob:o.glob}))if(p.type==="file"){let h=(await L(p.path)).split(`
`);for(let[g,y]of h.entries())if(y.includes(i)){if(l.push({path:p.path,line:g+1,text:x.text(y)}),l.length>=u)return l}}return l}),watch(i,o,l={}){b();let u=!1,f,p,h=()=>{},g=new AbortController,y=async()=>{try{if(await C(),u)return;let _=new Map((await W(i,l)).map((v)=>[v.path,`${v.size}:${v.modifiedAt}`]));if(f){for(let[v,ue]of _)if(!f.has(v)||f.get(v)!==ue){if(!u)o({type:f.has(v)?"modified":"added",path:v})}for(let v of f.keys())if(!_.has(v)&&!u)o({type:"removed",path:v})}f=_}catch(_){l.onError?.(x.error(_,d.name,a))}if(!u)p=setTimeout(()=>void y(),l.intervalMs??250),p.unref?.()},S=(_)=>new Promise((v)=>{h=v,p=setTimeout(v,_),p.unref?.()}),O=async(_)=>{while(!u){try{if(await C(),u)return;await _.call(c,a,m(i),{recursive:l.recursive??!1,signal:g.signal,onEvent(v){if(!u)o(v)}})}catch(v){if(u)return;if(v instanceof e&&v.code==="unsupported"){y();return}l.onError?.(x.error(v,d.name,a))}if(!u)await S(1000)}},F=()=>{u=!0,clearTimeout(p),h(),g.abort(),A.delete(F)};if(A.add(F),c.watch)O(c.watch);else y();return F},mark:(i=`mark-${Date.now()}-${Math.random().toString(36).slice(2)}`)=>E(async()=>{if(c.checkpoints==="files")await j(B(i),JSON.stringify(await Y()));else await J(B(i));return i}),changes:(i={})=>E(async()=>{if(c.checkpoints!=="files"){let g=(await le(i.since)).trim(),y=await J();if(!/^[0-9a-f]{40,64}$/.test(g))s("Invalid git checkpoint");let S=(await M(`diff --no-renames --name-status -z ${g} ${y}`)).split("\x00"),O={added:[],modified:[],removed:[],patch:x.text(await M(`diff --no-ext-diff --binary ${g} ${y}`))};for(let F=0;F+1<S.length;F+=2){let _=S[F],v=S[F+1];if(v)(_==="A"?O.added:_==="D"?O.removed:O.modified).push(m(v))}return O}let o=await V(i.since,()=>de(i.since??"start")),l=await Y(),u=Object.keys(l).filter((g)=>!(g in o)),f=Object.keys(o).filter((g)=>!(g in l)),p=Object.keys(l).filter((g)=>(g in o)&&o[g]!==l[g]),h=[...u,...p,...f].map((g)=>ye(T.relative("/workspace",g),g in o?Buffer.from(o[g]??"","base64").toString():void 0,g in l?Buffer.from(l[g]??"","base64").toString():void 0)).join("");return{added:u,modified:p,removed:f,patch:x.text(h)}})};return se.set(H,(i,o)=>E(()=>c.readRange?c.readRange(a,m(i),{offset:0,length:o+1}):c.read(a,m(i)))),H}import{stripVTControlCharacters as Ee}from"node:util";var oe=new WeakMap;function ve(d,a){oe.set(d,a)}function ae(d){let a=oe.get(d);if(!a)throw Error("Unknown sandbox handle. Secret redaction cannot be guaranteed. Use createSandbox or connectSandbox.");return a}function me(d,a){return ae(d).text(Ee(a))}function pe(d,a){let x={stdout:"plain",stderr:"plain"},b=N(ae(d),a,!0);return{push(C){let c=x[C.stream],A="";for(let k of C.text)switch(c){case"plain":if(k==="\x1B")c="escape";else if(k==="")c="csi";else if("".includes(k))c="string";else A+=k;break;case"escape":c=k==="["?"csi":"]PX^_".includes(k)?"string":k>=" "&&k<="/"?"escape":"plain";break;case"csi":if(k>="@"&&k<="~")c="plain";break;case"string":if(k==="\x07"||k==="")c="plain";else if(k==="\x1B")c="string_escape";break;case"string_escape":c=k==="\\"?"plain":"string";break;default:return c}if(x[C.stream]=c,A)b.push({stream:C.stream,text:A})},flush(){b.flush()}}}
export{ee,xe,fe,ve,me,pe};
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.