ts-pantry 0.11.179 → 0.11.180
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/bin/cli.js +1 -1
- package/dist/bin/desktop.js +1 -1
- package/dist/chunk-a5z1gffx.js +18 -0
- package/dist/chunk-g96atdt0.js +2 -0
- package/dist/{chunk-2th5ddt5.js → chunk-xn5c99z0.js} +1 -1
- package/dist/src/desktop/client.d.ts +3 -1
- package/dist/src/desktop/client.js +1 -1
- package/dist/src/desktop/service.d.ts +2 -0
- package/dist/src/desktop/service.js +1 -1
- package/dist/src/desktop/uninstall.d.ts +11 -0
- package/dist/src/native/index.js +1 -1
- package/dist/src/native/release.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5571vd8y.js +0 -2
- package/dist/chunk-y9k1j6rh.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,O,W,ke,ve,n,X,z,u,Z,E,_,L,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-yp7m08xe.js";import{a,C}from"../chunk-yg4wxzf8.js";import"../chunk-y67kbve9.js";import"../chunk-t965ankb.js";import{Sa}from"../chunk-hnhjtezs.js";import{d}from"../chunk-
|
|
2
|
+
import{q}from"../chunk-7q8as4h2.js";import{r,f,b,D,H,ye,k,R,I,O,W,ke,ve,n,X,z,u,Z,E,_,L,M,l,ee,Ce,je,Se,ha,fa}from"../chunk-yp7m08xe.js";import{a,C}from"../chunk-yg4wxzf8.js";import"../chunk-y67kbve9.js";import"../chunk-t965ankb.js";import{Sa}from"../chunk-hnhjtezs.js";import{d}from"../chunk-g96atdt0.js";import m from"node:fs";import v from"node:path";import s from"node:process";C();async function ae(t="src/pantry"){if(!m.existsSync(t))throw Error(`Pantry directory not found: ${t}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let e=[];function o(i,c=""){let g=m.readdirSync(i,{withFileTypes:!0}),p=v.join(i,"package.yml");if(c&&m.existsSync(p))e.push(c);for(let S of g)if(S.isDirectory()&&!S.name.startsWith(".")){let w=c?`${c}/${S.name}`:S.name,x=v.join(i,S.name);o(x,w)}}return o(t),console.log(`\uD83D\uDCE6 Found ${e.length} packages in local pantry`),e.sort()}async function ce(t=!1){async function e(p){let S=new URL("https://s3.amazonaws.com/dist.tea.xyz/");if(S.searchParams.set("list-type","2"),S.searchParams.set("prefix",""),S.searchParams.set("max-keys","1000"),p)S.searchParams.set("continuation-token",p);let w=await fetch(S.toString());if(!w.ok)throw Error(`Failed to fetch S3 listing: ${w.status}`);let x=await w.text(),B=[],J=x.match(/<Key>([^<]+)<\/Key>/g);if(J)for(let G of J){let U=G.replace(/<Key>([^<]+)<\/Key>/,"$1");B.push({Key:U})}let y=x.includes("<IsTruncated>true</IsTruncated>"),F=x.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/),h=F?F[1]:void 0;return{IsTruncated:y,NextContinuationToken:h,Contents:B}}console.log("Scraping packages from S3 registry...");let o=new Set,i;do{let p=await e(i);for(let S of p.Contents){let w=S.Key,x=w.split("/");if(x.length===0)continue;if(x[0].startsWith(".")||x[0].includes(" ")||w.match(/\.(md|txt|yml|yaml|json)$/i))continue;let B=["darwin","linux","windows"],J=-1;for(let y=1;y<x.length;y++)if(B.includes(x[y])){J=y;break}if(J>0){let y=x.slice(0,J).join("/");if(y.includes("."))o.add(y)}else if(x.length>=2&&x[0].includes(".")&&!x[1].startsWith("v")&&!x[1].match(/^\d/)){let y=`${x[0]}/${x[1]}`;o.add(y)}else if(x.length>=1&&x[0].includes("."))o.add(x[0])}i=p.NextContinuationToken,console.log(`Found ${o.size} packages so far...`)}while(i);let c=Array.from(o).sort(),g=[];for(let p of c){if(!p.includes(".")||p.match(/^[a-z0-9.-]+\.[a-z]{2,}(\/[\w.-]+){0,20}$/i)===null)continue;if(p.endsWith("/README.rst")||p.endsWith("/README")||p.includes("/docs/"))continue;if(p.endsWith("/.pkgroot"))continue;if(["amazon.com/aws","charm.sh","code.videolan.org","crates.io"].includes(p))continue;g.push(p)}return console.log(`\uD83D\uDCE6 Found ${g.length} valid packages in registry`),g}async function le(t,e){let i=`/**
|
|
3
3
|
* Constants used throughout the ts-pantry package
|
|
4
4
|
* This file is auto-generated from ${e}. Do not edit manually.
|
|
5
5
|
* Generated on ${new Date().toISOString()}
|
package/dist/bin/desktop.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import{q}from"../chunk-7q8as4h2.js";import"../chunk-t965ankb.js";import"../chunk-h6wpf5z0.js";import{G,K,fe,Ye}from"../chunk-
|
|
2
|
+
import{q}from"../chunk-7q8as4h2.js";import"../chunk-t965ankb.js";import"../chunk-h6wpf5z0.js";import{G,K,fe,Ye}from"../chunk-a5z1gffx.js";import{d}from"../chunk-g96atdt0.js";import{chmodSync as k,mkdirSync as h,renameSync as P,rmSync as b,writeFileSync as f}from"node:fs";import{homedir as S}from"node:os";import{isAbsolute as x,join as s}from"node:path";var a=(t)=>t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'");function D(t,e,r){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4
4
|
<plist version="1.0"><dict>
|
|
5
5
|
<key>Label</key><string>dev.pantry.desktop</string>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{de}from"./chunk-t965ankb.js";import{Be}from"./chunk-h6wpf5z0.js";import{createHash as De,randomBytes as Se,randomInt as Ie,timingSafeEqual as Ee}from"node:crypto";import{chmodSync as $e,existsSync as ue,lstatSync as ge,mkdirSync as Ae,readFileSync as Te,renameSync as je,writeFileSync as Oe}from"node:fs";import{homedir as he}from"node:os";import{isAbsolute as Ce,join as R}from"node:path";import{createHash as ne}from"node:crypto";import{execFileSync as re}from"node:child_process";import{createReadStream as ye}from"node:fs";import{lstat as B,mkdir as q,mkdtemp as ke,readFile as ae,readdir as L,readlink as be,realpath as S,rename as W,rmdir as ve}from"node:fs/promises";import{homedir as ie}from"node:os";import{basename as V,dirname as Z,isAbsolute as Pe,join as g,resolve as X,sep as xe}from"node:path";var U=(e,t)=>e===t||e.startsWith(t+xe),oe=(e)=>e.code==="ENOENT";function se(){return g(process.env.XDG_DATA_HOME||g(ie(),".local/share"),"pantry/global")}function H(e){return e.length>0&&e.length<=256&&/^[a-zA-Z0-9@][a-zA-Z0-9@._+/-]*$/.test(e)&&e.split("/").every((t)=>t&&t!=="."&&t!=="..")}async function J(e){try{let t=await B(e);return t.isDirectory()&&!t.isSymbolicLink()}catch(t){if(oe(t))return!1;throw t}}async function ce(e,t){if(!H(e))throw Error("Choose a valid Pantry package identifier.");let c=g(t,"packages"),o=g(c,e);if(!await J(o))return[];let i=await S(c);if(!U(await S(o),i))throw Error("Package storage leaves the Pantry user directory.");let s=[];for(let P of await L(o,{withFileTypes:!0})){if(!P.isDirectory()||!/^v[0-9]/.test(P.name))continue;let x=g(o,P.name);if(!U(await S(x),i))throw Error("Package version leaves the Pantry user directory.");s.push(x)}return s}async function M(e,t={}){try{return(await ce(e,t.store||se())).length>0}catch{return!1}}var Q=`s=$0
|
|
2
|
+
while [ -h "$s" ]; do
|
|
3
|
+
l=$(readlink "$s")
|
|
4
|
+
case $l in
|
|
5
|
+
/*) s=$l ;;
|
|
6
|
+
*) case $s in */*) s=\${s%/*}/$l ;; *) s=$l ;; esac ;;
|
|
7
|
+
esac
|
|
8
|
+
done
|
|
9
|
+
case $s in */*) d=\${s%/*} ;; *) d=. ;; esac
|
|
10
|
+
`;async function Y(e){let t=await B(e);if(t.isSymbolicLink())return X(Z(e),await be(e));if(!t.isFile()||t.size>65536)return null;let c=await ae(e,"utf8");for(let o of[`#!/bin/sh
|
|
11
|
+
${Q}exec "$d/`,`#!/bin/sh
|
|
12
|
+
${Q}exec bun "$d/`,`#!/bin/sh
|
|
13
|
+
exec "`,`#!/bin/sh
|
|
14
|
+
exec bun "`]){if(!c.startsWith(o))continue;let i=c.slice(o.length).match(/^([^"\r\n`$]+)"(?: '(?:[^']|'"'"')*')* "\$@"\n$/);if(!i)continue;let s=i[1];return o.includes("$d/")?X(Z(e),s):Pe(s)?s:null}return null}async function ee(e){let t=ne("sha256");for await(let c of ye(e))t.update(c);return t.digest("hex")}async function te(e){let t=g(e,"Contents/Info.plist"),c=await B(t);if(!c.isFile()||c.isSymbolicLink()||c.size>1048576)throw Error("Invalid application manifest.");let o=await ae(t),i=o.toString("utf8").match(/<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/)?.[1];if(i)return i;if(o.subarray(0,6).toString()==="bplist"&&process.platform==="darwin"){let s=re("/usr/libexec/PlistBuddy",["-c","Print :CFBundleIdentifier",t],{encoding:"utf8",timeout:5000,stdio:["ignore","pipe","ignore"]}).trim();if(s)return s}return ne("sha256").update(o).digest("hex")}async function le(e,t={},c=()=>{}){let o=t.store||se(),i=t.home||ie(),s=await ce(e,o);if(!s.length)throw Error("This package is not managed in the Pantry user directory.");let P=await Promise.all(s.map((a)=>S(a))),x=(a)=>P.some((r)=>U(a,r));for(let a of t.protectedPaths||[]){let r=await S(a).catch(()=>a);if(x(r))throw Error("Pantry is using this package to manage software. Its running package manager cannot uninstall itself.")}let T=new Map;async function b(a){let r=await B(a);T.set(a,{path:a,inode:Number(r.ino),device:Number(r.dev)})}async function j(a,r){if(!await J(a))return;for(let d of await L(a,{withFileTypes:!0})){let w=g(a,d.name);if(d.isDirectory()){if(r>0)await j(w,r-1);continue}let n=await Y(w);if(n&&x(await S(n).catch(()=>n)))await b(w)}}for(let a of["bin","sbin","lib","libexec","include","share"])await j(g(o,a),8);let F=new Map;async function I(a,r){for(let d of await L(a,{withFileTypes:!0})){let w=g(a,d.name),n=d.isDirectory()&&/\.app$/i.test(d.name),u=d.isFile()&&/\.(?:otf|ttf|ttc)$/i.test(d.name);if(n||u){let p=n?g(i,"Applications"):g(i,"Library/Fonts"),m=g(p,d.name),y=F.get(m);if(y)y.sources.push(w);else F.set(m,{sources:[w],app:n,root:p})}else if(d.isDirectory()&&r>0)await I(w,r-1)}}for(let a of s)await I(a,4);for(let[a,r]of F){let d;try{d=await B(a)}catch(u){if(oe(u))continue;throw u}if(d.isSymbolicLink()||(r.app?!d.isDirectory():!d.isFile()))throw Error(`Refusing to remove a replaced file: ${a}`);if(!U(await S(a),await S(r.root)))throw Error("An activated file leaves its user directory.");if(r.app){if((t.runningExecutables||(process.platform==="darwin"?re("/bin/ps",["-axo","comm="],{encoding:"utf8",timeout:5000,maxBuffer:4194304}).split(`
|
|
15
|
+
`).map((p)=>p.trim()):[])).some((p)=>U(p,a)))throw Error(`Quit ${V(a,".app")} before uninstalling it.`)}let w=r.app?await te(a):await ee(a),n=!1;for(let u of r.sources)if((r.app?await te(u):await ee(u))===w){n=!0;break}if(!n)throw Error(`The installed file differs from this Pantry package; it was kept: ${a}`);await b(a)}let O=g(o,"packages",e);for(let a of await L(O,{withFileTypes:!0})){if(!a.isSymbolicLink())continue;let r=g(O,a.name),d=await Y(r);if(d&&x(await S(d).catch(()=>d)))await b(r)}for(let a of s)await b(a);let E=g(i,".Trash");if(await q(E,{recursive:!0,mode:448}),!await J(E))throw Error("The user Trash must be a real directory.");let D=await ke(g(E,"Pantry-")),C=[];try{for(let[a,r]of[...T.values()].entries()){let d=await B(r.path);if(Number(d.ino)!==r.inode||Number(d.dev)!==r.device)throw Error("A managed file changed while preparing removal. Retry uninstall.");let w=g(D,String(a));await q(w,{mode:448});let n=g(w,V(r.path));await W(r.path,n),C.push({from:r.path,to:n})}}catch(a){for(let r of C.reverse())try{await W(r.to,r.from)}catch{c(`A file could not be restored. Recovery folder: ${D}
|
|
16
|
+
`)}throw a}await ve(O).catch(()=>{}),c(`Uninstalled ${e}. Managed files moved to ${D}. App data and other packages were kept.
|
|
17
|
+
`)}var N=(e)=>De("sha256").update(e).digest("hex"),Re=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;function G(){return R(process.env.XDG_DATA_HOME||R(he(),".local/share"),"pantry/desktop")}function K(e){Ae(e,{recursive:!0,mode:448});let t=ge(e);if(t.isSymbolicLink()||!t.isDirectory()||process.getuid&&t.uid!==process.getuid()||t.mode&63)throw Error("Pantry Desktop state must be an owner-only directory")}function pe(e){let t=ge(e);if(!t.isFile()||t.isSymbolicLink()||t.nlink!==1||t.size>40000000||process.getuid&&t.uid!==process.getuid()||t.mode&63)throw Error("Pantry Desktop state must be an owner-only file");return JSON.parse(Te(e,"utf8"))}function _(e,t){let c=`${e}.${crypto.randomUUID()}.tmp`;Oe(c,JSON.stringify(t),{mode:384,flag:"wx"}),je(c,e),$e(e,384)}function fe(e=G(),t=Date.now()){K(e);let c=String(Ie(1e7,1e8));return _(R(e,"pairing.json"),{hash:N(c),expiresAt:t+300000}),c}function me(e,t){return/^[a-f0-9]{64}$/.test(e)&&/^[a-f0-9]{64}$/.test(t)&&Ee(Buffer.from(e,"hex"),Buffer.from(t,"hex"))}function z(e){let{clientId:t,...c}=e;return c}function It(e){if(process.platform!=="darwin")return[];let t=(o)=>o.toLowerCase().replace(/[^a-z0-9]/g,""),c=new Map(e.filter((o)=>o.kind==="app").map((o)=>[t(o.name),o.domain]));return["/Applications",R(he(),"Applications")].flatMap((o)=>de(o)).flatMap((o)=>{let i=c.get(t(o.name));return i?[{name:i,version:o.version,applicationPath:o.path}]:[]})}function zt(e,t,c){let o=new Set(e.filter((s)=>s.kind==="app").map((s)=>s.domain)),i=new Map(t.filter((s)=>!o.has(s.name)).map((s)=>[s.name,{name:s.name,version:s.version}]));for(let s of c)if(s.applicationPath)i.set(s.name,s);return[...i.values()]}function Ye(e={}){let t=e.now??Date.now,c=e.stateDirectory??G();K(c);let o=R(c,"state.json"),i=ue(o)?pe(o):{clients:[],jobs:[]};if(!Array.isArray(i.clients)||!Array.isArray(i.jobs))throw Error("Invalid Pantry Desktop state");let s=()=>_(o,i);for(let n of i.jobs)if(n.status==="queued"||n.status==="running")n.status="failed",n.error="Pantry restarted before this package operation completed. Check installed packages before retrying.",n.finishedAt=new Date(t()).toISOString(),n.timezoneOffset=new Date(t()).getTimezoneOffset();s();let P=e.catalog??Be(),x=e.applications??(()=>It(P)),T=new Map(P.map((n)=>[n.domain,n])),b=e.pantryExecutable??Bun.which("pantry");if(!e.run&&(!b||!Ce(b)))throw Error("Install the Pantry CLI before starting its desktop bridge");let j,F=e.run??(async(n,u)=>{let p=Bun.spawn([b,...n],{cwd:c,stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,NO_COLOR:"1",CI:"1"}});j=p;let m=async(y)=>{let l=y.getReader(),f=new TextDecoder;try{while(!0){let h=await l.read();if(h.done)break;u(f.decode(h.value,{stream:!0}))}}finally{l.releaseLock()}};try{return await Promise.all([m(p.stdout),m(p.stderr)]),await p.exited}finally{j=void 0}}),I=Promise.resolve(),O=(n,u)=>{let p=I.then(()=>{if(D)throw Error("Pantry Desktop is stopping");return F(n,u)});return I=p.catch(()=>{}),p},E=!1,D=!1,C;async function a(){if(E||D)return;E=!0;try{while(!D){let n=i.jobs.find((p)=>p.status==="queued");if(!n)break;n.status="running",n.startedAt=new Date(t()).toISOString(),s();try{let p=T.get(n.domain)?.kind||n.kind||"cli";if(n.operation==="uninstall"){let m=I.then(()=>{if(D)throw Error("Pantry Desktop is stopping");return le(n.domain,{...e.removal,protectedPaths:[...e.removal?.protectedPaths||[],...b?[b]:[],process.execPath]},(y)=>{n.output=(n.output+y).slice(-32000)})});if(I=m.catch(()=>{}),await m,await M(n.domain,e.removal))throw Error("Package files are still present after removal.");n.status="succeeded"}else{let m=await O(["install","--user",...["app","font"].includes(p)?["--kind",p]:[],n.domain],(y)=>{n.output=(n.output+y).slice(-32000)});if(n.status=m===0?"succeeded":"failed",m)n.error=`Pantry installation exited with code ${m}. Expand installation details for the error, then retry.`;if(m===0&&p==="app"&&!x().some((y)=>y.name===n.domain&&y.applicationPath))n.status="failed",n.error="The download completed, but no usable application was found in Applications. Retry installation to install the app bundle."}}catch(p){n.status="failed",n.error=p instanceof Error?p.message:"Pantry package operation failed"}let u=new Date(t());n.finishedAt=u.toISOString(),n.timezoneOffset=u.getTimezoneOffset(),s()}}finally{E=!1}}let r=(n,u=200)=>Response.json(n,{status:u,headers:{"cache-control":"no-store"}}),d=[],w=Bun.serve({hostname:"127.0.0.1",port:e.port??46473,maxRequestBodySize:4096,async fetch(n){let u=new URL(n.url);if(n.headers.has("origin")||n.headers.get("host")!==`127.0.0.1:${w.port}`)return r({error:"Forbidden origin or host"},403);if(u.pathname==="/health"&&n.method==="GET")return r({protocolVersion:1,service:"pantry-desktop",capabilities:["install:user","uninstall:user","installed","jobs"]});if(u.pathname==="/pair"&&n.method==="POST"){while(d.length&&d[0]<t()-60000)d.shift();if(d.length>=10)return r({error:"Too many pairing attempts. Try again in a minute."},429);d.push(t());let l=await n.json().catch(()=>null);if(!l||typeof l.code!=="string"||!/^\d{8}$/.test(l.code)||typeof l.name!=="string"||!l.name.trim()||l.name.length>80)return r({error:"Provide the pairing code and application name."},422);let f=R(c,"pairing.json");if(!ue(f))return r({error:"Create a pairing code from the Pantry CLI first."},401);let h=pe(f);if(h.expiresAt<=t()||!me(h.hash,N(l.code)))return r({error:"The Pantry pairing code is invalid or expired."},401);if(i.clients.length>=100)return r({error:"Remove unused Pantry Desktop connections before pairing another app."},409);let A=Se(32).toString("base64url");return i.clients.push({id:crypto.randomUUID(),name:l.name.trim(),tokenHash:N(A)}),_(f,{hash:"",expiresAt:0}),s(),r({token:A},201)}let p=n.headers.get("authorization")?.match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1],m=p?i.clients.find((l)=>me(l.tokenHash,N(p))):void 0;if(!m)return r({error:"Connect this application to Pantry first."},401);if(u.pathname==="/v1/connection"&&n.method==="DELETE")return i.clients=i.clients.filter((l)=>l.id!==m.id),s(),r({disconnected:!0});if(u.pathname==="/v1/installed"&&n.method==="GET"){let l="";if(await O(["list","--format","json"],(h)=>{if(l.length<4000000)l+=h}))return r({error:"Pantry could not list installed packages."},502);try{let h=JSON.parse(l);if(!Array.isArray(h)||h.some((v)=>typeof v.name!=="string"||typeof v.version!=="string"))throw Error("Invalid installed package list");let A=zt(P,h,x()),k=await Promise.all(A.map(async(v)=>({...v,managed:await M(v.name,e.removal)})));for(let v of h)if(!k.some((we)=>we.name===v.name)&&await M(v.name,e.removal))k.push({name:v.name,version:v.version,managed:!0});return r({packages:k})}catch{return r({error:"Pantry returned an invalid installed package list."},502)}}if(["/v1/install","/v1/uninstall"].includes(u.pathname)&&n.method==="POST"){let l=u.pathname==="/v1/uninstall"?"uninstall":"install",f=await n.json().catch(()=>null);if(!f||typeof f.domain!=="string"||!H(f.domain)||l==="install"&&!T.has(f.domain)||typeof f.requestId!=="string"||!Re.test(f.requestId))return r({error:"Choose a package from the Pantry catalog and provide a request ID."},422);let h=i.jobs.find((k)=>k.clientId===m.id&&k.requestId===f.requestId);if(h)return h.domain===f.domain&&(h.operation||"install")===l?r({job:z(h)},202):r({error:"This request ID already belongs to another package or operation."},409);if(l==="uninstall"&&!await M(f.domain,e.removal))return r({error:"This package is not managed in the Pantry user directory."},409);if(i.jobs.some((k)=>k.domain===f.domain&&["queued","running"].includes(k.status)))return r({error:"Wait for this package operation to finish."},409);if(i.jobs.filter((k)=>k.status==="queued"||k.status==="running").length>=3)return r({error:"Wait for current Pantry package operations to finish."},429);let A={id:crypto.randomUUID(),requestId:f.requestId,clientId:m.id,domain:f.domain,operation:l,kind:T.get(f.domain)?.kind||"cli",status:"queued",output:"",createdAt:new Date(t()).toISOString()};if(i.jobs.push(A),i.jobs.length>1000)i.jobs.splice(0,i.jobs.length-1000);if(s(),!E)C=a();return r({job:z(A)},202)}if(u.pathname==="/v1/jobs"&&n.method==="GET")return r({jobs:i.jobs.filter((l)=>l.clientId===m.id).slice(-50).reverse().map(z)});let y=u.pathname.match(/^\/v1\/jobs\/([a-f0-9-]{36})$/i);if(y&&n.method==="GET"){let l=i.jobs.find((f)=>f.id===y[1]&&f.clientId===m.id);return l?r({job:z(l)}):r({error:"Pantry installation was not found."},404)}return r({error:"Not found"},404)},error(){return r({error:"Pantry Desktop could not complete this request."},500)}});return{server:w,async close(){D=!0,j?.kill(),await C,await I,await w.stop(!0)}}}
|
|
18
|
+
export{G,K,fe,It,zt,Ye};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Te}from"./chunk-yg4wxzf8.js";import{d}from"./chunk-
|
|
1
|
+
import{Te}from"./chunk-yg4wxzf8.js";import{d}from"./chunk-g96atdt0.js";import{existsSync as Qe,readFileSync as et}from"node:fs";import{join as tt,resolve as J,sep as rt}from"node:path";var ko={revision:"e1d6e40100ae2c35c96f9d96ed826f08ddf1f48b",version:"0.0.367"};function Re(r){let i=r.split(".");return i.length>1&&i.every((o)=>/^[A-Za-z]\w*$/.test(o))}function s(r,i){let o=J(r,i);if(o===J(r)||!o.startsWith(`${J(r)}${rt}`))throw Error(`Native output must be inside the project: ${i}`);return o}function p(r,i=!1){let o=tt(r,"pantry.json");if(!Qe(o)){if(i)throw Error("Native publishing requires pantry.json with a native configuration");return}let n=JSON.parse(et(o,"utf8")).native;if(!n){if(i)throw Error("pantry.json must declare native app settings");return}if(n.environment!==void 0&&(typeof n.environment!=="string"||!/^[a-z][a-z0-9-]*$/.test(n.environment)))throw Error("Invalid native release environment name");if(n.runtime&&(!/^[a-f0-9]{40}$/.test(n.runtime.revision)||!/^\d+\.\d+\.\d+$/.test(n.runtime.version)))throw Error("Craft requires an immutable 40-character Git revision and an exact version");for(let c of[n.build,...n.checks?.before??[],...n.checks?.after??[]])if(c!==void 0&&(!Array.isArray(c)||!c.length||c.some((a)=>typeof a!=="string"||!a)))throw Error("Native commands must be nonempty argument arrays");if(n.macos?.maxBundleSize!==void 0&&(!Number.isSafeInteger(n.macos.maxBundleSize)||n.macos.maxBundleSize<=0))throw Error("maxBundleSize must be a positive byte count");if(n.registry){if(typeof n.registry.domain!=="string"||!/^[a-z0-9](?:[a-z0-9._-]|\/(?=[a-z0-9])){0,213}$/i.test(n.registry.domain)||n.registry.domain.includes("..")||n.registry.domain.endsWith("/"))throw Error("Native registry publishing requires an exact package domain");if(n.registry.url){let c=new URL(n.registry.url);if(c.username||c.password||c.search||c.hash||c.protocol!=="https:"&&!(c.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(c.hostname)))throw Error("Native registry URL must use HTTPS, or HTTP on loopback for testing")}if(!n.macos?.notarize)throw Error("Native registry apps require notarized macOS distribution")}if(n.android){if(s(r,n.android.bundle),!Re(n.android.packageName)||!n.android.track||!["draft","completed","inProgress"].includes(n.android.status))throw Error("Android publishing requires a package name, track and explicit release status");let c=n.android.userFraction;if(n.android.status==="inProgress"?!(typeof c==="number"&&c>0&&c<1):c!==void 0)throw Error("Only an inProgress rollout requires userFraction between zero and one")}return n}import it from"node:process";import{spawn as nt}from"node:child_process";var t=(r,i,o={})=>new Promise((n,c)=>{if(o.timeoutMs!==void 0&&(!Number.isSafeInteger(o.timeoutMs)||o.timeoutMs<=0||o.timeoutMs>2147483647)){c(Error("A native command timeout must be a positive integer no greater than 2147483647ms"));return}let a=nt(r,i,{cwd:o.cwd,env:o.env??it.env,stdio:o.inherit?"inherit":[o.input===void 0?"ignore":"pipe","pipe","pipe"]}),u="",m="";a.stdout?.on("data",(h)=>{u+=h.toString()}),a.stderr?.on("data",(h)=>{m+=h.toString()});let y,g,f=!1,l=()=>{if(y!==void 0)clearTimeout(y)},v=()=>{a.stdin?.destroy(),a.stdout?.destroy(),a.stderr?.destroy()};if(a.once("error",(h)=>{g=f?Error(g.message,{cause:h}):h,l()}),a.stdin?.once("error",(h)=>{g=f?Error(g.message,{cause:h}):h}),a.once("exit",()=>{if(!f)return;v()}),a.once("close",(h)=>{if(l(),g)c(g);else n({exitCode:h??1,stdout:u,stderr:m})}),o.timeoutMs!==void 0)y=setTimeout(()=>{if(f=!0,g=Error(`Native command timed out after ${o.timeoutMs}ms: ${r}`),a.exitCode!==null||a.signalCode)v();else try{a.kill("SIGKILL")}catch(h){g=Error(g.message,{cause:h})}},o.timeoutMs);if(o.input!==void 0)a.stdin?.end(o.input)});function e(r,i){if(i.exitCode!==0)throw Error(`${r} failed (${i.exitCode}): ${i.stdout}
|
|
2
2
|
${i.stderr}`.trim());return i}import z from"node:process";import{createHash as at}from"node:crypto";import{existsSync as k,mkdirSync as ct,readFileSync as X,rmSync as ut,writeFileSync as pt}from"node:fs";import{join as N,resolve as dt}from"node:path";var H="(?:0|[1-9]\\d*)",ce="(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)",pe=`${H}\\.${H}\\.${H}(?:-${ce}(?:\\.${ce})*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?`,ot=new RegExp(`^${pe}$`),st=new RegExp(`^pantry\\s+(${pe})(?:\\s+\\([^\\r\\n()]+\\))?$`);if(!ot.test(d))throw Error("The native SDK requires a valid paired Pantry SDK/CLI version");var Oe=`^${d}`;async function Z(r,i,o){let n=`ts-pantry@${d} native provisioning requires Pantry ${Oe} on PATH in ${i}.`,c="Install or upgrade the Pantry CLI on that PATH before retrying.",a;try{a=await r("pantry",["--version"],{cwd:i,env:o,timeoutMs:1e4})}catch(m){throw Error(`${n} Could not run \`pantry --version\`. Install or upgrade the Pantry CLI on that PATH before retrying.`,{cause:m})}if(a.exitCode!==0)throw Error(`${n} \`pantry --version\` exited ${a.exitCode}. Install or upgrade the Pantry CLI on that PATH before retrying.`);let u=st.exec(a.stdout.trim()||a.stderr.trim())?.[1];if(!u)throw Error(`${n} \`pantry --version\` returned an invalid native CLI version. Install or upgrade the Pantry CLI on that PATH before retrying.`);if(Te(Oe,[u])!==u)throw Error(`${n} Found ${u}. Install or upgrade the Pantry CLI on that PATH before retrying.`)}function Ut(r,i=k){for(let o of[N(r,"bin","zig"),N(r,"zig")])if(i(o))return o;return null}function _a(r,i,o=z.arch){if(!/^[a-f0-9]{40}$/.test(r))throw Error("Craft revision must be immutable");if(!/^\d+\.\d+(?:\.\d+)?$/.test(i))throw Error("A valid minimum macOS version is required");let n=o==="arm64"?"aarch64":o==="x64"?"x86_64":void 0;if(!n)throw Error(`Unsupported native architecture: ${o}`);return`revision=${r};ReleaseSmall;js-runtime=false;target=${n}-macos.${i}`}function Ct(r,i,o=z.arch){if(!r.runtime)throw Error("No Craft runtime configured");return at("sha256").update(`${_a(r.runtime.revision,i,o)};version=${r.runtime.version};schema=1`).digest("hex")}function jt(r){let i=r.workspaces?.[""]?.system?.["ziglang.org"];if(typeof i!=="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(i))throw Error("Craft must lock an exact Zig compiler version");return i}function St(r){if(!k(N(r,"packages/zig/build.zig.zon")))throw Error("Craft dependency manifest is missing");let i=N(r,".github/actions/first-party-zig-deps/pins.env");if(!k(i))return{kind:"manifest"};let o=X(i,"utf8");return{kind:"legacy-pins",sources:[["zig-js","zig_js"],["zig-regex","zig_regex"],["zig-gc","zig_gc"]].map(([c,a])=>{let u=o.match(new RegExp(`^${a}=([a-f0-9]{40})$`,"m"))?.[1];if(!u)throw Error(`Missing upstream dependency pin: ${a}`);return{repository:`zig-utils/${c}`,revision:u,directory:c}})}}async function Ta(r,i,o,n={}){let c=n.env??z.env;if(c.CRAFT_BIN){let w=dt(r,c.CRAFT_BIN);if(!k(w))throw Error(`CRAFT_BIN does not exist: ${w}`);return w}if(!i.runtime)return;if(z.platform!=="darwin")throw Error("The configured macOS Craft runtime must be built on macOS");let a=n.command??t,{revision:u,version:m}=i.runtime,y=_a(u,o),g=N(r,".pantry/native/runtimes",Ct(i,o)),f=N(g,"Tools/craft"),l=N(f,"packages/zig/zig-out/bin/craft"),v=N(f,".pantry-runtime-profile"),h=()=>!k(l)||!k(v)||X(v,"utf8")!==y;if(h())await Z(a,k(f)?f:r,c);let E=async(w,I,P=c,x=!1)=>e(w[0],await a(w[0],w.slice(1),{cwd:I,env:P,inherit:x})),b=async(w,I,P)=>{if(!/^[a-f0-9]{40}$/.test(I))throw Error(`Missing immutable dependency pin: ${w}`);if(ct(P,{recursive:!0}),!k(N(P,".git")))await E(["git","init","--quiet"],P),await E(["git","remote","add","origin",`https://github.com/${w}.git`],P),await E(["git","fetch","--quiet","--depth","1","origin",I],P),await E(["git","checkout","--quiet","--detach","FETCH_HEAD"],P);let x=(await E(["git","rev-parse","HEAD"],P)).stdout.trim();if(x!==I)throw Error(`Unexpected source revision in ${P}: ${x}`);if((await E(["git","status","--porcelain","--untracked-files=no"],P)).stdout.trim())throw Error(`Modified runtime source in ${P}`)};await b("craft-native/craft",u,f);let R=St(f);if(R.kind==="legacy-pins")for(let w of R.sources)await b(w.repository,w.revision,N(g,"Libraries",w.directory));if(h()){await Z(a,f,c),ut(v,{force:!0});let w=JSON.parse(X(N(f,"pantry.lock"),"utf8")),I=jt(w);await E(["pantry","install",`ziglang.org@${I}`,"--no-save","--ignore-scripts"],f,c,!0);let P=N(f,"pantry/ziglang.org",`v${I}`),x=Ut(P);if(!x)throw Error(`Locked Zig compiler is missing under ${P}`);let M={...c,CRAFT_ZIG:x};if(R.kind==="manifest")await E(["bun","scripts/zig.ts","--core","build","--fetch"],f,M,!0);let ae=(await E(["xcrun","--sdk","macosx","--show-sdk-path"],f)).stdout.trim();if(!ae)throw Error("The macOS SDK is required");let Xe=y.split("target=")[1];await E(["bun","scripts/zig.ts","--core","--versioned","build","-Doptimize=ReleaseSmall","-Djs-runtime=false",`-Dtarget=${Xe}`,`-Dmacos-sdk=${ae}`],f,M,!0),pt(v,y)}let se=await E([l,"--version"],f);if(!`${se.stdout}${se.stderr}`.includes(`craft version ${m}`))throw Error(`Craft does not match configured version ${m}`);return l}import ft from"node:process";import{existsSync as fe,mkdirSync as lt,mkdtempSync as mt,readFileSync as yt,rmSync as de,writeFileSync as le}from"node:fs";import{tmpdir as gt}from"node:os";import{join as L,resolve as ht}from"node:path";function Q(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Dt(r){let i=(o)=>typeof o==="boolean"?`<${o}/>`:typeof o==="string"?`<string>${Q(o)}</string>`:Array.isArray(o)&&o.every((n)=>typeof n==="string")?`<array>${o.map((n)=>`<string>${Q(n)}</string>`).join("")}</array>`:(()=>{throw Error("Unsupported entitlement value")})();return`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
4
4
|
<plist version="1.0"><dict>${Object.entries(r).map(([o,n])=>`<key>${Q(o)}</key>${i(n)}`).join("")}</dict></plist>
|
|
@@ -3,6 +3,7 @@ export declare interface DesktopInstallJob {
|
|
|
3
3
|
id: string
|
|
4
4
|
requestId: string
|
|
5
5
|
domain: string
|
|
6
|
+
operation?: 'install' | 'uninstall'
|
|
6
7
|
kind?: 'app' | 'cli' | 'library' | 'font'
|
|
7
8
|
startedAt?: string
|
|
8
9
|
timezoneOffset?: number
|
|
@@ -12,7 +13,7 @@ export declare interface DesktopInstallJob {
|
|
|
12
13
|
finishedAt?: string
|
|
13
14
|
error?: string
|
|
14
15
|
}
|
|
15
|
-
export declare interface DesktopInstalledPackage { name: string, version: string, applicationPath?: string }
|
|
16
|
+
export declare interface DesktopInstalledPackage { name: string, version: string, applicationPath?: string, managed?: boolean }
|
|
16
17
|
export type DesktopFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
17
18
|
export declare class PantryDesktopError extends Error {
|
|
18
19
|
readonly status: number;
|
|
@@ -25,6 +26,7 @@ export declare class PantryDesktopClient {
|
|
|
25
26
|
pair(code: string, name: string): Promise<string>;
|
|
26
27
|
installed(): Promise<DesktopInstalledPackage[]>;
|
|
27
28
|
install(domain: string, requestId?: string): Promise<DesktopInstallJob>;
|
|
29
|
+
uninstall(domain: string, requestId?: string): Promise<DesktopInstallJob>;
|
|
28
30
|
jobs(): Promise<DesktopInstallJob[]>;
|
|
29
31
|
job(id: string): Promise<DesktopInstallJob>;
|
|
30
32
|
disconnect(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a="http://127.0.0.1:46473";class
|
|
1
|
+
var a="http://127.0.0.1:46473";class r extends Error{status;constructor(s,t){super(s);this.status=t;this.name="PantryDesktopError"}}class o{options;baseUrl;constructor(s={}){this.options=s;let t=new URL(s.baseUrl??"http://127.0.0.1:46473");if(t.protocol!=="http:"||t.hostname!=="127.0.0.1"||t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw Error("Pantry Desktop must use an IPv4 loopback address");this.baseUrl=t.origin}async request(s,t={}){let e=await(this.options.fetch??globalThis.fetch)(this.baseUrl+s,{...t,signal:t.signal??AbortSignal.timeout(15000),headers:{...this.options.token?{authorization:`Bearer ${this.options.token}`}:{},...t.body?{"content-type":"application/json"}:{},...t.headers}}),n=await e.json();if(!e.ok)throw new r(String(n.error||`Pantry Desktop request failed (${e.status})`),e.status);return n}async health(){return await this.request("/health")}async pair(s,t){let e=await this.request("/pair",{method:"POST",body:JSON.stringify({code:s,name:t})});if(typeof e.token!=="string")throw Error("Pantry did not return a connection token");return e.token}async installed(){return(await this.request("/v1/installed")).packages}async install(s,t=crypto.randomUUID()){return(await this.request("/v1/install",{method:"POST",body:JSON.stringify({domain:s,requestId:t})})).job}async uninstall(s,t=crypto.randomUUID()){return(await this.request("/v1/uninstall",{method:"POST",body:JSON.stringify({domain:s,requestId:t})})).job}async jobs(){return(await this.request("/v1/jobs")).jobs}async job(s){return(await this.request(`/v1/jobs/${encodeURIComponent(s)}`)).job}async disconnect(){await this.request("/v1/connection",{method:"DELETE"})}}export{o as PantryDesktopClient,r as PantryDesktopError,a as desktopBridgeUrl};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { DesktopInstalledPackage } from './client';
|
|
2
2
|
import type { PackageCatalogEntry } from '../catalog/types';
|
|
3
|
+
import type { UserPackageRemovalOptions } from './uninstall';
|
|
3
4
|
export declare function desktopStateDirectory(): string;
|
|
4
5
|
export declare function secureDesktopDirectory(directory: string): void;
|
|
5
6
|
/** Local terminal approval creates a short-lived, single-use pairing code. */
|
|
@@ -16,6 +17,7 @@ export declare interface DesktopBridgeOptions {
|
|
|
16
17
|
catalog?: readonly PackageCatalogEntry[]
|
|
17
18
|
run?: (args: string[], output: (text: string) => void) => Promise<number>
|
|
18
19
|
applications?: () => DesktopInstalledPackage[]
|
|
20
|
+
removal?: UserPackageRemovalOptions
|
|
19
21
|
now?: () => number
|
|
20
22
|
}
|
|
21
23
|
/** Standalone Pantry process. The launcher never spawns or embeds an installer. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{G,K,fe,It,zt,Ye}from"../../chunk-
|
|
1
|
+
import{G,K,fe,It,zt,Ye}from"../../chunk-a5z1gffx.js";import"../../chunk-h6wpf5z0.js";import"../../chunk-t965ankb.js";export{fe as createDesktopPairingCode,G as desktopStateDirectory,It as installedCatalogApplications,zt as mergeInstalledPackages,K as secureDesktopDirectory,Ye as startDesktopBridge};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function userPackageStore(): string;
|
|
2
|
+
export declare function validManagedDomain(domain: string): boolean;
|
|
3
|
+
export declare function isManagedUserPackage(domain: string, options?: UserPackageRemovalOptions): Promise<boolean>;
|
|
4
|
+
/** First-class Pantry Desktop removal: user scope only, never shell commands or name-based system-app deletion. */
|
|
5
|
+
export declare function uninstallUserPackage(domain: string, options?: UserPackageRemovalOptions, output?: (text: string) => void): Promise<void>;
|
|
6
|
+
export declare interface UserPackageRemovalOptions {
|
|
7
|
+
store?: string
|
|
8
|
+
home?: string
|
|
9
|
+
protectedPaths?: readonly string[]
|
|
10
|
+
runningExecutables?: readonly string[]
|
|
11
|
+
}
|
package/dist/src/native/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"../../chunk-yg4wxzf8.js";import{ko,Re,s,p,t,e,Oe,Ut,_a,Ct,jt,St,Ta,Dt,vo,xo,Le,Va,qa,Y,B,Ra,Oa,La,Me,j,Ma,Ne,ue,Fe,Na,Fa,he,At,S}from"../../chunk-
|
|
1
|
+
import"../../chunk-yg4wxzf8.js";import{ko,Re,s,p,t,e,Oe,Ut,_a,Ct,jt,St,Ta,Dt,vo,xo,Le,Va,qa,Y,B,Ra,Oa,La,Me,j,Ma,Ne,ue,Fe,Na,Fa,he,At,S}from"../../chunk-xn5c99z0.js";import{T,De,Ae,Ie,Da,Ia}from"../../chunk-hnhjtezs.js";import{createHash as Z,createSign as Q}from"node:crypto";import{createReadStream as U,existsSync as ee,statSync as te}from"node:fs";import{basename as re}from"node:path";import{finished as ie}from"node:stream/promises";var M="https://androidpublisher.googleapis.com",q="https://oauth2.googleapis.com/token";async function Ke(r,i={}){if(!ee(r.bundle)||!r.bundle.endsWith(".aab"))throw Error("Google Play delivery requires an existing signed .aab");if(!Re(r.packageName)||!r.track||!["draft","completed","inProgress"].includes(r.status))throw Error("Google Play requires a package, track and explicit release status");if(r.status==="inProgress"?!(typeof r.userFraction==="number"&&r.userFraction>0&&r.userFraction<1):r.userFraction!==void 0)throw Error("Only an inProgress release requires userFraction between zero and one");let o=JSON.parse(r.serviceAccount);if(o.type!=="service_account"||!o.client_email||!o.private_key)throw Error("A Google Play service account JSON key is required");let a=i.fetch??fetch,c=Math.floor((i.now?.()??Date.now())/1000),n=(b)=>Buffer.from(JSON.stringify(b)).toString("base64url"),u=`${n({alg:"RS256",typ:"JWT"})}.${n({iss:o.client_email,scope:"https://www.googleapis.com/auth/androidpublisher",aud:q,iat:c,exp:c+3600})}`,v=`${u}.${Q("RSA-SHA256").update(u).sign(o.private_key,"base64url")}`,f=await a(q,{method:"POST",body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:v})});if(!f.ok)throw Error(`Google Play authentication failed (${f.status})`);let d=await f.json();if(!d.access_token)throw Error("Google did not return an access token");let l={Authorization:`Bearer ${d.access_token}`,"Content-Type":"application/json"},g=`/androidpublisher/v3/applications/${encodeURIComponent(r.packageName)}/edits`,m=async(b,R,N)=>{let h=await a(`${M}${b}`,{method:R,headers:l,...N!==void 0?{body:JSON.stringify(N)}:{},signal:AbortSignal.timeout(120000)});if(!h.ok)throw Error(`Google Play ${R} failed (${h.status}): ${await h.text()}`);return h.status===204?{}:await h.json()},w=await m(g,"POST",{});if(typeof w.id!=="string"||!w.id)throw Error("Google Play did not return an edit ID");let A=`${g}/${encodeURIComponent(w.id)}`,C=!1;try{let b=Z("sha256");for await(let E of U(r.bundle))b.update(E);let R=b.digest("hex"),N=U(r.bundle),h=ie(N).then(()=>{return},(E)=>E),P;try{P=await a(`${M}/upload${A}/bundles?uploadType=media`,{method:"POST",headers:{Authorization:l.Authorization,"Content-Type":"application/octet-stream","Content-Length":String(te(r.bundle).size)},body:N,duplex:"half",signal:AbortSignal.timeout(120000)})}finally{N.destroy();let E=await h;if(E&&E.code!=="ERR_STREAM_PREMATURE_CLOSE")throw E}if(!P.ok)throw Error(`Google Play bundle upload failed (${P.status}): ${await P.text()}`);let x=await P.json();if(!Number.isSafeInteger(x.versionCode)||x.versionCode<=0||x.sha256?.toLowerCase()!==R)throw Error("Google Play uploaded bundle does not match the local SHA-256 and version code");if(await m(`${A}/tracks/${encodeURIComponent(r.track)}`,"PUT",{track:r.track,releases:[{status:r.status,versionCodes:[String(x.versionCode)],...r.releaseName?{name:r.releaseName}:{},...r.userFraction!==void 0?{userFraction:r.userFraction}:{},...r.releaseNotes?{releaseNotes:r.releaseNotes}:{}}]}),await m(`${A}:validate`,"POST"),!r.validateOnly){if((await m(`${A}:commit?changesInReviewBehavior=ERROR_IF_IN_REVIEW`,"POST")).id!==w.id)throw Error("Google Play commit did not confirm the edit ID");C=!0}return{schemaVersion:1,bundle:re(r.bundle),packageName:r.packageName,track:r.track,status:r.status,versionCode:x.versionCode,sha256:R,editId:w.id,validated:!0,committed:C,completedAt:new Date().toISOString()}}finally{if(!C)await m(A,"DELETE")}}import{chmodSync as ae,existsSync as G,mkdirSync as ne}from"node:fs";import{dirname as oe,resolve as se}from"node:path";import J from"node:process";var ce=String.raw`
|
|
2
2
|
import Foundation
|
|
3
3
|
import Security
|
|
4
4
|
import CryptoKit
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{qe}from"../../chunk-qhf2sgz4.js";import"../../chunk-yg4wxzf8.js";import{t,e,S}from"../../chunk-
|
|
1
|
+
import{qe}from"../../chunk-qhf2sgz4.js";import"../../chunk-yg4wxzf8.js";import{t,e,S}from"../../chunk-xn5c99z0.js";async function se(s,a,o={}){if(!["patch","minor","major"].includes(a.bump))throw Error("Native release bump must be patch, minor or major");let i=o.command??t,r=async(m)=>e("Native release Git check",await i("git",m,{cwd:s})).stdout.trim(),n=await r(["rev-parse","HEAD"]);if(await r(["branch","--show-current"])!=="main")throw Error("Native releases must be cut from main");if(await r(["status","--porcelain","--untracked-files=normal"]))throw Error("Commit native app source before releasing");await S(s,"check",{command:i}),await qe({cwd:s,release:a.bump,expectedSource:n,recursive:!0,commit:!a.dryRun,tag:!a.dryRun,push:!a.dryRun,dryRun:a.dryRun,yes:!0})}export{se as releaseNativeApp};
|
package/package.json
CHANGED
package/dist/chunk-5571vd8y.js
DELETED
package/dist/chunk-y9k1j6rh.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{de}from"./chunk-t965ankb.js";import{Be}from"./chunk-h6wpf5z0.js";import{createHash as H,randomBytes as M,randomInt as N,timingSafeEqual as q}from"node:crypto";import{chmodSync as F,existsSync as T,lstatSync as z,mkdirSync as _,readFileSync as V,renameSync as W,writeFileSync as X}from"node:fs";import{homedir as L}from"node:os";import{isAbsolute as Z,join as h}from"node:path";var P=(r)=>H("sha256").update(r).digest("hex"),Q=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;function G(){return h(process.env.XDG_DATA_HOME||h(L(),".local/share"),"pantry/desktop")}function K(r){_(r,{recursive:!0,mode:448});let n=z(r);if(n.isSymbolicLink()||!n.isDirectory()||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only directory")}function B(r){let n=z(r);if(!n.isFile()||n.isSymbolicLink()||n.nlink!==1||n.size>40000000||process.getuid&&n.uid!==process.getuid()||n.mode&63)throw Error("Pantry Desktop state must be an owner-only file");return JSON.parse(V(r,"utf8"))}function E(r,n){let d=`${r}.${crypto.randomUUID()}.tmp`;X(d,JSON.stringify(n),{mode:384,flag:"wx"}),W(d,r),F(r,384)}function fe(r=G(),n=Date.now()){K(r);let d=String(N(1e7,1e8));return E(h(r,"pairing.json"),{hash:P(d),expiresAt:n+300000}),d}function J(r,n){return/^[a-f0-9]{64}$/.test(r)&&/^[a-f0-9]{64}$/.test(n)&&q(Buffer.from(r,"hex"),Buffer.from(n,"hex"))}function w(r){let{clientId:n,...d}=r;return d}function It(r){if(process.platform!=="darwin")return[];let n=(c)=>c.toLowerCase().replace(/[^a-z0-9]/g,""),d=new Map(r.filter((c)=>c.kind==="app").map((c)=>[n(c.name),c.domain]));return["/Applications",h(L(),"Applications")].flatMap((c)=>de(c)).flatMap((c)=>{let a=d.get(n(c.name));return a?[{name:a,version:c.version,applicationPath:c.path}]:[]})}function zt(r,n,d){let c=new Set(r.filter((i)=>i.kind==="app").map((i)=>i.domain)),a=new Map(n.filter((i)=>!c.has(i.name)).map((i)=>[i.name,{name:i.name,version:i.version}]));for(let i of d)if(i.applicationPath)a.set(i.name,i);return[...a.values()]}function Ye(r={}){let n=r.now??Date.now,d=r.stateDirectory??G();K(d);let c=h(d,"state.json"),a=T(c)?B(c):{clients:[],jobs:[]};if(!Array.isArray(a.clients)||!Array.isArray(a.jobs))throw Error("Invalid Pantry Desktop state");let i=()=>E(c,a);for(let e of a.jobs)if(e.status==="queued"||e.status==="running")e.status="failed",e.error="Pantry restarted before this installation completed. Check installed packages before retrying.",e.finishedAt=new Date(n()).toISOString(),e.timezoneOffset=new Date(n()).getTimezoneOffset();i();let v=r.catalog??Be(),C=r.applications??(()=>It(v)),D=new Map(v.map((e)=>[e.domain,e])),I=r.pantryExecutable??Bun.which("pantry");if(!r.run&&(!I||!Z(I)))throw Error("Install the Pantry CLI before starting its desktop bridge");let S,R=r.run??(async(e,l)=>{let s=Bun.spawn([I,...e],{cwd:d,stdin:"ignore",stdout:"pipe",stderr:"pipe",env:{...process.env,NO_COLOR:"1",CI:"1"}});S=s;let p=async(g)=>{let t=g.getReader(),f=new TextDecoder;try{while(!0){let u=await t.read();if(u.done)break;l(f.decode(u.value,{stream:!0}))}}finally{t.releaseLock()}};try{return await Promise.all([p(s.stdout),p(s.stderr)]),await s.exited}finally{S=void 0}}),x=Promise.resolve(),O=(e,l)=>{let s=x.then(()=>{if(b)throw Error("Pantry Desktop is stopping");return R(e,l)});return x=s.catch(()=>{}),s},k=!1,b=!1,j;async function U(){if(k||b)return;k=!0;try{while(!b){let e=a.jobs.find((s)=>s.status==="queued");if(!e)break;e.status="running",e.startedAt=new Date(n()).toISOString(),i();try{let s=D.get(e.domain).kind,p=await O(["install","--user",...["app","font"].includes(s)?["--kind",s]:[],e.domain],(g)=>{e.output=(e.output+g).slice(-32000)});if(e.status=p===0?"succeeded":"failed",p)e.error=`Pantry installation exited with code ${p}. Expand installation details for the error, then retry.`;if(p===0&&s==="app"&&!C().some((g)=>g.name===e.domain&&g.applicationPath))e.status="failed",e.error="The download completed, but no usable application was found in Applications. Retry installation to install the app bundle."}catch(s){e.status="failed",e.error=s instanceof Error?s.message:"Pantry installation failed"}let l=new Date(n());e.finishedAt=l.toISOString(),e.timezoneOffset=l.getTimezoneOffset(),i()}}finally{k=!1}}let o=(e,l=200)=>Response.json(e,{status:l,headers:{"cache-control":"no-store"}}),y=[],A=Bun.serve({hostname:"127.0.0.1",port:r.port??46473,maxRequestBodySize:4096,async fetch(e){let l=new URL(e.url);if(e.headers.has("origin")||e.headers.get("host")!==`127.0.0.1:${A.port}`)return o({error:"Forbidden origin or host"},403);if(l.pathname==="/health"&&e.method==="GET")return o({protocolVersion:1,service:"pantry-desktop",capabilities:["install:user","installed","jobs"]});if(l.pathname==="/pair"&&e.method==="POST"){while(y.length&&y[0]<n()-60000)y.shift();if(y.length>=10)return o({error:"Too many pairing attempts. Try again in a minute."},429);y.push(n());let t=await e.json().catch(()=>null);if(!t||typeof t.code!=="string"||!/^\d{8}$/.test(t.code)||typeof t.name!=="string"||!t.name.trim()||t.name.length>80)return o({error:"Provide the pairing code and application name."},422);let f=h(d,"pairing.json");if(!T(f))return o({error:"Create a pairing code from the Pantry CLI first."},401);let u=B(f);if(u.expiresAt<=n()||!J(u.hash,P(t.code)))return o({error:"The Pantry pairing code is invalid or expired."},401);if(a.clients.length>=100)return o({error:"Remove unused Pantry Desktop connections before pairing another app."},409);let m=M(32).toString("base64url");return a.clients.push({id:crypto.randomUUID(),name:t.name.trim(),tokenHash:P(m)}),E(f,{hash:"",expiresAt:0}),i(),o({token:m},201)}let s=e.headers.get("authorization")?.match(/^Bearer ([A-Za-z0-9_-]{43})$/)?.[1],p=s?a.clients.find((t)=>J(t.tokenHash,P(s))):void 0;if(!p)return o({error:"Connect this application to Pantry first."},401);if(l.pathname==="/v1/connection"&&e.method==="DELETE")return a.clients=a.clients.filter((t)=>t.id!==p.id),i(),o({disconnected:!0});if(l.pathname==="/v1/installed"&&e.method==="GET"){let t="";if(await O(["list","--format","json"],(u)=>{if(t.length<4000000)t+=u}))return o({error:"Pantry could not list installed packages."},502);try{let u=JSON.parse(t);if(!Array.isArray(u)||u.some((m)=>typeof m.name!=="string"||typeof m.version!=="string"))throw Error("Invalid installed package list");return o({packages:zt(v,u,C())})}catch{return o({error:"Pantry returned an invalid installed package list."},502)}}if(l.pathname==="/v1/install"&&e.method==="POST"){let t=await e.json().catch(()=>null);if(!t||typeof t.domain!=="string"||!D.has(t.domain)||typeof t.requestId!=="string"||!Q.test(t.requestId))return o({error:"Choose a package from the Pantry catalog and provide a request ID."},422);let f=a.jobs.find((m)=>m.clientId===p.id&&m.requestId===t.requestId);if(f)return f.domain===t.domain?o({job:w(f)},202):o({error:"This request ID already belongs to another package."},409);if(a.jobs.filter((m)=>m.status==="queued"||m.status==="running").length>=3)return o({error:"Wait for current Pantry installations to finish."},429);let u={id:crypto.randomUUID(),requestId:t.requestId,clientId:p.id,domain:t.domain,kind:D.get(t.domain).kind,status:"queued",output:"",createdAt:new Date(n()).toISOString()};if(a.jobs.push(u),a.jobs.length>1000)a.jobs.splice(0,a.jobs.length-1000);if(i(),!k)j=U();return o({job:w(u)},202)}if(l.pathname==="/v1/jobs"&&e.method==="GET")return o({jobs:a.jobs.filter((t)=>t.clientId===p.id).slice(-50).reverse().map(w)});let g=l.pathname.match(/^\/v1\/jobs\/([a-f0-9-]{36})$/i);if(g&&e.method==="GET"){let t=a.jobs.find((f)=>f.id===g[1]&&f.clientId===p.id);return t?o({job:w(t)}):o({error:"Pantry installation was not found."},404)}return o({error:"Not found"},404)},error(){return o({error:"Pantry Desktop could not complete this request."},500)}});return{server:A,async close(){b=!0,S?.kill(),await j,await x,await A.stop(!0)}}}
|
|
2
|
-
export{G,K,fe,It,zt,Ye};
|