@absolutejs/absolute 0.20.0-beta.43 → 0.20.0-beta.45

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.
Files changed (77) hide show
  1. package/dist/angular/browser.js +378 -361
  2. package/dist/angular/browser.js.map +2 -2
  3. package/dist/angular/components/core/streamingSlotRegistrar.js +7 -7
  4. package/dist/angular/components/core/streamingSlotRegistry.js +4 -4
  5. package/dist/angular/index.js +300 -294
  6. package/dist/angular/index.js.map +2 -2
  7. package/dist/angular/server.js +54 -50
  8. package/dist/angular/server.js.map +2 -2
  9. package/dist/build.js +201 -204
  10. package/dist/build.js.map +3 -3
  11. package/dist/cli/config/client.js +12 -12
  12. package/dist/cli/config/server.js +1096 -1090
  13. package/dist/cli/index.js +1573 -1297
  14. package/dist/client/index.js +29 -25
  15. package/dist/client/index.js.map +2 -2
  16. package/dist/core/streamingSlotRegistrar.js +15 -13
  17. package/dist/core/streamingSlotRegistrar.js.map +2 -2
  18. package/dist/core/streamingSlotRegistry.js +11 -9
  19. package/dist/core/streamingSlotRegistry.js.map +2 -2
  20. package/dist/image-client/imageClient.js +7 -7
  21. package/dist/index.js +810 -733
  22. package/dist/index.js.map +7 -6
  23. package/dist/islands/browser.js +11 -9
  24. package/dist/islands/browser.js.map +2 -2
  25. package/dist/islands/index.js +39 -35
  26. package/dist/islands/index.js.map +2 -2
  27. package/dist/mobile/browser.js +23 -22
  28. package/dist/mobile/browser.js.map +3 -3
  29. package/dist/mobile/index.js +739 -426
  30. package/dist/mobile/index.js.map +11 -11
  31. package/dist/mobile/remoteMacAgentEntry.js +227 -37
  32. package/dist/mobile/shellBootstrap.js +0 -1
  33. package/dist/mobile/shellExpoAuth.js +184 -0
  34. package/dist/mobile/shellExpoDevices.js +4 -5
  35. package/dist/mobile/shellExpoSync.js +104 -0
  36. package/dist/mobile/shellSync.js +4 -4
  37. package/dist/react/browser.js +17 -15
  38. package/dist/react/browser.js.map +2 -2
  39. package/dist/react/components/browser/index.js +107 -107
  40. package/dist/react/components/index.js +118 -116
  41. package/dist/react/components/index.js.map +2 -2
  42. package/dist/react/hooks/index.js +11 -9
  43. package/dist/react/hooks/index.js.map +2 -2
  44. package/dist/react/index.js +53 -49
  45. package/dist/react/index.js.map +2 -2
  46. package/dist/react/jsxDevRuntimeCompat.js +11 -9
  47. package/dist/react/jsxDevRuntimeCompat.js.map +2 -2
  48. package/dist/react/jsxRuntimeCompat.js +11 -9
  49. package/dist/react/jsxRuntimeCompat.js.map +2 -2
  50. package/dist/react/router/browser.js +9 -7
  51. package/dist/react/router/browser.js.map +2 -2
  52. package/dist/react/router/index.js +9 -7
  53. package/dist/react/router/index.js.map +2 -2
  54. package/dist/react/server.js +12 -10
  55. package/dist/react/server.js.map +2 -2
  56. package/dist/src/mobile/devDeviceAdapter.d.ts +1 -1
  57. package/dist/src/mobile/expoBridge.d.ts +12 -12
  58. package/dist/src/mobile/nativeAuth.d.ts +6 -0
  59. package/dist/src/mobile/shellExpoAuth.d.ts +12 -0
  60. package/dist/src/mobile/shellExpoSync.d.ts +18 -0
  61. package/dist/svelte/browser.js +12 -10
  62. package/dist/svelte/browser.js.map +2 -2
  63. package/dist/svelte/index.js +47 -43
  64. package/dist/svelte/index.js.map +2 -2
  65. package/dist/svelte/server.js +29 -27
  66. package/dist/svelte/server.js.map +2 -2
  67. package/dist/vue/browser.js +14 -12
  68. package/dist/vue/browser.js.map +2 -2
  69. package/dist/vue/components/Image.js +9 -7
  70. package/dist/vue/components/Image.js.map +2 -2
  71. package/dist/vue/components/index.js +11 -9
  72. package/dist/vue/components/index.js.map +2 -2
  73. package/dist/vue/index.js +52 -48
  74. package/dist/vue/index.js.map +2 -2
  75. package/dist/vue/server.js +14 -12
  76. package/dist/vue/server.js.map +2 -2
  77. package/package.json +3 -2
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{mkdir as ks,readFile as Rs,rm as Ie,writeFile as Cs}from"fs/promises";import{join as ue}from"path";import{createInterface as $r}from"readline";import{resolve as Ue}from"path";var Tr=/^[A-Za-z][\w]*(?:\.[A-Za-z][\w]*)+$/,mr=/^[a-z][a-z0-9+.-]*$/,Dr=/^[A-Z0-9]{10}$/,Nr=/^[0-9A-F]{64}$/,Ir=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/,ee=(e,r,a)=>{let s=Ue(e),c=Ue(s,r);if(c!==s&&!c.startsWith(`${s}/`))throw TypeError(`${a} must remain inside the project root.`);return c},W=(e,r)=>{let a=e.trim();if(!a)throw TypeError(`${r} must not be empty.`);return a},Be=(e)=>{let r=W(e??"/","mobile.entry");if(!r.startsWith("/")||r.startsWith("//"))throw TypeError("mobile.entry must be an absolute application path.");return r},Mr=(e)=>{let r=new URL(W(e,"mobile.server.productionOrigin")),a=r.protocol==="http:"&&(r.hostname==="localhost"||r.hostname==="127.0.0.1"||r.hostname==="[::1]");if(r.protocol!=="https:"&&!a)throw TypeError("mobile.server.productionOrigin must use HTTPS, except for a loopback development origin.");if(r.username||r.password||r.pathname!=="/"||r.search||r.hash)throw TypeError("mobile.server.productionOrigin must be an origin without credentials, path, query, or hash.");return r.origin},kr=(e)=>{let r=[...new Set(e??["ios","android"])];if(r.length===0)throw TypeError("mobile.platforms must contain at least one platform.");return r},Rr=(e,r)=>{let a=(l)=>{let t=W(l,"mobile.deepLinks.hosts").toLowerCase();if(!Ir.test(t))throw TypeError("mobile.deepLinks.hosts entries must be valid hostnames without ports, wildcards, or paths.");return t},s=new URL(r).hostname,c=new Set(s==="[::1]"?[]:[a(s)]);for(let l of e??[])c.add(a(l));return[...c].sort()},Cr=(e)=>{if(e===void 0)return;let r=W(e,"mobile.deepLinks.apple.appIdPrefix").toUpperCase();if(!Dr.test(r))throw TypeError("mobile.deepLinks.apple.appIdPrefix must contain ten letters or digits.");return r},Wr=(e)=>{if(e===void 0)return;let r=W(e,"mobile.ios.version");if(!/^\d+(?:\.\d+){0,2}$/u.test(r))throw TypeError("mobile.ios.version must contain one to three dot-separated integer components, for example 1.4.0.");return r},Ur=(e)=>[...new Set((e??[]).map((r)=>W(r,"mobile.deepLinks.android.sha256CertificateFingerprints").replaceAll(":","").toUpperCase()).map((r)=>{if(!Nr.test(r))throw TypeError("mobile.deepLinks.android.sha256CertificateFingerprints entries must be SHA-256 certificate fingerprints.");return r.match(/.{2}/g)?.join(":")??r}))].sort(),Br=(e,r)=>{if(e.engine!=="expo")return{};let a=e.routes?.native??{},s={};for(let[c,l]of Object.entries(a)){let t=Be(c);if(t.includes("?")||t.includes("#")||t!=="/"&&t.endsWith("/"))throw TypeError(`mobile.routes.native route ${t} must be a canonical path without a query, fragment, or trailing slash.`);if(t==="/__absolute/native")throw TypeError("mobile.routes.native reserves /__absolute/native for the Expo diagnostic screen.");if(t.includes("*")||t.includes(":"))throw TypeError(`mobile.routes.native route ${t} must be static during the Expo experiment; parameters and wildcards are not supported yet.`);s[t]=ee(r,W(l,`mobile.routes.native[${t}]`),`mobile.routes.native[${t}]`)}return Object.fromEntries(Object.entries(s).sort(([c],[l])=>c.localeCompare(l)))},Je=(e,r)=>{let a=W(e.appId,"mobile.appId");if(!Tr.test(a))throw TypeError("mobile.appId must use reverse-domain notation, for example com.example.app.");let s=Mr(e.server.productionOrigin),c=(e.deepLinks?.scheme??a).trim().toLowerCase();if(c&&!mr.test(c))throw TypeError("mobile.deepLinks.scheme is not a valid URL scheme.");return{androidCertificateFingerprints:Ur(e.deepLinks?.android?.sha256CertificateFingerprints),appId:a,appleAppIdPrefix:Cr(e.deepLinks?.apple?.appIdPrefix),appName:W(e.appName,"mobile.appName"),bundleDirectory:ee(r,e.bundleDirectory??".absolutejs/mobile/web","mobile.bundleDirectory"),deepLinkHosts:Rr(e.deepLinks?.hosts,s),deepLinkScheme:c,engine:e.engine??"capacitor",entry:Be(e.entry),expoNativeRoutes:Br(e,r),...e.engine==="expo"?{expoSdkVersion:e.expo?.sdkVersion??57}:{},iosVersion:Wr(e.ios?.version),nativeProjectDirectory:ee(r,e.nativeProject?.directory??(e.engine==="expo"?".absolutejs/mobile/expo":"mobile"),"mobile.nativeProject.directory"),platforms:kr(e.platforms),productionOrigin:s,pushAndroidGoogleServicesFile:ee(r,e.pushNotifications?.android?.googleServicesFile??"google-services.json","mobile.pushNotifications.android.googleServicesFile")}};import{spawn as Pr}from"child_process";import{access as Yr}from"fs/promises";import{join as qr}from"path";import{randomUUID as Jr,X509Certificate as Hr}from"crypto";import{createServer as Lr}from"http";import{connect as Vr,createServer as He,isIP as Gr}from"net";import{readFile as Fr}from"fs/promises";var Ae=(e)=>new Promise((r,a)=>{e.close((s)=>{if(s)a(s);else r()})}),Le=(e,r)=>new Promise((a,s)=>{e.once("error",s),e.listen(r,"0.0.0.0",()=>{e.off("error",s);let c=e.address();if(!c||typeof c==="string"){s(Error("Could not determine the iOS device helper port."));return}a(c.port)})}),Xr=async()=>{let e=He(),r=await new Promise((a,s)=>{e.once("error",s),e.listen(0,"127.0.0.1",()=>{let c=e.address();if(!c||typeof c==="string"){s(Error("Could not allocate the iOS CA enrollment port."));return}a(c.port)})});return await Ae(e),r},ye=(e)=>{let r=e.trim();if(!r||r.length>253||/[\0\s/?#]/u.test(r))throw TypeError("Physical iOS development requires a valid LAN host.");return r},Ve=(e)=>{let r=e.trim();if(!r||r.length>256||/[\0\r\n]/u.test(r))throw TypeError("--ios-device requires a valid Xcode device identifier or name.");return r},Kr=(e,r,a)=>{let s=new URL(`${e}://localhost:${a}`),c=ye(r);return s.hostname=Gr(c)===6?`[${c}]`:c,s},re=async(e)=>{let a=new Hr(await Fr(e.certificateAuthorityPath)).raw,c=`/${Jr().replaceAll("-","")}/absolutejs-development-ca.cer`,l=Lr((w,b)=>{if(w.method!=="GET"||w.url!==c){b.writeHead(404,{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}),b.end("Not found.");return}b.writeHead(200,{"Cache-Control":"no-store","Content-Disposition":'attachment; filename="absolutejs-development-ca.cer"',"Content-Length":String(a.byteLength),"Content-Type":"application/x-x509-ca-cert","X-Content-Type-Options":"nosniff"}),b.end(a)}),t=await Xr();await Le(l,t);let u=Kr("http",e.displayHost,t);return u.pathname=c,{url:u.href,close:()=>Ae(l)}},ae=async(e)=>{let r=He((a)=>{let s=Vr({host:"127.0.0.1",port:e.targetPort});a.pipe(s),s.pipe(a);let c=()=>{a.destroy(),s.destroy()};a.once("error",c),s.once("error",c)});return await Le(r,e.listenPort),{close:()=>Ae(r)}};var Zr=60000,Qr=2000,zr=(e)=>({ABSOLUTE_EXPO_DEVELOPMENT:"1",...e.certificateAuthorityPath?{ABSOLUTE_EXPO_DEVELOPMENT_CA_PATH:e.certificateAuthorityPath}:{},...e.androidOrigin?{EXPO_PUBLIC_ABSOLUTE_DEV_ANDROID_ORIGIN:e.androidOrigin}:{},...e.iosOrigin?{EXPO_PUBLIC_ABSOLUTE_DEV_IOS_ORIGIN:e.iosOrigin}:{},...e.metroHost?{REACT_NATIVE_PACKAGER_HOSTNAME:e.metroHost}:{}}),ge=async(e)=>{let r=qr(e,"node_modules",".bin","expo");try{return await Yr(r),r}catch{throw TypeError("Expo dependencies are not installed in the generated shell. Run `absolute mobile init --yes`.")}},ir=(e,r)=>{if(e.engine!=="expo")throw TypeError("The Expo development controller requires Expo.");if(r.platforms.length===0&&r.metro==="external")throw TypeError("External Expo execution requires a target platform.");if([r.androidOrigin,r.iosOrigin].some((u)=>u&&new URL(u).protocol==="https:")&&!r.certificateAuthorityPath)throw TypeError("Expo HTTPS development requires the AbsoluteJS development CA certificate.");let s=zr(r),c={args:["start","--dev-client","--host","localhost","--port",String(r.metroPort)],env:s,role:"metro"},l=r.platforms.length===0?void 0:{args:["prebuild","--clean","--no-install","--platform",r.platforms.length===2?"all":r.platforms[0]??"all"],env:s,role:"native-prepare"},t=r.platforms.map((u)=>{let w=u==="android"?r.androidDevice:r.iosDevice;return{args:[`run:${u}`,"--no-bundler","--port",String(r.metroPort),...w?["--device",w]:[]],env:s,platform:u,role:"native-build"}});return{commands:[...l?[l]:[],...r.metro==="external"?[]:[c],...t],metroPort:r.metroPort,project:e.nativeProjectDirectory}},q=()=>new DOMException("Expo development aborted.","AbortError"),se=(e,r)=>{let a=(s)=>{if(!s)return;let c="";s.on("data",(l)=>{c+=l.toString("utf8");let t=c.indexOf(`
3
- `);while(t>=0)r(c.slice(0,t).replace(/\r$/u,"")),c=c.slice(t+1),t=c.indexOf(`
4
- `)}),s.on("end",()=>{if(c)r(c)})};a(e.stdout),a(e.stderr)},X=async(e)=>{if(e.exitCode!==null||e.killed)return;if(e.kill("SIGTERM"),await Promise.race([new Promise((r)=>e.once("exit",()=>r())),new Promise((r)=>setTimeout(r,Qr))]),e.exitCode===null)e.kill("SIGKILL")},Se=(e)=>new Promise((r)=>{if(e.exitCode!==null){r(e.exitCode);return}e.once("exit",(a)=>r(a??1))}),xe=async(e,r,a,s)=>{let c=e(r,a,{cwd:s.cwd,env:process.env,stdio:["ignore","pipe","pipe"]});se(c,s.log);let l=()=>void X(c);s.signal?.addEventListener("abort",l,{once:!0});let t=await Se(c);if(s.signal?.removeEventListener("abort",l),s.signal?.aborted)throw q();return t},Ge=async(e)=>{let r=ir(e.config,e),a=e.executable??await ge(r.project),s=e.spawnProcess??Pr,c=e.log??(()=>{return}),l={},t=null,u=async()=>{let d=t;t=null,await d?.close()},w=(d,E)=>{l[d]=(l[d]??0)+E,e.onPhaseTiming?.({durationMs:E,phase:d})},b=(d)=>{e.onStateChange?.(d)};if(e.signal?.aborted)throw q();let x=r.commands.find((d)=>d.role==="native-prepare"),A=r.commands.find((d)=>d.role==="metro"),f=r.commands.filter((d)=>d.role==="native-build"),O=async(d)=>{b("preparing-native");let E=performance.now(),m=s(a,d.args,{cwd:r.project,env:{...process.env,...d.env},stdio:["ignore","pipe","pipe"]});se(m,(U)=>{if(U)c(`[prebuild] ${U}`)});let M=()=>void X(m);e.signal?.addEventListener("abort",M,{once:!0});let N=await Se(m);if(e.signal?.removeEventListener("abort",M),e.signal?.aborted)throw q();if(N!==0)throw b("failed"),Error(`Expo native preparation exited with status ${N}.`);w("preparing-native",performance.now()-E)};if(x)await O(x);let n=A!==void 0;if(n)b("starting-metro");let y=performance.now(),S=A?s(a,A.args,{cwd:r.project,env:{...process.env,...A.env},stdio:["ignore","pipe","pipe"]}):void 0,D=!1,h,g=new Promise((d,E)=>{if(!S){d();return}let m=setTimeout(()=>{E(Error("Expo Metro did not become ready within 60 seconds."))},Zr);h=()=>{clearTimeout(m),d()},S.once("exit",(M)=>{if(!D)clearTimeout(m),E(Error(`Expo Metro exited with status ${M??1}.`))})});if(S)se(S,(d)=>{if(d)c(`[metro] ${d}`);if(!D&&/(?:Waiting on|Metro waiting on|Dev server ready)/iu.test(d))D=!0,h?.()});let C=()=>{if(S)X(S)};e.signal?.addEventListener("abort",C,{once:!0});let F=async(d)=>{if(e.signal?.aborted)throw q();let{platform:E}=d;if(!E)throw TypeError("Expo native build command is missing a platform.");let m=E==="android"?"building-android":"building-ios";b(m);let M=performance.now(),N=s(a,d.args,{cwd:r.project,env:{...process.env,...d.env},stdio:["ignore","pipe","pipe"]});se(N,(p)=>{if(p)c(`[${E}] ${p}`)});let U=()=>void X(N);e.signal?.addEventListener("abort",U,{once:!0});let B=await Se(N);if(e.signal?.removeEventListener("abort",U),e.signal?.aborted)throw q();if(B!==0)throw Error(`Expo ${E} development build exited with status ${B}.`);if(E==="ios"&&e.certificateAuthorityPath&&e.iosOrigin&&new URL(e.iosOrigin).protocol==="https:"&&!e.iosDevice){b("enrolling-trust");let p=performance.now(),fe={cwd:r.project,signal:e.signal,log:(We)=>We&&c(`[ios-trust] ${We}`)},Re=await xe(s,"xcrun",["simctl","keychain","booted","add-root-cert",e.certificateAuthorityPath],fe);if(Re!==0)throw Error(`Expo iOS Simulator development CA trust exited with status ${Re}.`);await xe(s,"xcrun",["simctl","terminate","booted",e.config.appId],fe);let Ce=await xe(s,"xcrun",["simctl","launch","booted",e.config.appId],fe);if(Ce!==0)throw Error(`Expo iOS Simulator relaunch exited with status ${Ce}.`);c("Installed the AbsoluteJS development CA into the Expo iOS Simulator and relaunched the app."),w("enrolling-trust",performance.now()-p)}let H=performance.now()-M;l[m]=H,e.onPhaseTiming?.({durationMs:H,phase:m})},o=async(d)=>{let[E,...m]=d;if(!E)return;await F(E),await o(m)},ne=async()=>{if(!e.iosDevice||!e.certificateAuthorityPath||!e.iosOrigin||new URL(e.iosOrigin).protocol!=="https:")return;b("enrolling-trust");let d=performance.now();t=await(e.startCaEnrollmentServer??re)({certificateAuthorityPath:e.certificateAuthorityPath,displayHost:new URL(e.iosOrigin).hostname}),c(`On the iOS device, open ${t.url}, install the AbsoluteJS development CA profile, then enable it under Settings > General > About > Certificate Trust Settings. This public CA endpoint exists only for this dev session.`),w("enrolling-trust",performance.now()-d)};try{if(await ne(),await g,n)w("starting-metro",performance.now()-y);return await o(f),b("ready"),{metroPort:r.metroPort,platforms:e.platforms,timings:l,close:async()=>{if(e.signal?.removeEventListener("abort",C),S)await X(S);await u(),b("closed")}}}catch(d){if(e.signal?.removeEventListener("abort",C),S)await X(S);throw await u(),b("failed"),d}};import{access as vr,cp as vs,mkdir as Fe,mkdtemp as js,readdir as jr,readFile as or,rename as pr,rm as os,writeFile as Xe}from"fs/promises";import{basename as ec,dirname as Ke,join as _,relative as ea,resolve as ra}from"path";var I=`// Generated by AbsoluteJS. Edit absolute.config.ts, then run absolute mobile sync.
5
- `;var aa=".absolutejs-expo-project",Z=async(e)=>{try{return await vr(e),!0}catch{return!1}},Pe=(e,r)=>{let a=ea(e,r).replaceAll("\\","/");return a.startsWith(".")?a:`./${a}`},sa=(e)=>e.split("/").filter(Boolean).map((r)=>{if(r.startsWith(":"))return`[${r.slice(1)}]`;if(r==="."||r===".."||!/^[A-Za-z0-9._~-]+$/u.test(r))throw TypeError(`Expo native route ${e} contains an unsupported segment ${r}.`);return r}),ca=(e,r)=>_(e,"app",...sa(r),"index.tsx"),la=()=>({dependencies:{expo:"~57.0.9","expo-asset":"~57.0.15","expo-constants":"~57.0.16","expo-dev-client":"~57.0.16","expo-file-system":"~57.0.6","expo-haptics":"~57.0.2","expo-linking":"~57.0.8","expo-router":"~57.0.17",react:"19.2.3","react-native":"0.86.3","react-native-safe-area-context":"~5.7.0","react-native-screens":"4.26.0","react-native-webview":"13.16.1"},devDependencies:{"@types/react":"~19.2.2",typescript:"~6.0.3"},main:"expo-router/entry",name:"absolutejs-expo-shell",private:!0,scripts:{android:"expo run:android",ios:"expo run:ios",start:"expo start --dev-client"},version:"0.0.0"}),ta=(e)=>({expo:{android:{intentFilters:e.deepLinkHosts.map((r)=>({action:"VIEW",autoVerify:!0,category:["BROWSABLE","DEFAULT"],data:[{host:r,pathPrefix:"/",scheme:"https"}]})),package:e.appId},experiments:{typedRoutes:!0},ios:{associatedDomains:e.deepLinkHosts.map((r)=>`applinks:${r}`),bundleIdentifier:e.appId,...e.iosVersion?{buildNumber:e.iosVersion}:{}},name:e.appName,plugins:["expo-router",["expo-dev-client",{launchMode:"most-recent"}]],runtimeVersion:{policy:"appVersion"},scheme:e.deepLinkScheme,slug:e.appId.toLowerCase().replaceAll(".","-"),version:e.iosVersion??"0.1.0"}}),wa=`${I}const config = require('./app.json');
2
+ import{mkdir as Co,readFile as Do,rm as Ue,writeFile as Ro}from"fs/promises";import{join as ve}from"path";import{createInterface as en}from"readline";import{resolve as We}from"path";var nn=/^[A-Za-z][\w]*(?:\.[A-Za-z][\w]*)+$/,rn=/^[a-z][a-z0-9+.-]*$/,on=/^[A-Z0-9]{10}$/,sn=/^[0-9A-F]{64}$/,an=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/,de=(e,t,n)=>{let r=We(e),o=We(r,t);if(o!==r&&!o.startsWith(`${r}/`))throw TypeError(`${n} must remain inside the project root.`);return o},U=(e,t)=>{let n=e.trim();if(!n)throw TypeError(`${t} must not be empty.`);return n},qe=(e)=>{let t=U(e??"/","mobile.entry");if(!t.startsWith("/")||t.startsWith("//"))throw TypeError("mobile.entry must be an absolute application path.");return t},cn=(e)=>{let t=new URL(U(e,"mobile.server.productionOrigin")),n=t.protocol==="http:"&&(t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]");if(t.protocol!=="https:"&&!n)throw TypeError("mobile.server.productionOrigin must use HTTPS, except for a loopback development origin.");if(t.username||t.password||t.pathname!=="/"||t.search||t.hash)throw TypeError("mobile.server.productionOrigin must be an origin without credentials, path, query, or hash.");return t.origin},ln=(e)=>{let t=[...new Set(e??["ios","android"])];if(t.length===0)throw TypeError("mobile.platforms must contain at least one platform.");return t},dn=(e,t)=>{let n=(s)=>{let i=U(s,"mobile.deepLinks.hosts").toLowerCase();if(!an.test(i))throw TypeError("mobile.deepLinks.hosts entries must be valid hostnames without ports, wildcards, or paths.");return i},r=new URL(t).hostname,o=new Set(r==="[::1]"?[]:[n(r)]);for(let s of e??[])o.add(n(s));return[...o].sort()},un=(e)=>{if(e===void 0)return;let t=U(e,"mobile.deepLinks.apple.appIdPrefix").toUpperCase();if(!on.test(t))throw TypeError("mobile.deepLinks.apple.appIdPrefix must contain ten letters or digits.");return t},pn=(e)=>{if(e===void 0)return;let t=U(e,"mobile.ios.version");if(!/^\d+(?:\.\d+){0,2}$/u.test(t))throw TypeError("mobile.ios.version must contain one to three dot-separated integer components, for example 1.4.0.");return t},mn=(e)=>[...new Set((e??[]).map((t)=>U(t,"mobile.deepLinks.android.sha256CertificateFingerprints").replaceAll(":","").toUpperCase()).map((t)=>{if(!sn.test(t))throw TypeError("mobile.deepLinks.android.sha256CertificateFingerprints entries must be SHA-256 certificate fingerprints.");return t.match(/.{2}/g)?.join(":")??t}))].sort(),fn=(e,t)=>{if(e.engine!=="expo")return{};let n=e.routes?.native??{},r={};for(let[o,s]of Object.entries(n)){let i=qe(o);if(i.includes("?")||i.includes("#")||i!=="/"&&i.endsWith("/"))throw TypeError(`mobile.routes.native route ${i} must be a canonical path without a query, fragment, or trailing slash.`);if(i==="/__absolute/native")throw TypeError("mobile.routes.native reserves /__absolute/native for the Expo diagnostic screen.");if(i.includes("*")||i.includes(":"))throw TypeError(`mobile.routes.native route ${i} must be static during the Expo experiment; parameters and wildcards are not supported yet.`);r[i]=de(t,U(s,`mobile.routes.native[${i}]`),`mobile.routes.native[${i}]`)}return Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s)))},Ge=(e,t)=>{let n=U(e.appId,"mobile.appId");if(!nn.test(n))throw TypeError("mobile.appId must use reverse-domain notation, for example com.example.app.");let r=cn(e.server.productionOrigin),o=(e.deepLinks?.scheme??n).trim().toLowerCase();if(o&&!rn.test(o))throw TypeError("mobile.deepLinks.scheme is not a valid URL scheme.");return{androidCertificateFingerprints:mn(e.deepLinks?.android?.sha256CertificateFingerprints),appId:n,appleAppIdPrefix:un(e.deepLinks?.apple?.appIdPrefix),appName:U(e.appName,"mobile.appName"),bundleDirectory:de(t,e.bundleDirectory??".absolutejs/mobile/web","mobile.bundleDirectory"),deepLinkHosts:dn(e.deepLinks?.hosts,r),deepLinkScheme:o,engine:e.engine??"capacitor",entry:qe(e.entry),expoNativeRoutes:fn(e,t),...e.engine==="expo"?{expoSdkVersion:e.expo?.sdkVersion??57}:{},iosVersion:pn(e.ios?.version),nativeProjectDirectory:de(t,e.nativeProject?.directory??(e.engine==="expo"?".absolutejs/mobile/expo":"mobile"),"mobile.nativeProject.directory"),platforms:ln(e.platforms),productionOrigin:r,pushAndroidGoogleServicesFile:de(t,e.pushNotifications?.android?.googleServicesFile??"google-services.json","mobile.pushNotifications.android.googleServicesFile")}};import{spawn as En}from"child_process";import{access as xn}from"fs/promises";import{join as In}from"path";import{randomUUID as gn,X509Certificate as hn}from"crypto";import{createServer as yn}from"http";import{connect as bn,createServer as ze,isIP as wn}from"net";import{readFile as vn}from"fs/promises";var Ee=(e)=>new Promise((t,n)=>{e.close((r)=>{if(r)n(r);else t()})}),Ke=(e,t)=>new Promise((n,r)=>{e.once("error",r),e.listen(t,"0.0.0.0",()=>{e.off("error",r);let o=e.address();if(!o||typeof o==="string"){r(Error("Could not determine the iOS device helper port."));return}n(o.port)})}),An=async()=>{let e=ze(),t=await new Promise((n,r)=>{e.once("error",r),e.listen(0,"127.0.0.1",()=>{let o=e.address();if(!o||typeof o==="string"){r(Error("Could not allocate the iOS CA enrollment port."));return}n(o.port)})});return await Ee(e),t},xe=(e)=>{let t=e.trim();if(!t||t.length>253||/[\0\s/?#]/u.test(t))throw TypeError("Physical iOS development requires a valid LAN host.");return t},Xe=(e)=>{let t=e.trim();if(!t||t.length>256||/[\0\r\n]/u.test(t))throw TypeError("--ios-device requires a valid Xcode device identifier or name.");return t},Sn=(e,t,n)=>{let r=new URL(`${e}://localhost:${n}`),o=xe(t);return r.hostname=wn(o)===6?`[${o}]`:o,r},ue=async(e)=>{let n=new hn(await vn(e.certificateAuthorityPath)).raw,o=`/${gn().replaceAll("-","")}/absolutejs-development-ca.cer`,s=yn((a,c)=>{if(a.method!=="GET"||a.url!==o){c.writeHead(404,{"Cache-Control":"no-store","Content-Type":"text/plain; charset=utf-8"}),c.end("Not found.");return}c.writeHead(200,{"Cache-Control":"no-store","Content-Disposition":'attachment; filename="absolutejs-development-ca.cer"',"Content-Length":String(n.byteLength),"Content-Type":"application/x-x509-ca-cert","X-Content-Type-Options":"nosniff"}),c.end(n)}),i=await An();await Ke(s,i);let l=Sn("http",e.displayHost,i);return l.pathname=o,{url:l.href,close:()=>Ee(s)}},pe=async(e)=>{let t=ze((n)=>{let r=bn({host:"127.0.0.1",port:e.targetPort});n.pipe(r),r.pipe(n);let o=()=>{n.destroy(),r.destroy()};n.once("error",o),r.once("error",o)});return await Ke(t,e.listenPort),{close:()=>Ee(t)}};var On=60000,_n=2000,Tn=(e)=>({ABSOLUTE_EXPO_DEVELOPMENT:"1",...e.certificateAuthorityPath?{ABSOLUTE_EXPO_DEVELOPMENT_CA_PATH:e.certificateAuthorityPath}:{},...e.androidOrigin?{EXPO_PUBLIC_ABSOLUTE_DEV_ANDROID_ORIGIN:e.androidOrigin}:{},...e.iosOrigin?{EXPO_PUBLIC_ABSOLUTE_DEV_IOS_ORIGIN:e.iosOrigin}:{},...e.metroHost?{REACT_NATIVE_PACKAGER_HOSTNAME:e.metroHost}:{}}),_e=async(e)=>{let t=In(e,"node_modules",".bin","expo");try{return await xn(t),t}catch{throw TypeError("Expo dependencies are not installed in the generated shell. Run `absolute mobile init --yes`.")}},Pn=(e,t)=>{if(e.engine!=="expo")throw TypeError("The Expo development controller requires Expo.");if(t.platforms.length===0&&t.metro==="external")throw TypeError("External Expo execution requires a target platform.");if([t.androidOrigin,t.iosOrigin].some((l)=>l&&new URL(l).protocol==="https:")&&!t.certificateAuthorityPath)throw TypeError("Expo HTTPS development requires the AbsoluteJS development CA certificate.");let r=Tn(t),o={args:["start","--dev-client","--host","localhost","--port",String(t.metroPort)],env:r,role:"metro"},s=t.platforms.length===0?void 0:{args:["prebuild","--clean","--no-install","--platform",t.platforms.length===2?"all":t.platforms[0]??"all"],env:r,role:"native-prepare"},i=t.platforms.map((l)=>{let a=l==="android"?t.androidDevice:t.iosDevice;return{args:[`run:${l}`,"--no-bundler","--port",String(t.metroPort),...a?["--device",a]:[]],env:r,platform:l,role:"native-build"}});return{commands:[...s?[s]:[],...t.metro==="external"?[]:[o],...i],metroPort:t.metroPort,project:e.nativeProjectDirectory}},ne=()=>new DOMException("Expo development aborted.","AbortError"),me=(e,t)=>{let n=(r)=>{if(!r)return;let o="";r.on("data",(s)=>{o+=s.toString("utf8");let i=o.indexOf(`
3
+ `);while(i>=0)t(o.slice(0,i).replace(/\r$/u,"")),o=o.slice(i+1),i=o.indexOf(`
4
+ `)}),r.on("end",()=>{if(o)t(o)})};n(e.stdout),n(e.stderr)},K=async(e)=>{if(e.exitCode!==null||e.killed)return;if(e.kill("SIGTERM"),await Promise.race([new Promise((t)=>e.once("exit",()=>t())),new Promise((t)=>setTimeout(t,_n))]),e.exitCode===null)e.kill("SIGKILL")},Oe=(e)=>new Promise((t)=>{if(e.exitCode!==null){t(e.exitCode);return}e.once("exit",(n)=>t(n??1))}),Ie=async(e,t,n,r)=>{let o=e(t,n,{cwd:r.cwd,env:process.env,stdio:["ignore","pipe","pipe"]});me(o,r.log);let s=()=>void K(o);r.signal?.addEventListener("abort",s,{once:!0});let i=await Oe(o);if(r.signal?.removeEventListener("abort",s),r.signal?.aborted)throw ne();return i},Ye=async(e)=>{let t=Pn(e.config,e),n=e.executable??await _e(t.project),r=e.spawnProcess??En,o=e.log??(()=>{return}),s={},i=null,l=async()=>{let m=i;i=null,await m?.close()},a=(m,A)=>{s[m]=(s[m]??0)+A,e.onPhaseTiming?.({durationMs:A,phase:m})},c=(m)=>{e.onStateChange?.(m)};if(e.signal?.aborted)throw ne();let h=t.commands.find((m)=>m.role==="native-prepare"),d=t.commands.find((m)=>m.role==="metro"),u=t.commands.filter((m)=>m.role==="native-build"),S=async(m)=>{c("preparing-native");let A=performance.now(),T=r(n,m.args,{cwd:t.project,env:{...process.env,...m.env},stdio:["ignore","pipe","pipe"]});me(T,(H)=>{if(H)o(`[prebuild] ${H}`)});let N=()=>void K(T);e.signal?.addEventListener("abort",N,{once:!0});let D=await Oe(T);if(e.signal?.removeEventListener("abort",N),e.signal?.aborted)throw ne();if(D!==0)throw c("failed"),Error(`Expo native preparation exited with status ${D}.`);a("preparing-native",performance.now()-A)};if(h)await S(h);let f=d!==void 0;if(f)c("starting-metro");let g=performance.now(),p=d?r(n,d.args,{cwd:t.project,env:{...process.env,...d.env},stdio:["ignore","pipe","pipe"]}):void 0,w=!1,y,b=new Promise((m,A)=>{if(!p){m();return}let T=setTimeout(()=>{A(Error("Expo Metro did not become ready within 60 seconds."))},On);y=()=>{clearTimeout(T),m()},p.once("exit",(N)=>{if(!w)clearTimeout(T),A(Error(`Expo Metro exited with status ${N??1}.`))})});if(p)me(p,(m)=>{if(m)o(`[metro] ${m}`);if(!w&&/(?:Waiting on|Metro waiting on|Dev server ready)/iu.test(m))w=!0,y?.()});let E=()=>{if(p)K(p)};e.signal?.addEventListener("abort",E,{once:!0});let _=async(m)=>{if(e.signal?.aborted)throw ne();let{platform:A}=m;if(!A)throw TypeError("Expo native build command is missing a platform.");let T=A==="android"?"building-android":"building-ios";c(T);let N=performance.now(),D=r(n,m.args,{cwd:t.project,env:{...process.env,...m.env},stdio:["ignore","pipe","pipe"]});me(D,(le)=>{if(le)o(`[${A}] ${le}`)});let H=()=>void K(D);e.signal?.addEventListener("abort",H,{once:!0});let V=await Oe(D);if(e.signal?.removeEventListener("abort",H),e.signal?.aborted)throw ne();if(V!==0)throw Error(`Expo ${A} development build exited with status ${V}.`);if(A==="ios"&&e.certificateAuthorityPath&&e.iosOrigin&&new URL(e.iosOrigin).protocol==="https:"&&!e.iosDevice){c("enrolling-trust");let le=performance.now(),Se={cwd:t.project,signal:e.signal,log:(Je)=>Je&&o(`[ios-trust] ${Je}`)},Ve=await Ie(r,"xcrun",["simctl","keychain","booted","add-root-cert",e.certificateAuthorityPath],Se);if(Ve!==0)throw Error(`Expo iOS Simulator development CA trust exited with status ${Ve}.`);await Ie(r,"xcrun",["simctl","terminate","booted",e.config.appId],Se);let Fe=await Ie(r,"xcrun",["simctl","launch","booted",e.config.appId],Se);if(Fe!==0)throw Error(`Expo iOS Simulator relaunch exited with status ${Fe}.`);o("Installed the AbsoluteJS development CA into the Expo iOS Simulator and relaunched the app."),a("enrolling-trust",performance.now()-le)}let J=performance.now()-N;s[T]=J,e.onPhaseTiming?.({durationMs:J,phase:T})},L=async(m)=>{let[A,...T]=m;if(!A)return;await _(A),await L(T)},j=async()=>{if(!e.iosDevice||!e.certificateAuthorityPath||!e.iosOrigin||new URL(e.iosOrigin).protocol!=="https:")return;c("enrolling-trust");let m=performance.now();i=await(e.startCaEnrollmentServer??ue)({certificateAuthorityPath:e.certificateAuthorityPath,displayHost:new URL(e.iosOrigin).hostname}),o(`On the iOS device, open ${i.url}, install the AbsoluteJS development CA profile, then enable it under Settings > General > About > Certificate Trust Settings. This public CA endpoint exists only for this dev session.`),a("enrolling-trust",performance.now()-m)};try{if(await j(),await b,f)a("starting-metro",performance.now()-g);return await L(u),c("ready"),{metroPort:t.metroPort,platforms:e.platforms,timings:s,close:async()=>{if(e.signal?.removeEventListener("abort",E),p)await K(p);await l(),c("closed")}}}catch(m){if(e.signal?.removeEventListener("abort",E),p)await K(p);throw await l(),c("failed"),m}};import{access as zn,cp as is,mkdir as bt,mkdtemp as as,readdir as Kn,readFile as Xn,rename as Yn,rm as cs,writeFile as wt}from"fs/promises";import{createHash as vt}from"crypto";import{basename as us,dirname as At,join as x,relative as Zn,resolve as Qn}from"path";import{readFileSync as Cn}from"fs";import{join as Dn}from"path";var Rn="@absolutejs/auth",Ze="0.75.6",Qe="@absolutejs/auth-expo",et="0.0.2",tt="2.31.0",nt="@absolutejs/sync-expo",rt="0.0.2";var Nn=["openid","profile"],Mn="@absolutejs/sync",ot=(e)=>{try{return JSON.parse(Cn(Dn(e,"package.json"),"utf8"))}catch{return}},st=(e,t)=>{if(typeof e!=="object"||e===null)return!1;return[Reflect.get(e,"dependencies"),Reflect.get(e,"devDependencies"),Reflect.get(e,"optionalDependencies"),Reflect.get(e,"peerDependencies")].some((n)=>typeof n==="object"&&n!==null&&Object.hasOwn(n,t))},kn=(e)=>{let t=e.deepLinkScheme??e.appId.toLowerCase();return{clientId:`absolutejs-native:${e.appId}`,issuer:e.productionOrigin,redirectUri:`${t}://auth/callback`,scopes:[...Nn]}};var Ln=(e)=>st(ot(e),Rn),it=(e)=>st(ot(e),Mn),at=(e,t)=>Ln(e)?kn(t):void 0;import{readFileSync as Hn}from"fs";import{dirname as Vn,join as gt,resolve as ht}from"path";var ct=Symbol.for("@absolutejs/sync/client-runtime-transport"),lt=globalThis,$n=(e)=>typeof e==="object"&&e!==null&&Array.isArray(Reflect.get(e,"installations"))&&Array.isArray(Reflect.get(e,"clients")),Qo=(()=>{let e=lt[ct];if($n(e))return e;if(typeof e==="object"&&e!==null&&Array.isArray(Reflect.get(e,"installations")))return Reflect.set(e,"clients",[]),e;let t={clients:[],installations:[]};return Object.defineProperty(lt,ct,{configurable:!1,enumerable:!1,value:t,writable:!1}),t})();class R extends Error{code;constructor(e,t){super(t);this.name="SyncLocalDataPolicyError",this.code=e}}class B extends Error{code;storedVersion;targetVersion;constructor(e,t,n={}){super(t);this.name="SyncLocalStoreSchemaError",this.code=e,this.storedVersion=n.storedVersion,this.targetVersion=n.targetVersion}}var fe=(e,t)=>{if(!Number.isSafeInteger(e)||e<1)throw new B("INVALID_PLAN",`${t} must be a positive safe integer`);return e},jn=(e)=>("components"in e),dt=(e,t)=>{if(e.length===0||e.trim()!==e||/^\*+$/.test(e)||e.includes("**"))throw new R("INVALID_POLICY",`${t}.match must be an exact name or a non-empty glob without adjacent wildcards.`)},Un=(e,t="localData")=>{if(e.maxBytesPerNamespace!==void 0&&(!Number.isSafeInteger(e.maxBytesPerNamespace)||e.maxBytesPerNamespace<1))throw new R("INVALID_POLICY",`${t}.maxBytesPerNamespace must be a positive safe integer.`);for(let[n,r]of(e.collections??[]).entries()){if(dt(r.match,`${t}.collections[${n}]`),r.maxAgeMs!==void 0&&(!Number.isSafeInteger(r.maxAgeMs)||r.maxAgeMs<1))throw new R("INVALID_POLICY",`${t}.collections[${n}].maxAgeMs must be a positive safe integer.`);if(r.persistence==="memory-only"&&r.protection==="required")throw new R("INVALID_POLICY",`${t}.collections[${n}] cannot require at-rest protection when it is memory-only.`);if(r.sensitivity!==void 0&&r.sensitivity!=="public"&&r.protection!=="required"&&r.persistence!=="memory-only")throw new R("INVALID_POLICY",`${t}.collections[${n}] declares ${r.sensitivity} data without required protection or memory-only persistence.`)}for(let[n,r]of(e.mutations??[]).entries()){if(dt(r.match,`${t}.mutations[${n}]`),r.conflict!==void 0&&r.conflict.strategy!=="client-wins"&&r.conflict.strategy!=="manual"&&r.conflict.strategy!=="server-wins")throw new R("INVALID_POLICY",`${t}.mutations[${n}].conflict.strategy is invalid.`);if(r.conflict?.maxAttempts!==void 0&&(!Number.isSafeInteger(r.conflict.maxAttempts)||r.conflict.maxAttempts<1))throw new R("INVALID_POLICY",`${t}.mutations[${n}].conflict.maxAttempts must be a positive safe integer.`);if(r.conflict?.maxAttempts!==void 0&&r.conflict.strategy!=="client-wins")throw new R("INVALID_POLICY",`${t}.mutations[${n}].conflict.maxAttempts is only valid for client-wins.`);if(r.persistence==="memory-only"&&r.protection==="required")throw new R("INVALID_POLICY",`${t}.mutations[${n}] cannot require at-rest protection when it is memory-only.`);if(r.sensitivity!==void 0&&r.sensitivity!=="public"&&r.protection!=="required"&&r.persistence!=="memory-only")throw new R("INVALID_POLICY",`${t}.mutations[${n}] declares ${r.sensitivity} arguments without required protection.`)}return e};var Bn=(e={version:1})=>{let t=jn(e)?[...e.components]:[{...e,id:"@absolutejs/app"}],n=new Set;for(let r of t){if(typeof r.id!=="string"||r.id.trim()!==r.id||r.id.length===0)throw new B("INVALID_PLAN","Sync schema component id must be non-empty and trimmed");if(n.has(r.id))throw new B("INVALID_PLAN",`Sync schema component "${r.id}" is declared more than once`);if(n.add(r.id),r.localData)Un(r.localData,`${r.id}.localData`)}return t.sort((r,o)=>r.id.localeCompare(o.id))};var pt=(e,t={version:1})=>{let n=Bn(t).map((s)=>{let i=ut(s.version,s);return{id:s.id,...ut(e[s.id]??i.minimumCompatibleVersion,s)}}),r=new Set(n.map((s)=>s.id)),o=Object.keys(e).filter((s)=>!r.has(s)).sort();return{components:n,orphanedComponents:o}};var ut=(e,t={version:1})=>{fe(e,"Stored Sync schema version");let n=fe(t.version,"Target Sync schema version"),r=[...t.migrations??[]].sort((a,c)=>a.toVersion-c.toVersion),o=new Set;for(let a of r){if(fe(a.toVersion,"Sync migration toVersion"),o.has(a.toVersion))throw new B("INVALID_PLAN",`Sync migration ${a.toVersion} is declared more than once`);o.add(a.toVersion)}let s=r[0]?r[0].toVersion-1:n,i=fe(t.minimumCompatibleVersion??s,"Minimum compatible Sync schema version");if(i>n)throw new B("INVALID_PLAN","Minimum compatible Sync schema version cannot exceed its target");if(e>n)throw new B("SCHEMA_TOO_NEW",`Stored Sync schema ${e} is newer than this runtime's schema ${n}`,{storedVersion:e,targetVersion:n});if(e<i)throw new B("SCHEMA_TOO_OLD",`Stored Sync schema ${e} is older than the minimum compatible schema ${i}`,{storedVersion:e,targetVersion:n});let l=[];for(let a=e+1;a<=n;a++){let c=r.find((h)=>h.toVersion===a);if(c===void 0)throw new B("MIGRATION_MISSING",`Sync migration ${a-1} -> ${a} is missing`,{storedVersion:e,targetVersion:n});l.push(c)}return{minimumCompatibleVersion:i,steps:l,targetVersion:n}};var Z=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),Te=(e)=>{try{let t=JSON.parse(Hn(e,"utf8"));return Z(t)?t:void 0}catch{return}},mt=(e)=>{let t=Reflect.get(e,"absolutejs");if(!Z(t))return;let n=Reflect.get(t,"sync");if(!Z(n))return;return Reflect.get(n,"localSchema")},Fn=(e,t)=>{let n=ht(e);while(!0){let r=gt(n,"node_modules",t,"package.json"),o=Te(r);if(o&&Reflect.get(o,"name")===t)return r;let s=Vn(n);if(s===n)return;n=s}},v=(e,t)=>TypeError(`Invalid AbsoluteJS Sync schema metadata for ${e}: ${t}`),Y=(e,t,n)=>{if(typeof e!=="number"||!Number.isSafeInteger(e)||e<1)throw v(t,`${n} must be a positive safe integer.`);return e},X=(e,t,n)=>{if(typeof e!=="string"||e.trim()!==e||e.length===0)throw v(t,`${n} must be a non-empty trimmed string.`);return e},W=(e,t,n)=>{if(!Z(e))throw v(t,n);return e},P=(e,t)=>e[t],Pe=(e,t,n)=>{if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map((r)=>Pe(r,t,n));if(Z(e))return Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Pe(o,t,n)]));throw v(t,`${n} must be JSON-safe.`)},Jn=(e,t,n)=>{let r=W(e,t,`migration operation ${n} must be an object.`),o=Reflect.get(r,"type"),s=X(Reflect.get(r,"collection"),t,`operation ${n}.collection`);if(o==="delete-collection")return{collection:s,type:o};if(o==="rename-field")return{collection:s,from:X(Reflect.get(r,"from"),t,`operation ${n}.from`),to:X(Reflect.get(r,"to"),t,`operation ${n}.to`),type:o};let i=X(Reflect.get(r,"field"),t,`operation ${n}.field`);if(o==="remove-field")return{collection:s,field:i,type:o};if(o==="set-default")return{collection:s,field:i,type:o,value:Pe(Reflect.get(r,"value"),t,`operation ${n}.value`)};throw v(t,`operation ${n}.type is not supported.`)},Wn=(e,t,n)=>{let r=W(e,t,`migration ${n} must be an object.`),o=new Set(["operations","toVersion"]),s=Object.keys(r).find((a)=>!o.has(a));if(s)throw v(t,`migration ${n}.${s} is not declarative metadata.`);let i=Reflect.get(r,"operations");if(i!==void 0&&!Array.isArray(i))throw v(t,`migration ${n}.operations must be an array.`);return{operations:(Array.isArray(i)?i:[]).map((a,c)=>Jn(a,t,c)),toVersion:Y(Reflect.get(r,"toVersion"),t,`migration ${n}.toVersion`)}},qn=(e,t)=>{let n=W(e,t,"localData must be an object."),r=new Set(["collections","maxBytesPerNamespace","mutations"]),o=Object.keys(n).find((h)=>!r.has(h));if(o)throw v(t,`localData.${o} is not supported.`);let s=Reflect.get(n,"collections"),i=Reflect.get(n,"mutations");if(s!==void 0&&!Array.isArray(s))throw v(t,"localData.collections must be an array.");if(i!==void 0&&!Array.isArray(i))throw v(t,"localData.mutations must be an array.");let l=Array.isArray(s)?s.map((h,d)=>{let u=W(h,t,`localData.collections[${d}] must be an object.`),S=new Set(["evictionPriority","match","maxAgeMs","onProtectionUnavailable","persistence","protection","sensitivity"]),f=Object.keys(u).find((L)=>!S.has(L));if(f)throw v(t,`localData.collections[${d}].${f} is not supported.`);let g=X(Reflect.get(u,"match"),t,`localData.collections[${d}].match`),p=P(u,"persistence"),w=P(u,"sensitivity"),y=P(u,"protection"),b=P(u,"onProtectionUnavailable"),E=P(u,"evictionPriority"),_=P(u,"maxAgeMs");if(p!==void 0&&p!=="durable"&&p!=="memory-only")throw v(t,`localData.collections[${d}].persistence is invalid.`);if(w!==void 0&&w!=="public"&&w!=="private"&&w!=="secret")throw v(t,`localData.collections[${d}].sensitivity is invalid.`);if(y!==void 0&&y!=="none"&&y!=="required")throw v(t,`localData.collections[${d}].protection is invalid.`);if(b!==void 0&&b!=="error"&&b!=="memory-only")throw v(t,`localData.collections[${d}].onProtectionUnavailable is invalid.`);if(E!==void 0&&E!=="critical"&&E!=="normal"&&E!=="disposable")throw v(t,`localData.collections[${d}].evictionPriority is invalid.`);return{match:g,...w?{sensitivity:w}:{},...p?{persistence:p}:{},...y?{protection:y}:{},...b?{onProtectionUnavailable:b}:{},...E?{evictionPriority:E}:{},..._===void 0?{}:{maxAgeMs:Y(_,t,`localData.collections[${d}].maxAgeMs`)}}}):void 0,a=Array.isArray(i)?i.map((h,d)=>{let u=W(h,t,`localData.mutations[${d}] must be an object.`),S=new Set(["conflict","match","onProtectionUnavailable","persistence","protection","sensitivity"]),f=Object.keys(u).find((_)=>!S.has(_));if(f)throw v(t,`localData.mutations[${d}].${f} is not supported.`);let g=P(u,"protection"),p=P(u,"sensitivity"),w=P(u,"persistence"),y=P(u,"onProtectionUnavailable"),b=P(u,"conflict"),E;if(b!==void 0){let _=W(b,t,`localData.mutations[${d}].conflict must be an object.`),L=Object.keys(_).find((A)=>A!=="maxAttempts"&&A!=="strategy");if(L)throw v(t,`localData.mutations[${d}].conflict.${L} is not supported.`);let j=P(_,"strategy");if(j!=="client-wins"&&j!=="manual"&&j!=="server-wins")throw v(t,`localData.mutations[${d}].conflict.strategy is invalid.`);let m=P(_,"maxAttempts");if(m!==void 0&&j!=="client-wins")throw v(t,`localData.mutations[${d}].conflict.maxAttempts requires client-wins.`);E={strategy:j,...m===void 0?{}:{maxAttempts:Y(m,t,`localData.mutations[${d}].conflict.maxAttempts`)}}}if(g!==void 0&&g!=="none"&&g!=="required")throw v(t,`localData.mutations[${d}].protection is invalid.`);if(p!==void 0&&p!=="public"&&p!=="private"&&p!=="secret")throw v(t,`localData.mutations[${d}].sensitivity is invalid.`);if(y!==void 0&&y!=="error"&&y!=="memory-only")throw v(t,`localData.mutations[${d}].onProtectionUnavailable is invalid.`);if(w!==void 0&&w!=="durable"&&w!=="memory-only")throw v(t,`localData.mutations[${d}].persistence is invalid.`);return{match:X(Reflect.get(u,"match"),t,`localData.mutations[${d}].match`),...E?{conflict:E}:{},...p?{sensitivity:p}:{},...y?{onProtectionUnavailable:y}:{},...w?{persistence:w}:{},...g?{protection:g}:{}}}):void 0,c=Reflect.get(n,"maxBytesPerNamespace");return{...l?{collections:l}:{},...a?{mutations:a}:{},...c===void 0?{}:{maxBytesPerNamespace:Y(c,t,"localData.maxBytesPerNamespace")}}},ft=(e,t)=>{let n=W(t,e,"localSchema must be an object."),r=new Set(["localData","migrations","minimumCompatibleVersion","version"]),o=Object.keys(n).find((d)=>!r.has(d));if(o)throw v(e,`${o} is not supported.`);let s=Y(Reflect.get(n,"version"),e,"version"),i=Reflect.get(n,"minimumCompatibleVersion"),l=i===void 0?Math.max(1,s-2):Y(i,e,"minimumCompatibleVersion"),a=Reflect.get(n,"migrations"),c=Reflect.get(n,"localData");if(a!==void 0&&!Array.isArray(a))throw v(e,"migrations must be an array.");let h=Array.isArray(a)?a:void 0;return{id:e,...c===void 0?{}:{localData:qn(c,e)},minimumCompatibleVersion:l,...Array.isArray(h)?{migrations:h.map((d,u)=>Wn(d,e,u))}:{},version:s}},Gn=(e)=>[Reflect.get(e,"dependencies"),Reflect.get(e,"optionalDependencies"),Reflect.get(e,"devDependencies"),Reflect.get(e,"peerDependencies")].flatMap((t)=>Z(t)?Object.keys(t):[]).filter((t,n,r)=>r.indexOf(t)===n).sort(),yt=(e)=>{let t=gt(ht(e),"package.json"),n=Te(t);if(!n)return{components:[{id:"@absolutejs/app",minimumCompatibleVersion:1,version:1}],sources:[]};let r=mt(n),o=[r===void 0?{id:"@absolutejs/app",minimumCompatibleVersion:1,version:1}:ft("@absolutejs/app",r)],s=[{id:"@absolutejs/app",manifestPath:t}];for(let i of Gn(n)){let l=Fn(e,i);if(!l)continue;let a=Te(l);if(!a)continue;let c=mt(a);if(c===void 0)continue;o.push(ft(i,c)),s.push({id:i,manifestPath:l})}return o.sort((i,l)=>i.id.localeCompare(l.id)),s.sort((i,l)=>i.id.localeCompare(l.id)),pt({},{components:o}),{components:o,sources:s}};var C=`// Generated by AbsoluteJS. Edit absolute.config.ts, then run absolute mobile sync.
5
+ `;var er=".absolutejs-expo-project",re=async(e)=>{try{return await zn(e),!0}catch{return!1}},St=(e,t)=>{let n=Zn(e,t).replaceAll("\\","/");return n.startsWith(".")?n:`./${n}`},tr=(e)=>e.split("/").filter(Boolean).map((t)=>{if(t.startsWith(":"))return`[${t.slice(1)}]`;if(t==="."||t===".."||!/^[A-Za-z0-9._~-]+$/u.test(t))throw TypeError(`Expo native route ${e} contains an unsupported segment ${t}.`);return t}),nr=(e,t)=>x(e,"app",...tr(t),"index.tsx"),rr=(e,t)=>({dependencies:{...e?{"@absolutejs/auth":Ze,[Qe]:et}:{},...t?{"@absolutejs/sync":tt,[nt]:rt}:{},expo:"~57.0.9","expo-asset":"~57.0.15","expo-constants":"~57.0.16","expo-dev-client":"~57.0.16","expo-file-system":"~57.0.6","expo-haptics":"~57.0.2","expo-linking":"~57.0.8",...t?{"expo-background-task":"~57.0.14","expo-network":"~57.0.1","expo-sqlite":"~57.0.2","expo-task-manager":"~57.0.14","expo-updates":"~57.0.19"}:{},"expo-router":"~57.0.17",...e?{"expo-secure-store":"~57.0.2","expo-web-browser":"~57.0.2"}:{},react:"19.2.3","react-native":"0.86.3","react-native-safe-area-context":"~5.7.0","react-native-screens":"4.26.0","react-native-webview":"13.16.1"},devDependencies:{"@types/react":"~19.2.2",typescript:"~6.0.3"},main:"expo-router/entry",name:"absolutejs-expo-shell",private:!0,scripts:{android:"expo run:android",ios:"expo run:ios",start:"expo start --dev-client"},version:"0.0.0"}),or=(e,t,n)=>({expo:{android:{intentFilters:e.deepLinkHosts.map((r)=>({action:"VIEW",autoVerify:!0,category:["BROWSABLE","DEFAULT"],data:[{host:r,pathPrefix:"/",scheme:"https"}]})),package:e.appId},experiments:{typedRoutes:!0},ios:{associatedDomains:e.deepLinkHosts.map((r)=>`applinks:${r}`),bundleIdentifier:e.appId,...e.iosVersion?{buildNumber:e.iosVersion}:{}},name:e.appName,plugins:["expo-router",["expo-dev-client",{launchMode:"most-recent"}],...t?["expo-secure-store"]:[],...n?["expo-sqlite","expo-background-task","expo-task-manager"]:[]],runtimeVersion:{policy:"appVersion"},scheme:e.deepLinkScheme,slug:e.appId.toLowerCase().replaceAll(".","-"),version:e.iosVersion??"0.1.0"}}),sr=`${C}const config = require('./app.json');
6
6
 
7
7
  if (process.env.ABSOLUTE_EXPO_DEVELOPMENT === '1' && process.env.ABSOLUTE_EXPO_DEVELOPMENT_CA_PATH) {
8
8
  config.expo.plugins = [
@@ -12,7 +12,7 @@ if (process.env.ABSOLUTE_EXPO_DEVELOPMENT === '1' && process.env.ABSOLUTE_EXPO_D
12
12
  }
13
13
 
14
14
  module.exports = config;
15
- `,ba=`${I}const { AndroidConfig, withAndroidManifest, withDangerousMod } = require('expo/config-plugins');
15
+ `,ir=`${C}const { AndroidConfig, withAndroidManifest, withDangerousMod } = require('expo/config-plugins');
16
16
  const { copyFile, mkdir } = require('node:fs/promises');
17
17
  const path = require('node:path');
18
18
 
@@ -51,7 +51,7 @@ const withAbsoluteDevelopmentCa = config => {
51
51
  };
52
52
 
53
53
  module.exports = withAbsoluteDevelopmentCa;
54
- `,ua=(e)=>`${I}const { getDefaultConfig } = require('expo/metro-config');
54
+ `,ar=(e)=>`${C}const { getDefaultConfig } = require('expo/metro-config');
55
55
  const path = require('node:path');
56
56
 
57
57
  const projectRoot = __dirname;
@@ -65,12 +65,22 @@ config.resolver.nodeModulesPaths = [
65
65
  config.watchFolders = [appRoot];
66
66
 
67
67
  module.exports = config;
68
- `,da=`${I}import { Stack } from 'expo-router';
68
+ `,cr=(e,t)=>`${C}import { Stack } from 'expo-router';
69
+ ${e?`import { useEffect, useState } from 'react';
70
+ import { startAbsoluteExpoAuth } from '../src/generated/AbsoluteAuth';`:""}
71
+ ${t?"import { startAbsoluteExpoSync } from '../src/generated/AbsoluteSync';":""}
69
72
 
70
73
  export default function AbsoluteLayout() {
74
+ ${e?`const [ready, setReady] = useState(false);
75
+ useEffect(() => {
76
+ let active = true;
77
+ void ${t?"startAbsoluteExpoSync":"startAbsoluteExpoAuth"}().then(() => { if (active) setReady(true); });
78
+ return () => { active = false; };
79
+ }, []);
80
+ if (!ready) return null;`:""}
71
81
  return <Stack screenOptions={{ headerShown: false }} />;
72
82
  }
73
- `,na=`${I}import * as Haptics from 'expo-haptics';
83
+ `,lr=`${C}import * as Haptics from 'expo-haptics';
74
84
  import { Link } from 'expo-router';
75
85
  import { Pressable, SafeAreaView, StyleSheet, Text, View } from 'react-native';
76
86
 
@@ -100,15 +110,137 @@ const styles = StyleSheet.create({
100
110
  page: { alignItems: 'center', backgroundColor: '#020617', flex: 1, justifyContent: 'center', padding: 20 },
101
111
  title: { color: '#f8fafc', fontSize: 32, fontWeight: '800' }
102
112
  });
103
- `,fa=(e)=>{let r=["/__absolute/native",...Object.keys(e.expoNativeRoutes)];return`${I}import * as Haptics from 'expo-haptics';
113
+ `,dr=(e,t)=>{let n=vt("sha256").update(t).digest("hex").slice(0,24);return`${C}import { createAbsoluteExpoAuthClient } from '@absolutejs/auth-expo';
114
+ import { createMobileAuthTransport, installAuthClientRuntimeTransport } from '@absolutejs/auth/client/mobile';
115
+
116
+ export const absoluteExpoAuth = createAbsoluteExpoAuthClient({
117
+ allowedOrigins: [${JSON.stringify(e.issuer)}],
118
+ clientId: ${JSON.stringify(e.clientId)},
119
+ issuer: ${JSON.stringify(e.issuer)},
120
+ redirectUri: ${JSON.stringify(e.redirectUri)},
121
+ resource: ${JSON.stringify(e.issuer)},
122
+ scopes: ${JSON.stringify(e.scopes)},
123
+ storagePrefix: ${JSON.stringify(`absolutejs.auth.${n}`)}
124
+ });
125
+ installAuthClientRuntimeTransport(createMobileAuthTransport(absoluteExpoAuth, { baseUrl: ${JSON.stringify(e.issuer)} }));
126
+
127
+ let currentPrincipal: Awaited<ReturnType<typeof absoluteExpoAuth.principal>> = null;
128
+ absoluteExpoAuth.onPrincipalChange(principal => {
129
+ currentPrincipal = principal;
130
+ });
131
+ export const getAbsoluteExpoAuthPrincipal = () => currentPrincipal;
132
+
133
+ let startPromise: Promise<void> | undefined;
134
+ export const startAbsoluteExpoAuth = () => {
135
+ startPromise ??= absoluteExpoAuth.start().then(async () => {
136
+ currentPrincipal = await absoluteExpoAuth.principal();
137
+ });
138
+
139
+ return startPromise;
140
+ };
141
+ `},ur=(e,t)=>{let n=vt("sha256").update(e.appId).digest("hex").slice(0,24),r=new URL("/__absolute/sync/background",e.productionOrigin).href,o=`${e.appId}.absolutejs.sync`;return`${C}import { runHeadlessSync } from '@absolutejs/sync/client/headless';
142
+ import type { SyncLocalStoreSchemaBundle } from '@absolutejs/sync/client';
143
+ import { installSyncClientRuntimeTransport } from '@absolutejs/sync/client/runtime';
144
+ import {
145
+ createExpoSyncBridgeHost,
146
+ createExpoSyncLocalStore,
147
+ createExpoSyncProtection,
148
+ createExpoSyncSocketBridgeHost,
149
+ defineExpoSyncBackgroundTask,
150
+ installExpoSyncLifecycle,
151
+ registerExpoSyncBackgroundTask
152
+ } from '@absolutejs/sync-expo';
153
+ import * as Updates from 'expo-updates';
154
+ import { absoluteExpoAuth, startAbsoluteExpoAuth } from './AbsoluteAuth';
155
+
156
+ const BACKGROUND_TASK = ${JSON.stringify(o)};
157
+ const BACKGROUND_ENDPOINT = ${JSON.stringify(r)};
158
+ const PRODUCTION_ORIGIN = ${JSON.stringify(e.productionOrigin)};
159
+ const STORAGE_SCHEMA: SyncLocalStoreSchemaBundle = ${JSON.stringify(t)};
160
+ const store = createExpoSyncLocalStore({
161
+ databaseName: ${JSON.stringify(`absolutejs-sync-${n}.db`)},
162
+ protection: createExpoSyncProtection({ storagePrefix: ${JSON.stringify(`absolutejs.sync.${n}`)} }),
163
+ storageSchema: STORAGE_SCHEMA
164
+ });
165
+
166
+ const runBackgroundSync = async () => {
167
+ await startAbsoluteExpoAuth();
168
+ const principal = await absoluteExpoAuth.principal();
169
+ if (!principal) return;
170
+ await runHeadlessSync({
171
+ endpoint: BACKGROUND_ENDPOINT,
172
+ fetch: (url, init) => absoluteExpoAuth.fetch(url, init),
173
+ namespace: principal.namespace,
174
+ store
175
+ });
176
+ };
177
+ defineExpoSyncBackgroundTask(BACKGROUND_TASK, runBackgroundSync);
178
+
179
+ let activeNamespace: string | undefined;
180
+ let started = false;
181
+ let startPromise: Promise<void> | undefined;
182
+ export const startAbsoluteExpoSync = () => {
183
+ startPromise ??= (async () => {
184
+ await startAbsoluteExpoAuth();
185
+ const principal = await absoluteExpoAuth.principal();
186
+ activeNamespace = principal?.namespace;
187
+ installSyncClientRuntimeTransport({
188
+ ...(principal ? { durable: { namespace: principal.namespace, store }, socketTicket: () => absoluteExpoAuth.socketTicket() } : {}),
189
+ registerClient: client => installExpoSyncLifecycle({ client })
190
+ });
191
+ await registerExpoSyncBackgroundTask(BACKGROUND_TASK, { minimumInterval: 15 });
192
+ started = true;
193
+ })();
194
+
195
+ return startPromise;
196
+ };
197
+
198
+ absoluteExpoAuth.onPrincipalChange(principal => {
199
+ if (!started || principal?.namespace === activeNamespace) return;
200
+ void Updates.reloadAsync();
201
+ });
202
+
203
+ export const createAbsoluteExpoSyncBridge = async (
204
+ emit: (event: 'sync.socket' | 'sync.wake', payload: Record<string, unknown>) => void
205
+ ) => {
206
+ await startAbsoluteExpoSync();
207
+ const principal = await absoluteExpoAuth.principal();
208
+ if (!principal) return {
209
+ close: () => undefined,
210
+ request: async () => { throw new Error('Expo Sync requires an authenticated principal.'); }
211
+ };
212
+ const transactions = createExpoSyncBridgeHost({ namespace: principal.namespace, store });
213
+ const sockets = createExpoSyncSocketBridgeHost({
214
+ allowedOrigin: PRODUCTION_ORIGIN,
215
+ emit: payload => emit('sync.socket', payload),
216
+ socketTicket: audience => absoluteExpoAuth.socketTicket(audience)
217
+ });
218
+ const removeLifecycle = installExpoSyncLifecycle({
219
+ client: { reconnect: () => emit('sync.wake', {}) }
220
+ });
221
+
222
+ return {
223
+ close: async () => {
224
+ removeLifecycle();
225
+ await Promise.all([transactions.close(), sockets.close()]);
226
+ },
227
+ request: (method: string, params: Record<string, unknown>) =>
228
+ method.startsWith('sync.socket.')
229
+ ? sockets.request(method, params)
230
+ : transactions.request(method, params)
231
+ };
232
+ };
233
+ `},pr=(e,t,n)=>{let r=["/__absolute/native",...Object.keys(e.expoNativeRoutes)];return`${C}import * as Haptics from 'expo-haptics';
104
234
  import * as Linking from 'expo-linking';
105
235
  import { router, usePathname } from 'expo-router';
106
236
  import { useEffect, useRef, useState } from 'react';
107
237
  import { ActivityIndicator, BackHandler, Platform, StyleSheet, View } from 'react-native';
108
238
  import { WebView, type WebViewMessageEvent } from 'react-native-webview';
109
239
  import { materializeAbsoluteWebBundle } from './webAssets';
240
+ ${t?"import { absoluteExpoAuth, getAbsoluteExpoAuthPrincipal, startAbsoluteExpoAuth } from './AbsoluteAuth';":""}
241
+ ${n?"import { createAbsoluteExpoSyncBridge, startAbsoluteExpoSync } from './AbsoluteSync';":""}
110
242
 
111
- const BRIDGE_FORMAT = 1;
243
+ const BRIDGE_FORMAT = 3;
112
244
  const MAX_MESSAGE_BYTES = 64 * 1024;
113
245
  const MAX_HTTP_BODY_BYTES = 48 * 1024;
114
246
  const NATIVE_ROUTES = new Set(${JSON.stringify(r)});
@@ -117,6 +249,8 @@ const DEV_ORIGIN = Platform.OS === 'android'
117
249
  ? process.env.EXPO_PUBLIC_ABSOLUTE_DEV_ANDROID_ORIGIN
118
250
  : process.env.EXPO_PUBLIC_ABSOLUTE_DEV_IOS_ORIGIN;
119
251
  const HMR_TARGET = Platform.OS === 'android' ? 'expo-android' : 'expo-ios';
252
+ const AUTH_ENABLED = ${t?"true":"false"};
253
+ const SYNC_ENABLED = ${n?"true":"false"};
120
254
 
121
255
  const bridgeBootstrap = (path: string) => {
122
256
  const initialPath = DEV_ORIGIN
@@ -124,6 +258,7 @@ const bridgeBootstrap = (path: string) => {
124
258
  : JSON.stringify(path);
125
259
  return \`(() => {
126
260
  const pending = new Map();
261
+ const listeners = new Map();
127
262
  let sequence = 0;
128
263
  let currentPath = \${initialPath};
129
264
  const send = value => {
@@ -133,6 +268,10 @@ const bridgeBootstrap = (path: string) => {
133
268
  };
134
269
  globalThis.__absoluteExpoReceive = source => {
135
270
  const message = JSON.parse(source);
271
+ if (message.kind === 'event') {
272
+ for (const listener of listeners.get(message.event) || []) listener(message.payload || {});
273
+ return;
274
+ }
136
275
  const operation = pending.get(message.id);
137
276
  if (!operation) return;
138
277
  pending.delete(message.id);
@@ -140,9 +279,18 @@ const bridgeBootstrap = (path: string) => {
140
279
  message.error ? operation.reject(new Error(message.error.message)) : operation.resolve(message.result);
141
280
  };
142
281
  globalThis.__absoluteExpoBridge = {
282
+ on(event, listener) {
283
+ const values = listeners.get(event) || new Set();
284
+ values.add(listener);
285
+ listeners.set(event, values);
286
+ return () => {
287
+ values.delete(listener);
288
+ if (values.size === 0) listeners.delete(event);
289
+ };
290
+ },
143
291
  request(method, params) {
144
292
  const id = 'web_' + Date.now().toString(36) + '_' + (++sequence).toString(36);
145
- send({ format: 1, id, kind: 'request', method, params, path: currentPath });
293
+ send({ format: 3, id, kind: 'request', method, params, path: currentPath });
146
294
  return new Promise((resolve, reject) => {
147
295
  const timer = setTimeout(() => {
148
296
  pending.delete(id);
@@ -153,7 +301,7 @@ const bridgeBootstrap = (path: string) => {
153
301
  },
154
302
  setPath(path) {
155
303
  currentPath = path;
156
- send({ format: 1, kind: 'event', event: 'navigation', path });
304
+ send({ format: 3, kind: 'event', event: 'navigation', path });
157
305
  }
158
306
  };
159
307
  if (\${DEV_ORIGIN ? 'true' : 'false'}) {
@@ -161,7 +309,7 @@ const bridgeBootstrap = (path: string) => {
161
309
  const path = location.pathname + location.search + location.hash;
162
310
  if (path === currentPath) return;
163
311
  currentPath = path;
164
- send({ format: 1, kind: 'event', event: 'navigation', path });
312
+ send({ format: 3, kind: 'event', event: 'navigation', path });
165
313
  };
166
314
  for (const method of ['pushState', 'replaceState']) {
167
315
  const original = history[method];
@@ -180,9 +328,9 @@ const bridgeBootstrap = (path: string) => {
180
328
  const url = new URL(anchor.href, location.href);
181
329
  if (!${JSON.stringify(r)}.includes(url.pathname)) return;
182
330
  event.preventDefault();
183
- send({ format: 1, kind: 'event', event: 'navigation', path: url.pathname + url.search + url.hash });
331
+ send({ format: 3, kind: 'event', event: 'navigation', path: url.pathname + url.search + url.hash });
184
332
  }, true);
185
- send({ format: 1, kind: 'event', event: 'ready', path: currentPath });
333
+ send({ format: 3, kind: 'event', event: 'ready', path: currentPath });
186
334
  })(); true;\`;
187
335
  };
188
336
 
@@ -198,16 +346,16 @@ const impact = async (params: Record<string, unknown>) => {
198
346
  };
199
347
 
200
348
  const bridgeFetch = async (params: Record<string, unknown>) => {
201
- if (params.method !== 'GET' || typeof params.url !== 'string' || typeof params.headers !== 'object' || params.headers === null || Array.isArray(params.headers)) throw new Error('Expo bridge HTTP request is invalid.');
349
+ if (typeof params.method !== 'string' || !['DELETE', 'GET', 'PATCH', 'POST', 'PUT'].includes(params.method) || typeof params.url !== 'string' || typeof params.headers !== 'object' || params.headers === null || Array.isArray(params.headers) || params.body !== undefined && typeof params.body !== 'string') throw new Error('Expo bridge HTTP request is invalid.');
202
350
  const url = new URL(params.url);
203
351
  if (url.origin !== PRODUCTION_ORIGIN || url.username || url.password) throw new Error('Expo bridge HTTP request left productionOrigin.');
204
352
  const headers = new Headers();
205
353
  for (const [name, value] of Object.entries(params.headers as Record<string, unknown>)) {
206
354
  const normalized = name.toLowerCase();
207
- if (typeof value !== 'string' || (normalized !== 'accept' && !normalized.startsWith('x-absolute-mobile-'))) throw new Error('Expo bridge HTTP header is not allowed.');
355
+ if (typeof value !== 'string' || (normalized !== 'accept' && normalized !== 'content-type' && !normalized.startsWith('x-absolute-mobile-'))) throw new Error('Expo bridge HTTP header is not allowed.');
208
356
  headers.set(normalized, value);
209
357
  }
210
- const response = await fetch(url, { headers, method: 'GET', redirect: 'manual' });
358
+ const response = await ${t?"absoluteExpoAuth.fetchOptional":"fetch"}(url, { ...(typeof params.body === 'string' ? { body: params.body } : {}), headers, method: params.method, redirect: 'manual' });
211
359
  if (new URL(response.url || url.href).origin !== PRODUCTION_ORIGIN || response.status >= 300 && response.status < 400) throw new Error('Expo bridge HTTP redirects are not allowed.');
212
360
  const body = await response.text();
213
361
  if (new TextEncoder().encode(body).byteLength > MAX_HTTP_BODY_BYTES) throw new Error('Expo bridge HTTP response exceeds 48 KiB.');
@@ -219,13 +367,42 @@ const bridgeFetch = async (params: Record<string, unknown>) => {
219
367
  return { body, headers: responseHeaders, status: response.status };
220
368
  };
221
369
 
370
+ const authStatus = async () => {
371
+ ${t?`const user = await absoluteExpoAuth.status();
372
+ const principal = getAbsoluteExpoAuthPrincipal();
373
+ return { principal: principal ? { namespace: principal.namespace } : null, user };`:"throw new Error('Expo Auth is not configured.');"}
374
+ };
375
+
222
376
  export function AbsoluteWebHost() {
223
377
  const pathname = usePathname() || '/';
224
378
  const webView = useRef<WebView>(null);
379
+ const syncBridge = useRef<{ close(): void | Promise<void>; request(method: string, params: Record<string, unknown>): Promise<unknown> } | undefined>(undefined);
225
380
  const [indexUri, setIndexUri] = useState<string>();
226
381
  const [canGoBack, setCanGoBack] = useState(false);
382
+ const [runtimeReady, setRuntimeReady] = useState(!AUTH_ENABLED && !SYNC_ENABLED);
227
383
  const activeWebPath = useRef(pathname);
228
384
 
385
+ useEffect(() => {
386
+ if (!AUTH_ENABLED && !SYNC_ENABLED) return;
387
+ let active = true;
388
+ ${t?`const stop = absoluteExpoAuth.onPrincipalChange(principal => {
389
+ if (!active) return;
390
+ const source = JSON.stringify({ event: 'auth.principal', format: BRIDGE_FORMAT, kind: 'event', path: activeWebPath.current, payload: { principal: principal ? { namespace: principal.namespace } : null } });
391
+ webView.current?.injectJavaScript(\`globalThis.__absoluteExpoReceive(\${JSON.stringify(source)}); true;\`);
392
+ });
393
+ void ${n?"startAbsoluteExpoSync":"startAbsoluteExpoAuth"}().then(async () => {
394
+ ${n?"syncBridge.current = await createAbsoluteExpoSyncBridge((event, payload) => {\n\t\t\t\tconst source = JSON.stringify({ event, format: BRIDGE_FORMAT, kind: 'event', path: activeWebPath.current, payload });\n\t\t\t\twebView.current?.injectJavaScript(`globalThis.__absoluteExpoReceive(${JSON.stringify(source)}); true;`);\n\t\t\t});":""}
395
+ if (active) setRuntimeReady(true);
396
+ });
397
+ return () => {
398
+ active = false;
399
+ stop();
400
+ const bridge = syncBridge.current;
401
+ syncBridge.current = undefined;
402
+ void bridge?.close();
403
+ };`:""}
404
+ }, []);
405
+
229
406
  useEffect(() => {
230
407
  if (DEV_ORIGIN) {
231
408
  const target = new URL(pathname, DEV_ORIGIN);
@@ -275,6 +452,19 @@ export function AbsoluteWebHost() {
275
452
  respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: null });
276
453
  } else if (message.method === 'http.fetch') {
277
454
  respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: await bridgeFetch(message.params as Record<string, unknown>) });
455
+ } else if (message.method === 'auth.signIn') {
456
+ ${t?`const params = message.params as Record<string, unknown>;
457
+ if (typeof params.email !== 'string' || typeof params.signup !== 'boolean') throw new Error('Expo Auth sign-in params are invalid.');
458
+ await absoluteExpoAuth.signIn({ authorizationParameters: { login_hint: params.email, ...(params.signup ? { screen_hint: 'signup' } : {}) } });
459
+ respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: await authStatus() });`:"throw new Error('Expo Auth is not configured.');"}
460
+ } else if (message.method === 'auth.signOut') {
461
+ ${t?`await absoluteExpoAuth.signOut();
462
+ respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: null });`:"throw new Error('Expo Auth is not configured.');"}
463
+ } else if (message.method === 'auth.status') {
464
+ respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: await authStatus() });
465
+ } else if (typeof message.method === 'string' && message.method.startsWith('sync.')) {
466
+ if (!syncBridge.current) throw new Error('Expo Sync bridge is unavailable.');
467
+ respond({ format: BRIDGE_FORMAT, id: message.id, kind: 'response', result: await syncBridge.current.request(message.method, message.params as Record<string, unknown>) });
278
468
  } else {
279
469
  throw new Error('Expo bridge method is not allowed.');
280
470
  }
@@ -283,7 +473,7 @@ export function AbsoluteWebHost() {
283
473
  }
284
474
  };
285
475
 
286
- if (!indexUri) return <View style={styles.loading}><ActivityIndicator /></View>;
476
+ if (!indexUri || !runtimeReady) return <View style={styles.loading}><ActivityIndicator /></View>;
287
477
  return <WebView
288
478
  allowFileAccess
289
479
  allowFileAccessFromFileURLs
@@ -304,47 +494,47 @@ export function AbsoluteWebHost() {
304
494
  }
305
495
 
306
496
  const styles = StyleSheet.create({ loading: { alignItems: 'center', flex: 1, justifyContent: 'center' }, web: { flex: 1 } });
307
- `},Aa=`${I}import { AbsoluteWebHost } from '../src/generated/AbsoluteWebHost';
497
+ `},mr=`${C}import { AbsoluteWebHost } from '../src/generated/AbsoluteWebHost';
308
498
 
309
499
  export default AbsoluteWebHost;
310
- `,ya=`${I}import { AbsoluteWebHost } from '../src/generated/AbsoluteWebHost';
500
+ `,fr=`${C}import { AbsoluteWebHost } from '../src/generated/AbsoluteWebHost';
311
501
 
312
502
  export default AbsoluteWebHost;
313
- `,xa=(e,r)=>`${I}export { default } from ${JSON.stringify(Pe(Ke(e),r).replace(/\.(?:[cm]?[jt]sx?)$/u,""))};
314
- `,Sa=(e,r)=>({compilerOptions:{paths:{"*":["./node_modules/*",`${Pe(r,e)}/node_modules/*`],react:["./node_modules/@types/react/index.d.ts"],"react/*":["./node_modules/@types/react/*"]},strict:!0},extends:"expo/tsconfig.base"}),ga=async(e,r,a)=>{if(await Fe(Ke(e),{recursive:!0}),await Z(e)){let c=await or(e,"utf8");if(c===r)return!1;if(!a&&!c.startsWith(I))throw TypeError(`Expo project file ${e} is not AbsoluteJS-managed; rerun with --force only after reviewing it.`)}let s=`${e}.${crypto.randomUUID()}.tmp`;return await Xe(s,r,{flag:"wx"}),await pr(s,e),!0},he=(e)=>`${JSON.stringify(e,null,"\t")}
315
- `,ha=`${I}export const materializeAbsoluteWebBundle = async () => {
503
+ `,gr=(e,t)=>`${C}export { default } from ${JSON.stringify(St(At(e),t).replace(/\.(?:[cm]?[jt]sx?)$/u,""))};
504
+ `,hr=(e,t,n,r)=>({compilerOptions:{paths:{...n?{"@absolutejs/auth":["./node_modules/@absolutejs/auth/dist/index.d.ts"],"@absolutejs/auth/*":["./node_modules/@absolutejs/auth/dist/*"]}:{},...r?{"@absolutejs/sync":["./node_modules/@absolutejs/sync/dist/index.d.ts"],"@absolutejs/sync-expo":["./node_modules/@absolutejs/sync-expo/dist/index.d.ts"],"@absolutejs/sync-expo/*":["./node_modules/@absolutejs/sync-expo/dist/*"],"@absolutejs/sync/*":["./node_modules/@absolutejs/sync/dist/*"]}:{},"*":["./node_modules/*",`${St(t,e)}/node_modules/*`],react:["./node_modules/@types/react/index.d.ts"],"react/*":["./node_modules/@types/react/*"]},strict:!0},extends:"expo/tsconfig.base"}),yr=async(e,t,n)=>{if(await bt(At(e),{recursive:!0}),await re(e)){let o=await Xn(e,"utf8");if(o===t)return!1;if(!n&&!o.startsWith(C))throw TypeError(`Expo project file ${e} is not AbsoluteJS-managed; rerun with --force only after reviewing it.`)}let r=`${e}.${crypto.randomUUID()}.tmp`;return await wt(r,t,{flag:"wx"}),await Yn(r,e),!0},Ce=(e)=>`${JSON.stringify(e,null,"\t")}
505
+ `,br=`${C}export const materializeAbsoluteWebBundle = async () => {
316
506
  throw new Error('The embedded AbsoluteJS bundle is unavailable. Run absolute prepare before a production Expo build.');
317
507
  };
318
- `,Ye=async(e,r)=>{if(e.engine!=="expo")throw TypeError("Expo project generation requires mobile.engine: expo.");let a=ra(r.projectRoot),s=e.nativeProjectDirectory,c=Object.entries(e.expoNativeRoutes),t=(await Promise.all(c.map(async([f,O])=>({exists:await Z(O),module:O,route:f})))).find((f)=>!f.exists);if(t)throw TypeError(`Expo native route ${t.route} references missing module ${t.module}.`);let u=_(s,aa);if(await Z(s)&&!await Z(u)){if((await jr(s)).length>0&&!r.force)throw TypeError(`Expo project directory ${s} is not AbsoluteJS-managed; rerun with --force only after reviewing it.`)}await Fe(s,{recursive:!0}),await Xe(u,`format=1
319
- `);let w=new Map([[_(s,".gitignore"),`.expo/
508
+ `,Et=async(e,t)=>{if(e.engine!=="expo")throw TypeError("Expo project generation requires mobile.engine: expo.");let n=Qn(t.projectRoot),r=e.nativeProjectDirectory,o=at(n,e),s=Boolean(o&&it(n)),i=s?{components:yt(n).components}:void 0,l=Object.entries(e.expoNativeRoutes),c=(await Promise.all(l.map(async([p,w])=>({exists:await re(w),module:w,route:p})))).find((p)=>!p.exists);if(c)throw TypeError(`Expo native route ${c.route} references missing module ${c.module}.`);let h=x(r,er);if(await re(r)&&!await re(h)){if((await Kn(r)).length>0&&!t.force)throw TypeError(`Expo project directory ${r} is not AbsoluteJS-managed; rerun with --force only after reviewing it.`)}await bt(r,{recursive:!0}),await wt(h,`format=1
509
+ `);let d=Boolean(o),u=new Map([[x(r,".gitignore"),`.expo/
320
510
  android/
321
511
  ios/
322
512
  node_modules/
323
- `],[_(s,"app.json"),he(ta(e))],[_(s,"app.config.js"),wa],[_(s,"package.json"),he(la())],[_(s,"metro.config.js"),ua(a)],[_(s,"plugins","withAbsoluteDevelopmentCa.js"),ba],[_(s,"tsconfig.json"),he(Sa(a,s))],[_(s,"app","_layout.tsx"),da],[_(s,"app","__absolute","native","index.tsx"),na],[_(s,"src","generated","AbsoluteWebHost.tsx"),fa(e)]]),b=_(s,"src","generated","webAssets.ts");if(!await Z(b))w.set(b,ha);if(!e.expoNativeRoutes["/"])w.set(_(s,"app","index.tsx"),Aa);w.set(_(s,"app","[...absolute].tsx"),ya);for(let[f,O]of c){let n=f==="/"?_(s,"app","index.tsx"):ca(s,f);w.set(n,xa(n,O))}return{changed:(await Promise.all([...w].map(([f,O])=>ga(f,O,!0)))).filter(Boolean).length,path:s,written:[...w.keys()]}};import{createHash as dr,randomUUID as Fa}from"crypto";import{access as Xa,copyFile as ar,mkdir as P,readFile as te,rename as Ka,rm as _e,writeFile as G}from"fs/promises";import{isIP as Pa}from"net";import{dirname as nr,isAbsolute as Ya,join as T,relative as qa,resolve as we,sep as Za}from"path";import{access as Ea}from"fs/promises";import{homedir as Qe}from"os";import{join as i}from"path";import{existsSync as nc,readFileSync as Oa}from"fs";var Q=1000;var qe=60000;var Oe=2;var z=(e)=>{let r;if(e<Q)r=`${e.toFixed(Oe)}ms`;else if(e<qe)r=`${(e/Q).toFixed(Oe)}s`;else{let a=Math.round(e/Q),s=Math.floor(a/60),c=a%60;r=c===0?`${s}m`:`${s}m ${c}s`}return r};var Ze=()=>{try{let e=Oa("/proc/version","utf-8");return/microsoft|wsl/i.test(e)}catch{return!1}};var ze="AbsoluteJS_API_36",$a=(e)=>{try{let r=Bun.spawnSync(e,{stderr:"ignore",stdout:"pipe"});return{exitCode:r.exitCode,stdout:r.stdout.toString()}}catch{return{exitCode:1,stdout:""}}},_a=(e)=>{try{let r=JSON.parse(e);if(typeof r!=="object"||r===null)return!1;let a=Reflect.get(r,"runtimes");if(!Array.isArray(a))return!1;return a.some((s)=>typeof s==="object"&&s!==null&&Reflect.get(s,"isAvailable")===!0&&typeof Reflect.get(s,"identifier")==="string"&&String(Reflect.get(s,"identifier")).includes("iOS"))}catch{return!1}},Ta=(e)=>{let r=/^([a-z]):[\\/](.*)$/i.exec(e.trim());if(!r)return e.trim().replaceAll("\\","/");return`/mnt/${r[1]?.toLowerCase()}/${r[2]?.replaceAll("\\","/")}`},ma=()=>{try{let e=Bun.spawnSync(["cmd.exe","/d","/c","echo","%LOCALAPPDATA%"],{stderr:"ignore",stdout:"pipe"});if(e.exitCode!==0)return;let r=e.stdout.toString().trim();if(!r||r==="%LOCALAPPDATA%")return;return Ta(r)}catch{return}},Da=(e,r=process.env)=>{if(e==="windows")return i(r.LOCALAPPDATA??i(Qe(),"AppData","Local"),"AbsoluteJS","Android","Sdk");if(e==="wsl"){let a=ma();if(a)return i(a,"AbsoluteJS","Android","Sdk")}return i(Qe(),".absolutejs","android-sdk")},Na=async(e)=>{try{return await Ea(e),!0}catch{return!1}},ce=(e=process.platform,r=Ze())=>{if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"&&r)return"wsl";return"linux"},Ia=(e,r)=>{if(e==="wsl")return[`${r}.exe`,`${r}.bat`,r];if(e==="windows")return[r,`${r}.exe`,`${r}.bat`];return[r]},L=async(e,r,a,s)=>{let l=(await Promise.all(r.map(async(t)=>await a.exists(t)?t:void 0))).find((t)=>t!==void 0);if(l)return l;for(let t of Ia(s,e)){let u=a.which(t);if(u)return u}return},V=(e,r,a,s,c)=>s?{id:e,label:r,path:s,platform:a,status:"pass"}:{id:e,label:r,platform:a,remediation:c,status:"fail"},ie=async(e={})=>{let r=e.env??process.env,a=e.host??ce(),s=e.exists??Na,c=e.which??((h)=>Bun.which(h)),l=e.capture??$a,t=e.androidRoot===null?void 0:e.androidRoot??r.ANDROID_HOME??r.ANDROID_SDK_ROOT??Da(a,r),u=a==="windows"||a==="wsl",w=(h)=>t?i(t,...h):void 0,b=(h)=>h.filter((g)=>Boolean(g)),x=await L("adb",b([w(["platform-tools",u?"adb.exe":"adb"])]),{exists:s,which:c},a),A=await L("emulator",b([w(["emulator",u?"emulator.exe":"emulator"])]),{exists:s,which:c},a),f=await L("sdkmanager",b([w(["cmdline-tools","latest","bin",u?"sdkmanager.bat":"sdkmanager"])]),{exists:s,which:c},a),O=await L("avdmanager",b([w(["cmdline-tools","latest","bin",u?"avdmanager.bat":"avdmanager"])]),{exists:s,which:c},a),n=await L("java",[],{exists:s,which:c},a),y=[{id:"host",label:`Development host: ${a}`,platform:"host",status:"pass"},V("android.adb","Android Debug Bridge","android",x,"Install Android SDK Platform Tools or expose adb on PATH."),V("android.emulator","Android Emulator","android",A,"Install the Android Emulator from Android Studio SDK Manager."),V("android.sdkmanager","Android SDK Manager","android",f,"Install Android SDK Command-line Tools (latest)."),V("android.avdmanager","Android Virtual Device Manager","android",O,"Install Android SDK Command-line Tools (latest)."),V("android.java","Java runtime","android",n,"Install the JDK required by the configured Android Gradle plugin.")];if(A){let h=l([A,"-list-avds"]),g=h.exitCode===0&&h.stdout.split(/\r?\n/).includes(ze);y.push({id:"android.avd",label:`AbsoluteJS Android emulator (${ze})`,platform:"android",remediation:g?void 0:"Run absolute mobile doctor android --fix to provision the managed emulator.",status:g?"pass":"fail"})}if(a==="wsl")y.push({id:"android.virtualization",label:x?.endsWith(".exe")?"Windows-host Android bridge available to WSL":"WSL requires a Windows-host emulator bridge or Linux KVM",platform:"android",remediation:x?.endsWith(".exe")?void 0:"Expose the Windows Android SDK adb.exe to WSL, or enable /dev/kvm for a Linux SDK.",status:x?.endsWith(".exe")?"pass":"warn"});else if(a==="linux"){let h=await s("/dev/kvm");y.push({id:"android.virtualization",label:"Linux KVM acceleration",platform:"android",remediation:h?void 0:"Enable KVM and grant the current user access to /dev/kvm.",status:h?"pass":"warn"})}if(a!=="macos")return y.push({id:"ios.simulator",label:"iOS Simulator requires macOS and Xcode",platform:"ios",status:"skip"}),y;let S=await L("xcrun",[],{exists:s,which:c},a),D=await L("xcodebuild",[],{exists:s,which:c},a);if(y.push(V("ios.xcrun","Xcode command runner","ios",S,"Install Xcode and select it with xcode-select."),V("ios.xcodebuild","Xcode build system","ios",D,"Install Xcode and select it with xcode-select.")),S){let h=l([S,"simctl","list","runtimes","--json"]),g=h.exitCode===0&&_a(h.stdout);y.push({id:"ios.runtime",label:"iOS Simulator runtime",platform:"ios",remediation:g?void 0:"Run absolute mobile doctor ios --fix to download an iOS Simulator runtime.",status:g?"pass":"fail"})}return y};import{access as Ma,readFile as ka,rename as Ra,writeFile as Ca}from"fs/promises";import{relative as Wa,resolve as ve}from"path";var je="capacitor.config.ts",Ee=(e,r)=>Wa(e,r).replaceAll("\\","/"),Ua=(e,r)=>`import type { CapacitorConfig } from '@capacitor/cli';
513
+ `],[x(r,"app.json"),Ce(or(e,d,s))],[x(r,"app.config.js"),sr],[x(r,"package.json"),Ce(rr(d,s))],[x(r,"metro.config.js"),ar(n)],[x(r,"plugins","withAbsoluteDevelopmentCa.js"),ir],[x(r,"tsconfig.json"),Ce(hr(n,r,d,s))],[x(r,"app","_layout.tsx"),cr(d,s)],[x(r,"app","__absolute","native","index.tsx"),lr],[x(r,"src","generated","AbsoluteWebHost.tsx"),pr(e,o,s)]]);if(o)u.set(x(r,"src","generated","AbsoluteAuth.ts"),dr(o,e.appId));if(i)u.set(x(r,"src","generated","AbsoluteSync.ts"),ur(e,i));let S=x(r,"src","generated","webAssets.ts");if(!await re(S))u.set(S,br);if(!e.expoNativeRoutes["/"])u.set(x(r,"app","index.tsx"),mr);u.set(x(r,"app","[...absolute].tsx"),fr);for(let[p,w]of l){let y=p==="/"?x(r,"app","index.tsx"):nr(r,p);u.set(y,gr(y,w))}return{changed:(await Promise.all([...u].map(([p,w])=>yr(p,w,!0)))).filter(Boolean).length,path:r,written:[...u.keys()]}};import{createHash as Ft,randomUUID as Br}from"crypto";import{access as Hr,copyFile as kt,mkdir as ee,readFile as ye,rename as Vr,rm as Me,writeFile as z}from"fs/promises";import{isIP as Fr}from"net";import{dirname as Jt,isAbsolute as Jr,join as O,relative as Wr,resolve as be,sep as qr}from"path";import{access as vr}from"fs/promises";import{homedir as Ot}from"os";import{join as ie}from"path";import{existsSync as xs,readFileSync as wr}from"fs";var oe=1000;var xt=60000;var De=2;var se=(e)=>{let t;if(e<oe)t=`${e.toFixed(De)}ms`;else if(e<xt)t=`${(e/oe).toFixed(De)}s`;else{let n=Math.round(e/oe),r=Math.floor(n/60),o=n%60;t=o===0?`${r}m`:`${r}m ${o}s`}return t};var It=()=>{try{let e=wr("/proc/version","utf-8");return/microsoft|wsl/i.test(e)}catch{return!1}};var _t="AbsoluteJS_API_36",Ar=(e)=>{try{let t=Bun.spawnSync(e,{stderr:"ignore",stdout:"pipe"});return{exitCode:t.exitCode,stdout:t.stdout.toString()}}catch{return{exitCode:1,stdout:""}}},Sr=(e)=>{try{let t=JSON.parse(e);if(typeof t!=="object"||t===null)return!1;let n=Reflect.get(t,"runtimes");if(!Array.isArray(n))return!1;return n.some((r)=>typeof r==="object"&&r!==null&&Reflect.get(r,"isAvailable")===!0&&typeof Reflect.get(r,"identifier")==="string"&&String(Reflect.get(r,"identifier")).includes("iOS"))}catch{return!1}},Er=(e)=>{let t=/^([a-z]):[\\/](.*)$/i.exec(e.trim());if(!t)return e.trim().replaceAll("\\","/");return`/mnt/${t[1]?.toLowerCase()}/${t[2]?.replaceAll("\\","/")}`},xr=()=>{try{let e=Bun.spawnSync(["cmd.exe","/d","/c","echo","%LOCALAPPDATA%"],{stderr:"ignore",stdout:"pipe"});if(e.exitCode!==0)return;let t=e.stdout.toString().trim();if(!t||t==="%LOCALAPPDATA%")return;return Er(t)}catch{return}},Ir=(e,t=process.env)=>{if(e==="windows")return ie(t.LOCALAPPDATA??ie(Ot(),"AppData","Local"),"AbsoluteJS","Android","Sdk");if(e==="wsl"){let n=xr();if(n)return ie(n,"AbsoluteJS","Android","Sdk")}return ie(Ot(),".absolutejs","android-sdk")},Or=async(e)=>{try{return await vr(e),!0}catch{return!1}},ge=(e=process.platform,t=It())=>{if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux"&&t)return"wsl";return"linux"},_r=(e,t)=>{if(e==="wsl")return[`${t}.exe`,`${t}.bat`,t];if(e==="windows")return[t,`${t}.exe`,`${t}.bat`];return[t]},q=async(e,t,n,r)=>{let s=(await Promise.all(t.map(async(i)=>await n.exists(i)?i:void 0))).find((i)=>i!==void 0);if(s)return s;for(let i of _r(r,e)){let l=n.which(i);if(l)return l}return},G=(e,t,n,r,o)=>r?{id:e,label:t,path:r,platform:n,status:"pass"}:{id:e,label:t,platform:n,remediation:o,status:"fail"},Tt=async(e={})=>{let t=e.env??process.env,n=e.host??ge(),r=e.exists??Or,o=e.which??((y)=>Bun.which(y)),s=e.capture??Ar,i=e.androidRoot===null?void 0:e.androidRoot??t.ANDROID_HOME??t.ANDROID_SDK_ROOT??Ir(n,t),l=n==="windows"||n==="wsl",a=(y)=>i?ie(i,...y):void 0,c=(y)=>y.filter((b)=>Boolean(b)),h=await q("adb",c([a(["platform-tools",l?"adb.exe":"adb"])]),{exists:r,which:o},n),d=await q("emulator",c([a(["emulator",l?"emulator.exe":"emulator"])]),{exists:r,which:o},n),u=await q("sdkmanager",c([a(["cmdline-tools","latest","bin",l?"sdkmanager.bat":"sdkmanager"])]),{exists:r,which:o},n),S=await q("avdmanager",c([a(["cmdline-tools","latest","bin",l?"avdmanager.bat":"avdmanager"])]),{exists:r,which:o},n),f=await q("java",[],{exists:r,which:o},n),g=[{id:"host",label:`Development host: ${n}`,platform:"host",status:"pass"},G("android.adb","Android Debug Bridge","android",h,"Install Android SDK Platform Tools or expose adb on PATH."),G("android.emulator","Android Emulator","android",d,"Install the Android Emulator from Android Studio SDK Manager."),G("android.sdkmanager","Android SDK Manager","android",u,"Install Android SDK Command-line Tools (latest)."),G("android.avdmanager","Android Virtual Device Manager","android",S,"Install Android SDK Command-line Tools (latest)."),G("android.java","Java runtime","android",f,"Install the JDK required by the configured Android Gradle plugin.")];if(d){let y=s([d,"-list-avds"]),b=y.exitCode===0&&y.stdout.split(/\r?\n/).includes(_t);g.push({id:"android.avd",label:`AbsoluteJS Android emulator (${_t})`,platform:"android",remediation:b?void 0:"Run absolute mobile doctor android --fix to provision the managed emulator.",status:b?"pass":"fail"})}if(n==="wsl")g.push({id:"android.virtualization",label:h?.endsWith(".exe")?"Windows-host Android bridge available to WSL":"WSL requires a Windows-host emulator bridge or Linux KVM",platform:"android",remediation:h?.endsWith(".exe")?void 0:"Expose the Windows Android SDK adb.exe to WSL, or enable /dev/kvm for a Linux SDK.",status:h?.endsWith(".exe")?"pass":"warn"});else if(n==="linux"){let y=await r("/dev/kvm");g.push({id:"android.virtualization",label:"Linux KVM acceleration",platform:"android",remediation:y?void 0:"Enable KVM and grant the current user access to /dev/kvm.",status:y?"pass":"warn"})}if(n!=="macos")return g.push({id:"ios.simulator",label:"iOS Simulator requires macOS and Xcode",platform:"ios",status:"skip"}),g;let p=await q("xcrun",[],{exists:r,which:o},n),w=await q("xcodebuild",[],{exists:r,which:o},n);if(g.push(G("ios.xcrun","Xcode command runner","ios",p,"Install Xcode and select it with xcode-select."),G("ios.xcodebuild","Xcode build system","ios",w,"Install Xcode and select it with xcode-select.")),p){let y=s([p,"simctl","list","runtimes","--json"]),b=y.exitCode===0&&Sr(y.stdout);g.push({id:"ios.runtime",label:"iOS Simulator runtime",platform:"ios",remediation:b?void 0:"Run absolute mobile doctor ios --fix to download an iOS Simulator runtime.",status:b?"pass":"fail"})}return g};import{access as Tr,readFile as Pr,rename as Cr,writeFile as Dr}from"fs/promises";import{relative as Rr,resolve as Pt}from"path";var Ct="capacitor.config.ts",Re=(e,t)=>Rr(e,t).replaceAll("\\","/"),Nr=(e,t)=>`import type { CapacitorConfig } from '@capacitor/cli';
324
514
 
325
515
  const config: CapacitorConfig = {
326
516
  appId: ${JSON.stringify(e.appId)},
327
517
  appName: ${JSON.stringify(e.appName)},
328
- webDir: ${JSON.stringify(Ee(r,e.bundleDirectory))},
518
+ webDir: ${JSON.stringify(Re(t,e.bundleDirectory))},
329
519
  android: {
330
- path: ${JSON.stringify(Ee(r,`${e.nativeProjectDirectory}/android`))}
520
+ path: ${JSON.stringify(Re(t,`${e.nativeProjectDirectory}/android`))}
331
521
  },
332
522
  ios: {
333
- path: ${JSON.stringify(Ee(r,`${e.nativeProjectDirectory}/ios`))}
523
+ path: ${JSON.stringify(Re(t,`${e.nativeProjectDirectory}/ios`))}
334
524
  }
335
525
  };
336
526
 
337
527
  export default config;
338
- `,Ba=async(e)=>{try{return await Ma(e),!0}catch{return!1}},oe=async(e,r)=>{let a=ve(r.projectRoot),s=ve(a,je),c=Ua(e,a);if(await Ba(s)){if(await ka(s,"utf8")===c)return{changed:!1,path:s};if(!r.force)throw TypeError(`${je} already exists and differs; rerun with --force only after reviewing it.`)}let l=`${s}.${crypto.randomUUID()}.tmp`;return await Ca(l,c,{flag:"wx"}),await Ra(l,s),{changed:!0,path:s}};import{createHash as Ja}from"crypto";import{access as Dc,copyFile as Nc,mkdir as Ic,mkdtemp as Mc,readdir as Ha,readFile as La,rename as kc,rm as Rc,stat as Cc,writeFile as Wc}from"fs/promises";import{dirname as Bc,isAbsolute as Jc,join as Va,relative as pe,resolve as Hc,sep as Lc}from"path";var Ga=new Set(["Pods","DerivedData","build","xcuserdata"]),er=async(e,r=e,a={})=>{let s=await Ha(r,{withFileTypes:!0});return(await Promise.all(s.sort((l,t)=>l.name.localeCompare(t.name)).map(async(l)=>{let t=Va(r,l.name),u=pe(e,t).replaceAll("\\","/");if(l.isDirectory()&&(Ga.has(l.name)||u==="App/App/public"&&a.includePublicBundle!==!0))return[];if(l.isDirectory())return er(e,t,a);return l.isFile()?[t]:[]}))).flat()},rr=async(e,r={})=>{let a=Ja("sha256"),s=await er(e,e,r),c=await Promise.all(s.map((l)=>La(l)));return s.forEach((l,t)=>{a.update(pe(e,l).replaceAll("\\","/")),a.update("\x00"),a.update(c[t]??new Uint8Array),a.update("\x00")}),a.digest("hex")};var $e="AbsoluteJS iPhone",sr=180000,Qa=1000,Te=1,me=1,R=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),J=async(e)=>{try{return await Xa(e),!0}catch{return!1}},K=(e)=>e?.throwIfAborted(),za=(e,r={})=>{try{let a=Bun.spawnSync(e,{cwd:r.cwd,env:r.env,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return{exitCode:a.exitCode,stderr:a.stderr.toString(),stdout:a.stdout.toString()}}catch(a){return{exitCode:1,stderr:a instanceof Error?a.message:String(a),stdout:""}}},fr=async(e,r={})=>{return Bun.spawn(e,{cwd:r.cwd,env:r.env,signal:r.signal,stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited},ia=(e,r={})=>{Bun.spawn(e,{cwd:r.cwd,env:r.env,signal:r.signal,stderr:"ignore",stdin:"ignore",stdout:"ignore"})},cr=async(e,r)=>{let a=e.getReader(),s=new TextDecoder,c="",l=async()=>{let{done:t,value:u}=await a.read();if(t)return;c+=s.decode(u,{stream:!0});let w=c.split(/\r?\n/u);c=w.pop()??"",w.forEach(r),await l()};try{if(await l(),c+=s.decode(),c)r(c)}finally{a.releaseLock()}},va=(e,r,a)=>{let s=Bun.spawn(e,{cwd:r.cwd,env:r.env,signal:r.signal,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return cr(s.stdout,a),cr(s.stderr,a),{close:async()=>{try{s.kill()}catch{}await s.exited.catch(()=>{return})}}},k=async(e,r,a,s)=>{let c=await a(e,s);if(c!==0)throw Error(`${r} failed with status ${c}.`)},ja=async(e,r,a,s)=>{if(!e.https)return;if(!e.certificateAuthorityPath)throw Error("iOS Simulator HTTPS requires the AbsoluteJS development CA certificate.");await k([e.project.xcrun,"simctl","keychain",r,"add-root-cert",e.certificateAuthorityPath],"iOS Simulator development CA trust",a,{signal:e.signal}),s("Installed the AbsoluteJS development CA into this iOS Simulator trust store.")},lr=(e,r,a)=>a?[e.xcrun,"devicectl","device","process","launch","--terminate-existing","--device",r,e.config.appId]:[e.xcrun,"simctl","launch","--terminate-running-process",r,e.config.appId],j=(e,r)=>{if(e.exitCode!==0)throw Error(`${r} failed: ${e.stderr.trim()||e.stdout.trim()||`status ${e.exitCode}`}`);return e.stdout.trim()},De=(e,r)=>{try{let a=JSON.parse(e);if(R(a))return a}catch{}throw Error(`Invalid ${r} JSON from simctl.`)},oa=(e)=>{let a=De(e,"device type").devicetypes;if(!Array.isArray(a))return[];return a.flatMap((s)=>{if(!R(s))return[];let{identifier:c}=s,{name:l}=s;return typeof c==="string"&&typeof l==="string"?[{identifier:c,name:l}]:[]})},pa=(e)=>{let r=De(e,"runtime"),{runtimes:a}=r;if(!Array.isArray(a))return[];return a.flatMap((s)=>{if(!R(s))return[];let{identifier:c}=s,{name:l}=s,{version:t}=s;if(typeof c!=="string"||typeof l!=="string"||typeof t!=="string")return[];return[{identifier:c,isAvailable:s.isAvailable!==!1,name:l,version:t}]})},es=(e)=>{let r=De(e,"device"),{devices:a}=r;if(!R(a))return[];return Object.entries(a).flatMap(([s,c])=>{if(!Array.isArray(c))return[];return c.flatMap((l)=>{if(!R(l))return[];let{name:t}=l,{state:u}=l,{udid:w}=l;if(typeof t!=="string"||typeof u!=="string"||typeof w!=="string")return[];return[{isAvailable:l.isAvailable!==!1,name:t,runtime:s,state:u,udid:w}]})})},tr=(e)=>e.split(".").map((r)=>Number(r)),rs=(e,r)=>{let a=tr(e),s=tr(r),c=Math.max(a.length,s.length);for(let l=0;l<c;l++){let t=(a[l]??0)-(s[l]??0);if(t!==0)return t}return 0},as=(e)=>e.filter((r)=>r.isAvailable&&r.identifier.includes("SimRuntime.iOS-")).sort((r,a)=>rs(a.version,r.version))[0],wr=(e)=>Number(/iPhone\s+(\d+)/u.exec(e)?.[1]??0),ss=(e)=>e.filter((r)=>r.name.startsWith("iPhone")).sort((r,a)=>{let s=wr(a.name)-wr(r.name);if(s!==0)return s;let c=a.name.includes("Pro")?1:0,l=r.name.includes("Pro")?1:0;return c-l})[0],Ar=(e)=>{let r=T(e,".absolutejs","mobile","ios-dev-session");return{configBackup:T(r,"capacitor-config.backup"),infoBackup:T(r,"Info.plist.backup"),journal:T(r,"journal.json"),root:r}},yr=(e)=>T(e,".absolutejs","mobile","ios-native-cache.json"),v=(e,r)=>{let a=qa(we(e),we(r));return a===""||!a.startsWith(`..${Za}`)&&a!==".."&&!Ya(a)},cs=(e)=>{if(!R(e)||e.format!==Te)return null;let{configBackupPath:r}=e,{infoBackupPath:a}=e,{infoPath:s}=e,{nativeConfigPath:c}=e;if(typeof r!=="string"||typeof a!=="string"||typeof s!=="string"||typeof c!=="string")return null;return{configBackupPath:r,format:Te,infoBackupPath:a,infoPath:s,nativeConfigPath:c}},le=async(e)=>{let r=Ar(e);if(!await J(r.journal))return await _e(r.root,{force:!0,recursive:!0}),!1;let a=await te(r.journal,"utf8").then((s)=>cs(JSON.parse(s))).catch(()=>null);if(!a||!v(e,a.nativeConfigPath)||!v(e,a.infoPath)||!v(r.root,a.configBackupPath)||!v(r.root,a.infoBackupPath))throw Error(`Refusing unsafe or invalid iOS dev journal at ${r.journal}.`);if(await J(a.configBackupPath))await ar(a.configBackupPath,a.nativeConfigPath);if(await J(a.infoBackupPath))await ar(a.infoBackupPath,a.infoPath);return await _e(r.root,{force:!0,recursive:!0}),!0},ls=(e,r)=>{if(!r)return e;let a=/(<key>NSAllowsArbitraryLoads<\/key>\s*)<false\s*\/>/u;if(a.test(e))return e.replace(a,"$1<true/>");if(/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/u.test(e))return e;let s=/(<key>NSAppTransportSecurity<\/key>\s*<dict>)/u;if(s.test(e))return e.replace(s,`$1
528
+ `,Mr=async(e)=>{try{return await Tr(e),!0}catch{return!1}},Dt=async(e,t)=>{let n=Pt(t.projectRoot),r=Pt(n,Ct),o=Nr(e,n);if(await Mr(r)){if(await Pr(r,"utf8")===o)return{changed:!1,path:r};if(!t.force)throw TypeError(`${Ct} already exists and differs; rerun with --force only after reviewing it.`)}let s=`${r}.${crypto.randomUUID()}.tmp`;return await Dr(s,o,{flag:"wx"}),await Cr(s,r),{changed:!0,path:r}};import{createHash as kr}from"crypto";import{access as js,copyFile as Us,mkdir as Bs,mkdtemp as Hs,readdir as Lr,readFile as $r,rename as Vs,rm as Fs,stat as Js,writeFile as Ws}from"fs/promises";import{dirname as Gs,isAbsolute as zs,join as jr,relative as Rt,resolve as Ks,sep as Xs}from"path";var Ur=new Set(["Pods","DerivedData","build","xcuserdata"]),Nt=async(e,t=e,n={})=>{let r=await Lr(t,{withFileTypes:!0});return(await Promise.all(r.sort((s,i)=>s.name.localeCompare(i.name)).map(async(s)=>{let i=jr(t,s.name),l=Rt(e,i).replaceAll("\\","/");if(s.isDirectory()&&(Ur.has(s.name)||l==="App/App/public"&&n.includePublicBundle!==!0))return[];if(s.isDirectory())return Nt(e,i,n);return s.isFile()?[i]:[]}))).flat()},Mt=async(e,t={})=>{let n=kr("sha256"),r=await Nt(e,e,t),o=await Promise.all(r.map((s)=>$r(s)));return r.forEach((s,i)=>{n.update(Rt(e,s).replaceAll("\\","/")),n.update("\x00"),n.update(o[i]??new Uint8Array),n.update("\x00")}),n.digest("hex")};var Ne="AbsoluteJS iPhone",Lt=180000,Gr=1000,ke=1,Le=1,k=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),F=async(e)=>{try{return await Hr(e),!0}catch{return!1}},Q=(e)=>e?.throwIfAborted(),zr=(e,t={})=>{try{let n=Bun.spawnSync(e,{cwd:t.cwd,env:t.env,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return{exitCode:n.exitCode,stderr:n.stderr.toString(),stdout:n.stdout.toString()}}catch(n){return{exitCode:1,stderr:n instanceof Error?n.message:String(n),stdout:""}}},Wt=async(e,t={})=>Bun.spawn(e,{cwd:t.cwd,env:t.env,signal:t.signal,stderr:"inherit",stdin:"inherit",stdout:"inherit"}).exited,Kr=(e,t={})=>{Bun.spawn(e,{cwd:t.cwd,env:t.env,signal:t.signal,stderr:"ignore",stdin:"ignore",stdout:"ignore"})},$t=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,o="",s=async()=>{let{done:i,value:l}=await n.read();if(i)return;o+=r.decode(l,{stream:!0});let a=o.split(/\r?\n/u);o=a.pop()??"",a.forEach(t),await s()};try{if(await s(),o+=r.decode(),o)t(o)}finally{n.releaseLock()}},Xr=(e,t,n)=>{let r=Bun.spawn(e,{cwd:t.cwd,env:t.env,signal:t.signal,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return $t(r.stdout,n),$t(r.stderr,n),{close:async()=>{try{r.kill()}catch{}await r.exited.catch(()=>{return})}}},M=async(e,t,n,r)=>{let o=await n(e,r);if(o!==0)throw Error(`${t} failed with status ${o}.`)},Yr=async(e,t,n,r)=>{if(!e.https)return;if(!e.certificateAuthorityPath)throw Error("iOS Simulator HTTPS requires the AbsoluteJS development CA certificate.");await M([e.project.xcrun,"simctl","keychain",t,"add-root-cert",e.certificateAuthorityPath],"iOS Simulator development CA trust",n,{signal:e.signal}),r("Installed the AbsoluteJS development CA into this iOS Simulator trust store.")},jt=(e,t,n)=>n?[e.xcrun,"devicectl","device","process","launch","--terminate-existing","--device",t,e.config.appId]:[e.xcrun,"simctl","launch","--terminate-running-process",t,e.config.appId],ce=(e,t)=>{if(e.exitCode!==0)throw Error(`${t} failed: ${e.stderr.trim()||e.stdout.trim()||`status ${e.exitCode}`}`);return e.stdout.trim()},$e=(e,t)=>{try{let n=JSON.parse(e);if(k(n))return n}catch{}throw Error(`Invalid ${t} JSON from simctl.`)},Zr=(e)=>{let n=$e(e,"device type").devicetypes;if(!Array.isArray(n))return[];return n.flatMap((r)=>{if(!k(r))return[];let{identifier:o}=r,{name:s}=r;return typeof o==="string"&&typeof s==="string"?[{identifier:o,name:s}]:[]})},Qr=(e)=>{let t=$e(e,"runtime"),{runtimes:n}=t;if(!Array.isArray(n))return[];return n.flatMap((r)=>{if(!k(r))return[];let{identifier:o}=r,{name:s}=r,{version:i}=r;if(typeof o!=="string"||typeof s!=="string"||typeof i!=="string")return[];return[{identifier:o,isAvailable:r.isAvailable!==!1,name:s,version:i}]})},eo=(e)=>{let t=$e(e,"device"),{devices:n}=t;if(!k(n))return[];return Object.entries(n).flatMap(([r,o])=>{if(!Array.isArray(o))return[];return o.flatMap((s)=>{if(!k(s))return[];let{name:i}=s,{state:l}=s,{udid:a}=s;if(typeof i!=="string"||typeof l!=="string"||typeof a!=="string")return[];return[{isAvailable:s.isAvailable!==!1,name:i,runtime:r,state:l,udid:a}]})})},Ut=(e)=>e.split(".").map((t)=>Number(t)),to=(e,t)=>{let n=Ut(e),r=Ut(t),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=(n[s]??0)-(r[s]??0);if(i!==0)return i}return 0},no=(e)=>e.filter((t)=>t.isAvailable&&t.identifier.includes("SimRuntime.iOS-")).sort((t,n)=>to(n.version,t.version))[0],Bt=(e)=>Number(/iPhone\s+(\d+)/u.exec(e)?.[1]??0),ro=(e)=>e.filter((t)=>t.name.startsWith("iPhone")).sort((t,n)=>{let r=Bt(n.name)-Bt(t.name);if(r!==0)return r;let o=n.name.includes("Pro")?1:0,s=t.name.includes("Pro")?1:0;return o-s})[0],qt=(e)=>{let t=O(e,".absolutejs","mobile","ios-dev-session");return{configBackup:O(t,"capacitor-config.backup"),infoBackup:O(t,"Info.plist.backup"),journal:O(t,"journal.json"),root:t}},Gt=(e)=>O(e,".absolutejs","mobile","ios-native-cache.json"),ae=(e,t)=>{let n=Wr(be(e),be(t));return n===""||!n.startsWith(`..${qr}`)&&n!==".."&&!Jr(n)},oo=(e)=>{if(!k(e)||e.format!==ke)return null;let{configBackupPath:t}=e,{infoBackupPath:n}=e,{infoPath:r}=e,{nativeConfigPath:o}=e;if(typeof t!=="string"||typeof n!=="string"||typeof r!=="string"||typeof o!=="string")return null;return{configBackupPath:t,format:ke,infoBackupPath:n,infoPath:r,nativeConfigPath:o}},he=async(e)=>{let t=qt(e);if(!await F(t.journal))return await Me(t.root,{force:!0,recursive:!0}),!1;let n=await ye(t.journal,"utf8").then((r)=>oo(JSON.parse(r))).catch(()=>null);if(!n||!ae(e,n.nativeConfigPath)||!ae(e,n.infoPath)||!ae(t.root,n.configBackupPath)||!ae(t.root,n.infoBackupPath))throw Error(`Refusing unsafe or invalid iOS dev journal at ${t.journal}.`);if(await F(n.configBackupPath))await kt(n.configBackupPath,n.nativeConfigPath);if(await F(n.infoBackupPath))await kt(n.infoBackupPath,n.infoPath);return await Me(t.root,{force:!0,recursive:!0}),!0},so=(e,t)=>{if(!t)return e;let n=/(<key>NSAllowsArbitraryLoads<\/key>\s*)<false\s*\/>/u;if(n.test(e))return e.replace(n,"$1<true/>");if(/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/u.test(e))return e;let r=/(<key>NSAppTransportSecurity<\/key>\s*<dict>)/u;if(r.test(e))return e.replace(r,`$1
339
529
  <key>NSAllowsArbitraryLoads</key>
340
530
  <true/>`);return e.replace(/<dict>/u,`<dict>
341
531
  <key>NSAppTransportSecurity</key>
342
532
  <dict>
343
533
  <key>NSAllowsArbitraryLoads</key>
344
534
  <true/>
345
- </dict>`)},ts=async(e,r,a,s="localhost")=>{let c=Ar(e.projectRoot);await le(e.projectRoot);let l=T(e.nativeDirectory,"App","App","capacitor.config.json"),t=T(e.nativeDirectory,"App","App","Info.plist"),[u,w]=await Promise.all([te(l,"utf8"),te(t,"utf8")]),b=JSON.parse(u);if(!R(b))throw Error(`Invalid Capacitor native config at ${l}.`);await P(c.root,{recursive:!0}),await Promise.all([G(c.configBackup,u,{flag:"wx"}),G(c.infoBackup,w,{flag:"wx"})]);let x={configBackupPath:c.configBackup,format:Te,infoBackupPath:c.infoBackup,infoPath:t,nativeConfigPath:l};await G(c.journal,`${JSON.stringify(x,null,"\t")}
346
- `,{flag:"wx"});let A=new URL(`${a?"https":"http"}://localhost:${r}${e.config.entry}`);A.hostname=Pa(s)===6?`[${s}]`:s,A.searchParams.set("__absolute_target","capacitor-ios");let f=b.server;b.server={...R(f)?f:{},cleartext:!a,url:A.href},await Promise.all([G(l,`${JSON.stringify(b,null,"\t")}
347
- `),G(t,ls(w,!a))])},ws=(e)=>{if(!R(e))return null;let{appId:r,fingerprint:a,format:s,installations:c}=e;if(s!==me||typeof r!=="string"||typeof a!=="string"||!R(c)||!Object.values(c).every((l)=>typeof l==="string"))return null;return{appId:r,fingerprint:a,format:s,installations:Object.fromEntries(Object.entries(c).map(([l,t])=>[l,String(t)]))}},bs=(e)=>te(yr(e),"utf8").then((r)=>ws(JSON.parse(r))).catch(()=>null),xr=async(e,r)=>{let a=yr(e),s=`${a}.${process.pid}.${Fa()}.tmp`;await P(nr(a),{recursive:!0});try{await G(s,`${JSON.stringify(r,null,"\t")}
348
- `,{flag:"wx"}),await Ka(s,a)}finally{await _e(s,{force:!0}).catch(()=>{return})}},us=async(e,r={})=>rr(e.nativeDirectory,r),Sr=(e,r)=>{let a=r([e,"simctl","list","devices","available","-j"]);return es(j(a,"iOS simulator discovery"))},ds=async(e,r)=>{let a=pa(j(r([e.xcrun,"simctl","list","runtimes","-j"]),"iOS runtime discovery")),s=as(a);if(!s)throw Error("No available iOS Simulator runtime. Run absolute mobile doctor ios --fix.");let[c]=Sr(e.xcrun,r).filter((w)=>w.isAvailable&&w.name===$e&&w.runtime===s.identifier).sort((w,b)=>Number(b.state==="Booted")-Number(w.state==="Booted"));if(c)return{created:!1,device:c};let l=oa(j(r([e.xcrun,"simctl","list","devicetypes","-j"]),"iOS device-type discovery")),t=ss(l);if(!t)throw Error("Xcode did not report an iPhone simulator type.");let[u]=j(r([e.xcrun,"simctl","create",$e,t.identifier,s.identifier]),"iOS simulator creation").split(/\s/u);if(!u)throw Error("simctl did not return the created simulator UDID.");return{created:!0,device:{isAvailable:!0,name:$e,runtime:s.identifier,state:"Shutdown",udid:u}}},ns=async(e,r,a,s,c)=>{let l=Date.now()+sr,t=async()=>{if(K(c),Sr(e.xcrun,a).find((w)=>w.udid===r)?.state==="Booted")return;if(Date.now()>l)throw Error(`iOS simulator ${r} did not finish booting within ${sr/1000}s.`);await s(Qa),await t()};return t()},fs=(e,r,a)=>{if(r.state==="Booted")return;j(a([e.xcrun,"simctl","boot",r.udid]),"iOS simulator boot")},br=(e,r,a)=>{let s=a([e.xcrun,"simctl","get_app_container",r,e.config.appId,"app"]);return s.exitCode===0&&s.stdout.trim()?s.stdout.trim():void 0},As=(e,r,a)=>{let s=a([e.xcrun,"devicectl","device","info","details","--device",r]);if(s.exitCode!==0)throw Error(`Physical iOS device ${JSON.stringify(r)} is unavailable: ${s.stderr.trim()||s.stdout.trim()||"pair it in Xcode Device Hub, trust this Mac, unlock it, and enable Developer Mode."}`)},ys=(e,r,a)=>{let s=a([e.xcrun,"devicectl","device","info","apps","--device",r]);return s.exitCode===0&&s.stdout.includes(e.config.appId)},xs=async(e,r,a,s,c)=>{let l=T(e.projectRoot,".absolutejs","mobile","ios-derived-data",dr("sha256").update(e.config.appId).digest("hex").slice(0,16));await P(l,{recursive:!0}),await k([e.xcodebuild,"-workspace",T(e.nativeDirectory,"App","App.xcworkspace"),"-scheme","App","-configuration","Debug","-destination",`platform=iOS Simulator,id=${r}`,"-derivedDataPath",l,"build"],"iOS simulator build",s,{cwd:e.nativeDirectory,signal:c});let t=T(l,"Build","Products","Debug-iphonesimulator","App.app");if(!await J(t))throw Error(`Xcode did not produce the simulator app at ${t}.`);return t},Ss=async(e,r,a,s)=>{let c=T(e.projectRoot,".absolutejs","mobile","ios-derived-data",dr("sha256").update(e.config.appId).digest("hex").slice(0,16));await P(c,{recursive:!0}),await k([e.xcodebuild,"-workspace",T(e.nativeDirectory,"App","App.xcworkspace"),"-scheme","App","-configuration","Debug","-destination",`platform=iOS,id=${r}`,"-derivedDataPath",c,"-allowProvisioningUpdates","build"],"iOS physical-device build (configure automatic signing and a Development Team in Xcode if this is the first run)",a,{cwd:e.nativeDirectory,signal:s});let l=T(c,"Build","Products","Debug-iphoneos","App.app");if(!await J(l))throw Error(`Xcode did not produce the physical-device app at ${l}.`);return l},gs=async(e)=>{if(e.cache?.appId===e.project.config.appId&&e.cache.fingerprint===e.fingerprint&&e.cache.installations[e.identifier]===e.fingerprint&&ys(e.project,e.identifier,e.capture))return e.log("iOS native app is unchanged on the selected physical device; skipped Xcode build and install."),!0;e.log("iOS native inputs changed or the physical-device install is stale; rebuilding."),e.transition("building");let a=await Ss(e.project,e.identifier,e.run,e.signal);return K(e.signal),e.transition("installing"),await k([e.project.xcrun,"devicectl","device","install","app","--device",e.identifier,a],"iOS physical-device app installation",e.run,{signal:e.signal}),await xr(e.project.projectRoot,{appId:e.project.config.appId,fingerprint:e.fingerprint,format:me,installations:{...e.cache?.appId===e.project.config.appId?e.cache.installations:{},[e.identifier]:e.fingerprint}}).catch((s)=>e.log(`iOS native cache could not be saved: ${s instanceof Error?s.message:String(s)}`)),!1},hs=async(e)=>{let r=br(e.project,e.udid,e.capture);if(e.cache?.appId===e.project.config.appId&&e.cache.fingerprint===e.fingerprint&&r!==void 0&&e.cache.installations[e.udid]===r)return e.log(`iOS native app is unchanged on ${e.udid}; skipped Xcode build and install.`),!0;e.log("iOS native inputs changed or the installed app is stale; rebuilding."),e.transition("building");let s=await xs(e.project,e.udid,e.fingerprint,e.run,e.signal);K(e.signal),e.transition("installing"),await k([e.project.xcrun,"simctl","install",e.udid,s],"iOS simulator app installation",e.run,{signal:e.signal});let c=br(e.project,e.udid,e.capture);if(c)await xr(e.project.projectRoot,{appId:e.project.config.appId,fingerprint:e.fingerprint,format:me,installations:{[e.udid]:c}}).catch((l)=>e.log(`iOS native cache could not be saved: ${l instanceof Error?l.message:String(l)}`));return!1},Os=/((?:authorization|cookie|password|secret|token|oauth[_-]?code)\s*[:=]\s*)([^\s,;]+)/giu,Es=new RegExp(String.raw`\bBearer\s+[A-Za-z0-9._~+/-]+=*`,"giu"),$s=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu,_s=new RegExp(String.raw`\s(Debug|Info|Notice|Error|Fault)\s+.*?\[[^\]]+\]\s+\[([^\]]+)\]\s*(.*)$`,"iu"),Ts=(e)=>{let r=ms(e).trim();if(!r)return null;let a=_s.exec(r),s=a?.[1]?.toLowerCase();return{level:s==="debug"||s==="error"||s==="fault"||s==="notice"?s:"info",message:a?.[3]?.trim()||r,tag:a?.[2]?.trim()||"App"}},ms=(e)=>e.replaceAll(Es,"Bearer [REDACTED]").replaceAll($s,"[REDACTED_JWT]").replaceAll(Os,"$1[REDACTED]").replaceAll(/\p{C}/gu,""),ur=(e,r,a)=>{if(!a.nativeLog)return null;let s=a.startNativeLogs??va,c=a.deviceIdentifier?[e.xcrun,"devicectl","device","process","launch","--console","--terminate-existing","--device",r,e.config.appId]:[e.xcrun,"simctl","spawn",r,"log","stream","--style","compact","--level","debug","--predicate",'process == "App"'];return s(c,{signal:a.signal},(l)=>{let t=Ts(l);if(t)a.nativeLog?.(t)})},Ds=[["syncing","Capacitor sync"],["configuring","dev config"],["fingerprinting","fingerprint"],["booting","simulator"],["connecting","device ready"],["enrolling-trust","HTTPS trust"],["checking-native","app check"],["building","Xcode"],["installing","install"],["launching","launch"],["streaming-logs","logs"]],Ns=(e)=>Ds.map(([r,a])=>{let s=e[r];return s===void 0?null:`${a} ${z(s)}`}).filter((r)=>r!==null).join(", "),gr=async(e,r)=>{if(ce()!=="macos")throw Error("iOS development requires macOS and Xcode.");let a=r.target??"simulator",s=we(r.projectRoot),c=await ie({host:"macos"}),l=c.filter((A)=>A.platform==="ios"&&!(a==="device"&&A.id==="ios.runtime")&&(A.status==="fail"||A.status==="warn"));if(l.length>0)throw Error(`iOS ${a} development is not ready: ${l.map(({label:A})=>A).join(", ")}.`);let t=c.find((A)=>A.id==="ios.xcrun")?.path,u=c.find((A)=>A.id==="ios.xcodebuild")?.path;if(!t||!u)throw Error("Xcode tools disappeared after readiness checks.");let w=T(s,"node_modules",".bin","cap");if(!await J(w))throw Error("Capacitor CLI is not installed. Run absolute mobile init first.");await oe(e,{projectRoot:s}),await P(e.bundleDirectory,{recursive:!0});let b=T(e.bundleDirectory,"index.html");if(!await J(b))await G(b,`<!doctype html><title>AbsoluteJS mobile development</title>
349
- `);let x=T(e.nativeProjectDirectory,"ios");if(!await J(x)){if(!r.createNativeProject)throw Error("iOS native project has not been created.");if(await(r.run??fr)([w,"add","ios"],{cwd:s})!==0)throw Error("Capacitor iOS project creation failed.")}return{cap:w,config:e,nativeDirectory:x,projectRoot:s,xcodebuild:u,xcrun:t}},Is=async(e)=>{if(e.transition("connecting"),As(e.project,e.deviceIdentifier,e.capture),!e.startOptions.https)return{caEnrollmentServer:null,startedSimulator:!1,udid:e.deviceIdentifier};if(!e.startOptions.certificateAuthorityPath)throw Error("Physical iOS HTTPS development requires the AbsoluteJS development CA certificate.");e.transition("enrolling-trust");let a=await(e.startOptions.startCaEnrollmentServer??re)({certificateAuthorityPath:e.startOptions.certificateAuthorityPath,displayHost:e.serverHost});return e.log(`On the iOS device, open ${a.url}, install the AbsoluteJS development CA profile, then enable it under Settings > General > About > Certificate Trust Settings. This public CA endpoint exists only for this dev session.`),{caEnrollmentServer:a,startedSimulator:!1,udid:e.deviceIdentifier}},Ms=async(e)=>{e.transition("booting");let r=await ds(e.project,e.capture),{device:a}=r,s=r.created||a.state!=="Booted";return fs(e.project,a,e.capture),e.spawn(["open","-a","Simulator","--args","-CurrentDeviceUDID",a.udid]),e.transition("connecting"),await ns(e.project,a.udid,e.capture,e.sleep,e.startOptions.signal),await k([e.project.xcrun,"simctl","bootstatus",a.udid,"-b"],"iOS simulator boot readiness",e.run,{signal:e.startOptions.signal}),await ja(e.startOptions,a.udid,e.run,e.log),{caEnrollmentServer:null,startedSimulator:s,udid:a.udid}},Ne=async(e)=>{let{project:r}=e,a=e.deviceIdentifier?Ve(e.deviceIdentifier):void 0,s=a?"device":"simulator",c=a?ye(e.serverHost??""):"localhost",l=e.capture??za,t=e.run??fr,u=e.sleep??Bun.sleep,w=e.spawn??ia,b=e.log??console.log,x=performance.now(),A=performance.now(),f={},O="syncing",n=(g)=>{if(g===O){e.onStateChange?.(g);return}let C=performance.now(),F=C-A;f[O]=(f[O]??0)+F,e.onPhaseTiming?.({durationMs:F,phase:O,totalMs:C-x}),O=g,A=C,e.onStateChange?.(g)},y=null,S=null,D=async()=>{let g=y;y=null,await g?.close().catch(()=>{return})},h=async(g)=>{if(a&&e.nativeLog){await D(),y=ur(r,g,e);return}await k(lr(r,g,a!==void 0),"iOS app relaunch",t,{signal:e.signal})};try{if(await le(r.projectRoot),K(e.signal),n("syncing"),await k([r.cap,"sync","ios"],"Capacitor iOS synchronization",t,{cwd:r.projectRoot,signal:e.signal}),n("configuring"),e.embeddedBundle!==!0)await ts(r,e.port,e.https===!0,c);K(e.signal);let g=performance.now(),C=us(r,{includePublicBundle:e.embeddedBundle===!0}).then((B)=>{return f.fingerprinting=performance.now()-g,B}),F=a?await Is({capture:l,deviceIdentifier:a,log:b,project:r,serverHost:c,startOptions:e,transition:n}):await Ms({capture:l,log:b,project:r,run:t,sleep:u,spawn:w,startOptions:e,transition:n}),{caEnrollmentServer:o,startedSimulator:ne,udid:d}=F;S=o;let E=await C;n("checking-native");let m=await bs(r.projectRoot),M=a?await gs({cache:m,capture:l,fingerprint:E,identifier:a,log:b,project:r,run:t,signal:e.signal,transition:n}):await hs({cache:m,capture:l,fingerprint:E,log:b,project:r,run:t,signal:e.signal,transition:n,udid:d});if(K(e.signal),e.nativeLog)n("streaming-logs");if(y=ur(r,d,e),n("launching"),!a||!y)await k(lr(r,d,a!==void 0),"iOS app launch",t,{signal:e.signal});n("ready"),f.total=performance.now()-x,b(e.embeddedBundle===!0?`iOS ${s} connected with the embedded bundle and backend on port ${e.port} in ${z(f.total)} (${M?"native cache hit":"native build installed"}).`:`iOS ${s} connected with HMR on port ${e.port} in ${z(f.total)} (${M?"native cache hit":"native build installed"}).`),b(`iOS startup: ${Ns(f)}.`);let N=!1,U=async()=>{if(N)return;N=!0,n("closing"),await D(),await S?.close().catch(()=>{return}),S=null,await le(r.projectRoot),n("closed")};return{close:U,nativeCacheHit:M,startedSimulator:ne,targetKind:s,timings:{...f},udid:d,rebuild:async()=>{if(N)throw Error("iOS development session is closed.");return b("iOS native inputs changed; rebuilding without restarting the dev server."),await U(),Ne(e)},relaunch:async()=>{if(N)throw Error("iOS development session is closed.");n("launching");try{await h(d),n("ready"),b(`iOS app relaunched on the selected ${s}.`)}catch(B){throw n("failed"),B}},screenshot:async(B)=>{if(a)throw Error("Physical iOS screenshots are captured in Xcode Device Hub; the CLI never records a device screen automatically.");let H=we(r.projectRoot,B);if(!v(r.projectRoot,H))throw Error("iOS screenshot destination must remain inside the project.");return await P(nr(H),{recursive:!0}),await k([r.xcrun,"simctl","io",d,"screenshot",H],"iOS simulator screenshot",t,{signal:e.signal}),H},get state(){return O}}}catch(g){throw n("failed"),await D(),await S?.close().catch(()=>{return}),await le(r.projectRoot),g}};var hr="ABSOLUTE_REMOTE_MAC\t",be=2;var $=(e)=>process.stdout.write(`${hr}${JSON.stringify({...e,v:be})}
350
- `),de=(e)=>e instanceof Error?e.message:String(e),Y=(e,r)=>{let a=e.indexOf(r);return a<0?void 0:e[a+1]},Ws=(e)=>{let r=Number(Y(e,"--port"));if(!Number.isInteger(r)||r<1||r>65535)throw TypeError("Remote iOS agent requires a valid --port.");return r},Me=(e,r)=>{let a=Y(e,r);if(a===void 0)return;let s=Number(a);if(!Number.isInteger(s)||s<1||s>65535)throw TypeError(`Remote iOS agent requires a valid ${r}.`);return s},Us=(e)=>{let r=Y(e,"--mobile-config");if(!r)throw TypeError("Remote iOS agent requires --mobile-config.");let a=JSON.parse(Buffer.from(r,"base64url").toString("utf8"));if(typeof a!=="object"||a===null)throw TypeError("Remote iOS agent received an invalid mobile config.");return a},Or=async(e,r)=>{let a=e.getReader(),s=new TextDecoder,c="";try{while(!0){let{done:l,value:t}=await a.read();if(l)break;c+=s.decode(t,{stream:!0});let u=c.split(/\r?\n/u);c=u.pop()??"",u.forEach(r)}}finally{a.releaseLock()}},ke=async(e,r={})=>{let a=Bun.spawn(e,{cwd:r.cwd,env:r.env,signal:r.signal,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return Or(a.stdout,(s)=>$({message:s,type:"log"})),Or(a.stderr,(s)=>$({message:s,type:"log"})),a.exited},Bs=(e,r={})=>{try{let a=Bun.spawnSync(e,{cwd:r.cwd,env:r.env,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return{exitCode:a.exitCode,stderr:a.stderr.toString(),stdout:a.stdout.toString()}}catch(a){return{exitCode:1,stderr:de(a),stdout:""}}},Er=(e)=>({engine:"capacitor",nativeCacheHit:e.nativeCacheHit,startedSimulator:e.startedSimulator,targetKind:e.targetKind,timings:e.timings,type:"ready",udid:e.udid}),Js=async(e)=>{if(e.config.engine!=="expo")throw TypeError("The remote Expo executor requires Expo configuration.");let r=Me(e.args,"--metro-port");if(r===void 0)throw TypeError("Remote Expo execution requires --metro-port.");let a=Me(e.args,"--metro-relay-port");if(e.deviceIdentifier&&a===void 0)throw TypeError("Remote physical Expo execution requires --metro-relay-port.");let s=await Ye(e.config,{projectRoot:process.cwd()}),c=await Bun.file(ue(s.path,"node_modules","expo","package.json")).exists();if(!c){$({state:"preparing-native",type:"state"});let w=performance.now(),b=await ke([process.execPath,"install"],{cwd:s.path});if(b!==0)throw Error(`Remote Expo dependency installation exited with status ${b}.`);$({durationMs:performance.now()-w,phase:"preparing-native",type:"timing"})}let l,t,u;try{l=e.deviceIdentifier?await ae({listenPort:e.port,targetPort:e.relayPort??0}):void 0,t=e.deviceIdentifier?await ae({listenPort:r,targetPort:a??0}):void 0,u=await Ge({certificateAuthorityPath:e.certificateAuthorityPath,config:e.config,executable:await ge(s.path),iosDevice:e.deviceIdentifier,iosOrigin:`${e.args.includes("--https")?"https":"http"}://${e.serverHost??"localhost"}:${e.port}`,metro:"external",metroHost:e.serverHost??"localhost",metroPort:r,platforms:["ios"],log:(b)=>$({message:b,type:"log"}),onPhaseTiming:(b)=>$({...b,type:"timing"}),onStateChange:(b)=>$({state:b,type:"state"})}),$({engine:"expo",nativeCacheHit:c,startedSimulator:!1,targetKind:e.deviceIdentifier?"device":"simulator",timings:u.timings,type:"ready",udid:e.deviceIdentifier??"booted"});let w=$r({input:process.stdin,terminal:!1});try{for await(let b of w){let x;try{if(x=JSON.parse(b),x.v!==be||typeof x.id!=="string"||x.command!=="close")throw Error("Invalid remote Expo request.");await u.close(),$({id:x.id,ok:!0,type:"response"});return}catch(A){$({error:de(A),id:x?.id??"",ok:!1,type:"response"})}}}finally{w.close()}}finally{await u?.close().catch(()=>{return}),await Promise.all([l?.close().catch(()=>{return}),t?.close().catch(()=>{return})])}},Hs=async(e)=>{if(process.platform!=="darwin")throw Error("The AbsoluteJS remote iOS agent can run only on macOS.");let r=process.cwd(),a=Je(Us(e),r),s=Ws(e),c=Y(e,"--ios-device"),l=Y(e,"--server-host"),t=Me(e,"--relay-port");if(c&&(!l||t===void 0))throw TypeError("Remote physical iOS development requires --server-host and --relay-port.");let u=Y(e,"--certificate-authority"),w=u?ue(r,".absolutejs","mobile",`remote-dev-ca-${process.pid}.pem`):void 0;if(w&&u)await ks(ue(r,".absolutejs","mobile"),{recursive:!0}),await Cs(w,Buffer.from(u,"base64url"));if(a.engine==="expo"){try{await Js({args:e,certificateAuthorityPath:w,config:a,deviceIdentifier:c,port:s,relayPort:t,serverHost:l})}finally{if(w)await Ie(w,{force:!0})}return}let b=await gr(a,{createNativeProject:!1,projectRoot:r,run:ke,target:c?"device":"simulator"}),x=c?await ae({listenPort:s,targetPort:t??0}):void 0,A={capture:Bs,certificateAuthorityPath:w,deviceIdentifier:c,https:e.includes("--https"),port:s,project:b,run:ke,serverHost:l,log:(n)=>$({message:n,type:"log"}),nativeLog:(n)=>$({entry:n,type:"native-log"}),onPhaseTiming:(n)=>$({...n,type:"timing"}),onStateChange:(n)=>$({state:n,type:"state"}),spawn:(n,y={})=>{Bun.spawn(n,{cwd:y.cwd,env:y.env,signal:y.signal,stderr:"ignore",stdin:"ignore",stdout:"ignore"})}},f;try{f=await Ne(A)}catch(n){if(await x?.close().catch(()=>{return}),w)await Ie(w,{force:!0});throw n}$(Er(f));let O=$r({input:process.stdin,terminal:!1});try{for await(let n of O){let y;try{if(y=JSON.parse(n),y.v!==be||typeof y.id!=="string")throw Error("Invalid remote Mac request.");let S;if(y.command==="close")await f.close();else if(y.command==="relaunch")await f.relaunch();else if(y.command==="rebuild")f=await f.rebuild(),S=Er(f);else if(y.command==="screenshot"){let D=ue(".absolutejs","mobile","remote-screenshot.png"),h=await f.screenshot(D);S={data:(await Rs(h)).toString("base64")}}else throw Error("Unknown remote Mac request.");if($({id:y.id,ok:!0,result:S,type:"response"}),y.command==="close")return}catch(S){$({error:de(S),id:y?.id??"",ok:!1,type:"response"})}}}finally{if(O.close(),await f.close().catch(()=>{return}),await x?.close().catch(()=>{return}),w)await Ie(w,{force:!0})}},_r=async(e)=>{try{await Hs(e)}catch(r){$({error:de(r),type:"fatal"}),process.exitCode=1}};await _r(process.argv.slice(2));
535
+ </dict>`)},io=async(e,t,n,r="localhost")=>{let o=qt(e.projectRoot);await he(e.projectRoot);let s=O(e.nativeDirectory,"App","App","capacitor.config.json"),i=O(e.nativeDirectory,"App","App","Info.plist"),[l,a]=await Promise.all([ye(s,"utf8"),ye(i,"utf8")]),c=JSON.parse(l);if(!k(c))throw Error(`Invalid Capacitor native config at ${s}.`);await ee(o.root,{recursive:!0}),await Promise.all([z(o.configBackup,l,{flag:"wx"}),z(o.infoBackup,a,{flag:"wx"})]);let h={configBackupPath:o.configBackup,format:ke,infoBackupPath:o.infoBackup,infoPath:i,nativeConfigPath:s};await z(o.journal,`${JSON.stringify(h,null,"\t")}
536
+ `,{flag:"wx"});let d=new URL(`${n?"https":"http"}://localhost:${t}${e.config.entry}`);d.hostname=Fr(r)===6?`[${r}]`:r,d.searchParams.set("__absolute_target","capacitor-ios");let u=c.server;c.server={...k(u)?u:{},cleartext:!n,url:d.href},await Promise.all([z(s,`${JSON.stringify(c,null,"\t")}
537
+ `),z(i,so(a,!n))])},ao=(e)=>{if(!k(e))return null;let{appId:t,fingerprint:n,format:r,installations:o}=e;if(r!==Le||typeof t!=="string"||typeof n!=="string"||!k(o)||!Object.values(o).every((s)=>typeof s==="string"))return null;return{appId:t,fingerprint:n,format:r,installations:Object.fromEntries(Object.entries(o).map(([s,i])=>[s,String(i)]))}},co=(e)=>ye(Gt(e),"utf8").then((t)=>ao(JSON.parse(t))).catch(()=>null),zt=async(e,t)=>{let n=Gt(e),r=`${n}.${process.pid}.${Br()}.tmp`;await ee(Jt(n),{recursive:!0});try{await z(r,`${JSON.stringify(t,null,"\t")}
538
+ `,{flag:"wx"}),await Vr(r,n)}finally{await Me(r,{force:!0}).catch(()=>{return})}},lo=async(e,t={})=>Mt(e.nativeDirectory,t),Kt=(e,t)=>{let n=t([e,"simctl","list","devices","available","-j"]);return eo(ce(n,"iOS simulator discovery"))},uo=async(e,t)=>{let n=Qr(ce(t([e.xcrun,"simctl","list","runtimes","-j"]),"iOS runtime discovery")),r=no(n);if(!r)throw Error("No available iOS Simulator runtime. Run absolute mobile doctor ios --fix.");let[o]=Kt(e.xcrun,t).filter((a)=>a.isAvailable&&a.name===Ne&&a.runtime===r.identifier).sort((a,c)=>Number(c.state==="Booted")-Number(a.state==="Booted"));if(o)return{created:!1,device:o};let s=Zr(ce(t([e.xcrun,"simctl","list","devicetypes","-j"]),"iOS device-type discovery")),i=ro(s);if(!i)throw Error("Xcode did not report an iPhone simulator type.");let[l]=ce(t([e.xcrun,"simctl","create",Ne,i.identifier,r.identifier]),"iOS simulator creation").split(/\s/u);if(!l)throw Error("simctl did not return the created simulator UDID.");return{created:!0,device:{isAvailable:!0,name:Ne,runtime:r.identifier,state:"Shutdown",udid:l}}},po=async(e,t,n,r,o)=>{let s=Date.now()+Lt,i=async()=>{if(Q(o),Kt(e.xcrun,n).find((a)=>a.udid===t)?.state==="Booted")return;if(Date.now()>s)throw Error(`iOS simulator ${t} did not finish booting within ${Lt/1000}s.`);await r(Gr),await i()};return i()},mo=(e,t,n)=>{if(t.state==="Booted")return;ce(n([e.xcrun,"simctl","boot",t.udid]),"iOS simulator boot")},Ht=(e,t,n)=>{let r=n([e.xcrun,"simctl","get_app_container",t,e.config.appId,"app"]);return r.exitCode===0&&r.stdout.trim()?r.stdout.trim():void 0},fo=(e,t,n)=>{let r=n([e.xcrun,"devicectl","device","info","details","--device",t]);if(r.exitCode!==0)throw Error(`Physical iOS device ${JSON.stringify(t)} is unavailable: ${r.stderr.trim()||r.stdout.trim()||"pair it in Xcode Device Hub, trust this Mac, unlock it, and enable Developer Mode."}`)},go=(e,t,n)=>{let r=n([e.xcrun,"devicectl","device","info","apps","--device",t]);return r.exitCode===0&&r.stdout.includes(e.config.appId)},ho=async(e,t,n,r,o)=>{let s=O(e.projectRoot,".absolutejs","mobile","ios-derived-data",Ft("sha256").update(e.config.appId).digest("hex").slice(0,16));await ee(s,{recursive:!0}),await M([e.xcodebuild,"-workspace",O(e.nativeDirectory,"App","App.xcworkspace"),"-scheme","App","-configuration","Debug","-destination",`platform=iOS Simulator,id=${t}`,"-derivedDataPath",s,"build"],"iOS simulator build",r,{cwd:e.nativeDirectory,signal:o});let i=O(s,"Build","Products","Debug-iphonesimulator","App.app");if(!await F(i))throw Error(`Xcode did not produce the simulator app at ${i}.`);return i},yo=async(e,t,n,r)=>{let o=O(e.projectRoot,".absolutejs","mobile","ios-derived-data",Ft("sha256").update(e.config.appId).digest("hex").slice(0,16));await ee(o,{recursive:!0}),await M([e.xcodebuild,"-workspace",O(e.nativeDirectory,"App","App.xcworkspace"),"-scheme","App","-configuration","Debug","-destination",`platform=iOS,id=${t}`,"-derivedDataPath",o,"-allowProvisioningUpdates","build"],"iOS physical-device build (configure automatic signing and a Development Team in Xcode if this is the first run)",n,{cwd:e.nativeDirectory,signal:r});let s=O(o,"Build","Products","Debug-iphoneos","App.app");if(!await F(s))throw Error(`Xcode did not produce the physical-device app at ${s}.`);return s},bo=async(e)=>{if(e.cache?.appId===e.project.config.appId&&e.cache.fingerprint===e.fingerprint&&e.cache.installations[e.identifier]===e.fingerprint&&go(e.project,e.identifier,e.capture))return e.log("iOS native app is unchanged on the selected physical device; skipped Xcode build and install."),!0;e.log("iOS native inputs changed or the physical-device install is stale; rebuilding."),e.transition("building");let n=await yo(e.project,e.identifier,e.run,e.signal);return Q(e.signal),e.transition("installing"),await M([e.project.xcrun,"devicectl","device","install","app","--device",e.identifier,n],"iOS physical-device app installation",e.run,{signal:e.signal}),await zt(e.project.projectRoot,{appId:e.project.config.appId,fingerprint:e.fingerprint,format:Le,installations:{...e.cache?.appId===e.project.config.appId?e.cache.installations:{},[e.identifier]:e.fingerprint}}).catch((r)=>e.log(`iOS native cache could not be saved: ${r instanceof Error?r.message:String(r)}`)),!1},wo=async(e)=>{let t=Ht(e.project,e.udid,e.capture);if(e.cache?.appId===e.project.config.appId&&e.cache.fingerprint===e.fingerprint&&t!==void 0&&e.cache.installations[e.udid]===t)return e.log(`iOS native app is unchanged on ${e.udid}; skipped Xcode build and install.`),!0;e.log("iOS native inputs changed or the installed app is stale; rebuilding."),e.transition("building");let r=await ho(e.project,e.udid,e.fingerprint,e.run,e.signal);Q(e.signal),e.transition("installing"),await M([e.project.xcrun,"simctl","install",e.udid,r],"iOS simulator app installation",e.run,{signal:e.signal});let o=Ht(e.project,e.udid,e.capture);if(o)await zt(e.project.projectRoot,{appId:e.project.config.appId,fingerprint:e.fingerprint,format:Le,installations:{[e.udid]:o}}).catch((s)=>e.log(`iOS native cache could not be saved: ${s instanceof Error?s.message:String(s)}`));return!1},vo=/((?:authorization|cookie|password|secret|token|oauth[_-]?code)\s*[:=]\s*)([^\s,;]+)/giu,Ao=new RegExp(String.raw`\bBearer\s+[A-Za-z0-9._~+/-]+=*`,"giu"),So=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu,Eo=new RegExp(String.raw`\s(Debug|Info|Notice|Error|Fault)\s+.*?\[[^\]]+\]\s+\[([^\]]+)\]\s*(.*)$`,"iu"),xo=(e)=>{let t=Io(e).trim();if(!t)return null;let n=Eo.exec(t),r=n?.[1]?.toLowerCase();return{level:r==="debug"||r==="error"||r==="fault"||r==="notice"?r:"info",message:n?.[3]?.trim()||t,tag:n?.[2]?.trim()||"App"}},Io=(e)=>e.replaceAll(Ao,"Bearer [REDACTED]").replaceAll(So,"[REDACTED_JWT]").replaceAll(vo,"$1[REDACTED]").replaceAll(/\p{C}/gu,""),Vt=(e,t,n)=>{if(!n.nativeLog)return null;let r=n.startNativeLogs??Xr,o=n.deviceIdentifier?[e.xcrun,"devicectl","device","process","launch","--console","--terminate-existing","--device",t,e.config.appId]:[e.xcrun,"simctl","spawn",t,"log","stream","--style","compact","--level","debug","--predicate",'process == "App"'];return r(o,{signal:n.signal},(s)=>{let i=xo(s);if(i)n.nativeLog?.(i)})},Oo=[["syncing","Capacitor sync"],["configuring","dev config"],["fingerprinting","fingerprint"],["booting","simulator"],["connecting","device ready"],["enrolling-trust","HTTPS trust"],["checking-native","app check"],["building","Xcode"],["installing","install"],["launching","launch"],["streaming-logs","logs"]],_o=(e)=>Oo.map(([t,n])=>{let r=e[t];return r===void 0?null:`${n} ${se(r)}`}).filter((t)=>t!==null).join(", "),Xt=async(e,t)=>{if(ge()!=="macos")throw Error("iOS development requires macOS and Xcode.");let n=t.target??"simulator",r=be(t.projectRoot),o=await Tt({host:"macos"}),s=o.filter((d)=>d.platform==="ios"&&!(n==="device"&&d.id==="ios.runtime")&&(d.status==="fail"||d.status==="warn"));if(s.length>0)throw Error(`iOS ${n} development is not ready: ${s.map(({label:d})=>d).join(", ")}.`);let i=o.find((d)=>d.id==="ios.xcrun")?.path,l=o.find((d)=>d.id==="ios.xcodebuild")?.path;if(!i||!l)throw Error("Xcode tools disappeared after readiness checks.");let a=O(r,"node_modules",".bin","cap");if(!await F(a))throw Error("Capacitor CLI is not installed. Run absolute mobile init first.");await Dt(e,{projectRoot:r}),await ee(e.bundleDirectory,{recursive:!0});let c=O(e.bundleDirectory,"index.html");if(!await F(c))await z(c,`<!doctype html><title>AbsoluteJS mobile development</title>
539
+ `);let h=O(e.nativeProjectDirectory,"ios");if(!await F(h)){if(!t.createNativeProject)throw Error("iOS native project has not been created.");if(await(t.run??Wt)([a,"add","ios"],{cwd:r})!==0)throw Error("Capacitor iOS project creation failed.")}return{cap:a,config:e,nativeDirectory:h,projectRoot:r,xcodebuild:l,xcrun:i}},To=async(e)=>{if(e.transition("connecting"),fo(e.project,e.deviceIdentifier,e.capture),!e.startOptions.https)return{caEnrollmentServer:null,startedSimulator:!1,udid:e.deviceIdentifier};if(!e.startOptions.certificateAuthorityPath)throw Error("Physical iOS HTTPS development requires the AbsoluteJS development CA certificate.");e.transition("enrolling-trust");let n=await(e.startOptions.startCaEnrollmentServer??ue)({certificateAuthorityPath:e.startOptions.certificateAuthorityPath,displayHost:e.serverHost});return e.log(`On the iOS device, open ${n.url}, install the AbsoluteJS development CA profile, then enable it under Settings > General > About > Certificate Trust Settings. This public CA endpoint exists only for this dev session.`),{caEnrollmentServer:n,startedSimulator:!1,udid:e.deviceIdentifier}},Po=async(e)=>{e.transition("booting");let t=await uo(e.project,e.capture),{device:n}=t,r=t.created||n.state!=="Booted";return mo(e.project,n,e.capture),e.spawn(["open","-a","Simulator","--args","-CurrentDeviceUDID",n.udid]),e.transition("connecting"),await po(e.project,n.udid,e.capture,e.sleep,e.startOptions.signal),await M([e.project.xcrun,"simctl","bootstatus",n.udid,"-b"],"iOS simulator boot readiness",e.run,{signal:e.startOptions.signal}),await Yr(e.startOptions,n.udid,e.run,e.log),{caEnrollmentServer:null,startedSimulator:r,udid:n.udid}},je=async(e)=>{let{project:t}=e,n=e.deviceIdentifier?Xe(e.deviceIdentifier):void 0,r=n?"device":"simulator",o=n?xe(e.serverHost??""):"localhost",s=e.capture??zr,i=e.run??Wt,l=e.sleep??Bun.sleep,a=e.spawn??Kr,c=e.log??console.log,h=performance.now(),d=performance.now(),u={},S="syncing",f=(b)=>{if(b===S){e.onStateChange?.(b);return}let E=performance.now(),_=E-d;u[S]=(u[S]??0)+_,e.onPhaseTiming?.({durationMs:_,phase:S,totalMs:E-h}),S=b,d=E,e.onStateChange?.(b)},g=null,p=null,w=async()=>{let b=g;g=null,await b?.close().catch(()=>{return})},y=async(b)=>{if(n&&e.nativeLog){await w(),g=Vt(t,b,e);return}await M(jt(t,b,n!==void 0),"iOS app relaunch",i,{signal:e.signal})};try{if(await he(t.projectRoot),Q(e.signal),f("syncing"),await M([t.cap,"sync","ios"],"Capacitor iOS synchronization",i,{cwd:t.projectRoot,signal:e.signal}),f("configuring"),e.embeddedBundle!==!0)await io(t,e.port,e.https===!0,o);Q(e.signal);let b=performance.now(),E=lo(t,{includePublicBundle:e.embeddedBundle===!0}).then((V)=>(u.fingerprinting=performance.now()-b,V)),_=n?await To({capture:s,deviceIdentifier:n,log:c,project:t,serverHost:o,startOptions:e,transition:f}):await Po({capture:s,log:c,project:t,run:i,sleep:l,spawn:a,startOptions:e,transition:f}),{caEnrollmentServer:L,startedSimulator:j,udid:m}=_;p=L;let A=await E;f("checking-native");let T=await co(t.projectRoot),N=n?await bo({cache:T,capture:s,fingerprint:A,identifier:n,log:c,project:t,run:i,signal:e.signal,transition:f}):await wo({cache:T,capture:s,fingerprint:A,log:c,project:t,run:i,signal:e.signal,transition:f,udid:m});if(Q(e.signal),e.nativeLog)f("streaming-logs");if(g=Vt(t,m,e),f("launching"),!n||!g)await M(jt(t,m,n!==void 0),"iOS app launch",i,{signal:e.signal});f("ready"),u.total=performance.now()-h,c(e.embeddedBundle===!0?`iOS ${r} connected with the embedded bundle and backend on port ${e.port} in ${se(u.total)} (${N?"native cache hit":"native build installed"}).`:`iOS ${r} connected with HMR on port ${e.port} in ${se(u.total)} (${N?"native cache hit":"native build installed"}).`),c(`iOS startup: ${_o(u)}.`);let D=!1,H=async()=>{if(D)return;D=!0,f("closing"),await w(),await p?.close().catch(()=>{return}),p=null,await he(t.projectRoot),f("closed")};return{close:H,nativeCacheHit:N,startedSimulator:j,targetKind:r,timings:{...u},udid:m,rebuild:async()=>{if(D)throw Error("iOS development session is closed.");return c("iOS native inputs changed; rebuilding without restarting the dev server."),await H(),je(e)},relaunch:async()=>{if(D)throw Error("iOS development session is closed.");f("launching");try{await y(m),f("ready"),c(`iOS app relaunched on the selected ${r}.`)}catch(V){throw f("failed"),V}},screenshot:async(V)=>{if(n)throw Error("Physical iOS screenshots are captured in Xcode Device Hub; the CLI never records a device screen automatically.");let J=be(t.projectRoot,V);if(!ae(t.projectRoot,J))throw Error("iOS screenshot destination must remain inside the project.");return await ee(Jt(J),{recursive:!0}),await M([t.xcrun,"simctl","io",m,"screenshot",J],"iOS simulator screenshot",i,{signal:e.signal}),J},get state(){return S}}}catch(b){throw f("failed"),await w(),await p?.close().catch(()=>{return}),await he(t.projectRoot),b}};var Yt="ABSOLUTE_REMOTE_MAC\t",we=2;var I=(e)=>process.stdout.write(`${Yt}${JSON.stringify({...e,v:we})}
540
+ `),Ae=(e)=>e instanceof Error?e.message:String(e),te=(e,t)=>{let n=e.indexOf(t);return n<0?void 0:e[n+1]},No=(e)=>{let t=Number(te(e,"--port"));if(!Number.isInteger(t)||t<1||t>65535)throw TypeError("Remote iOS agent requires a valid --port.");return t},Be=(e,t)=>{let n=te(e,t);if(n===void 0)return;let r=Number(n);if(!Number.isInteger(r)||r<1||r>65535)throw TypeError(`Remote iOS agent requires a valid ${t}.`);return r},Mo=(e)=>{let t=te(e,"--mobile-config");if(!t)throw TypeError("Remote iOS agent requires --mobile-config.");let n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(typeof n!=="object"||n===null)throw TypeError("Remote iOS agent received an invalid mobile config.");return n},Zt=async(e,t)=>{let n=e.getReader(),r=new TextDecoder,o="";try{while(!0){let{done:s,value:i}=await n.read();if(s)break;o+=r.decode(i,{stream:!0});let l=o.split(/\r?\n/u);o=l.pop()??"",l.forEach(t)}}finally{n.releaseLock()}},He=async(e,t={})=>{let n=Bun.spawn(e,{cwd:t.cwd,env:t.env,signal:t.signal,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return Zt(n.stdout,(r)=>I({message:r,type:"log"})),Zt(n.stderr,(r)=>I({message:r,type:"log"})),n.exited},ko=(e,t={})=>{try{let n=Bun.spawnSync(e,{cwd:t.cwd,env:t.env,stderr:"pipe",stdin:"ignore",stdout:"pipe"});return{exitCode:n.exitCode,stderr:n.stderr.toString(),stdout:n.stdout.toString()}}catch(n){return{exitCode:1,stderr:Ae(n),stdout:""}}},Qt=(e)=>({engine:"capacitor",nativeCacheHit:e.nativeCacheHit,startedSimulator:e.startedSimulator,targetKind:e.targetKind,timings:e.timings,type:"ready",udid:e.udid}),Lo=async(e)=>{if(e.config.engine!=="expo")throw TypeError("The remote Expo executor requires Expo configuration.");let t=Be(e.args,"--metro-port");if(t===void 0)throw TypeError("Remote Expo execution requires --metro-port.");let n=Be(e.args,"--metro-relay-port");if(e.deviceIdentifier&&n===void 0)throw TypeError("Remote physical Expo execution requires --metro-relay-port.");let r=await Et(e.config,{projectRoot:process.cwd()}),o=await Bun.file(ve(r.path,"node_modules","expo","package.json")).exists();if(!o){I({state:"preparing-native",type:"state"});let a=performance.now(),c=await He([process.execPath,"install"],{cwd:r.path});if(c!==0)throw Error(`Remote Expo dependency installation exited with status ${c}.`);I({durationMs:performance.now()-a,phase:"preparing-native",type:"timing"})}let s,i,l;try{s=e.deviceIdentifier?await pe({listenPort:e.port,targetPort:e.relayPort??0}):void 0,i=e.deviceIdentifier?await pe({listenPort:t,targetPort:n??0}):void 0,l=await Ye({certificateAuthorityPath:e.certificateAuthorityPath,config:e.config,executable:await _e(r.path),iosDevice:e.deviceIdentifier,iosOrigin:`${e.args.includes("--https")?"https":"http"}://${e.serverHost??"localhost"}:${e.port}`,metro:"external",metroHost:e.serverHost??"localhost",metroPort:t,platforms:["ios"],log:(c)=>I({message:c,type:"log"}),onPhaseTiming:(c)=>I({...c,type:"timing"}),onStateChange:(c)=>I({state:c,type:"state"})}),I({engine:"expo",nativeCacheHit:o,startedSimulator:!1,targetKind:e.deviceIdentifier?"device":"simulator",timings:l.timings,type:"ready",udid:e.deviceIdentifier??"booted"});let a=en({input:process.stdin,terminal:!1});try{for await(let c of a){let h;try{if(h=JSON.parse(c),h.v!==we||typeof h.id!=="string"||h.command!=="close")throw Error("Invalid remote Expo request.");await l.close(),I({id:h.id,ok:!0,type:"response"});return}catch(d){I({error:Ae(d),id:h?.id??"",ok:!1,type:"response"})}}}finally{a.close()}}finally{await l?.close().catch(()=>{return}),await Promise.all([s?.close().catch(()=>{return}),i?.close().catch(()=>{return})])}},$o=async(e)=>{if(process.platform!=="darwin")throw Error("The AbsoluteJS remote iOS agent can run only on macOS.");let t=process.cwd(),n=Ge(Mo(e),t),r=No(e),o=te(e,"--ios-device"),s=te(e,"--server-host"),i=Be(e,"--relay-port");if(o&&(!s||i===void 0))throw TypeError("Remote physical iOS development requires --server-host and --relay-port.");let l=te(e,"--certificate-authority"),a=l?ve(t,".absolutejs","mobile",`remote-dev-ca-${process.pid}.pem`):void 0;if(a&&l)await Co(ve(t,".absolutejs","mobile"),{recursive:!0}),await Ro(a,Buffer.from(l,"base64url"));if(n.engine==="expo"){try{await Lo({args:e,certificateAuthorityPath:a,config:n,deviceIdentifier:o,port:r,relayPort:i,serverHost:s})}finally{if(a)await Ue(a,{force:!0})}return}let c=await Xt(n,{createNativeProject:!1,projectRoot:t,run:He,target:o?"device":"simulator"}),h=o?await pe({listenPort:r,targetPort:i??0}):void 0,d={capture:ko,certificateAuthorityPath:a,deviceIdentifier:o,https:e.includes("--https"),port:r,project:c,run:He,serverHost:s,log:(f)=>I({message:f,type:"log"}),nativeLog:(f)=>I({entry:f,type:"native-log"}),onPhaseTiming:(f)=>I({...f,type:"timing"}),onStateChange:(f)=>I({state:f,type:"state"}),spawn:(f,g={})=>{Bun.spawn(f,{cwd:g.cwd,env:g.env,signal:g.signal,stderr:"ignore",stdin:"ignore",stdout:"ignore"})}},u;try{u=await je(d)}catch(f){if(await h?.close().catch(()=>{return}),a)await Ue(a,{force:!0});throw f}I(Qt(u));let S=en({input:process.stdin,terminal:!1});try{for await(let f of S){let g;try{if(g=JSON.parse(f),g.v!==we||typeof g.id!=="string")throw Error("Invalid remote Mac request.");let p;if(g.command==="close")await u.close();else if(g.command==="relaunch")await u.relaunch();else if(g.command==="rebuild")u=await u.rebuild(),p=Qt(u);else if(g.command==="screenshot"){let w=ve(".absolutejs","mobile","remote-screenshot.png"),y=await u.screenshot(w);p={data:(await Do(y)).toString("base64")}}else throw Error("Unknown remote Mac request.");if(I({id:g.id,ok:!0,result:p,type:"response"}),g.command==="close")return}catch(p){I({error:Ae(p),id:g?.id??"",ok:!1,type:"response"})}}}finally{if(S.close(),await u.close().catch(()=>{return}),await h?.close().catch(()=>{return}),a)await Ue(a,{force:!0})}},tn=async(e)=>{try{await $o(e)}catch(t){I({error:Ae(t),type:"fatal"}),process.exitCode=1}};await tn(process.argv.slice(2));