@coreframe/scripts 0.2.42 → 0.2.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/coreframe.js +20 -19
- package/package.json +8 -8
package/dist/coreframe.js
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"@alloc/cmd-ts";import{array as t,command as n,extendType as r,flag as i,multioption as a,number as o,oneOf as s,option as c,optional as l,positional as u,rest as d,restPositionals as f,string as p,subcommands as m}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as h,checkDeployMigrations as g,checkSchemaPush as _,collectDeployMigrationFiles as v,createLocalPostgresDb as
|
|
3
|
-
`)}function
|
|
2
|
+
import*as e from"@alloc/cmd-ts";import{array as t,command as n,extendType as r,flag as i,multioption as a,number as o,oneOf as s,option as c,optional as l,positional as u,rest as d,restPositionals as f,string as p,subcommands as m}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as h,checkDeployMigrations as g,checkSchemaPush as _,collectDeployMigrationFiles as v,createLocalPostgresDb as y,createProjectPostgresDatabaseAdapter as b,createProjectSqliteDatabaseAdapter as x,createProjectSqliteDrizzleDatabase as S,ensureLocalDb as C,filterPendingMigrations as w,formatDbErrorMessage as T,formatMigrationList as E,formatMigrationScanFailures as ee,migrateHeldMigrations as te,migrateLocalDb as ne,readAppliedMigrationNames as re,reportLocalDatabaseInventory as ie,resetLocalDb as ae,runDrizzleKitCommand as oe,scanDeployMigrationFiles as se,seedLocalDb as ce,setupLocalDb as le,startProjectPostgres as D,startProjectTurso as ue,stopProjectPostgres as de}from"@coreframe/db";import{checkFlutterClient as O,classifyFlutterDevOutputLine as fe,ensureFlutterDevAssetDirectories as pe,flutterPlatforms as k,generateFlutterNativeBridge as A,prepareFlutterClient as me,prepareFlutterDevOutput as he,productionApiOrigin as j,runFlutterAcceptance as ge}from"@coreframe/flutter-tools";import M,{dirname as N,isAbsolute as _e,join as P,posix as ve,resolve as F,sep as ye}from"node:path";import I from"nano-spawn";import{spawnSync as L}from"node:child_process";import{chmodSync as be,existsSync as R,lstatSync as xe,mkdirSync as Se,mkdtempSync as Ce,readFileSync as z,readlinkSync as we,rmSync as Te,symlinkSync as Ee,watch as De,writeFileSync as B}from"node:fs";import{homedir as Oe,networkInterfaces as ke,tmpdir as Ae}from"node:os";import*as V from"@clack/prompts";import{addAsset as je,backupAssets as Me,buildAssets as Ne,checkAssets as Pe,printAssetResult as Fe,publishAssets as Ie}from"@coreframe/assets";import{assertAssetCredentialProfile as Le,configureAssetCredentials as Re,createB2PrivateObjectStore as ze}from"@coreframe/object-storage";import{access as Be,chmod as Ve,copyFile as He,cp as Ue,mkdir as H,mkdtemp as We,readFile as U,readdir as Ge,rename as Ke,rm as W,stat as qe,writeFile as G}from"node:fs/promises";import{importProjectDependency as Je,importProjectModule as Ye,normalizeWorkerEnvironment as Xe,primaryWorkerConfigPath as Ze,readProjectConfig as K,wranglerEnvironmentNames as Qe}from"@coreframe/config";import{createHash as $e,randomUUID as q}from"node:crypto";import J from"node:process";import{finished as et}from"node:stream/promises";import{createPrefixStream as tt,supervise as nt}from"procband";import{createConnection as rt,createServer as it}from"node:net";import{inspectDevelopmentJobStates as at}from"@coreframe/jobs";import{parse as ot,stringify as st}from"yaml";import{accessTokenSigningSecretName as ct,clearAppliedPendingWorkerSecrets as lt,deployEnvironments as ut,discardPendingWorkerSecret as dt,discoverStagingUrl as ft,inspectWorkerEnvironment as pt,materializeBuiltClientDeployConfig as mt,materializeBuiltWorkerDeployConfig as ht,materializePrimaryWorkerTypeConfig as gt,parseDeclaredWorkerSecretEnv as _t,prepareAccessTokenSigningSecret as vt,prepareReviewerDeploy as yt,queueWorkerSecret as bt,queueWorkerSecrets as xt,readDeclaredWorkerSecrets as St,readPackageJson as Ct,readPendingWorkerSecretSnapshot as wt,readPrimaryWorkerConfig as Tt,reassignStagingHostname as Et,releaseName as Dt,resolveDeployConfig as Ot,resolveDeployD1Database as kt,resolveReleaseVersion as At,rotateAccessTokenSigningSecret as jt,runAfterWorkerDeploy as Mt,runPostDeployChecks as Nt,validateWorkerEnvironmentForDeploy as Pt,verifyAccessTokenSigningSecret as Ft,writePackageVersion as It}from"@coreframe/deploy";import{inspect as Lt,parseEnv as Rt}from"node:util";import{once as zt}from"node:events";import{connectDevSupervisor as Bt,createDevStartupTiming as Vt,devHttpsCertEnv as Ht,devHttpsKeyEnv as Ut,isManagedDevCheckout as Wt,isPrimaryCheckout as Gt,prepareDevHttps as Kt}from"@coreframe/dev";import{devJobsEnv as qt}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Jt,managedDevFlutterRestartFileEnv as Yt}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as Xt}from"leylines";import{setTimeout as Zt}from"node:timers/promises";import{determineAgent as Qt}from"@vercel/detect-agent";import{runPreview as $t}from"@coreframe/preview";const en=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,tn=`COREFRAME_FLUTTER_DEVELOPMENT`,nn=[`filtered`,`full`];function rn(e,{noCodesign:t=!1}={}){return{...e,[en]:`.dev`,[tn]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function an(e=!1){return e?`debug`:`profile`}function on({device:e,mode:t,platform:n}){if(t===`profile`&&!e.physical)throw Error(`Flutter profile mode is unavailable on ${n===`ios`?`iOS simulator`:`Android emulator`}s. Re-run with --flutter-debug or select a physical device.`)}function sn({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--machine`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const cn=[`web`,...k];function ln(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(gn(e,{profile:r,simulator:i}),e===`web`)return[vn(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=j(t);return[{kind:`prepare`,platform:e},vn(`flutter`,un(e,a,{profile:r,simulator:i}),F(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function un(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){gn(e,{profile:r,simulator:i});let a=j(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function dn(e,{profile:t=!1}={}){let n=t?`profile`:`release`,r=F(e,`src-flutter/build/app/outputs/flutter-apk/app-${n}.apk`),i=JSON.stringify(r);return[`Android ${n} build succeeded.`,``,`Install it on a connected Android device:`,` 1. Enable Developer options and USB debugging, connect the device, and accept the authorization prompt.`,` 2. Verify the device is visible:`,` adb devices`,` 3. Install or update the APK:`,` adb install -r ${i}`,``,`If multiple devices are connected, use:`,` adb -s <device-id> install -r ${i}`].join(`
|
|
3
|
+
`)}function fn(e,{profile:t=!1,simulator:n=!1}={}){let r=t?`profile`:`release`,i=F(e,`src-flutter/build/ios/${n?`iphonesimulator`:`iphoneos`}/Runner.app`),a=JSON.stringify(i);return n?[`iOS Simulator ${r} build succeeded.`,``,`Install it on a booted iOS Simulator:`,` 1. Verify available simulators:`,` xcrun simctl list devices`,` 2. Install the app:`,` xcrun simctl install booted ${a}`,``,"If multiple simulators are available, replace `booted` with the simulator UDID."].join(`
|
|
4
4
|
`):[`iOS ${r} build succeeded.`,``,`Install it on a connected iOS device:`,` 1. Enable Developer Mode, connect the device, and trust this Mac if prompted.`,` 2. Verify the device is visible:`,` xcrun devicectl list devices`,` 3. Install the signed app:`,` xcrun devicectl device install app --device <device-id> ${a}`,``,`If multiple devices are connected, use the device UDID shown by devicectl.`].join(`
|
|
5
|
-
`)}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)}async function fn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=he,runCommand:s=mn}={}){pn(r,{profile:i,simulator:a});let c={...n};delete c[Zt],delete c[Qt],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:A(e??n.COREFRAME_API_ORIGIN);for(let e of on(r,{apiOrigin:l,cwd:t,profile:i,simulator:a})){if(e.kind===`prepare`){if(!l)throw Error(`A production API origin is required for the Flutter ${e.platform} build.`);await o({apiOrigin:l,cwd:t,environment:c,platform:e.platform});continue}await s(e.command,e.args,{cwd:e.cwd,env:{...c,...e.environment}})}r===`android`?console.log(cn(t,{profile:i})):r===`ios`?console.log(ln(t,{profile:i,simulator:a})):r===`windows`?console.log(un(t)):r===`linux`&&console.log(dn(t))}function pn(e,{profile:t,simulator:n}){if(t&&e===`web`)throw Error(`The --profile flag is only supported for Flutter build targets.`);if(n&&e!==`ios`)throw Error(`The --simulator flag is only supported for the iOS build target.`);if(t&&n)throw Error(`Flutter profile builds are not supported for the iOS simulator.`)}async function mn(e,t,{cwd:n,env:r}){await F(e,t,{cwd:n,env:r,stdio:`inherit`})}function hn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const gn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return A(e)}}),_n=n({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:u({type:l(s(an)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(gn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:i({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>fn({apiOrigin:e,platform:t,profile:n,simulator:r})});function vn(e){return e.apiKey??process.env.TYPESAFE_API_KEY??process.env.JEV_API_KEY}function yn(e){return e.baseUrl??process.env.TYPESAFE_API_BASE??process.env.JEV_API_BASE??`https://jevtypesafeai.com/api/v1/decide`}function bn(){return{resolvable:{type:`noul`,instructions:`Can these conflicting changes be mechanically combined without choosing between behaviors or losing either side's intent? Answer yes only when a resolution preserves both sides' semantics.`},strategy:{type:`choice`,instructions:`Which resolution strategy preserves both sides' intent?`,criteria:{keep_both:`both changes apply independently; concatenate or interleave them`,take_ours:`the ours side already supersedes or subsumes the theirs side`,take_theirs:`the theirs side already supersedes or subsumes the ours side`,combine_statements:`statements from both sides must be merged into shared code`}},risk:{type:`score`,instructions:`Risk that a mechanically produced resolution silently changes behavior, on an ordered scale.`,criteria:[`minimal`,`low`,`moderate`,`elevated`,`high`,`severe`]}}}async function xn(e,t={}){let n=vn(t);if(!n)return{called:!1,approved:!1,reason:`jev_unavailable: no API key`};let r={state:e,questions:bn()},i;try{let e=await(t.fetchImpl??fetch)(yn(t),{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(r),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!e.ok)return{called:!0,approved:!1,reason:`jev_unavailable: HTTP ${e.status}`};i=await e.json()}catch(e){return{called:!0,approved:!1,reason:`jev_unavailable: ${e instanceof Error?e.message:String(e)}`}}let a=i.answers?.resolvable?.noul;if(typeof a!=`number`||Number.isNaN(a))return{called:!0,approved:!1,reason:`jev_inconclusive: missing noul answer`,answers:i.answers};let o=t.noulThreshold??.8,s=t.confidenceThreshold??.7,c=i.answers?.strategy?.confidence??i.answers?.risk?.confidence;if(a<o)return{called:!0,approved:!1,reason:`jev_refused: resolvable ${a.toFixed(2)} < ${o}`,answers:i.answers};if(c!==void 0&&c<s)return{called:!0,approved:!1,reason:`jev_inconclusive: confidence ${c.toFixed(2)} < ${s}`,answers:i.answers};let l=i.answers?.strategy?.choice;return{called:!0,approved:!0,reason:`jev approved: resolvable ${a.toFixed(2)}${l?`, strategy ${l}`:``}`,answers:i.answers}}async function Sn(e,t={}){await Promise.all(e.map(async e=>{if(e.tier!==`judgment`)return;let n=await xn({file:e.path,reasons:e.reasons,entities:e.entities,evidence:e.evidence},t);e.gate=n,e.decision=n.approved?`resolvable`:`escalate`,e.reasons.push(n.reason)}))}const Cn=`safe`,wn=`judgment`,J=`unsafe`,Tn=new Set([`both_added`,`rename_rename`,`rename_modify`]),En=new Set([`both_modified`,`modify_delete`,...Tn]);function Dn(e,t,n){let r=I(t,n,{cwd:e,encoding:`utf8`});if(r.error)throw r.error;return r}function On(e,t=`git`){let n=Dn(e,t,[`ls-files`,`-u`,`-z`]);if(n.status!==0)throw Error(`git ls-files -u failed: ${n.stderr.trim()||n.stdout.trim()}`);let r=new Set;for(let e of n.stdout.split(`\0`)){if(!e)continue;let t=e.indexOf(` `);t!==-1&&r.add(e.slice(t+1))}return[...r]}function kn(e,t,n=`weave`){let r=I(n,[`explain`,t,`--json`],{cwd:e,encoding:`utf8`});if(r.error)return{error:`weave unavailable: ${r.error.message}`};if(r.status!==0){let e=(r.stderr||r.stdout).toString().trim();return{error:`weave explain failed (${r.status}): ${e}`}}try{return{explain:JSON.parse(r.stdout)}}catch{return{error:`weave explain returned unparseable output`}}}function An(e,t,n,r=`git`){let i=Dn(e,r,[`show`,`:${t}:${n}`]);return i.status===0?i.stdout:void 0}function jn(e){return e.collision??[]}function Mn(e){return jn(e).length>0&&e.ours?.action===`modified`&&e.theirs?.action===`modified`}function Nn(e){let t=e.kind??`unknown`,n=e.entity??`(file)`,r=[],i=(e,r)=>({entity:n,kind:t,tier:e,reasons:[r]});if(!En.has(t))return i(J,`unrecognized conflict kind "${t}"`);if(Tn.has(t))return i(J,`${t}: divergent definitions of the same-named entity`);if(t===`modify_delete`){if((e.contested_hunks??0)===0){let i=e.repair?.kept_by;return r.push(`modify_delete with no contested hunks (decide_existence${i?`, kept_by=${i}`:``})`),{entity:n,kind:t,tier:wn,reasons:r}}return i(J,`modify_delete with contested hunks: deleted entity was also rewritten`)}let a=e.hunks??[];if(a.every(e=>jn(e).length===0))return r.push(`both sides wrote adjacent lines only; no shared base statement rewritten`),{entity:n,kind:t,tier:Cn,reasons:r};if(a.some(Mn))return i(J,`collision on the same base statement: both sides rewrote it differently`);let o=a.reduce((e,t)=>e+jn(t).length,0);return o<=3?(r.push(`contested collision bounded to ${o} statement(s)`),{entity:n,kind:t,tier:wn,reasons:r}):i(J,`contested collision spans ${o} base statements`)}const Pn={[Cn]:0,[wn]:1,[J]:2};function Fn(e,t){if(t.error||!t.explain)return{path:e,tier:J,decision:`escalate`,reasons:[t.error??`no analysis`],entities:[],analysisError:t.error};let n=(t.explain.conflicts??[]).map(Nn),r=n.reduce((e,t)=>Pn[t.tier]>Pn[e]?t.tier:e,Cn),i=n.flatMap(e=>e.reasons.map(t=>`${e.entity}: ${t}`));return{path:e,tier:r,decision:r===`safe`?`resolvable`:`escalate`,reasons:i,entities:n}}const In=12e3;function Ln(e,t,n,r,i){let a={base:An(e,1,t,r),ours:An(e,2,t,r),theirs:An(e,3,t,r)},o=e=>e===void 0||e.length<=In?e:`${e.slice(0,In)}\n… truncated`,s={base:o(a.base),ours:o(a.ours),theirs:o(a.theirs)},c={};if(a.base&&(a.ours||a.theirs)){let e=we(N(je(),`coreframe-conflicts-`));try{let n=N(e,`base`);z(n,a.base);for(let r of[`ours`,`theirs`]){let o=a[r];if(!o)continue;let s=N(e,r);z(s,o);let l=I(i,[`patch`,`extract`,n,s,`--path`,t],{encoding:`utf8`});if(l.status===0)try{c[r]=JSON.parse(l.stdout)}catch{c[r]={error:`unparseable patch ops`}}}}catch{}finally{Ee(e,{recursive:!0,force:!0})}}return{explain:n,stages:s,entityOps:c}}async function Rn(e){let t=e.gitBin??`git`,n=e.weaveBin??process.env.COREFRAME_WEAVE_BIN??`weave`,r=On(e.worktree,t).map(r=>{let i=kn(e.worktree,r,n),a=Fn(r,i);return a.tier===`judgment`&&(a.evidence=Ln(e.worktree,r,i.explain,t,n)),a}),i=r.filter(e=>e.tier===wn);i.length>0&&await Sn(i,e.jev??{});let a={total:r.length,safe:r.filter(e=>e.tier===Cn).length,judgment:r.filter(e=>e.tier===wn).length,unsafe:r.filter(e=>e.tier===J).length},o=r.every(e=>e.decision===`resolvable`)?`cheap-llm-resolvable`:`escalate`;return{worktree:e.worktree,recommendation:o,files:r,summary:a}}function zn(e){for(let t of e.files){let e=t.decision===`resolvable`?` `:`!`;console.log(`${e} ${t.tier.padEnd(8)} ${t.decision.padEnd(10)} ${t.path}`);for(let e of t.reasons)console.log(` ${e}`)}let{summary:t}=e;console.log(`\n${t.total} conflicted file(s): ${t.safe} safe, ${t.judgment} judgment, ${t.unsafe} unsafe`),console.log(`recommendation: ${e.recommendation}`)}const Bn=m({name:`conflicts`,description:`Classify rebase/merge conflicts in a worktree as cheap-LLM-resolvable or escalate.`,cmds:{classify:n({name:`classify`,description:`Analyze unmerged index stages with weave and emit a per-conflict verdict. Judgment-tier conflicts are gated through the TypeSafe Jev decide API when TYPESAFE_API_KEY (or JEV_API_KEY) is set; any Jev failure escalates.`,args:{worktree:c({long:`worktree`,type:l(p),description:`Worktree to inspect. Defaults to the current directory.`}),json:i({long:`json`,description:`Print the full structured report instead of a summary.`,defaultValue:()=>!1})},handler:async({worktree:e,json:t})=>{let n=await Rn({worktree:e??process.cwd()});t?console.log(JSON.stringify(n,void 0,2)):zn(n),n.recommendation!==`cheap-llm-resolvable`&&(process.exitCode=1)}})}}),Vn=/^[a-f0-9]{64}$/,Hn=/^[a-f0-9]{40}$/,Un=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Wn(e){if(!Vn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function Gn(e){if(!Hn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function Kn(e,t){if(!Un.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function qn(e){return`projects/${Kn(e,`Project ID`)}/i18n/v1`}function Jn(e,t){return Wn(t),`${qn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function Yn(e,t){return Gn(t),`${qn(e)}/commits/${t}.json`}function Xn(e,t){return Zn(t),`${qn(e)}/releases/${encodeURIComponent(t)}.json`}function Zn(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function Y(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=P(e),r=P(n,t);if(r!==n&&!r.startsWith(`${n}${be}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function X(e,t,n){return`${e.directory}/${t}/${n}.json`}function Qn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function $n(e){await F(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function er({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=Y(t,X(e,n,a)),s=await ar(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=N(r,`${n}-${a}.json`);await V(M(l),{recursive:!0}),await Ue(o,l),i.push({path:o,backup:l}),await or(o,c)}await F(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await Ue(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await U(Y(t,Qn(e,n,r)),{force:!0})}}}async function tr({config:e,cwd:t}){let n=[];for(let r of e.locales)if(r!==e.sourceLocale)for(let i of e.catalogs){let a=await ar(Y(t,X(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>dr(e).localeCompare(dr(t)))}async function nr({config:e,cwd:t,messages:n,env:r=process.env}){if(n.length===0)return{translations:[],version:1};if(!e.generator)throw Error(`I18n preparation found ${n.length} missing translations, but no generator is configured.`);let i={messages:n,sourceLocale:e.sourceLocale,version:1};return sr(await cr({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function rr({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[dr(e),e])),a=new Map;for(let e of r.translations){let t=dr(e);if(!i.has(t))throw Error(`Translation generator returned unexpected entry ${e.locale}:${e.catalog}:${e.id}.`);if(a.has(t))throw Error(`Translation generator returned duplicate entry ${e.locale}:${e.catalog}:${e.id}.`);if(!e.translation.trim())throw Error(`Translation generator returned an empty entry ${e.locale}:${e.id}.`);a.set(t,e.translation)}let o=[...i.keys()].filter(e=>!a.has(e));if(o.length>0)throw Error(`Translation generator omitted ${o.length} required entries.`);let s=await Ye(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(dr(e));lr({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=Y(t,X(e,n,r)),o=await ar(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(dr({catalog:r,id:e,locale:n}));if(i!==void 0){if(t.translation?.trim())throw Error(`Refusing to overwrite preserved translation ${n}:${e}.`);t.translation=i,s=!0}}s&&await or(i,o)}}async function ir({config:e,cwd:t}){let n=await tr({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Ye(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await ar(Y(t,X(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);lr({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function ar(e){let t=JSON.parse(await H(e,`utf8`));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Lingui rich JSON catalog must be an object: ${e}.`);for(let[n,r]of Object.entries(t)){if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Invalid Lingui rich JSON message ${n} in ${e}.`);let t=r;if(t.translation!==void 0&&typeof t.translation!=`string`)throw Error(`Invalid translation value for ${n} in ${e}.`);if(t.message!==void 0&&t.message!==null&&typeof t.message!=`string`)throw Error(`Invalid source message value for ${n} in ${e}.`);if(t.context!==void 0&&typeof t.context!=`string`)throw Error(`Invalid context value for ${n} in ${e}.`);if(t.obsolete!==void 0&&typeof t.obsolete!=`boolean`)throw Error(`Invalid obsolete marker for ${n} in ${e}.`);if(t.comments!==void 0&&(!Array.isArray(t.comments)||t.comments.some(e=>typeof e!=`string`)))throw Error(`Invalid comments for ${n} in ${e}.`);if(t.origin!==void 0&&(!Array.isArray(t.origin)||t.origin.some(e=>!Array.isArray(e)||typeof e[0]!=`string`||e[1]!==void 0&&typeof e[1]!=`number`)))throw Error(`Invalid origins for ${n} in ${e}.`);if(t.placeholders!==void 0&&(!t.placeholders||typeof t.placeholders!=`object`||Array.isArray(t.placeholders)))throw Error(`Invalid placeholders for ${n} in ${e}.`)}return t}async function or(e,t){await V(M(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await W(n,`${JSON.stringify(t,null,2)}\n`),await qe(n,e)}function sr(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Translation generator returned invalid JSON.`)}if(!t||typeof t!=`object`||t.version!==1||!Array.isArray(t.translations))throw Error(`Translation generator returned an invalid response envelope.`);for(let e of t.translations)if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.catalog!=`string`||typeof e.locale!=`string`||typeof e.translation!=`string`)throw Error(`Translation generator returned an invalid translation entry.`);return t}function cr({args:e,command:t,cwd:n,env:r,input:i}){return F(t,e,{cwd:n,env:r,stdio:[{string:i},`pipe`,`ignore`]}).then(({stdout:e})=>{if(Buffer.byteLength(e)>10*1024*1024)throw Error(`Translation generator output exceeded 10 MiB.`);return e}).catch(()=>{throw Error(`Translation generator exited unsuccessfully.`)})}function lr({compileMessage:e,id:t,locale:n,source:r,translation:i}){let a,o;try{a=e.compileMessageOrThrow(r),o=e.compileMessageOrThrow(i)}catch{throw Error(`Translation ${n}:${t} is not valid ICU MessageFormat.`)}let s=ur(a),c=ur(o);if(s.length!==c.length||s.some((e,t)=>e!==c[t]))throw Error(`Translation ${n}:${t} does not preserve source ICU placeholders.`)}function ur(e){let t=[];function n(e){for(let r of e){if(typeof r==`string`)continue;let[e,i=`argument`,a]=r;if(t.push(`${e}:${i}`),a&&typeof a==`object`&&!Array.isArray(a))for(let e of Object.values(a))Array.isArray(e)&&n(e)}}return n(e),t.sort()}function dr(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function fr(e){return $e(`sha256`).update(e).digest(`hex`)}async function pr(e){return fr(await H(e))}function mr(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function hr({bucket:e,digest:t,projectId:n,source:r,store:i}){if(Wn(t),await pr(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=Jn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${K()}.verify`;try{if(await i.download(e,a,o),await pr(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await U(o,{force:!0})}}async function gr({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=mr(n),o=N(i,`reference-${K()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await H(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await U(o,{force:!0})}await W(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await U(o,{force:!0})}let s=N(i,`reference-${K()}.verify.json`);try{if(await r.download(e,t,s),!(await H(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await U(s,{force:!0})}}async function _r({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=mr(t),o=fr(a),s=N(i,`manifest-${o}.json`);await W(s,a,{flag:`wx`});try{await hr({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await U(s,{force:!0})}return o}async function vr({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=N(r,`reference-${K()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await H(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return Gn(r.revision),Wn(r.snapshot),r}finally{await U(i,{force:!0})}}async function yr({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await vr({bucket:e,key:Yn(t,n),store:r,temporaryDirectory:i});if(a&&a.revision!==n)throw Error(`I18n commit reference does not match requested revision ${n}.`);return a}async function br({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await gr({bucket:e,key:Yn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await gr({bucket:e,key:Xn(t,i),reference:n,store:r,temporaryDirectory:a})}async function xr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){Wn(n);let o=N(P(t),`v1`,`sha256`,n.slice(0,2),n);if(await Cr(o,n)===!1){await V(M(o),{recursive:!0});let t=`${o}.${process.pid}.${K()}.tmp`;try{if(await i.download(e,Jn(r,n),t),await pr(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await U(o,{force:!0}),await qe(t,o)}finally{await U(t,{force:!0})}}await V(M(a),{recursive:!0});let s=`${a}.${process.pid}.${K()}.tmp`;try{if(await Ue(o,s),await pr(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await U(a,{force:!0}),await qe(s,a)}finally{await U(s,{force:!0})}}async function Sr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=N(a,`manifest-${n}.json`);await xr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await H(o,`utf8`));if(s.version!==1||s.projectId!==r||typeof s.revision!=`string`||!Array.isArray(s.files)||!Array.isArray(s.catalogs)||s.catalogs.some(e=>typeof e!=`string`)||!Array.isArray(s.locales)||s.locales.some(e=>typeof e!=`string`)||typeof s.sourceLocale!=`string`||typeof s.generator!=`string`||typeof s.linguiVersion!=`string`)throw Error(`Invalid i18n snapshot manifest ${n}.`);Gn(s.revision),s.baseline!==void 0&&Wn(s.baseline);for(let e of s.files){if(!e||typeof e!=`object`||typeof e.path!=`string`||typeof e.digest!=`string`||typeof e.size!=`number`)throw Error(`Invalid file entry in i18n snapshot manifest ${n}.`);Wn(e.digest)}return s}async function Cr(e,t){try{return(await Je(e)).isFile()&&await pr(e)===t}catch{return!1}}async function wr({cwd:e=process.cwd(),env:t=process.env}={}){let n=await G({cwd:e});if(!n.i18n)return;let r=t.COREFRAME_I18N_RELEASE_REVISION;if(r){if(Or(kr(n.i18n))===`multilingual`){await Dr({cwd:e,env:t,revision:r});return}console.log(`I18n source-only mode: building source catalogs for ${r}; no prepared translation snapshot is required.`)}await $n(e)}async function Tr({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await G({cwd:e});if(!n.i18n)return;let r=kr(n.i18n),i=Y(e,r.directory);try{if(!(await Je(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await $n(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Je(Y(e,X(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await $n(e);return}}async function Er({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){Zn(r),await Rr(e);let i=await Lr(e);await zr(e,r,i);let a=await G({cwd:e});if(!a.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);let o=kr(a.i18n);if(Or(o)===`source-only`)return{mode:`source-only`,sourceLocale:o.sourceLocale};let s=await Ar({cwd:e,env:t,projectConfig:a,store:n}),c=await Ge(N(je(),`coreframe-i18n-prepare-`));try{let n=await yr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,revision:i,store:s.store,temporaryDirectory:c});if(n){let e=await Sr({bucket:s.assets.sourceBucket,cacheRoot:s.cacheRoot,digest:n.snapshot,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return Ir(s,e,i),await Mr(s,e),await br({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:n,store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!0,snapshot:n.snapshot}}return await Fr(s,c,async()=>{let n=await jr(s,i,c);n||await Pr(s),await $n(e);let a=await tr({config:s.config,cwd:e}),o=await nr({config:s.config,cwd:e,env:t,messages:a});await rr({config:s.config,cwd:e,missing:a,response:o}),await ir({config:s.config,cwd:e}),await er({config:s.config,cwd:e,strict:!0,temporaryDirectory:c});let l=await Nr(s),u={...n?{baseline:n}:{},catalogs:s.config.catalogs,files:l,generator:a.length>0?s.config.generator?.id??`unconfigured`:`none`,linguiVersion:await Br(e),locales:s.config.locales,projectId:s.assets.projectId,revision:i,sourceLocale:s.config.sourceLocale,version:1},d=await _r({bucket:s.assets.sourceBucket,manifest:u,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return await br({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:{revision:i,snapshot:d,version:1},store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!1,snapshot:d}})}finally{await U(c,{force:!0,recursive:!0})}}async function Dr({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await G({cwd:e});if(!i.i18n)return;let a=await Ar({cwd:e,env:t,store:r,projectConfig:i}),o=Gn(n??await Lr(e)),s=await Ge(N(je(),`coreframe-i18n-materialize-`));try{let e=await yr({bucket:a.assets.sourceBucket,projectId:a.assets.projectId,revision:o,store:a.store,temporaryDirectory:s});if(!e)throw Error(`No prepared i18n snapshot exists for commit ${o}. Push a v* tag for this commit and wait for the translation gate.`);let t=await Sr({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return Ir(a,t,o),await Mr(a,t),{revision:o,snapshot:e.snapshot}}finally{await U(s,{force:!0,recursive:!0})}}function Or(e){return e.locales.length===1&&e.locales[0]===e.sourceLocale?`source-only`:`multilingual`}function kr(e){let t=Kn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>Kn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>Kn(e,`Catalog`)))];if(n.length===0||!n.includes(t))throw Error(`I18n locales must include the source locale.`);if(r.length===0)throw Error(`I18n configuration requires at least one catalog.`);if(e.generator&&(!e.generator.command.trim()||!e.generator.id.trim()))throw Error(`I18n generator command and ID must be non-empty.`);return{catalogs:r,directory:e.directory??`locales`,generator:e.generator,locales:n,sourceLocale:t}}async function Ar({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await G({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:P(e,`.coreframe`,`i18n`,`cache`),config:kr(i.i18n),cwd:P(e),env:t,store:r??Be({config:a,env:t})}}async function jr(e,t,n){let{stdout:r}=await F(`git`,[`rev-list`,`--first-parent`,`--skip=1`,t],{cwd:e.cwd,stdin:`ignore`});for(let t of r.split(/\r?\n/).filter(Boolean)){let r=await yr({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:Gn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Sr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return Ir(e,i,t),await Mr(e,i),r.snapshot}}async function Mr(e,t){for(let n of t.files)if(await xr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:Y(e.cwd,n.path)}),(await Je(Y(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function Nr(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=X(e.config,n,r),a=Y(e.cwd,i),o=await pr(a);await hr({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Je(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Pr(e){let{stdout:t}=await F(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await F(`git`,[`log`,`-1`,`--format=%H`,`--diff-filter=AM`,`--`,`:(top)${`${n}${e.config.directory}/${e.config.sourceLocale}/${e.config.catalogs[0]}.po`}`],{cwd:e.cwd,stdin:`ignore`}),i=r.trim();if(!i)return!1;let a=(await Ye(`@lingui/format-po`,e.cwd)).formatter({lineNumbers:!1}),o=!1;for(let t of e.config.locales)for(let r of e.config.catalogs){let s=`${n}${`${e.config.directory}/${t}/${r}.po`}`;try{let{stdout:n}=await F(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await or(Y(e.cwd,X(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Fr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=X(e.config,n,i),o=Y(e.cwd,a);try{await Ve(o)}catch{continue}let s=N(t,`previous-catalogs`,a);await V(M(s),{recursive:!0}),await qe(o,s),r.push({backup:s,path:o})}try{let e=await n();return await U(N(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await U(Y(e.cwd,X(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await V(M(t),{recursive:!0}),await qe(e,t);throw t}}function Ir(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>X(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function Lr(e){let{stdout:t}=await F(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return Gn(t.trim())}async function Rr(e){let{stdout:t}=await F(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function zr(e,t,n){let{stdout:r}=await F(`git`,[`rev-parse`,`${t}^{commit}`],{cwd:e,stdin:`ignore`});if(r.trim()!==n)throw Error(`Release tag ${t} does not point to checked-out commit ${n}.`)}async function Br(e){let{stdout:t}=await F(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const Vr=[`Use a B2 Multi-Bucket Application Key restricted to the configured private build-object and public generated-assets buckets.`,`Required capabilities: listAllBucketNames, readFiles, and writeFiles.`,`Deletion, bucket-management, and key-management capabilities are not needed.`].join(` `),Hr=r(p,{displayName:`widths`,description:`Comma-separated responsive variant widths.`,async from(e){let t=e.split(`,`).map(e=>Number(e));if(t.length===0||t.some(e=>!Number.isInteger(e)||e<=0)||t.some((e,n)=>n>0&&e<=t[n-1]))throw Error(`Widths must be positive, unique, strictly ascending integers.`);return t}}),Ur=r(p,{displayName:`profile`,async from(e){return Re(e)}}),Wr=r(p,{displayName:`pack`,description:`Asset pack name, such as training-videos.`,async from(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))throw Error(`Asset pack names must use lowercase hyphen-separated segments.`);return e}}),Gr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return A(e)}}),Kr=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${Vr}`,args:{profile:u({type:Ur,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{B.note(Vr,`Required B2 key access`);let t=await B.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(B.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await B.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(B.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await ze({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:n({name:`add`,args:{file:u({type:p,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:c({long:`id`,type:p,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:c({long:`alt`,type:l(p),description:`Required alt text for raster image and SVG assets.`}),pack:c({long:`pack`,type:l(Wr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(Hr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>Ie(await Me({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:n({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:c({long:`branch`,type:p,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await Ne({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:n({name:`build`,args:{id:c({long:`id`,type:l(p),description:`Build only one logical asset ID.`}),pack:c({long:`pack`,type:l(Wr),description:`Build only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>Ie(await Pe({id:e,pack:n}),t,{kind:`build`})}),check:n({name:`check`,args:{fix:i({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:c({long:`pack`,type:l(Wr),description:`Check only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await Fe({fix:e,pack:n});Ie(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(Wr),description:`Publish only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Le({pack:t});Ie(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(Wr),description:`Report status for only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Fe({pack:t});Ie(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),qr=m({name:`flutter`,cmds:{acceptance:n({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Gr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>_e({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:n({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:i({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>k({check:e})}),prepare:n({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:u({type:s(O),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Gr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>he({apiOrigin:e,platform:t})}),check:n({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:u({type:s(O),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Gr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>D({apiOrigin:e,platform:t})})}}),Jr=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await wr()}}),materialize:n({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:c({long:`revision`,type:l(p),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Dr({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:n({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot. Source-only projects skip translation preparation.`,args:{tag:c({long:`tag`,type:p,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await Er({tag:e});if(t.mode===`source-only`){console.log(`Skipped i18n release preparation: the supported locales contain only the source locale "${t.sourceLocale}", so no translation snapshot is required.`);return}console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),Yr=q.platform===`win32`?`react-router.cmd`:`react-router`,Xr=q.platform===`win32`?`panda.cmd`:`panda`;async function Zr(e=q.cwd()){await ei(e),await $r(e,[`typegen`])}async function Qr(e=q.cwd(),t=q.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=j.resolve(e,`.coreframe/dashboard-build`),i=j.join(r,`client`),a=j.resolve(e,`dist/client/__dashboard`);await U(r,{force:!0,recursive:!0});let o=await G({cwd:e});if(o.deploy?.mode===`client`||o.dashboard?.enabled===!1){await U(a,{force:!0,recursive:!0});return}await ti(e,Xr,[`build`],t),await $r(e,[`build`,...n?[`--mode`,n]:[]],t),await U(a,{force:!0,recursive:!0}),await V(j.dirname(a),{recursive:!0}),await We(i,a,{recursive:!0})}async function $r(e,t,n=q.env){await ti(e,Yr,t,n)}async function ei(e){await U(j.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function ti(e,t,n,r=q.env){await F(t,n,{cwd:j.resolve(e,`dashboard`),env:{...r,PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Z={access:Ve,chmod:He,mkdir:V,mkdtemp:Ge,readFile:H,readFileSync:R,rm:U,writeFile:W},ni={getAvailablePort:ii},ri={homedir:ke,kill:q.kill,networkInterfaces:Ae,tmpdir:je};async function ii(){let e=it();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,t)});let t=e.address();if(!t||typeof t==`string`)throw Error(`Could not allocate an available TCP port.`);return t.port}finally{e.listening&&await new Promise((t,n)=>{e.close(e=>e?n(e):t())})}}function ai({host:e=`127.0.0.1`,port:t,start:n}){let r,i=!1,a=!1,o=!1,s,c,l,u,d,f=new Set,p=new Promise((e,t)=>{u=e,d=t}),m=e=>{a||o||(o=!0,d(e))},h=()=>(s||=Promise.resolve().then(n).catch(e=>{throw m(e),e}),s),g=e=>{f.add(e),e.once(`close`,()=>f.delete(e)),e.pause(),_(e).catch(t=>{m(t),e.destroy()})},_=async e=>{let t=await h();if(a||e.destroyed)return;let n=await oi(t,()=>a);if(a||e.destroyed){n.destroy();return}f.add(n),n.once(`close`,()=>f.delete(n)),n.on(`error`,()=>e.destroy()),n.once(`close`,()=>e.destroy()),e.on(`error`,()=>n.destroy()),e.once(`close`,()=>n.destroy()),e.pipe(n),n.pipe(e)};return{close:async()=>l||(l=(async()=>{a=!0,o||(o=!0,u());for(let e of f)e.destroy();f.clear(),c&&!i&&await Promise.allSettled([c]),!(!r||!i)&&(await new Promise(e=>{r.close(()=>e())}),i=!1)})(),l),fail:m,listen:async()=>c||(r=it(g),c=new Promise((n,a)=>{let o=e=>{if(i){m(e);return}a(e)};r.once(`error`,o),r.once(`listening`,()=>{i=!0,r.off(`error`,o),r.on(`error`,m),n()}),r.listen(t,e)}),c),wait:()=>p}}async function oi(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await si(e)}catch(e){if(r=e,Date.now()>=n)break;await new Promise(e=>setTimeout(e,50))}throw r instanceof Error?r:Error(`Could not connect to the dashboard.`)}function si({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=rt({host:e,port:t}),a=e=>{i.off(`connect`,o),i.destroy(),r(e)},o=()=>{i.off(`error`,a),n(i)};i.once(`error`,a),i.once(`connect`,o)})}const ci=q.platform===`win32`?`react-router.cmd`:`react-router`;function li(e){return L(j.resolve(e,`dashboard/dashboard.config.ts`))}function ui({cwd:e,env:t,port:n}){let r=t.PATH??t.Path??``,i,a,o=!1,s,c,l=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{d()};return q.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([et(t.stdout),et(t.stderr)]),i===e&&(i=void 0)}};a=ai({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await ni.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=tt({label:`dashboard`}),s=tt({color:`red`,label:`dashboard`});a.pipe(q.stdout,{end:!1}),s.pipe(q.stderr,{end:!1});let l=F(ci,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:j.resolve(e,`dashboard`),env:{...t,PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([fi(l.stdout,a),fi(l.stderr,s)]);return c=u(l,{outputTasks:d,stderr:s,stdout:a}),{host:`127.0.0.1`,port:n}}});let d=async()=>s||(s=(async()=>{o=!0,await a?.close(),i?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),await c;for(let{handler:e,signal:t}of l)q.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function di({cwd:e=q.cwd(),env:t=q.env,port:n}){let r=ui({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function fi(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const pi=m({name:`dashboard`,cmds:{dev:n({name:`dev`,args:{port:c({long:`port`,type:o,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>di({port:e})}),build:n({name:`build`,args:{mode:c({long:`mode`,type:l(p),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>Qr(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>Zr()})}});function mi(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}async function hi({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await xi(t),o=await Si(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=at({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=yi(s,{all:e,ids:n,matches:r},{defaultAll:!0});return{database:{dialect:a.dialect,state:o?`existing`:`missing`},jobs:s.filter(e=>c.has(e.id)),version:1}}async function gi({all:e,breakLeases:t=!1,cwd:n=process.cwd(),dryRun:r=!1,ids:i=[],json:a=!1,matches:o=[],now:s=new Date,yes:c=!1}){let l=await hi({all:!0,cwd:n,now:s}),u=yi(l.jobs,{all:e,ids:i,matches:o},{defaultAll:!1}),d=l.jobs.filter(e=>u.has(e.id)),f=d.filter(e=>e.lease===`active`);if(r)return{database:l.database,dryRun:!0,jobs:d.map(e=>({id:e.id,status:e.lease===`active`&&!t?`blocked-active-lease`:e.persisted?`would-reset`:`no-state`})),version:1};if(f.length>0&&!t)throw Error(`Cannot reset active development job ${Ei(f.map(e=>e.id))}. Wait for the lease to expire or pass --break-leases.`);if((t||e||o.length>0||d.length>1)&&!c){if(a||!process.stdin.isTTY)throw Error(`This reset requires --yes when prompts are unavailable.`);let e=await B.confirm({message:`Reset local development state for ${d.length} job${d.length===1?``:`s`}?`});if(B.isCancel(e)||!e)throw Error(`Development job state reset was cancelled.`)}if(l.database.state===`missing`)return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:`no-state`})),version:1};let p=await xi(n),m=await Si(p.config,n,async e=>p.module.developmentJobs.createStateAdmin(e).reset({breakLeases:t,jobIds:[...u],now:s}));if(!m)throw Error(`The local database disappeared before development job state was reset.`);if(m.activeLeaseIds.length>0&&!t)throw Error(`Cannot reset active development job ${Ei(m.activeLeaseIds)}. Wait for the lease to expire or pass --break-leases.`);let h=new Set(m.resetIds);return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:h.has(e.id)?`reset`:`no-state`})),version:1}}function _i(e){let t=Ti(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${Di([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,wi(e.lastSucceededAt),wi(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${wi(e.leaseUntil)}`]))}`}function vi(e){let t=Ti(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${Di([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function yi(e,{all:t=!1,ids:n=[],matches:r=[]},{defaultAll:i}){if(t&&(n.length>0||r.length>0))throw Error(`Use --all or explicit job selectors, not both.`);if(!t&&n.length===0&&r.length===0){if(i)return new Set(e.map(e=>e.id));throw Error(`Select one or more jobs by ID or --match, or pass --all.`)}let a=new Set(e.map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)throw Error(`Unknown development job ${Ei(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=bi(t),r=e.filter(e=>n.test(e.id));if(r.length===0)throw Error(`Development job pattern ${JSON.stringify(t)} matched no jobs.`);for(let e of r)s.add(e.id)}return s}function bi(e){if(!e)throw Error(`Development job patterns must not be empty.`);let t=[...e].map(e=>e===`*`?`.*`:e===`?`?`.`:e.replace(/[\\^$.[\]{}()+|]/gu,`\\$&`)).join(``);return RegExp(`^${t}$`,`u`)}async function xi(e){let t=await G({cwd:e}),n=t.jobs?.entry;if(!n)throw Error(`coreframe.config.ts must configure jobs.entry before managing development job state.`);let r=await Xe(n,e);if(!r.developmentJobs||!Array.isArray(r.developmentJobs.jobs)||typeof r.developmentJobs.createStateAdmin!=`function`)throw Error(`${n} must export developmentJobs with jobs and createStateAdmin properties.`);return{config:t,dialect:t.database?.dialect??`postgres`,module:r}}async function Si(e,t,n){try{var r=mi();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?j.resolve(t,`.coreframe/turso.db`):j.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await Je(o)}catch(e){if(Oi(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=mi();let r=await x({cwd:t,env:i.a(await de({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ci(n,r)}finally{r.$client.close()}}catch(e){i.e=e}finally{await i.d()}let s=await ee({cwd:t,env:r.a(await E({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ci(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Ci(e,t){try{return await e(t)}catch(e){throw ki(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function wi(e){return e?.toISOString()??`-`}function Ti(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function Ei(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function Di(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),r=e=>e.map((e,t)=>e.padEnd(n[t])).join(` `).trimEnd();return[r(e),r(n.map(e=>`-`.repeat(e))),...t.map(r)].join(`
|
|
8
|
-
`)}function
|
|
9
|
-
`).map(e=>e.trim()).filter(Boolean):[];for(let n of[`+refs/heads/*:refs/remotes/${e}/*`,`+refs/tags/*:${
|
|
10
|
-
`).map(e=>e.trim()).filter(Boolean)}function
|
|
11
|
-
`)}`);return{name:e,ref:n.refLabel}}function
|
|
12
|
-
`)}\nApply and verify ${n} before continuing.`)}}function
|
|
13
|
-
`)])),encoding:`utf8`});if(n.status!==0){let e=n.stderr.trim()||n.stdout.trim();throw Error(`Could not apply recipe patches.${e?`\n${e}`:``}`)}}function
|
|
14
|
-
`).map(e=>e.trim()).filter(Boolean)}const
|
|
5
|
+
`)}function pn(e){return[`Windows release build succeeded.`,``,`The unpackaged application bundle is at ${JSON.stringify(F(e,`src-flutter/build/windows/x64/runner/Release`))}.`,`Create and sign an installer with the Windows packaging workflow for distribution.`].join(`
|
|
6
|
+
`)}function mn(e){return[`Linux release build succeeded.`,``,`The application bundle is at ${JSON.stringify(F(e,`src-flutter/build/linux/x64/release/bundle`))}.`,`Package the bundle with the Linux distribution format used by your release process.`].join(`
|
|
7
|
+
`)}async function hn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=me,runCommand:s=_n}={}){gn(r,{profile:i,simulator:a});let c={...n};delete c[en],delete c[tn],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:j(e??n.COREFRAME_API_ORIGIN);for(let e of ln(r,{apiOrigin:l,cwd:t,profile:i,simulator:a})){if(e.kind===`prepare`){if(!l)throw Error(`A production API origin is required for the Flutter ${e.platform} build.`);await o({apiOrigin:l,cwd:t,environment:c,platform:e.platform});continue}await s(e.command,e.args,{cwd:e.cwd,env:{...c,...e.environment}})}r===`android`?console.log(dn(t,{profile:i})):r===`ios`?console.log(fn(t,{profile:i,simulator:a})):r===`windows`?console.log(pn(t)):r===`linux`&&console.log(mn(t))}function gn(e,{profile:t,simulator:n}){if(t&&e===`web`)throw Error(`The --profile flag is only supported for Flutter build targets.`);if(n&&e!==`ios`)throw Error(`The --simulator flag is only supported for the iOS build target.`);if(t&&n)throw Error(`Flutter profile builds are not supported for the iOS simulator.`)}async function _n(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function vn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const yn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return j(e)}}),bn=n({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:u({type:l(s(cn)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(yn),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:i({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>hn({apiOrigin:e,platform:t,profile:n,simulator:r})});function xn(e){return e.apiKey??process.env.TYPESAFE_API_KEY??process.env.JEV_API_KEY}function Sn(e){return e.baseUrl??process.env.TYPESAFE_API_BASE??process.env.JEV_API_BASE??`https://jevtypesafeai.com/api/v1/decide`}function Cn(){return{resolvable:{type:`noul`,instructions:`Can these conflicting changes be mechanically combined without choosing between behaviors or losing either side's intent? Answer yes only when a resolution preserves both sides' semantics.`},strategy:{type:`choice`,instructions:`Which resolution strategy preserves both sides' intent?`,criteria:{keep_both:`both changes apply independently; concatenate or interleave them`,take_ours:`the ours side already supersedes or subsumes the theirs side`,take_theirs:`the theirs side already supersedes or subsumes the ours side`,combine_statements:`statements from both sides must be merged into shared code`}},risk:{type:`score`,instructions:`Risk that a mechanically produced resolution silently changes behavior, on an ordered scale.`,criteria:[`minimal`,`low`,`moderate`,`elevated`,`high`,`severe`]}}}async function wn(e,t={}){let n=xn(t);if(!n)return{called:!1,approved:!1,reason:`jev_unavailable: no API key`};let r={state:e,questions:Cn()},i;try{let e=await(t.fetchImpl??fetch)(Sn(t),{method:`POST`,headers:{Authorization:`Bearer ${n}`,"Content-Type":`application/json`},body:JSON.stringify(r),signal:AbortSignal.timeout(t.timeoutMs??1e4)});if(!e.ok)return{called:!0,approved:!1,reason:`jev_unavailable: HTTP ${e.status}`};i=await e.json()}catch(e){return{called:!0,approved:!1,reason:`jev_unavailable: ${e instanceof Error?e.message:String(e)}`}}let a=i.answers?.resolvable?.noul;if(typeof a!=`number`||Number.isNaN(a))return{called:!0,approved:!1,reason:`jev_inconclusive: missing noul answer`,answers:i.answers};let o=t.noulThreshold??.8,s=t.confidenceThreshold??.7,c=i.answers?.strategy?.confidence??i.answers?.risk?.confidence;if(a<o)return{called:!0,approved:!1,reason:`jev_refused: resolvable ${a.toFixed(2)} < ${o}`,answers:i.answers};if(c!==void 0&&c<s)return{called:!0,approved:!1,reason:`jev_inconclusive: confidence ${c.toFixed(2)} < ${s}`,answers:i.answers};let l=i.answers?.strategy?.choice;return{called:!0,approved:!0,reason:`jev approved: resolvable ${a.toFixed(2)}${l?`, strategy ${l}`:``}`,answers:i.answers}}async function Tn(e,t={}){await Promise.all(e.map(async e=>{if(e.tier!==`judgment`)return;let n=await wn({file:e.path,reasons:e.reasons,entities:e.entities,evidence:e.evidence},t);e.gate=n,e.decision=n.approved?`resolvable`:`escalate`,e.reasons.push(n.reason)}))}const En=`safe`,Dn=`judgment`,Y=`unsafe`,On=new Set([`both_added`,`rename_rename`,`rename_modify`]),kn=new Set([`both_modified`,`modify_delete`,...On]);function An(e,t,n){let r=L(t,n,{cwd:e,encoding:`utf8`});if(r.error)throw r.error;return r}function jn(e,t=`git`){let n=An(e,t,[`ls-files`,`-u`,`-z`]);if(n.status!==0)throw Error(`git ls-files -u failed: ${n.stderr.trim()||n.stdout.trim()}`);let r=new Set;for(let e of n.stdout.split(`\0`)){if(!e)continue;let t=e.indexOf(` `);t!==-1&&r.add(e.slice(t+1))}return[...r]}function Mn(e,t,n=`weave`){let r=L(n,[`explain`,t,`--json`],{cwd:e,encoding:`utf8`});if(r.error)return{error:`weave unavailable: ${r.error.message}`};if(r.status!==0){let e=(r.stderr||r.stdout).toString().trim();return{error:`weave explain failed (${r.status}): ${e}`}}try{return{explain:JSON.parse(r.stdout)}}catch{return{error:`weave explain returned unparseable output`}}}function Nn(e,t,n,r=`git`){let i=An(e,r,[`show`,`:${t}:${n}`]);return i.status===0?i.stdout:void 0}function Pn(e){return e.collision??[]}function Fn(e){return Pn(e).length>0&&e.ours?.action===`modified`&&e.theirs?.action===`modified`}function In(e){let t=e.kind??`unknown`,n=e.entity??`(file)`,r=[],i=(e,r)=>({entity:n,kind:t,tier:e,reasons:[r]});if(!kn.has(t))return i(Y,`unrecognized conflict kind "${t}"`);if(On.has(t))return i(Y,`${t}: divergent definitions of the same-named entity`);if(t===`modify_delete`){if((e.contested_hunks??0)===0){let i=e.repair?.kept_by;return r.push(`modify_delete with no contested hunks (decide_existence${i?`, kept_by=${i}`:``})`),{entity:n,kind:t,tier:Dn,reasons:r}}return i(Y,`modify_delete with contested hunks: deleted entity was also rewritten`)}let a=e.hunks??[];if(a.every(e=>Pn(e).length===0))return r.push(`both sides wrote adjacent lines only; no shared base statement rewritten`),{entity:n,kind:t,tier:En,reasons:r};if(a.some(Fn))return i(Y,`collision on the same base statement: both sides rewrote it differently`);let o=a.reduce((e,t)=>e+Pn(t).length,0);return o<=3?(r.push(`contested collision bounded to ${o} statement(s)`),{entity:n,kind:t,tier:Dn,reasons:r}):i(Y,`contested collision spans ${o} base statements`)}const Ln={[En]:0,[Dn]:1,[Y]:2};function Rn(e,t){if(t.error||!t.explain)return{path:e,tier:Y,decision:`escalate`,reasons:[t.error??`no analysis`],entities:[],analysisError:t.error};let n=(t.explain.conflicts??[]).map(In),r=n.reduce((e,t)=>Ln[t.tier]>Ln[e]?t.tier:e,En),i=n.flatMap(e=>e.reasons.map(t=>`${e.entity}: ${t}`));return{path:e,tier:r,decision:r===`safe`?`resolvable`:`escalate`,reasons:i,entities:n}}const zn=12e3;function Bn(e,t,n,r,i){let a={base:Nn(e,1,t,r),ours:Nn(e,2,t,r),theirs:Nn(e,3,t,r)},o=e=>e===void 0||e.length<=zn?e:`${e.slice(0,zn)}\n… truncated`,s={base:o(a.base),ours:o(a.ours),theirs:o(a.theirs)},c={};if(a.base&&(a.ours||a.theirs)){let e=Ce(P(Ae(),`coreframe-conflicts-`));try{let n=P(e,`base`);B(n,a.base);for(let r of[`ours`,`theirs`]){let o=a[r];if(!o)continue;let s=P(e,r);B(s,o);let l=L(i,[`patch`,`extract`,n,s,`--path`,t],{encoding:`utf8`});if(l.status===0)try{c[r]=JSON.parse(l.stdout)}catch{c[r]={error:`unparseable patch ops`}}}}catch{}finally{Te(e,{recursive:!0,force:!0})}}return{explain:n,stages:s,entityOps:c}}async function Vn(e){let t=e.gitBin??`git`,n=e.weaveBin??process.env.COREFRAME_WEAVE_BIN??`weave`,r=jn(e.worktree,t).map(r=>{let i=Mn(e.worktree,r,n),a=Rn(r,i);return a.tier===`judgment`&&(a.evidence=Bn(e.worktree,r,i.explain,t,n)),a}),i=r.filter(e=>e.tier===Dn);i.length>0&&await Tn(i,e.jev??{});let a={total:r.length,safe:r.filter(e=>e.tier===En).length,judgment:r.filter(e=>e.tier===Dn).length,unsafe:r.filter(e=>e.tier===Y).length},o=r.every(e=>e.decision===`resolvable`)?`cheap-llm-resolvable`:`escalate`;return{worktree:e.worktree,recommendation:o,files:r,summary:a}}function Hn(e){for(let t of e.files){let e=t.decision===`resolvable`?` `:`!`;console.log(`${e} ${t.tier.padEnd(8)} ${t.decision.padEnd(10)} ${t.path}`);for(let e of t.reasons)console.log(` ${e}`)}let{summary:t}=e;console.log(`\n${t.total} conflicted file(s): ${t.safe} safe, ${t.judgment} judgment, ${t.unsafe} unsafe`),console.log(`recommendation: ${e.recommendation}`)}const Un=m({name:`conflicts`,description:`Classify rebase/merge conflicts in a worktree as cheap-LLM-resolvable or escalate.`,cmds:{classify:n({name:`classify`,description:`Analyze unmerged index stages with weave and emit a per-conflict verdict. Judgment-tier conflicts are gated through the TypeSafe Jev decide API when TYPESAFE_API_KEY (or JEV_API_KEY) is set; any Jev failure escalates.`,args:{worktree:c({long:`worktree`,type:l(p),description:`Worktree to inspect. Defaults to the current directory.`}),json:i({long:`json`,description:`Print the full structured report instead of a summary.`,defaultValue:()=>!1})},handler:async({worktree:e,json:t})=>{let n=await Vn({worktree:e??process.cwd()});t?console.log(JSON.stringify(n,void 0,2)):Hn(n),n.recommendation!==`cheap-llm-resolvable`&&(process.exitCode=1)}})}}),Wn=/^[a-f0-9]{64}$/,Gn=/^[a-f0-9]{40}$/,Kn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function qn(e){if(!Wn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function Jn(e){if(!Gn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function Yn(e,t){if(!Kn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function Xn(e){return`projects/${Yn(e,`Project ID`)}/i18n/v1`}function Zn(e,t){return qn(t),`${Xn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function Qn(e,t){return Jn(t),`${Xn(e)}/commits/${t}.json`}function $n(e,t){return er(t),`${Xn(e)}/releases/${encodeURIComponent(t)}.json`}function er(e){if(!e.startsWith(`v`)||e.length<2||e.length>128||/\s/.test(e)||e.includes(`..`))throw Error(`Release tag "${e}" must be a valid v-prefixed tag.`);return e}function X(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=F(e),r=F(n,t);if(r!==n&&!r.startsWith(`${n}${ye}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function Z(e,t,n){return`${e.directory}/${t}/${n}.json`}function tr(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function nr(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function rr({config:e,cwd:t,strict:n,temporaryDirectory:r}){let i=[];try{for(let n of e.locales)for(let a of e.catalogs){let o=X(t,Z(e,n,a)),s=await cr(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=P(r,`${n}-${a}.json`);await H(N(l),{recursive:!0}),await He(o,l),i.push({path:o,backup:l}),await lr(o,c)}await I(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await He(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await W(X(t,tr(e,n,r)),{force:!0})}}}async function ir({config:e,cwd:t}){let n=[];for(let r of e.locales)if(r!==e.sourceLocale)for(let i of e.catalogs){let a=await cr(X(t,Z(e,r,i)));for(let[e,t]of Object.entries(a)){if(t.obsolete||t.translation?.trim())continue;let a=t.message;if(typeof a!=`string`||!a)throw Error(`Missing source message metadata for ${r}:${e}.`);n.push({catalog:i,comments:t.comments?.filter(e=>typeof e==`string`)??[],context:t.context,id:e,locale:r,message:a,origins:t.origin?.map(([e,t])=>t?`${e}:${t}`:e)??[],placeholders:Object.keys(t.placeholders??{}).sort()})}}return n.sort((e,t)=>mr(e).localeCompare(mr(t)))}async function ar({config:e,cwd:t,messages:n,env:r=process.env}){if(n.length===0)return{translations:[],version:1};if(!e.generator)throw Error(`I18n preparation found ${n.length} missing translations, but no generator is configured.`);let i={messages:n,sourceLocale:e.sourceLocale,version:1};return ur(await dr({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function or({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[mr(e),e])),a=new Map;for(let e of r.translations){let t=mr(e);if(!i.has(t))throw Error(`Translation generator returned unexpected entry ${e.locale}:${e.catalog}:${e.id}.`);if(a.has(t))throw Error(`Translation generator returned duplicate entry ${e.locale}:${e.catalog}:${e.id}.`);if(!e.translation.trim())throw Error(`Translation generator returned an empty entry ${e.locale}:${e.id}.`);a.set(t,e.translation)}let o=[...i.keys()].filter(e=>!a.has(e));if(o.length>0)throw Error(`Translation generator omitted ${o.length} required entries.`);let s=await Je(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(mr(e));fr({compileMessage:s,id:e.id,locale:e.locale,source:e.message,translation:t})}for(let n of e.locales)if(n!==e.sourceLocale)for(let r of e.catalogs){let i=X(t,Z(e,n,r)),o=await cr(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(mr({catalog:r,id:e,locale:n}));if(i!==void 0){if(t.translation?.trim())throw Error(`Refusing to overwrite preserved translation ${n}:${e}.`);t.translation=i,s=!0}}s&&await lr(i,o)}}async function sr({config:e,cwd:t}){let n=await ir({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Je(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await cr(X(t,Z(e,n,i)));for(let[e,t]of Object.entries(a))if(!t.obsolete){if(typeof t.message!=`string`||typeof t.translation!=`string`)throw Error(`Incomplete source metadata for active translation ${n}:${e}.`);fr({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function cr(e){let t=JSON.parse(await U(e,`utf8`));if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Lingui rich JSON catalog must be an object: ${e}.`);for(let[n,r]of Object.entries(t)){if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`Invalid Lingui rich JSON message ${n} in ${e}.`);let t=r;if(t.translation!==void 0&&typeof t.translation!=`string`)throw Error(`Invalid translation value for ${n} in ${e}.`);if(t.message!==void 0&&t.message!==null&&typeof t.message!=`string`)throw Error(`Invalid source message value for ${n} in ${e}.`);if(t.context!==void 0&&typeof t.context!=`string`)throw Error(`Invalid context value for ${n} in ${e}.`);if(t.obsolete!==void 0&&typeof t.obsolete!=`boolean`)throw Error(`Invalid obsolete marker for ${n} in ${e}.`);if(t.comments!==void 0&&(!Array.isArray(t.comments)||t.comments.some(e=>typeof e!=`string`)))throw Error(`Invalid comments for ${n} in ${e}.`);if(t.origin!==void 0&&(!Array.isArray(t.origin)||t.origin.some(e=>!Array.isArray(e)||typeof e[0]!=`string`||e[1]!==void 0&&typeof e[1]!=`number`)))throw Error(`Invalid origins for ${n} in ${e}.`);if(t.placeholders!==void 0&&(!t.placeholders||typeof t.placeholders!=`object`||Array.isArray(t.placeholders)))throw Error(`Invalid placeholders for ${n} in ${e}.`)}return t}async function lr(e,t){await H(N(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await G(n,`${JSON.stringify(t,null,2)}\n`),await Ke(n,e)}function ur(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Translation generator returned invalid JSON.`)}if(!t||typeof t!=`object`||t.version!==1||!Array.isArray(t.translations))throw Error(`Translation generator returned an invalid response envelope.`);for(let e of t.translations)if(!e||typeof e!=`object`||typeof e.id!=`string`||typeof e.catalog!=`string`||typeof e.locale!=`string`||typeof e.translation!=`string`)throw Error(`Translation generator returned an invalid translation entry.`);return t}function dr({args:e,command:t,cwd:n,env:r,input:i}){return I(t,e,{cwd:n,env:r,stdio:[{string:i},`pipe`,`ignore`]}).then(({stdout:e})=>{if(Buffer.byteLength(e)>10*1024*1024)throw Error(`Translation generator output exceeded 10 MiB.`);return e}).catch(()=>{throw Error(`Translation generator exited unsuccessfully.`)})}function fr({compileMessage:e,id:t,locale:n,source:r,translation:i}){let a,o;try{a=e.compileMessageOrThrow(r),o=e.compileMessageOrThrow(i)}catch{throw Error(`Translation ${n}:${t} is not valid ICU MessageFormat.`)}let s=pr(a),c=pr(o);if(s.length!==c.length||s.some((e,t)=>e!==c[t]))throw Error(`Translation ${n}:${t} does not preserve source ICU placeholders.`)}function pr(e){let t=[];function n(e){for(let r of e){if(typeof r==`string`)continue;let[e,i=`argument`,a]=r;if(t.push(`${e}:${i}`),a&&typeof a==`object`&&!Array.isArray(a))for(let e of Object.values(a))Array.isArray(e)&&n(e)}}return n(e),t.sort()}function mr(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function hr(e){return $e(`sha256`).update(e).digest(`hex`)}async function gr(e){return hr(await U(e))}function _r(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function vr({bucket:e,digest:t,projectId:n,source:r,store:i}){if(qn(t),await gr(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=Zn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${q()}.verify`;try{if(await i.download(e,a,o),await gr(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await W(o,{force:!0})}}async function yr({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=_r(n),o=P(i,`reference-${q()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await U(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await W(o,{force:!0})}await G(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await W(o,{force:!0})}let s=P(i,`reference-${q()}.verify.json`);try{if(await r.download(e,t,s),!(await U(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await W(s,{force:!0})}}async function br({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=_r(t),o=hr(a),s=P(i,`manifest-${o}.json`);await G(s,a,{flag:`wx`});try{await vr({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await W(s,{force:!0})}return o}async function xr({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=P(r,`reference-${q()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await U(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return Jn(r.revision),qn(r.snapshot),r}finally{await W(i,{force:!0})}}async function Sr({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await xr({bucket:e,key:Qn(t,n),store:r,temporaryDirectory:i});if(a&&a.revision!==n)throw Error(`I18n commit reference does not match requested revision ${n}.`);return a}async function Cr({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await yr({bucket:e,key:Qn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await yr({bucket:e,key:$n(t,i),reference:n,store:r,temporaryDirectory:a})}async function wr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){qn(n);let o=P(F(t),`v1`,`sha256`,n.slice(0,2),n);if(await Er(o,n)===!1){await H(N(o),{recursive:!0});let t=`${o}.${process.pid}.${q()}.tmp`;try{if(await i.download(e,Zn(r,n),t),await gr(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await W(o,{force:!0}),await Ke(t,o)}finally{await W(t,{force:!0})}}await H(N(a),{recursive:!0});let s=`${a}.${process.pid}.${q()}.tmp`;try{if(await He(o,s),await gr(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await W(a,{force:!0}),await Ke(s,a)}finally{await W(s,{force:!0})}}async function Tr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=P(a,`manifest-${n}.json`);await wr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await U(o,`utf8`));if(s.version!==1||s.projectId!==r||typeof s.revision!=`string`||!Array.isArray(s.files)||!Array.isArray(s.catalogs)||s.catalogs.some(e=>typeof e!=`string`)||!Array.isArray(s.locales)||s.locales.some(e=>typeof e!=`string`)||typeof s.sourceLocale!=`string`||typeof s.generator!=`string`||typeof s.linguiVersion!=`string`)throw Error(`Invalid i18n snapshot manifest ${n}.`);Jn(s.revision),s.baseline!==void 0&&qn(s.baseline);for(let e of s.files){if(!e||typeof e!=`object`||typeof e.path!=`string`||typeof e.digest!=`string`||typeof e.size!=`number`)throw Error(`Invalid file entry in i18n snapshot manifest ${n}.`);qn(e.digest)}return s}async function Er(e,t){try{return(await qe(e)).isFile()&&await gr(e)===t}catch{return!1}}async function Dr({cwd:e=process.cwd(),env:t=process.env}={}){let n=await K({cwd:e});if(!n.i18n)return;let r=t.COREFRAME_I18N_RELEASE_REVISION;if(r){if(jr(Mr(n.i18n))===`multilingual`){await Ar({cwd:e,env:t,revision:r});return}console.log(`I18n source-only mode: building source catalogs for ${r}; no prepared translation snapshot is required.`)}await nr(e)}async function Or({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await K({cwd:e});if(!n.i18n)return;let r=Mr(n.i18n),i=X(e,r.directory);try{if(!(await qe(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await nr(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await qe(X(e,Z(r,t,n)))).isFile())throw Error(`I18n catalog path is not a file: ${t}/${n}.json.`)}catch(t){if(t.code!==`ENOENT`)throw t;await nr(e);return}}async function kr({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){er(r),await Vr(e);let i=await Br(e);await Hr(e,r,i);let a=await K({cwd:e});if(!a.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);let o=Mr(a.i18n);if(jr(o)===`source-only`)return{mode:`source-only`,sourceLocale:o.sourceLocale};let s=await Nr({cwd:e,env:t,projectConfig:a,store:n}),c=await We(P(Ae(),`coreframe-i18n-prepare-`));try{let n=await Sr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,revision:i,store:s.store,temporaryDirectory:c});if(n){let e=await Tr({bucket:s.assets.sourceBucket,cacheRoot:s.cacheRoot,digest:n.snapshot,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return zr(s,e,i),await Fr(s,e),await Cr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:n,store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!0,snapshot:n.snapshot}}return await Rr(s,c,async()=>{let n=await Pr(s,i,c);n||await Lr(s),await nr(e);let a=await ir({config:s.config,cwd:e}),o=await ar({config:s.config,cwd:e,env:t,messages:a});await or({config:s.config,cwd:e,missing:a,response:o}),await sr({config:s.config,cwd:e}),await rr({config:s.config,cwd:e,strict:!0,temporaryDirectory:c});let l=await Ir(s),u={...n?{baseline:n}:{},catalogs:s.config.catalogs,files:l,generator:a.length>0?s.config.generator?.id??`unconfigured`:`none`,linguiVersion:await Ur(e),locales:s.config.locales,projectId:s.assets.projectId,revision:i,sourceLocale:s.config.sourceLocale,version:1},d=await br({bucket:s.assets.sourceBucket,manifest:u,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return await Cr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,reference:{revision:i,snapshot:d,version:1},store:s.store,tag:r,temporaryDirectory:c}),{mode:`multilingual`,reused:!1,snapshot:d}})}finally{await W(c,{force:!0,recursive:!0})}}async function Ar({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await K({cwd:e});if(!i.i18n)return;let a=await Nr({cwd:e,env:t,store:r,projectConfig:i}),o=Jn(n??await Br(e)),s=await We(P(Ae(),`coreframe-i18n-materialize-`));try{let e=await Sr({bucket:a.assets.sourceBucket,projectId:a.assets.projectId,revision:o,store:a.store,temporaryDirectory:s});if(!e)throw Error(`No prepared i18n snapshot exists for commit ${o}. Push a v* tag for this commit and wait for the translation gate.`);let t=await Tr({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return zr(a,t,o),await Fr(a,t),{revision:o,snapshot:e.snapshot}}finally{await W(s,{force:!0,recursive:!0})}}function jr(e){return e.locales.length===1&&e.locales[0]===e.sourceLocale?`source-only`:`multilingual`}function Mr(e){let t=Yn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>Yn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>Yn(e,`Catalog`)))];if(n.length===0||!n.includes(t))throw Error(`I18n locales must include the source locale.`);if(r.length===0)throw Error(`I18n configuration requires at least one catalog.`);if(e.generator&&(!e.generator.command.trim()||!e.generator.id.trim()))throw Error(`I18n generator command and ID must be non-empty.`);return{catalogs:r,directory:e.directory??`locales`,generator:e.generator,locales:n,sourceLocale:t}}async function Nr({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await K({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:F(e,`.coreframe`,`i18n`,`cache`),config:Mr(i.i18n),cwd:F(e),env:t,store:r??ze({config:a,env:t})}}async function Pr(e,t,n){let{stdout:r}=await I(`git`,[`rev-list`,`--first-parent`,`--skip=1`,t],{cwd:e.cwd,stdin:`ignore`});for(let t of r.split(/\r?\n/).filter(Boolean)){let r=await Sr({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:Jn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Tr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return zr(e,i,t),await Fr(e,i),r.snapshot}}async function Fr(e,t){for(let n of t.files)if(await wr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await qe(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function Ir(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=Z(e.config,n,r),a=X(e.cwd,i),o=await gr(a);await vr({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await qe(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Lr(e){let{stdout:t}=await I(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await I(`git`,[`log`,`-1`,`--format=%H`,`--diff-filter=AM`,`--`,`:(top)${`${n}${e.config.directory}/${e.config.sourceLocale}/${e.config.catalogs[0]}.po`}`],{cwd:e.cwd,stdin:`ignore`}),i=r.trim();if(!i)return!1;let a=(await Je(`@lingui/format-po`,e.cwd)).formatter({lineNumbers:!1}),o=!1;for(let t of e.config.locales)for(let r of e.config.catalogs){let s=`${n}${`${e.config.directory}/${t}/${r}.po`}`;try{let{stdout:n}=await I(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await lr(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Rr(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=Z(e.config,n,i),o=X(e.cwd,a);try{await Be(o)}catch{continue}let s=P(t,`previous-catalogs`,a);await H(N(s),{recursive:!0}),await Ke(o,s),r.push({backup:s,path:o})}try{let e=await n();return await W(P(t,`previous-catalogs`),{force:!0,recursive:!0}),e}catch(t){for(let t of e.config.locales)for(let n of e.config.catalogs)await W(X(e.cwd,Z(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await H(N(t),{recursive:!0}),await Ke(e,t);throw t}}function zr(e,t,n){if(t.revision!==n||t.projectId!==e.assets.projectId||t.sourceLocale!==e.config.sourceLocale||JSON.stringify(t.locales)!==JSON.stringify(e.config.locales)||JSON.stringify(t.catalogs)!==JSON.stringify(e.config.catalogs))throw Error(`I18n snapshot does not match commit or project configuration.`);let r=e.config.locales.flatMap(t=>e.config.catalogs.map(n=>Z(e.config,t,n))),i=t.files.map(e=>e.path);if(new Set(i).size!==i.length||JSON.stringify(i.sort())!==JSON.stringify(r.sort()))throw Error(`I18n snapshot has an incomplete or unexpected artifact set.`)}async function Br(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return Jn(t.trim())}async function Vr(e){let{stdout:t}=await I(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function Hr(e,t,n){let{stdout:r}=await I(`git`,[`rev-parse`,`${t}^{commit}`],{cwd:e,stdin:`ignore`});if(r.trim()!==n)throw Error(`Release tag ${t} does not point to checked-out commit ${n}.`)}async function Ur(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const Wr=[`Use a B2 Multi-Bucket Application Key restricted to the configured private build-object and public generated-assets buckets.`,`Required capabilities: listAllBucketNames, readFiles, and writeFiles.`,`Deletion, bucket-management, and key-management capabilities are not needed.`].join(` `),Gr=r(p,{displayName:`widths`,description:`Comma-separated responsive variant widths.`,async from(e){let t=e.split(`,`).map(e=>Number(e));if(t.length===0||t.some(e=>!Number.isInteger(e)||e<=0)||t.some((e,n)=>n>0&&e<=t[n-1]))throw Error(`Widths must be positive, unique, strictly ascending integers.`);return t}}),Kr=r(p,{displayName:`profile`,async from(e){return Le(e)}}),qr=r(p,{displayName:`pack`,description:`Asset pack name, such as training-videos.`,async from(e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e))throw Error(`Asset pack names must use lowercase hyphen-separated segments.`);return e}}),Jr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return j(e)}}),Yr=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${Wr}`,args:{profile:u({type:Kr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{V.note(Wr,`Required B2 key access`);let t=await V.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(V.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await V.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(V.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await Re({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:n({name:`add`,args:{file:u({type:p,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:c({long:`id`,type:p,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:c({long:`alt`,type:l(p),description:`Required alt text for raster image and SVG assets.`}),pack:c({long:`pack`,type:l(qr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(Gr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>Fe(await je({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:n({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:c({long:`branch`,type:p,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await Me({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:n({name:`build`,args:{id:c({long:`id`,type:l(p),description:`Build only one logical asset ID.`}),pack:c({long:`pack`,type:l(qr),description:`Build only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>Fe(await Ne({id:e,pack:n}),t,{kind:`build`})}),check:n({name:`check`,args:{fix:i({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:c({long:`pack`,type:l(qr),description:`Check only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await Pe({fix:e,pack:n});Fe(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(qr),description:`Publish only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Ie({pack:t});Fe(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(qr),description:`Report status for only one named asset pack.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await Pe({pack:t});Fe(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),Xr=m({name:`flutter`,cmds:{acceptance:n({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Jr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>ge({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:n({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:i({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>A({check:e})}),prepare:n({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Jr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>me({apiOrigin:e,platform:t})}),check:n({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:u({type:s(k),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:c({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:Jr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>O({apiOrigin:e,platform:t})})}}),Zr=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Dr()}}),materialize:n({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:c({long:`revision`,type:l(p),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Ar({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:n({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot. Source-only projects skip translation preparation.`,args:{tag:c({long:`tag`,type:p,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await kr({tag:e});if(t.mode===`source-only`){console.log(`Skipped i18n release preparation: the supported locales contain only the source locale "${t.sourceLocale}", so no translation snapshot is required.`);return}console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),Qr=J.platform===`win32`?`react-router.cmd`:`react-router`,$r=J.platform===`win32`?`panda.cmd`:`panda`;async function ei(e=J.cwd()){await ri(e),await ni(e,[`typegen`])}async function ti(e=J.cwd(),t=J.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=M.resolve(e,`.coreframe/dashboard-build`),i=M.join(r,`client`),a=M.resolve(e,`dist/client/__dashboard`);await W(r,{force:!0,recursive:!0});let o=await K({cwd:e});if(o.deploy?.mode===`client`||o.dashboard?.enabled===!1){await W(a,{force:!0,recursive:!0});return}await ii(e,$r,[`build`],t),await ni(e,[`build`,...n?[`--mode`,n]:[]],t),await W(a,{force:!0,recursive:!0}),await H(M.dirname(a),{recursive:!0}),await Ue(i,a,{recursive:!0})}async function ni(e,t,n=J.env){await ii(e,Qr,t,n)}async function ri(e){await W(M.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function ii(e,t,n,r=J.env){await I(t,n,{cwd:M.resolve(e,`dashboard`),env:{...r,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const ai={access:Be,chmod:Ve,mkdir:H,mkdtemp:We,readFile:U,readFileSync:z,rm:W,writeFile:G},oi={getAvailablePort:ci},si={homedir:Oe,kill:J.kill,networkInterfaces:ke,tmpdir:Ae};async function ci(){let e=it();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,t)});let t=e.address();if(!t||typeof t==`string`)throw Error(`Could not allocate an available TCP port.`);return t.port}finally{e.listening&&await new Promise((t,n)=>{e.close(e=>e?n(e):t())})}}function li({host:e=`127.0.0.1`,port:t,start:n}){let r,i=!1,a=!1,o=!1,s,c,l,u,d,f=new Set,p=new Promise((e,t)=>{u=e,d=t}),m=e=>{a||o||(o=!0,d(e))},h=()=>(s||=Promise.resolve().then(n).catch(e=>{throw m(e),e}),s),g=e=>{f.add(e),e.once(`close`,()=>f.delete(e)),e.pause(),_(e).catch(t=>{m(t),e.destroy()})},_=async e=>{let t=await h();if(a||e.destroyed)return;let n=await ui(t,()=>a);if(a||e.destroyed){n.destroy();return}f.add(n),n.once(`close`,()=>f.delete(n)),n.on(`error`,()=>e.destroy()),n.once(`close`,()=>e.destroy()),e.on(`error`,()=>n.destroy()),e.once(`close`,()=>n.destroy()),e.pipe(n),n.pipe(e)};return{close:async()=>l||(l=(async()=>{a=!0,o||(o=!0,u());for(let e of f)e.destroy();f.clear(),c&&!i&&await Promise.allSettled([c]),!(!r||!i)&&(await new Promise(e=>{r.close(()=>e())}),i=!1)})(),l),fail:m,listen:async()=>c||(r=it(g),c=new Promise((n,a)=>{let o=e=>{if(i){m(e);return}a(e)};r.once(`error`,o),r.once(`listening`,()=>{i=!0,r.off(`error`,o),r.on(`error`,m),n()}),r.listen(t,e)}),c),wait:()=>p}}async function ui(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await di(e)}catch(e){if(r=e,Date.now()>=n)break;await new Promise(e=>setTimeout(e,50))}throw r instanceof Error?r:Error(`Could not connect to the dashboard.`)}function di({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=rt({host:e,port:t}),a=e=>{i.off(`connect`,o),i.destroy(),r(e)},o=()=>{i.off(`error`,a),n(i)};i.once(`error`,a),i.once(`connect`,o)})}const fi=J.platform===`win32`?`react-router.cmd`:`react-router`;function pi(e){return R(M.resolve(e,`dashboard/dashboard.config.ts`))}function mi({cwd:e,env:t,port:n}){let r=t.PATH??t.Path??``,i,a,o=!1,s,c,l=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{d()};return J.on(e,t),{handler:t,signal:e}}),u=async(e,t)=>{try{await e,o||a?.fail(Error(`The dashboard development server stopped unexpectedly.`))}catch(e){o||a?.fail(e)}finally{await t.outputTasks,t.stdout.end(),t.stderr.end(),await Promise.allSettled([et(t.stdout),et(t.stderr)]),i===e&&(i=void 0)}};a=li({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await oi.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=tt({label:`dashboard`}),s=tt({color:`red`,label:`dashboard`});a.pipe(J.stdout,{end:!1}),s.pipe(J.stderr,{end:!1});let l=I(fi,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:M.resolve(e,`dashboard`),env:{...t,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([gi(l.stdout,a),gi(l.stderr,s)]);return c=u(l,{outputTasks:d,stderr:s,stdout:a}),{host:`127.0.0.1`,port:n}}});let d=async()=>s||(s=(async()=>{o=!0,await a?.close(),i?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),await c;for(let{handler:e,signal:t}of l)J.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function hi({cwd:e=J.cwd(),env:t=J.env,port:n}){let r=mi({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function gi(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const _i=m({name:`dashboard`,cmds:{dev:n({name:`dev`,args:{port:c({long:`port`,type:o,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>hi({port:e})}),build:n({name:`build`,args:{mode:c({long:`mode`,type:l(p),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>ti(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>ei()})}});function vi(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function r(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var r=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(r===void 0&&(r=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var i=r;if(typeof r!=`function`)throw TypeError(`Object is not disposable.`);i&&(r=function(){try{i.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:r,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var r,i=this.e,a=0;function o(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(o);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(o,s)}else a|=1}catch(e){return s(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function s(n){return i=i===t?n:new e(n,i),o()}return o()}}}async function yi({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await Ti(t),o=await Ei(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=at({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=Ci(s,{all:e,ids:n,matches:r},{defaultAll:!0});return{database:{dialect:a.dialect,state:o?`existing`:`missing`},jobs:s.filter(e=>c.has(e.id)),version:1}}async function bi({all:e,breakLeases:t=!1,cwd:n=process.cwd(),dryRun:r=!1,ids:i=[],json:a=!1,matches:o=[],now:s=new Date,yes:c=!1}){let l=await yi({all:!0,cwd:n,now:s}),u=Ci(l.jobs,{all:e,ids:i,matches:o},{defaultAll:!1}),d=l.jobs.filter(e=>u.has(e.id)),f=d.filter(e=>e.lease===`active`);if(r)return{database:l.database,dryRun:!0,jobs:d.map(e=>({id:e.id,status:e.lease===`active`&&!t?`blocked-active-lease`:e.persisted?`would-reset`:`no-state`})),version:1};if(f.length>0&&!t)throw Error(`Cannot reset active development job ${Ai(f.map(e=>e.id))}. Wait for the lease to expire or pass --break-leases.`);if((t||e||o.length>0||d.length>1)&&!c){if(a||!process.stdin.isTTY)throw Error(`This reset requires --yes when prompts are unavailable.`);let e=await V.confirm({message:`Reset local development state for ${d.length} job${d.length===1?``:`s`}?`});if(V.isCancel(e)||!e)throw Error(`Development job state reset was cancelled.`)}if(l.database.state===`missing`)return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:`no-state`})),version:1};let p=await Ti(n),m=await Ei(p.config,n,async e=>p.module.developmentJobs.createStateAdmin(e).reset({breakLeases:t,jobIds:[...u],now:s}));if(!m)throw Error(`The local database disappeared before development job state was reset.`);if(m.activeLeaseIds.length>0&&!t)throw Error(`Cannot reset active development job ${Ai(m.activeLeaseIds)}. Wait for the lease to expire or pass --break-leases.`);let h=new Set(m.resetIds);return{database:l.database,dryRun:!1,jobs:d.map(e=>({id:e.id,status:h.has(e.id)?`reset`:`no-state`})),version:1}}function xi(e){let t=ki(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${ji([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,Oi(e.lastSucceededAt),Oi(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${Oi(e.leaseUntil)}`]))}`}function Si(e){let t=ki(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${ji([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function Ci(e,{all:t=!1,ids:n=[],matches:r=[]},{defaultAll:i}){if(t&&(n.length>0||r.length>0))throw Error(`Use --all or explicit job selectors, not both.`);if(!t&&n.length===0&&r.length===0){if(i)return new Set(e.map(e=>e.id));throw Error(`Select one or more jobs by ID or --match, or pass --all.`)}let a=new Set(e.map(e=>e.id)),o=n.filter(e=>!a.has(e));if(o.length>0)throw Error(`Unknown development job ${Ai(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=wi(t),r=e.filter(e=>n.test(e.id));if(r.length===0)throw Error(`Development job pattern ${JSON.stringify(t)} matched no jobs.`);for(let e of r)s.add(e.id)}return s}function wi(e){if(!e)throw Error(`Development job patterns must not be empty.`);let t=[...e].map(e=>e===`*`?`.*`:e===`?`?`.`:e.replace(/[\\^$.[\]{}()+|]/gu,`\\$&`)).join(``);return RegExp(`^${t}$`,`u`)}async function Ti(e){let t=await K({cwd:e}),n=t.jobs?.entry;if(!n)throw Error(`coreframe.config.ts must configure jobs.entry before managing development job state.`);let r=await Ye(n,e);if(!r.developmentJobs||!Array.isArray(r.developmentJobs.jobs)||typeof r.developmentJobs.createStateAdmin!=`function`)throw Error(`${n} must export developmentJobs with jobs and createStateAdmin properties.`);return{config:t,dialect:t.database?.dialect??`postgres`,module:r}}async function Ei(e,t,n){try{var r=vi();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?M.resolve(t,`.coreframe/turso.db`):M.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await qe(o)}catch(e){if(Mi(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=vi();let r=await S({cwd:t,env:i.a(await ue({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Di(n,r)}finally{r.$client.close()}}catch(e){i.e=e}finally{await i.d()}let s=await y({cwd:t,env:r.a(await D({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Di(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Di(e,t){try{return await e(t)}catch(e){throw Ni(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function Oi(e){return e?.toISOString()??`-`}function ki(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function Ai(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function ji(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),r=e=>e.map((e,t)=>e.padEnd(n[t])).join(` `).trimEnd();return[r(e),r(n.map(e=>`-`.repeat(e))),...t.map(r)].join(`
|
|
8
|
+
`)}function Mi(e){return e instanceof Error&&`code`in e}function Ni(e){let t=e;for(;t instanceof Error;){let e=t.message.toLowerCase();if(e.includes(`coreframe_dev_job_state`)&&(e.includes(`does not exist`)||e.includes(`no such table`)))return!0;t=t.cause}return!1}const Pi={ids:f({type:p,displayName:`job`,description:`Exact local development job IDs.`}),matches:a({type:t(p),long:`match`,description:`Select job IDs with an anchored * and ? glob. Repeat to add patterns.`,defaultValue:()=>[]})},Fi=m({name:`jobs`,cmds:{status:n({name:`status`,description:`Inspect local development job cooldown and lease state.`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1}),...Pi},handler:async({ids:e,json:t,matches:n})=>{let r=await yi({ids:e,matches:n});console.log(t?JSON.stringify(r):xi(r))}}),reset:n({name:`reset`,description:`Make local development jobs eligible for their next startup check.`,args:{all:i({long:`all`,description:`Select every configured and orphaned development job.`,defaultValue:()=>!1}),breakLeases:i({long:`break-leases`,description:`Invalidate active job leases. The original invocation may keep running.`,defaultValue:()=>!1}),dryRun:i({long:`dry-run`,description:`Show the reset without changing local state.`,defaultValue:()=>!1}),json:i({long:`json`,description:`Print machine-readable JSON without prompting.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Confirm a multi-job, pattern, all-job, or lease-breaking reset.`,defaultValue:()=>!1}),...Pi},handler:async({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o})=>{let s=await bi({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o});console.log(i?JSON.stringify(s):Si(s))}})}}),Ii=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Li(e,t){let n=zi(e,t);if(!Bi(n)||!Vi(n,[`description`,`requires`,`routes`,`verifier`])||!Ui(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Ui))||n.verifier!==void 0&&!Ui(n.verifier)||!Array.isArray(n.routes))throw Error(`${t} must contain a description string, routes array, and optional requires and verifier fields.`);let r=(n.requires??[]).map(e=>Ri(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Bi(e)||!Hi(e,[`path`,`router`,`when`])||!Ui(e.path)||!Ui(e.router)||!Ui(e.when))throw Error(`${t} route ${n+1} must contain router, path, and when strings.`);return{path:e.path,router:e.router,when:e.when}}),a=i.map(e=>`${e.router}\0${e.path}`);if(new Set(a).size!==a.length)throw Error(`${t} contains a duplicate router and path pair.`);return{description:n.description,requires:r,routes:i,verifier:n.verifier}}function Ri(e){if(!Ii.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function zi(e,t){try{return ot(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Bi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vi(e,t){return Object.keys(e).every(e=>t.includes(e))}function Hi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Ui(e){return typeof e==`string`&&e.length>0}const Wi=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,Gi=`template`;function Ki(e=Gi){return`refs/remotes/${e}/tags`}function Q(e,t=Gi){return Wi.test(e)?`${Ki(t)}/v${e}`:e.startsWith(`v`)&&Wi.test(e.slice(1))?`${Ki(t)}/${e}`:e}function qi(e){return e.startsWith(`refs/remotes/`)?e.slice(13):e}function Ji(e,t=Gi){return`${Q(e,t)}:template`}function Yi(e,t,n=Gi){return`${Ji(e,n)}/${t}`}function Xi(e,t){return L(`git`,e,{cwd:t,encoding:`utf8`})}function Zi(e,t){let n=Xi(e,t);if(n.status!==0){let t=n.stderr.trim()||n.stdout.trim();throw Error(`Git command failed: git ${e.join(` `)}${t?`\n${t}`:``}`)}return n.stdout}function Qi(e,t){let n=Xi([`remote`,`get-url`,e],t);if(n.status===2)return null;if(n.status!==0){let t=n.stderr.trim()||n.stdout.trim();throw Error(`Could not inspect remote ${e}.${t?`\n${t}`:``}`)}return n.stdout.trim()}function $i(e,t){Xi([`config`,`--get`,`remote.${e}.tagOpt`],t).stdout.trim()!==`--no-tags`&&Zi([`config`,`remote.${e}.tagOpt`,`--no-tags`],t);let n=Xi([`config`,`--get-all`,`remote.${e}.fetch`],t),r=n.status===0?n.stdout.split(`
|
|
9
|
+
`).map(e=>e.trim()).filter(Boolean):[];for(let n of[`+refs/heads/*:refs/remotes/${e}/*`,`+refs/tags/*:${Ki(e)}/*`])r.includes(n)||Zi([`config`,`--add`,`remote.${e}.fetch`,n],t)}function ea(e,t){return Zi([`for-each-ref`,`--format=%(refname)`,t],e).split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean)}function ta(e,t){return Zi([`rev-parse`,`--verify`,`${e}^{commit}`],t).trim()}function na(e,t){let n=`${Ki(e)}/`,r=new Set(ea(t,Ki(e)).map(e=>e.slice(n.length))),i=[],a=[];for(let e of ea(t,`refs/tags`)){let o=e.slice(10);if(r.has(o)){if(ta(e,t)!==ta(`${n}${o}`,t)){a.push(o);continue}Zi([`update-ref`,`-d`,e],t),i.push(o)}}i.length>0&&console.log(`Removed ${i.length} copied ${e} tag(s) from refs/tags/ so they cannot be pushed to this repository's own remotes.`),a.length>0&&console.log(`Kept local tag(s) that share a name with ${e} tags but point at different commits: ${a.join(`, `)}`)}function ra({cwd:e=process.cwd(),fetch:t=!0,remote:n=Gi,url:r=`https://github.com/coreframe-js/coreframe.git`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Zi([`rev-parse`,`--show-toplevel`],e);let i=Qi(n,e);if(i===null)Zi([`remote`,`add`,n,r],e),console.log(`Added ${n} remote: ${r}`);else if(i===r)console.log(`${n} remote already points at ${r}`);else throw Error(`${n} remote points at ${i}, not ${r}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);$i(n,e),t&&(Zi([`fetch`,n,`--prune`],e),console.log(`Fetched ${n}.`)),na(n,e)}function ia({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=ca(e),a=fa(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??la(i),n);return ra({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,refLabel:qi(o),repositoryRoot:a}}function aa(e,t,n){return oa(e,t,n).toString(`utf8`)}function oa(e,t,n){let r=`${t}:${n}`,i=L(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${pa([`show`,r],i)}`);return i.stdout}function sa(e,t,n){let r=L(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(pa([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function ca(e){let t=F(e);for(;;){let e=P(t,`package.json`),n=da(e);if(n!==void 0&&ua(n,e).engines?.coreframe)return t;let r=N(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function la(e){let t=P(e,`package.json`),n=da(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=ua(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function ua(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function da(e){try{return z(e,`utf8`)}catch(e){if(ma(e)&&e.code===`ENOENT`)return;throw e}}function fa(e,t){let n=L(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(pa(t,n));return n.stdout.trim()}function pa(e,t){let n=t.stderr.toString(`utf8`).trim()||t.stdout.toString(`utf8`).trim();return`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`}function ma(e){return e instanceof Error&&`code`in e}const ha=[{path:`package.json`,requirement:`retain the Coreframe Flutter JavaScript runtime used by src-flutter`,test:e=>e.includes(`"@coreframe/flutter-js"`)},{path:`coreframe.config.ts`,requirement:`enable web and at least one Flutter development platform`,test:wa},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:Ta},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:Ea},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>Ca(e,[`configureShellQueryFocus`,`initializeShellClient`,`authSessionHint`,`authClient.signOut()`,`clearSession`])},{path:`src/web/entry.client.tsx`,requirement:`load the package-owned Flutter development tools only for non-browser development`,test:e=>Ca(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ga=`src-flutter/lib/application.dart`,_a=`src/api/worker/auth-origin.ts`;function va(e){let t=[];for(let n of ha){let r=P(e,n.path);if(!R(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=z(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=ya(e,t),r=ba(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ga} loopbackPort (${n}) must match ${_a} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function ya(e,t){let n=xa(e,ga,t);if(n===void 0)return;let r=n.match(/^\s*loopbackPort\s*:\s*(\d+)\s*,?\s*$/m)?.[1],i=n.match(/^\s*loopbackPort\s*:\s*([A-Za-z_]\w*)\s*,?\s*$/m)?.[1],a=i?n.match(RegExp(`^\\s*(?:static\\s+)?const\\s+${i}\\s*=\\s*(\\d+)\\s*;\\s*$`,`m`))?.[1]:void 0,o=Sa(r??a);return o===void 0&&t.push(`${ga} must configure loopbackPort as a fixed integer port.`),o}function ba(e,t){let n=xa(e,_a,t);if(n===void 0)return;let r=Sa(n.match(/^\s*export\s+const\s+FLUTTER_LOOPBACK_ORIGIN\s*=\s*["']http:\/\/localhost:(\d+)["']\s*;?\s*$/m)?.[1]);return r===void 0&&t.push(`${_a} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function xa(e,t,n){let r=P(e,t);if(!R(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return z(r,`utf8`)}function Sa(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function Ca(e,t){return t.every(t=>e.includes(t))}function wa(e){let t=e.match(/\bplatforms\s*:\s*\[([\s\S]*?)\]/)?.[1];if(!t)return!1;let n=new Set([...t.matchAll(/(["'`])([^"'`]*)\1/g)].map(e=>e[2]));return n.has(`web`)&&[`ios`,`android`,`linux`,`macos`,`windows`].some(e=>n.has(e))}function Ta(e){try{let t=ot(e);if(!Da(t)||!Da(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return Da(n)&&n.sdk===`flutter`}catch{return!1}}function Ea(e){let t=/const\s+(\w+)\s*=\s*kDebugMode\s*&&\s*bool\.fromEnvironment\(\s*['"]ENABLE_FLUTTER_DRIVER['"]\s*\)/u.exec(e),n=e.indexOf(`enableFlutterDriverExtension()`),r=e.indexOf(`runCoreframeApplication(`),i=t?RegExp(`if\\s*\\(\\s*${t[1]}\\s*\\)\\s*\\{[^{}]*enableFlutterDriverExtension\\(\\)[^{}]*\\}`,`u`):void 0;return e.includes(`package:flutter_driver/driver_extension.dart`)&&i?.test(e)===!0&&n>=0&&r>=0&&n<r}function Da(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oa({name:e,...t}){let n=ia(t),r=`recipes/${e}/recipe.yaml`,i=ja(Li(aa(n.repositoryRoot,n.ref,r),r).verifier,n.projectRoot);if(i.length>0)throw Error(`Recipe ${e} verification failed:\n${i.map(e=>`- ${e}`).join(`
|
|
11
|
+
`)}`);return{name:e,ref:n.refLabel}}function ka(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Aa(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=ja(Li(aa(t.repositoryRoot,t.ref,e),e).verifier,t.projectRoot);if(r.length>0)throw Error(`Recipe ${n} is required but is not fully applied:\n${r.map(e=>`- ${e}`).join(`
|
|
12
|
+
`)}\nApply and verify ${n} before continuing.`)}}function ja(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return va(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Ma({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Ri(n);let a=ia({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,refLabel:c,repositoryRoot:l}=a,u=`recipes/${n}`,d=`${u}/recipe.yaml`,f=Li(aa(l,s,d),d);Aa(f.requires,a);let p=aa(l,s,`${u}/RECIPE.md`),m=sa(l,s,`${u}/files`),h=sa(l,s,`${u}/patches`),g=sa(l,s,`${u}/.agents`),_=new Map,v=new Map,y=[],b=[],x=[],S=[],C=[],w=[];for(let e of m){let t=e.slice(`${u}/files/`.length);if(za(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);_.set(t,oa(l,s,e)),v.set(t,e)}for(let e of g){let t=e.slice(`${u}/`.length);if(Ia(t,`Recipe asset ${e}`),_.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);_.set(t,oa(l,s,e)),v.set(t,e)}for(let e of h){let t=Ba(e,u);if(_.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=oa(l,s,e);Va(n.toString(`utf8`),t,e),Ra(o,t),Ha(o,n,!1)?(y.push({contents:n,destinationPath:t}),S.push(t)):Ha(o,n,!0)?C.push(t):x.push({destination:t,source:e})}let T=new Map;for(let[e,t]of _){let r=Ga(Ra(o,e));if(r===void 0)T.set(e,t),b.push(e);else if(r.equals(t))C.push(e);else if(e.startsWith(`.agents/`))throw Error(`Recipe ${n} cannot replace modified ${e}. Reconcile that agent asset manually.`);else x.push({destination:e,source:v.get(e)})}let E=new Map;for(let e of f.routes){if(Ia(e.router,`Recipe route router`),La(e.path,`Recipe route path`),_.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!_.has(e.path)&&!R(Ra(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=E.get(e.router)??Pa(Ka(Ra(o,e.router),e.router),e.router);E.set(e.router,t);let r=t.routes.find(t=>t.path===e.path);if(r){if(r.when!==e.when)throw Error(`Recipe ${n} route ${e.path} conflicts with the existing trigger in ${e.router}.`);continue}t.routes.push({path:e.path,when:e.when})}for(let[e,t]of E){t.routes.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path));let n=Ka(Ra(o,e),e),r=st(t,{lineWidth:0});r===n?C.push(e):(T.set(e,r),w.push(e))}for(let{destinationPath:e}of y)if(T.has(e))throw Error(`Recipe cannot both write and patch ${e}.`);for(let[e,t]of T){let n=Ra(o,e);Se(N(n),{recursive:!0}),B(n,t)}return y.length>0&&Ua(o,y.map(({contents:e})=>e)),{created:b.sort(),instructions:p,mergeRequired:x.sort((e,t)=>e.destination.localeCompare(t.destination)),name:n,patched:S.sort(),ref:c,unchanged:[...new Set(C)].sort(),updated:w.sort()}}function Na(e){console.log(`Prepared Coreframe recipe ${e.name} from ${e.ref}.`);for(let t of e.created)console.log(`created: ${t}`);for(let t of e.updated)console.log(`updated: ${t}`);for(let t of e.patched)console.log(`patched: ${t}`);for(let t of e.mergeRequired)console.log(`merge-required: ${t.destination} (source: ${e.ref}:${t.source})`);for(let t of e.unchanged)console.log(`unchanged: ${t}`);console.log(`\nContinue by following ${e.ref}:recipes/${e.name}/RECIPE.md:\n`),console.log(e.instructions.trimEnd())}function Pa(e,t){let n=Fa(e,t);if(!qa(n)||!Ja(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Ya)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!qa(e)||!Ja(e,[`path`,`when`])||!Ya(e.path)||!Ya(e.when))throw Error(`${t} route ${n+1} must contain path and when strings.`);return{path:e.path,when:e.when}}),i=r.map(e=>e.path);if(new Set(i).size!==i.length)throw Error(`${t} contains duplicate route paths.`);return{rules:n.rules,routes:r}}function Fa(e,t){try{return ot(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Ia(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);za(e,t)}function La(e,t){if(za(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function Ra(e,t){za(t,`Recipe destination`);let n=P(e,t),r=e;for(let e of t.split(`/`))if(r=P(r,e),R(r)&&xe(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function za(e,t){if(e.length===0||_e(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||ve.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function Ba(e,t){let n=e.slice(`${t}/patches/`.length);if(!n.endsWith(`.patch`))throw Error(`Recipe patch ${e} must use a .patch suffix.`);let r=n.slice(0,-6);return za(r,`Recipe patch ${e}`),r}function Va(e,t,n){let r=e.match(/^diff --git .+$/gmu)??[],i=e.match(/^--- .+$/gmu)??[],a=e.match(/^\+\+\+ .+$/gmu)??[];if(r.length!==1||r[0]!==`diff --git a/${t} b/${t}`||i.length!==1||a.length!==1||i[0]!==`--- a/${t}`||a[0]!==`+++ b/${t}`||/^(?:deleted file mode |GIT binary patch$|new file mode |rename from |rename to )/mu.test(e))throw Error(`Recipe patch ${n} must modify only ${t}.`)}function Ha(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),L(`git`,r,{cwd:e,input:t}).status===0}function Ua(e,t){let n=L(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
|
|
13
|
+
`)])),encoding:`utf8`});if(n.status!==0){let e=n.stderr.trim()||n.stdout.trim();throw Error(`Could not apply recipe patches.${e?`\n${e}`:``}`)}}function Wa(e){return Ga(e)?.toString(`utf8`)}function Ga(e){try{return z(e)}catch(e){if(Xa(e)&&e.code===`ENOENT`)return;throw e}}function Ka(e,t){let n=Wa(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function qa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ja(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Ya(e){return typeof e==`string`&&e.length>0}function Xa(e){return e instanceof Error&&`code`in e}function Za(e={}){let{ref:t,refLabel:n,repositoryRoot:r}=ia(e),i=sa(r,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let n=e.split(`/`)[1];return Ri(n),{description:Li(aa(r,t,e),e).description,name:n}});return i.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:i,ref:n}}function Qa(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const $a=`.agents/skills/coreframe-upgrade/SKILL.md`;function eo(e,t={}){return L(`git`,e,t)}function to(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function no(e,t,n){let r=Yi(e,t,n),i=eo([`show`,r],{encoding:`utf8`});if(i.status!==0){let e=to(i);throw Error(`Could not read ${r}.${e?` ${e}`:``}`)}return i.stdout.toString()}function ro(){let e=eo([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=to(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function io(e,t){let n=Ce(P(Ae(),`coreframe-upgrade-skill-`)),r=P(n,`SKILL.md`);try{B(r,t);let n=to(eo([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{Te(n,{force:!0,recursive:!0})}}function ao({apply:e,remote:t,target:n}){let r=P(ro(),$a),i=Q(n,t);if(!R(r))throw Error(`Local ${$a} does not exist.`);let a=z(r,`utf8`),o=no(n,$a,t),s=qi(i);return a===o?(console.log(`Coreframe upgrade skill matches ${s}:template/${$a}.`),0):e?(B(r,o),console.error(`Updated ${$a} from ${s}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${s}:template/${$a}.`),console.error(`Run again with --apply to update it, then reread ${$a} before continuing.`),io(r,o),20)}const oo=[{matches:e=>e===`drizzle`||e.startsWith(`drizzle/`),reason:`project-owned migration history`},{matches:e=>e===`drizzle-hold`||e.startsWith(`drizzle-hold/`),reason:`project-owned migration history`},{matches:e=>e===`src/web/routes.ts`||e.startsWith(`src/web/app/routes/`),reason:`downstream-owned demonstration routes`},{matches:e=>e===`pnpm-lock.yaml`||e===`src-flutter/pubspec.lock`,reason:`downstream-owned dependency lockfile`}],so=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],co=new Set([`100644`,`100755`,`120000`]);function lo(e,t={}){return L(`git`,e,t)}function uo(e){let t=lo(e,{encoding:`utf8`});if(t.status!==0){let n=t.stderr.toString().trim()||t.stdout.toString().trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout.toString()}function fo(e){let t=lo(e);if(t.status!==0){let n=t.stderr.toString(`utf8`).trim()||t.stdout.toString(`utf8`).trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout}function po(){return uo([`rev-parse`,`--show-toplevel`]).trim()}function mo(e){let t=P(e,`package.json`);if(!R(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(z(t,`utf8`)).engines?.coreframe;if(typeof n!=`string`||n.length===0)throw Error(`Missing --base <git-ref>, and package.json engines.coreframe is not set.`);return n}function ho(e){let t=[],n=0;for(let r=0;r<e.length;r+=1)e[r]===0&&(t.push(e.subarray(n,r).toString(`utf8`)),n=r+1);return t.filter(e=>e.length>0)}function go(e,t){let n=ho(fo([`diff`,`--name-status`,`-z`,`--no-renames`,Ji(e),Ji(t),`--`])),r=[];for(let e=0;e<n.length;e+=2){let t=n[e],i=n[e+1];if(!t||!i)throw Error(`Could not parse git diff --name-status output.`);r.push({path:i,status:t})}return r}function _o(e,t){let n=fo([`ls-tree`,`-z`,`-r`,Ji(e),`--`,t]);if(n.length===0)return null;let r=ho(n)[0],i=r.indexOf(` `);if(i===-1)throw Error(`Could not parse git ls-tree output for ${e}:${t}.`);let[a,o,s]=r.slice(0,i).split(` `);if(!a||!o||!s)throw Error(`Could not parse git ls-tree metadata for ${e}:${t}.`);return{mode:a,object:s,path:t,type:o}}function vo(e){return fo([`cat-file`,`blob`,e.object])}function yo(e,t){let n=F(e,t),r=e.endsWith(ye)?e:`${e}${ye}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function bo(e){try{return xe(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function xo(e){return(e.mode&73)!=0}function So(e){return e===null||e.type===`blob`&&co.has(e.mode)}function Co(e){return oo.find(t=>t.matches(e))?.reason}function wo(e){return so.find(t=>t.matches(e))?.reason}function To(e,t,n){let r=yo(e,t);if(n===null)return{matches:!bo(r)};if(!So(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=xe(r)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return{matches:!1,reason:`path is missing from worktree`};throw e}let a=vo(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(we(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?xo(i):!xo(i))?{matches:z(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function Eo(e){bo(e)&&Te(e,{force:!0,recursive:!1})}function Do(e,t,n){let r=yo(e,t);if(n===null){Eo(r);return}if(Se(N(r),{recursive:!0}),n.mode===`120000`){Eo(r),Ee(vo(n).toString(`utf8`),r);return}let i=bo(r)?xe(r):null;i&&!i.isFile()&&Eo(r),B(r,vo(n)),be(r,n.mode===`100755`?493:420)}function Oo(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function ko(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t){let t=e.reason?` (${e.reason})`:``;console.log(` ${e.action}: ${e.path}${t}`)}console.log(``)}}function Ao(e){let t=po(),n=Q(e.base??mo(t),e.remote),r=Q(e.target,e.remote),i=go(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=Co(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=_o(n,e.path),u=_o(r,e.path),d=Oo(l,u),f=u===null?wo(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!So(l)||!So(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(To(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=To(t,e.path,l);if(!p.matches){s.push({action:d,path:e.path,reason:p.reason??`downstream differs from base template`});continue}a.push({action:d,path:e.path,targetEntry:u})}if(e.apply)for(let e of a)Do(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${qi(n)} -> ${qi(r)}`),console.log(``),ko(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),ko(`Ignored downstream-owned paths`,o),ko(`Skipped for agent review`,s),c.length>0&&console.log(`${c.length} changed template path(s) already matched the target state.`),i.length===0&&console.log(`No template file changes found in the requested range.`),!e.apply&&a.length>0&&(console.log(``),console.log(`Run with --apply to write the ${a.length} clean update(s).`))}function jo({base:e,cwd:t=process.cwd(),remote:n=Gi,target:r}){let i=[`for-each-ref`,`--sort=v:refname`,`--format=%(refname)`,`--merged`,Q(r,n)];e&&i.push(`--no-merged`,Q(e,n)),i.push(`${Ki(n)}/v[0-9]*`);let a=L(`git`,i,{cwd:t,encoding:`utf8`});if(a.status!==0){let e=a.stderr.trim()||a.stdout.trim();throw Error(`Git command failed: git ${i.join(` `)}${e?`\n${e}`:``}`)}return a.stdout.split(`
|
|
14
|
+
`).map(e=>e.trim()).filter(Boolean)}const Mo=[`dependencies`,`devDependencies`];function No(e){let t=L(`git`,e,{encoding:`utf8`});if(t.status!==0){let n=t.stderr.trim()||t.stdout.trim();throw Error(`Git command failed: git ${e.join(` `)}${n?`\n${n}`:``}`)}return t.stdout}function Po(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Fo(e,t,n){let r=`${Q(e,n)}:${t}`;return Po(No([`show`,r]),r)}function Io(e){return e.startsWith(`@coreframe/`)}function Lo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function Ro(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function zo(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=ve.normalize(ve.join(`template`,r,`package.json`));if(r.length===0||ve.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function Bo(e,t){let n=Fo(e,`template/package.json`,t),r=[],i=new Set;for(let a of Mo)for(let[o,s]of Object.entries(n[a]??{})){if(!Io(o)||!Ro(s))continue;if(i.has(o))throw Error(`Target template declares ${o} more than once.`);let n=zo(s,o),c=Fo(e,n,t);if(c.name!==o||typeof c.version!=`string`)throw Error(`${Q(e,t)}:${n} must declare ${o} with a version.`);r.push({group:a,name:o,spec:`^${c.version}`}),i.add(o)}return r}function Vo(e,t){for(let n of Mo){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Ho(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
|
|
15
15
|
`)?`
|
|
16
|
-
`:``;
|
|
17
|
-
`),`Pending Worker secret updates`),l?.accessTokenSigningSecret.provisioned&&B.log.info(`Provisioning Coreframe-managed access-token signing material.`),await os(n);let ee=o.mode===`full`?await Zo(a,n,t):!1;try{g&&await Nt(Go,r,p),B.log.step(`Running pre-deploy build`),await F(`pnpm`,[`build`],{env:ds(h),stdio:`inherit`}),B.log.step(s?`Running release build and uploading PostHog source maps`:`Running release build`),_=!0,await F(`pnpm`,[`build`],{env:h,stdio:`inherit`}),ee&&(B.log.step(`Running deploy-safe database migrations`),await F(`pnpm`,[`exec`,`drizzle-kit`,`migrate`],{env:h,stdio:`inherit`})),B.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let e={...l?.dashboardPassword?{DASHBOARD_PASSWORD:l.dashboardPassword}:{},...l?.accessTokenSigningSecret.value?{[ct]:l.accessTokenSigningSecret.value}:{},...l?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await cs(e):void 0,i={...h};delete i.CLOUDFLARE_ENV;let u=o.mode===`full`?await ht({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:m}}}):await mt(process.cwd());try{await F(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,u.path,`--strict`,`--keep-vars`,`--tag`,m,`--message`,`Deploy ${m}`,...t?[`--secrets-file`,t.path]:[]],{env:i,stdio:`inherit`}),l&&(await lt(l.pendingWorkerSecrets),await Mt({environment:n.environment}))}finally{await u.dispose(),await t?.dispose()}let d={environment:n.environment,releaseName:m,url:c,version:p};o.mode===`full`&&o.afterWorkerDeploy&&(B.log.step(`Running required after-Worker deploy hook`),await kt(o,d)),n.skipPostDeployChecks||(B.log.step(`Running post-deploy checks`),await At(o,d)),B.outro(`Deployed ${m} to ${n.environment}`)}catch(e){throw!_&&g&&await W(Go,i),e}}async function qo(e){let t;try{t=await H(`.env.deploy`,`utf8`)}catch(e){if(ls(e)&&e.code===`ENOENT`)return;throw e}for(let[n,r]of Object.entries(Ft(t)))e[n]===void 0&&(e[n]=r)}function Jo(e){return{environment:Yo(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Yo(e){if(e&&ut.includes(e))return e;throw Error(`Deploy environment must be one of: ${ut.join(`, `)}.`)}async function Xo(e,t,n){let r=await Ct({environment:e}),i=n.dashboard?.enabled===!1?void 0:r.values.DASHBOARD_PASSWORD??await ss(t,e);return jt(await pt({environment:e}),e,{availableNames:[...Object.keys(r.values),...i?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await vt({environment:e}),dashboardPassword:i,pendingWorkerSecrets:r}}async function Zo(e,t,n){let r=e.database?.dialect??`postgres`,i;switch(r){case`postgres`:i=await y({env:n});break;case`sqlite`:i=await b({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let{appliedMigrations:a,pendingMigrations:o}=await Qo(i),s=await ce(o);if(s.length>0){if(a.size>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations and apply them with \`pnpm db migrate-held\`.\n${ne(s)}`);B.log.warn(`Pending deploy migrations contain SQL that is unsafe for an existing deployment, but the target database has no applied migrations, so no deployed app version can depend on the current schema. Proceeding with deploy migrations.\n${ne(s)}`)}return es(t,o)}async function Qo(e){try{return await $o(e)}finally{await e.close?.()}}async function $o(e){let t=await v(),n=await ae(e);return{appliedMigrations:n,pendingMigrations:C(t,n)}}async function es(e,t){if(t.length===0)return B.log.info(`No pending deploy migrations.`),!1;if(B.note(te(t),`Pending deploy migrations`),e.runMigrations)return!0;if(e.skipMigrations)return!1;if(!process.stdout.isTTY)throw Error(`Pending migrations require --run-migrations or --skip-migrations in noninteractive deploys.`);let n=await B.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(B.isCancel(n))throw B.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function ts(){let{stdout:e}=await F(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await F(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function ns(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function rs(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function is(e,t,n=ft){return e.url?as(e.url,t):t===`staging`&&e.stagingHostname?as(await n(),t):as(void 0,t)}function as(e,t){if(!e)throw Error(`Missing ${t} deploy URL. Set DEPLOY_URL or deploy.environments.${t}.url in coreframe.config.ts.`);let n;try{n=new URL(e)}catch{throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`);return n.toString()}async function os(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await B.confirm({initialValue:!1,message:`Deploy to production?`});if(B.isCancel(t)||!t)throw B.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}async function ss(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Ft(await H(`.env`,`utf8`))}catch(e){throw ls(e)&&e.code===`ENOENT`?Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`):e}let i=r.DASHBOARD_PASSWORD?.trim();if(!i)throw Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`);return i}async function cs(e){let t=await Ge(N(je(),`coreframe-deploy-secrets-`)),n=N(t,`secrets.json`);return await W(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>U(t,{force:!0,recursive:!0})}}function ls(e){return e instanceof Error&&`code`in e}function us(e,t,n,r,i){return{...e,CLOUDFLARE_ENV:t,DEPLOY_ENV:t,POSTHOG_RELEASE:n,POSTHOG_RELEASE_NAME:e.POSTHOG_RELEASE_NAME??r,POSTHOG_RELEASE_VERSION:e.POSTHOG_RELEASE_VERSION??i}}function ds(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function fs(){let e=await ms();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function ps(e){let t=await ms(),n=hs();await Z.mkdir(j.dirname(n),{recursive:!0}),await Z.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function ms(){try{let e=await Z.readFile(hs(),`utf8`),t=JSON.parse(e);return gs(t)?t:{}}catch{return{}}}function hs(){return j.join(ri.homedir(),`.coreframe`,`preferences.json`)}function gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function _s({env:e=q.env,interactive:t=q.stdin.isTTY===!0,platform:n,target:r}){let i=await ws(n,e).catch(()=>[]),a=r?Hs(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Cs(i,n,t);let o=r?Hs(await Es(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Ds(o,n,e,t);let s=await Ts(n,e),c=r?Hs(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Cs(s,n,t);let l=n===`ios`?`iOS`:`Android`;throw Error(r?`Could not find a ${l} device matching "${r}".`:`No connected ${l} devices or available ${l} ${n===`ios`?`simulators`:`emulators`} were detected.`)}async function vs(e){let{device:t,host:n,interactive:r=q.stdin.isTTY===!0}=e;if(!t.physical&&n===void 0)return;if(typeof n==`string`&&n!==`0.0.0.0`&&n!==`::`)return n;let i=Ws();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await xs();if(a&&i.includes(a))return a;if(i.length===1)return await Ss(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await B.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(B.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await Ss(o),o}async function ys({device:e,env:t=q.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await Fs(e.id,a,t)}catch{B.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:bs(i,await vs({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function bs(e,t,n){let r=t??(e===`android`?`10.0.2.2`:`127.0.0.1`);return`http://${r.includes(`:`)&&!r.startsWith(`[`)?`[${r}]`:r}:${n}`}async function xs(){return(await fs()).mobileDevHost}async function Ss(e){try{await ps({mobileDevHost:e})}catch(e){B.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Cs(e,t,n){if(e.length===1)return e[0];if(!n)throw Error(`Multiple ${t===`ios`?`iOS`:`Android`} devices were detected. Pass a device name explicitly.`);let r=await B.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(B.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function ws(e,t){return e===`android`?ks(t):js(t)}async function Ts(e,t){return e===`android`?As(t):Ms(t)}async function Es(e){let{stdout:t}=await F(`flutter`,[`emulators`],{env:e});return t.split(/\r?\n/).flatMap(e=>{let[t,n,,r]=e.split(/\s*•\s*/).map(e=>e.trim());return t&&n&&(r===`android`||r===`ios`)?[{id:t,label:n,name:n,physical:!1,platform:r}]:[]})}async function Ds(e,t,n,r){let i=await Os(t,n).catch(()=>[]),{stdout:a}=await F(`flutter`,[`emulators`,`--launch`,e.id],{env:n});if(/No emulator found|More than one emulator matches/i.test(a))throw Error(a.trim());let o=Date.now()+3e4;do{let a=await Os(t,n).catch(()=>[]),o=Hs(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Cs(s,t,r);if(a.length===1)return a[0];await Jt(250)}while(Date.now()<o);let s=t===`ios`?`iOS simulator`:`Android emulator`;throw Error(`Flutter launched "${e.id}", but no ${s} became available.`)}async function Os(e,t){return e===`ios`?Ms(t,`booted`):(await ks(t)).filter(e=>!e.physical)}async function ks(e){let t=await Ps(e,`platform-tools`,q.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await F(t,[`devices`],{env:e}),r=n.split(/\r?\n/).map(e=>e.match(/^(\S+)\s+device(?:\s|$)/)?.[1]).filter(e=>e!==void 0);return(await Promise.all(r.map(async n=>{let r=await Ls(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await zs(t,e,n,r):await Bs(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(Gs)}async function As(e){let{stdout:t}=await F(await Ps(e,`emulator`,q.platform===`win32`?`emulator.exe`:`emulator`),[`-list-avds`],{env:e});return t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!/^(INFO|WARNING|ERROR)\s+\|/.test(e)).map(e=>({id:e,label:e,name:e,physical:!1}))}async function js(e){let t=await Z.mkdtemp(j.join(ri.tmpdir(),`coreframe-ios-devices-`)),n=j.join(t,`devices.json`);try{return await Z.writeFile(n,``),await F(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Z.readFile(n,`utf8`)).result?.devices??[]).filter(Ns).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(Gs)}finally{await Z.rm(t,{force:!0,recursive:!0})}}async function Ms(e,t=`available`){let{stdout:n}=await F(`xcrun`,[`simctl`,`list`,`--json`,`devices`,t],{env:e}),r=JSON.parse(n);return Object.entries(r.devices??{}).filter(([e])=>e.includes(`iOS-`)).flatMap(([,e])=>e).flatMap(e=>e.name&&e.udid?[{id:e.udid,label:e.name,name:e.name,physical:!1}]:[]).sort(Gs)}function Ns(e){return e.connectionProperties?.tunnelState!==`unavailable`&&typeof e.hardwareProperties?.platform==`string`&&(e.hardwareProperties.platform.includes(`iOS`)||e.hardwareProperties.platform.includes(`xrOS`))&&typeof e.deviceProperties?.name==`string`&&typeof e.hardwareProperties.productType==`string`&&typeof e.hardwareProperties.udid==`string`}async function Ps(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:Is(e);for(let e of i){let r=j.join(e,t,n);try{return await Z.access(r),r}catch{}}return n}async function Fs(e,t,n){let r=await Ps(n,`platform-tools`,q.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await F(r,[`-s`,e,`reverse`,`tcp:0`,`tcp:${t}`],{env:n,timeout:3e3}),a=Number(i.trim());if(!Number.isInteger(a)||a<1||a>65535)throw Error(`ADB did not return a valid reverse TCP port.`);let o=`tcp:${a}`,s=!1;return{async close(){s||(s=!0,await F(r,[`-s`,e,`reverse`,`--remove`,o],{env:n,timeout:3e3}).catch(()=>void 0))},serverUrl:`http://127.0.0.1:${a}`,viteHost:`127.0.0.1`}}function Is(e){return q.platform===`darwin`?[j.join(ri.homedir(),`Library`,`Android`,`sdk`)]:q.platform===`win32`&&e.LOCALAPPDATA?[j.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[j.join(ri.homedir(),`Android`,`Sdk`)]}async function Ls(e,t,n,r){return(await Rs(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function Rs(e,t,n){return(await F(e,n,{env:t,timeout:3e3})).stdout}async function zs(e,t,n,r){return Rs(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function Bs(e,t,n,r){return Rs(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>Vs(e)||r).catch(()=>r)}function Vs(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function Hs(e,t){let n=e.map(e=>({device:e,score:Math.max(Us(t,e.name),Us(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function Us(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r===n)return 1e4;let i=r.indexOf(n);if(i>=0)return 5e3-i;let a=0,o=0;for(let e of n){let t=r.indexOf(e,o);if(t<0)return 0;a+=t===o?2:1,o=t+1}return a}function Ws(){return[...new Set(Object.values(ri.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function Gs(e,t){return e.label.localeCompare(t.label)}var Ks=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!Zs(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:Zs(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...Js(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!Zs(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=$s(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(Qs(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r($s(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*qs(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function Js({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(Xs(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=Ys(t.level);return!n&&e===`debug`?[]:[...$(Xs(t.message),e),...n?$(Xs(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(Xs(t.message),Ys(t.level)):e===`app.warning`?$(Xs(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(Xs(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(Qs(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function Ys(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function Xs(e){return typeof e==`string`&&e.length>0?e:void 0}function Zs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qs(e){if(typeof e==`string`)return e;if(Zs(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function $s(e){return e instanceof Error?e:Error(Qs(e))}async function ec(e,t){if(!e)return()=>void 0;Ce(j.dirname(e),{recursive:!0}),z(e,``,{flag:`a`});let n;try{n=R(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Oe(e,{persistent:!1},()=>{if(i)return;let a=++r;H(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function tc(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const nc=q.platform===`win32`?`portless.cmd`:`portless`,rc=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),ic=/^Proxy is already running on port (\d+)\.$/,ac=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function oc(e){let t=e.split(/(\r\n|\n)/),n=[];for(let e=0;e<t.length;){let r=t[e],i=t[e+2],a=r?.replace(rc,``).trim().match(ic);if(a?.[1]!==void 0&&i!==void 0&&ac.test(i.replace(rc,``).trim())){n.push(`Portless proxy is running on port ${a[1]}.`),t[e+1]!==void 0&&n.push(t[e+1]),e+=t[e+3]===void 0?3:4;continue}n.push(t[e]??``),e+=1}return n.join(``)}function sc(e){let t=oc(e);t&&q.stdout.write(t.endsWith(`
|
|
18
|
-
`)?t:`${t}\n`)}async function cc({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await Yt()).isAgent?!1:Ht(e)}async function lc({cwd:e,env:t,lan:n=!1}){let r=j.join(`node_modules`,`.bin`,nc),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await F(j.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});sc(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&sc(e.stdout),e}}function uc({host:e,lan:t=!1,port:n}){return[...t?[`--lan`]:[],`run`,...n===void 0?[]:[`--app-port`,String(n)],`react-router`,`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e]]}const dc=j.join(`.coreframe`,`dev`,`session.json`);async function fc({appOrigin:e,cwd:t,device:n,flutterMcp:r,flutterMode:i,id:a,localOrigin:o,now:s=new Date,pid:c=process.pid,platform:l}){let u=j.resolve(t,dc),d=j.dirname(u),f={version:2,id:a,pid:c,projectRoot:j.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:j.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await V(d,{recursive:!0});let t=j.join(d,`.session-${a}.json`);await W(t,e,{mode:384}),await He(t,384),await qe(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=hc(t.appId),i;if(e===`daemon.connected`){let e=gc(t.pid),r=hc(t.version);i={...pc(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...pc(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=hc(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=hc(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=hc(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=mc(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:mc(f.flutter)},await m())},async close(){await p;try{JSON.parse(await H(u,`utf8`)).id===a&&await U(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function pc(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function mc(e){return{...pc(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function hc(e){return typeof e==`string`?e:void 0}function gc(e){return typeof e==`number`?e:void 0}const _c=`extension:dev`;function vc(e){if(!L(N(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=N(e,`package.json`),n;try{n=JSON.parse(R(t,`utf8`))}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}if(!n||typeof n!=`object`||!(`scripts`in n)||!n.scripts||typeof n.scripts!=`object`||!(`extension:dev`in n.scripts)||typeof n.scripts[`extension:dev`]!=`string`)throw Error(`package.json must define scripts.${_c} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function yc({host:e,port:t}){let n=[...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)]];return[`run`,_c,...n.length>0?[`--`,...n]:[]]}const bc=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],xc=[`managed-dev-overlay`],Sc=j.resolve(`node_modules`,`.bin`),Cc=q.platform===`win32`?`pnpm.cmd`:`pnpm`,wc=q.platform===`win32`?`portless.cmd`:`portless`,Tc=q.platform===`win32`?`react-router.cmd`:`react-router`,Ec=`Lost connection to device.`;async function Dc({cwd:e=q.cwd(),debug:t,device:n,env:r=q.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=q.stdin.isTTY===!0,lan:u=!1,managed:d=!1,noCodesign:f=!1,noManaged:p=!1,noDevJobs:m=!1,platform:h=`web`,verbose:g=!1,webPort:_}={}){let v=Rt({env:r}),ee=r.PATH??r.Path??``,y=Bc(h)?h:void 0,b=tn(i||a),x=zc(_??r.COREFRAME_WEB_PORT),S,C,w,te,ne,re,ie,ae,se,T,ce,le,ue,E=!1,fe,D=r;if(d&&p)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&d)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&y===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(a&&y===void 0)throw Error(`The --flutter-mcp option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(f&&h!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(o===`full`&&y===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(h===`webext`){if(d||p||t!==void 0||g)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);vc(e)}if(c&&h!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&h!==`ios`&&h!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let pe=await v.measure(`routing`,()=>cc({cwd:e,env:r,platform:h}));pe&&await v.measure(`portless`,()=>lc({cwd:e,env:r,lan:u}));let O=y===void 0?h===`web`?x??await ni.getAvailablePort():h===`webext`?x:void 0:x??await ni.getAvailablePort(),k,he=new Promise(e=>{k=e}),A=()=>{E||(E=!0,k(),C?.kill(`SIGTERM`),re?.kill(`SIGTERM`),ie?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ae?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),se?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),_e().catch(()=>void 0))},_e=()=>te?(ne??=te[Symbol.asyncDispose](),ne):Promise.resolve(),M=e=>{fe??=e,A()},ve=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>M(e);return q.on(e,t),{handler:t,signal:e}}),N=async e=>{let t=nt(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{ce=y?qt({path:j.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await _s({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&nn({device:_,mode:b,platform:i});let x=y?ce?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;T=i&&_&&O!==void 0?await ys({device:_,env:r,host:s,interactive:l,platform:i,port:O}):void 0;let C=T?.viteHost??(y?i?!0:`127.0.0.1`:s),ne=O===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${O}`,fe=y===void 0?ne:T?.serverUrl??bs(y,void 0,O),k={},_e=!1,M;[k,_e]=await Promise.all([v.measure(`config`,()=>G({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await Vt(e))]),await v.measure(`i18n`,()=>Tr({cwd:e,projectConfig:k})),M=h!==`webext`&&k.dashboard?.enabled!==!1&&li(e)?await ni.getAvailablePort():void 0;let ve=await v.measure(`https`,async()=>c&&!pe?Ut({cwd:e}):void 0),ye=tc(r,h);D={...ye,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Wt]:K()}:void 0,...y?{COREFRAME_PLATFORM:y,[Kt]:j.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...ve?{[zt]:ve.cert,[Bt]:ve.key}:void 0,...M?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${M}`}:void 0},ne!==void 0&&fe!==void 0&&(le=await fc({appOrigin:fe,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:K(),localOrigin:ne,platform:h}));let P=async()=>{if(!M)return;let t=ui({cwd:e,env:D,port:M});se=t;try{await t.listen(),await t.wait()}finally{await t.close(),se===t&&(se=void 0)}},be=async()=>{let t=tt({label:`web`}),n=tt({color:`red`,label:`web`});t.pipe(q.stdout,{end:!1}),n.pipe(q.stderr,{end:!1}),ie=F(pe?wc:Tc,pe?uc({host:C,lan:u,port:O}):Rc({host:C,port:O,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...D,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[D.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Sc+j.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([Pc(ie.stdout,t),Pc(ie.stderr,n)]);try{await ie;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([et(t),et(n)]),ie=void 0}},I=async()=>{let t=tt({label:`webext`}),n=tt({color:`red`,label:`webext`});t.pipe(q.stdout,{end:!1}),n.pipe(q.stderr,{end:!1}),ae=F(Cc,yc({host:s,port:O}),{cwd:e,env:D,stdin:`inherit`});let r=Promise.allSettled([Pc(ae.stdout,t),Pc(ae.stderr,n)]);try{await ae;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([et(t),et(n)]),ae=void 0}},xe=async t=>{let n,r,i=!1,s,c=ec(D[Kt],()=>{if(E||!n||!r||s||b!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(b===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);x?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),q.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),q.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!E;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await ge():void 0,u=F(`flutter`,rn({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:fe,verbose:g}),{cwd:j.join(e,`src-flutter`),env:en(ye,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new Ks({onEvent:async e=>{Ac(e.params.message)&&(s=!0),await le?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await It(t.stdin,`drain`)}}),p=e=>kc(qs(e,d),()=>s=!0);S=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(Nc(p(u),x,`output`)):Promise.all([Mc(p(u.stdout),q.stdout,x,`stdout`),Oc(u.stderr,q.stderr,x,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!E)continue;if(E)return;let n=l?await B.confirm({initialValue:!0,message:s?`${Ec} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(B.isCancel(n)||!n){if(!e&&!s){B.log.warn(`Flutter exited unexpectedly.`);return}B.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??he);return}}finally{S===u&&(S=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),le?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);x?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},L=async()=>{if(h===`web`){await be();return}let t=be().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await me({cwd:e});try{await Promise.race([t,xe(t)])}finally{A(),await Promise.allSettled([t,S]),S=void 0}},Se=async()=>{let t=nt({name:`panda`,command:Cc,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:D});re=t;try{if(await t.expectSuccess(),!E)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!E)throw e}finally{re===t&&(re=void 0)}},Ce=async()=>{if(h===`webext`){await I();return}let e=Se(),t=L(),n=M?P():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{A(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(_e&&(D={...D,[Gt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(ue=await v.measure(`supervisor`,()=>Lt({cwd:e,env:r})))),E)return;if(h===`webext`){v.report(),await Ce();return}if(k.database?.dialect===`sqlite`){if(await v.measure(`database`,async()=>{let t=await de({config:k,cwd:e,env:r,tursoOutput:q.stdout,useSupervisorLease:!0});te=t,D={...D,...t.env}}),await v.measure(`schema`,()=>N({name:`db`,command:Cc,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E)return;oe({cwd:e,env:D,dialect:`sqlite`})}if(Lc(k)){let t=tt({label:`postgres`});t.pipe(q.stdout,{end:!1});try{let n=await v.measure(`database`,()=>Ic({config:k,cwd:e,env:D,failIfRunning:!0,interactive:l,isStopping:()=>E,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;w=n,D={...D,...n.env};try{E||await v.measure(`schema`,()=>N({name:`db`,command:Cc,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E||(oe({cwd:e,env:D,dialect:`postgres`}),v.report(),await Ce())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await Ce()}finally{A(),await T?.close(),T=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await _e()}finally{try{await le?.close()}finally{ue?.close(),ce?.close();for(let{handler:e,signal:t}of ve)q.off(t,e)}}fe&&(q.exitCode??=fe===`SIGINT`?130:143)}Fc(e)}}async function Oc(e,t,n,r){for await(let i of jc(e,n,r))t.write(`${i}\n`)||await It(t,`drain`)}async function*kc(e,t){for await(let n of e)Ac(n.message)&&t(),yield n}function Ac(e){return typeof e==`string`&&e.trim()===Ec}async function*jc(e,t,n){for await(let r of e){let e=pe(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function Mc(e,t,n,r){for await(let i of Nc(e,n,r))t.write(`${i}\n`)||await It(t,`drain`)}async function*Nc(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function Pc(e,t){for await(let n of e)t.write(`${n}\n`)||await It(t,`drain`)}function Fc(e){if(e)throw e}async function Ic({interactive:e,isStopping:t,...n}){try{return await E(n)}catch(r){if(!(r instanceof h)||!e)throw r;let i=await B.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(B.isCancel(i)||!i){B.cancel(`Keeping the existing PostgreSQL process.`);return}return await fe(r),t()?void 0:E(n)}}function Lc(e){return(e.database?.dialect??`postgres`)===`postgres`}function Rc({host:e,port:t,strictPort:n=!1}){return[`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)],...n?[`--strictPort`]:[]]}function zc(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`COREFRAME_WEB_PORT must be a valid TCP port.`);return t}function Bc(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function Vc(e={}){let t=e.cwd??q.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Ve(j.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Xe(n,t);if(!e.default||typeof e.default!=`object`)throw Error(`scripts/preview.ts must default-export preview hooks.`);for(let t of[`beforeBuild`,`afterBuild`])if(e.default[t]!==void 0&&typeof e.default[t]!=`function`)throw Error(`scripts/preview.ts ${t} must be a function.`);r=e.default}return Xt({...e,cwd:t},r)}const Hc=`worker-configuration.d.ts`;async function Uc({check:e=!1,cwd:t=process.cwd()}={}){let n=await G({cwd:t}),r=await gt({coreframeConfig:n,cwd:t}),i=P(t,Hc),a=P(t,`.coreframe-worker-types-${K()}.d.ts`);try{try{await F(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw Wc(e),e}let o=Gc(await H(a,`utf8`)),s=Qe(r.config),c=Ze(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${Kc(c)}\n`;if(e){if(await H(i,`utf8`).catch(()=>``)!==l)throw Error(`${Hc} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await H(i,`utf8`).catch(()=>``);return u!==l&&await W(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await U(a,{force:!0})}}function Wc(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
19
|
-
`)?t:`${t}\n`)}function Gc(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
20
|
-
`)}function
|
|
21
|
-
`)}const qc=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),Jc=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],Yc=[`dashboard`,`node_modules/@coreframe/dashboard/dist/package/app`,`node_modules/@coreframe/dashboard/package.json`,`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`],Xc=[`coreframe.config.ts`,`node_modules/@coreframe/config/dist`,`node_modules/@coreframe/config/package.json`,`node_modules/@coreframe/deploy/dist`,`node_modules/@coreframe/deploy/package.json`,`node_modules/wrangler/package.json`,`package.json`,`pnpm-lock.yaml`,`src/api`,`wrangler.jsonc`],Zc=`.coreframe/typegen.json`,Qc=[`web`,`dashboard`,`worker`];async function $c({checkWorker:e=!1,cwd:t=q.cwd(),runners:n={}}={}){let r=await rl(t)??{generators:{},schemaVersion:1},i=[];return i.push(await tl({cwd:t,inputPaths:Jc,name:`web`,outputPath:`.react-router`,run:()=>(n.web??nl)(t),state:r})),i.push(await tl({cwd:t,inputPaths:Yc,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??Zr)(t),state:r})),i.push(await tl({cwd:t,inputPaths:Xc,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??Uc)({check:e,cwd:t}),state:r})),i}function el(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function tl({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await al(e,t),s=await ol(e,r),c=a.generators[n];if(s&&c?.inputFingerprint===o&&c.outputFingerprint===s)return{changed:!1,name:n,ran:!1};await i();let l=await ol(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await il(e,a),{changed:s!==l,name:n,ran:!0}}async function nl(e){let t=q.platform===`win32`?`react-router.cmd`:`react-router`,n=q.env;await F(t,[`typegen`],{cwd:e,env:{...n,PATH:j.resolve(e,`node_modules/.bin`)+j.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function rl(e){try{let t=JSON.parse(await H(j.resolve(e,Zc),`utf8`));if(!ul(t)||t.schemaVersion!==1)return;let n={};if(!ul(t.generators))return;for(let e of Qc){let r=t.generators[e];ul(r)&&typeof r.inputFingerprint==`string`&&typeof r.outputFingerprint==`string`&&(n[e]={inputFingerprint:r.inputFingerprint,outputFingerprint:r.outputFingerprint})}return{generators:n,schemaVersion:1}}catch{return}}async function il(e,t){let n=j.resolve(e,Zc);await V(j.dirname(n),{recursive:!0}),await W(n,`${JSON.stringify(t)}\n`,{mode:384})}async function al(e,t){let n=$e(`sha256`);for(let r of[...t].sort()){let t=j.resolve(e,r),i=await cl(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await sl(t)){let i=j.join(t,r),a=j.relative(e,i).split(j.sep).join(`/`);n.update(`${a}\0`),n.update(await H(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await H(t)))}return n.digest(`hex`)}async function ol(e,t){if(await cl(j.resolve(e,t)))return al(e,[t])}async function sl(e){let t=[];async function n(e,r){let i=await Ke(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(qc.has(a.name))continue;await n(j.join(e,a.name),j.join(r,a.name))}else a.isFile()&&t.push(j.join(r,a.name))}return await n(e,``),t.sort()}async function cl(e){try{return await Je(e)}catch(e){if(ll(e))return;throw e}}function ll(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const dl=j.resolve(`node_modules`,`.bin`);q.env.PATH=dl+j.delimiter+q.env.PATH;const fl=q.platform===`win32`?`tsc.cmd`:`tsc`,pl=[{name:`scripts`,path:`scripts/tsconfig.json`},{name:`shared`,path:`src/shared/tsconfig.json`},{name:`api`,path:`src/api/tsconfig.json`},{name:`worker`,path:`src/api/worker/tsconfig.json`},{name:`web`,path:`src/web/tsconfig.json`},{name:`dashboard`,path:`dashboard/tsconfig.json`}];async function ml(){await $c({checkWorker:!0});let e=[];for(let t of pl)try{await Ve(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>nt({name:e.name,command:fl,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(q.exitCode=n[0].exitCode)}const hl=r(s(xc),{displayName:`feature`,from:async e=>e}),gl=r(s($t),{displayName:`filtered|full`,from:async e=>e}),_l=[`Cookies and sessions are origin-scoped.`,`Exact-host passkeys may require re-registration unless a stable eligible parent RP ID was configured in advance.`,`External OAuth callbacks such as Google may need updating.`,`Database data and private backend resources are unchanged.`],vl=n({name:`deploy`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:i({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:i({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:i({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Ko([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),yl=m({name:`staging`,cmds:{reassign:n({name:`reassign`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await wt();if(e){console.log(JSON.stringify({...t,notices:_l}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${_l.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ft();console.log(e?JSON.stringify({url:t}):t)}})}}),bl=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:i({long:`yes`,short:`y`,description:`Confirm immediate signing-secret replacement and invalidation of outstanding access JWTs.`,defaultValue:()=>!1})},handler:async({environment:e,yes:t})=>{if(!t)throw Error(`Access-token signing-secret rotation requires --yes because it immediately invalidates outstanding access JWTs.`);await Ot({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:n({name:`status`,args:{environment:u({type:l(s(ut)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await pt({environment:e});console.log(t?JSON.stringify(n):El(n))}}),set:n({name:`set`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:u({type:l(p),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:i({long:`bulk`,description:`Queue known secrets from pasted or piped dotenv-formatted contents.`,defaultValue:()=>!1})},handler:async({environment:e,name:t,bulk:n})=>{if(n&&t)throw Error(`Use either a secret name or --bulk, not both.`);if(t){await yt({environment:e,name:t,value:await Dl(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await xt(),i=n?await kl(r):await Ol(r,e);await bt({environment:e,values:i});let a=Object.keys(i).sort();console.log(a.length>0?`Queued ${a.join(`, `)} for ${e}. Run coreframe deploy ${e} to apply.`:`No ${e} Worker secret updates were queued.`)}}),discard:n({name:`discard`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:u({type:p,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await dt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),xl=n({name:`typecheck`,args:{},handler:ml}),Sl=m({name:`worker`,cmds:{typegen:n({name:`typegen`,args:{check:i({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await Uc({check:e});console.log(e?`${jl(t.path)} is current.`:`${jl(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Cl=n({name:`dev`,args:{debug:c({long:`debug`,type:l(hl),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:i({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:i({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:c({long:`flutter-output`,type:gl,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:i({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:c({long:`host`,type:l(p),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:i({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:i({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:i({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:i({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:i({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:u({type:l(s(bc)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:u({type:l(p),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:c({long:`port`,type:l(o),description:`Port for the web development server.`}),verbose:i({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,flutterDebug:n,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,simulator:m,verbose:h})=>{let g=wl({device:t,flutterDebug:n,platform:f,simulator:m});return Dc({debug:e,device:g.device,flutterDebug:g.flutterDebug,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f??`web`,verbose:h,webPort:p})}});function wl({device:e,flutterDebug:t,platform:n,simulator:r}){if(!r)return{device:e,flutterDebug:t};if(n!==`ios`)throw Error(`The --simulator flag is only supported for the iOS development target.`);if(e!==void 0)throw Error(`The --simulator flag cannot be combined with an explicit device.`);return{device:`apple_ios_simulator`,flutterDebug:!0}}const Tl=n({name:`preview`,args:{host:c({long:`host`,type:l(p),description:`Host address for the preview server.`}),port:c({long:`port`,type:l(o),description:`Port for the preview server.`})},handler:({host:e,port:t})=>Vc({host:e,port:t})});function El(e){if(e.entries.length===0)return`No Worker environment values are declared in coreframe.config.ts.`;let t=e.entries.map(e=>[e.name,e.kind,e.local===`override`?`override`:`built-in default`,e.deployed.staging.replaceAll(`_`,` `),e.deployed.production.replaceAll(`_`,` `)]),n=[`Name`,`Kind`,`Local`,`Staging`,`Production`],r=n.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),i=(e,t=` `)=>e.map((e,n)=>e.padEnd(r[n],t)).join(` | `).trimEnd();return[i(n),i(r.map(e=>``.padEnd(e,`-`)),`-`),...t.map(e=>i(e))].join(`
|
|
22
|
-
`)}async function Dl(e){if(!q.stdin.isTTY){let e=``;for await(let t of q.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await B.password({message:`Enter the new value for ${e}`});if(B.isCancel(t))throw B.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function Ol(e,t){if(!q.stdin.isTTY)throw Error(`Interactive secret setup requires a terminal. Provide a secret name or use --bulk with piped dotenv contents.`);if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let n={};for(let r of e){let e=r.requiredIn.includes(t),i=await B.password({message:`${r.name}: ${r.description}${e?` (required)`:` (optional; leave blank to skip)`}`,validate:n=>e&&!n?.trim()?`${r.name} is required in ${t}.`:void 0});if(B.isCancel(i))throw B.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function kl(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=q.stdin.isTTY?await B.multiline({message:`Paste dotenv-formatted Worker secrets. Press Enter twice to submit.`,validate:e=>e?.trim()?void 0:`Paste at least one dotenv entry.`}):await Al();if(B.isCancel(t))throw B.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=_t(t,e);return n.length>0&&B.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function Al(){let e=``;for await(let t of q.stdin)e+=t.toString();return e}function jl(e){return e.split(/[\\/]/).at(-1)??e}const Ml=n({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await $c();for(let t of e)console.log(el(t))}});function Nl(e,{formatMessage:t,temporaryDirectory:n=je(),write:r=e=>console.error(e)}={}){let i=zl(e),a=Hl(Fl(e,t),i);try{let t=N(we(N(n,`coreframe-error-`)),`error.log`);return z(t,`${Hl(Il(e),i)}\n`,{mode:384}),r(`Error: ${a}\nFull diagnostic: ${t}`),t}catch{r(`Error: ${a}\nThe full diagnostic could not be written to the temporary directory.`);return}}function Pl(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,Nl(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function Fl(e,t){try{return t?.(e)||(e instanceof Error?e.message:String(e)).split(/\r?\n/,1)[0]||`Unknown error`}catch{return`Unknown error`}}function Il(e){try{let t=Ll(e);if(!(e instanceof Error)||!Rl(t))return Pt(t,{customInspect:!1,depth:10});let n=typeof t.stack==`string`?t.stack:`${e.name}: ${e.message}`;return delete t.name,delete t.message,delete t.stack,`${n}${Reflect.ownKeys(t).length?`\n${Pt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function Ll(e,t=new WeakMap){if((typeof e!=`object`||!e)&&typeof e!=`function`)return e;let n=e,r=t.get(n);if(r)return r;if(typeof e==`function`)return`[Function${e.name?`: ${e.name}`:``}]`;let i=Array.isArray(e)?[]:{};t.set(n,i),e instanceof Error&&(i.name=e.name,i.message=e.message,i.stack=e.stack??`${e.name}: ${e.message}`);for(let r of Reflect.ownKeys(n)){if(typeof r!=`string`||r.toLowerCase()===`env`||Array.isArray(e)&&r===`length`||e instanceof Error&&(r===`name`||r===`message`||r===`stack`))continue;let a=Object.getOwnPropertyDescriptor(n,r);!a||!(`value`in a)||Object.defineProperty(i,r,{configurable:!0,enumerable:!0,value:Ll(a.value,t),writable:!0})}return i}function Rl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zl(e,t=new WeakSet){let n=new Set;function r(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let i=e;if(!t.has(i)){t.add(i);for(let e of Reflect.ownKeys(i)){if(typeof e!=`string`)continue;let t=Object.getOwnPropertyDescriptor(i,e);!t||!(`value`in t)||(e.toLowerCase()===`env`?Bl(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function Bl(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&Vl(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function Vl(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function Hl(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const Ul=m({name:`coreframe`,cmds:{build:_n,conflicts:Bn,dashboard:pi,assets:Kr,flutter:qr,i18n:Jr,jobs:ji,deploy:vl,staging:yl,secrets:bl,typegen:Ml,typecheck:xl,worker:Sl,dev:Cl,preview:Tl,upgrade:Ho,recipes:Uo,db:Wo}});import.meta.main&&Pl(Ul,{formatMessage:process.argv[2]===`db`?w:void 0});export{Ul as coreframeCli};
|
|
16
|
+
`:``;B(e,`${JSON.stringify(n,null,r)}${i}`)}function Uo(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function Wo(e){let t=F(No([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=z(t,`utf8`),r=Po(n,t),i=Q(e.target,e.remote),a=Bo(e.target,e.remote),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=Vo(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Lo(t.spec)){l.push(`linked: ${e.name} ${t.spec}`);continue}if(t.spec===e.spec){u+=1;continue}s.push({...e,currentGroup:t.group,currentSpec:t.spec})}let d=Mo.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>Io(e)&&!o.has(e)).map(([t,n])=>`review: ${t} ${n} (${e})`));if(e.apply&&s.length>0){for(let e of s)r[e.currentGroup][e.name]=e.spec;Ho(t,n,r)}console.log(`Coreframe package sync: ${qi(i)}`),console.log(``),Uo(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Uo(`Missing target Coreframe packages`,c),Uo(`Locally linked Coreframe packages`,l),Uo(`Downstream-only Coreframe packages`,d),u>0&&console.log(`${u} Coreframe package(s) already match the target versions.`),s.length===0?console.log(`No Coreframe package version updates found.`):e.apply||(console.log(``),console.log(`Run with --apply to write the ${s.length} package update(s).`))}const Go={...p,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Ri(e)}},Ko=m({name:`upgrade`,cmds:{"ensure-template-remote":n({name:`ensure-template-remote`,args:{remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Remote name to ensure.`}),url:c({long:`url`,type:l(p),description:`Template repository URL. Defaults to the upstream Coreframe repository.`}),noFetch:i({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,url:n})=>ra({fetch:!e,remote:t,url:n})}),"check-skill-current":n({name:`check-skill-current`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,remote:t,target:n})=>{process.exitCode=ao({apply:e,remote:t,target:n})}}),"fast-forward-template-files":n({name:`fast-forward-template-files`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),base:c({long:`base`,type:l(p),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,remote:n,target:r})=>Ao({apply:e,base:t,remote:n,target:r})}),"list-template-versions":n({name:`list-template-versions`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),base:c({long:`base`,type:l(p),description:`Previous Coreframe template git ref. Omit to list every released version.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`})},handler:({base:e,remote:t,target:n})=>{for(let r of jo({base:e,remote:t,target:n}))console.log(r)}}),"sync-coreframe-packages":n({name:`sync-coreframe-packages`,args:{target:c({long:`target`,type:p,description:`Target Coreframe template git ref.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),apply:i({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,remote:t,target:n})=>Wo({apply:e,remote:t,target:n})})}}),qo=m({name:`recipes`,cmds:{apply:n({name:`apply`,args:{recipe:u({type:Go,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Na(Ma({fetch:!e,name:t,remote:n,target:r}))}),list:n({name:`list`,args:{target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>Qa(Za({fetch:!e,remote:t,target:n}))}),verify:n({name:`verify`,args:{recipe:u({type:Go,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:c({long:`target`,type:l(p),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:c({long:`remote`,type:p,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:i({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>ka(Oa({fetch:!e,name:t,remote:n,target:r}))})}}),Jo=m({name:`db`,cmds:{ensure:n({name:`ensure`,args:{},handler:C}),generate:n({name:`generate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>oe(`generate`,e)}),migrate:n({name:`migrate`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>oe(`migrate`,e)}),"migrate-held":n({name:`migrate-held`,args:{local:i({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>te({target:e?`local`:`deployment`})}),"migrate-local":n({name:`migrate-local`,args:{},handler:ne}),"migrations-check":n({name:`migrations-check`,args:{},handler:g}),reset:n({name:`reset`,args:{},handler:ae}),seed:n({name:`seed`,args:{},handler:()=>ce()}),"schema-check":n({name:`schema-check`,args:{seed:i({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>_({seed:e})}),setup:n({name:`setup`,args:{},handler:()=>le()}),studio:n({name:`studio`,args:{args:d({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>oe(`studio`,e)})}}),Yo=`package.json`;async function Xo(e=process.argv.slice(2),t=process.env){let n=Qo(e);gs(n),await Zo(t);let{packageJson:r,source:i}=await Ct(Yo),a=await K(),o=Ot(a.deploy,n.environment,t);_s(n,o.mode);let s=!!(t.POSTHOG_API_KEY&&t.POSTHOG_PROJECT_ID);!s&&(t.POSTHOG_API_KEY||t.POSTHOG_PROJECT_ID)&&V.log.warn(`PostHog source map upload is disabled because only one of POSTHOG_API_KEY or POSTHOG_PROJECT_ID is set.`);let c=await vs(o,n.environment,()=>ft({env:t})),l=await yt(o,a,c,t),u=o.mode===`full`?await es(n.environment,t,a):void 0,d=await hs(),f=a.i18n?Mr(a.i18n):void 0;f&&jr(f)===`source-only`?V.log.info(`I18n source-only mode (${f.sourceLocale}): no prepared translation snapshot is required; source catalogs build directly.`):await Ar({env:t,revision:d});let p=d.slice(0,12),m=At(n.environment,r.version,p),h=Dt(r.name,m),g={...Ts(t,n.environment,h,r.name,m),...f?{COREFRAME_I18N_RELEASE_REVISION:d}:{}},_=n.environment===`production`,v=!1;V.intro(`Deploy ${h} to ${n.environment}`);let y=Object.keys(u?.pendingWorkerSecrets.values??{}).sort();y.length>0&&V.note(y.join(`
|
|
17
|
+
`),`Pending Worker secret updates`),u?.accessTokenSigningSecret.provisioned&&V.log.info(`Provisioning Coreframe-managed access-token signing material.`),await bs(n);let b=o.mode===`full`?await ts(a,n,t):{kind:`none`};try{_&&await It(Yo,r,m),V.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:Es(g),stdio:`inherit`}),V.log.step(s?`Running release build and uploading PostHog source maps`:`Running release build`),v=!0,await I(`pnpm`,[`build`],{env:g,stdio:`inherit`});let e={...g};delete e.CLOUDFLARE_ENV,b.kind===`drizzle`?(V.log.step(`Running deploy-safe database migrations`),await I(`pnpm`,[`exec`,`drizzle-kit`,`migrate`],{env:g,stdio:`inherit`})):b.kind===`d1`&&(V.log.step(`Applying deploy-safe D1 migrations with Wrangler`),await I(`pnpm`,ss(n.environment,[`d1`,`migrations`,`apply`,b.database.binding,`--remote`]),{env:e,stdio:`inherit`})),V.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let t={...u?.dashboardPassword?{DASHBOARD_PASSWORD:u.dashboardPassword}:{},...u?.accessTokenSigningSecret.value?{[ct]:u.accessTokenSigningSecret.value}:{},...u?.pendingWorkerSecrets.values},i=Object.keys(t).length>0?await Ss(t):void 0,d=o.mode===`full`?await ht({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:h}}}):await mt(process.cwd());try{await I(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,d.path,`--strict`,`--keep-vars`,`--tag`,h,`--message`,`Deploy ${h}`,...i?[`--secrets-file`,i.path]:[]],{env:e,stdio:`inherit`}),u&&(await lt(u.pendingWorkerSecrets),await Ft({environment:n.environment}))}finally{await d.dispose(),await i?.dispose()}let f={environment:n.environment,releaseName:h,url:c,version:m};o.mode===`full`&&o.afterWorkerDeploy&&(V.log.step(`Running required after-Worker deploy hook`),await Mt(o,f)),l&&(V.log.step(`Provisioning and verifying deployment reviewer`),await l.run(f)),n.skipPostDeployChecks||(V.log.step(`Running post-deploy checks`),await Nt(o,f)),V.outro(`Deployed ${h} to ${n.environment}`)}catch(e){throw!v&&_&&await G(Yo,i),e}}async function Zo(e){let t;try{t=await U(`.env.deploy`,`utf8`)}catch(e){if(Cs(e)&&e.code===`ENOENT`)return;throw e}for(let[n,r]of Object.entries(Rt(t)))e[n]===void 0&&(e[n]=r)}function Qo(e){return{environment:$o(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function $o(e){if(e&&ut.includes(e))return e;throw Error(`Deploy environment must be one of: ${ut.join(`, `)}.`)}async function es(e,t,n){let r=await wt({environment:e}),i=n.dashboard?.enabled===!1?void 0:r.values.DASHBOARD_PASSWORD??await xs(t,e);return Pt(await pt({environment:e}),e,{availableNames:[...Object.keys(r.values),...i?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await vt({environment:e}),dashboardPassword:i,pendingWorkerSecrets:r}}async function ts(e,t,n){let r=e.database?.dialect??`postgres`,i=e.database?.d1Binding;if(i!==void 0&&r!==`sqlite`)throw Error(`database.d1Binding in coreframe.config.ts requires database.dialect "sqlite".`);if(r===`sqlite`&&i!==!1){let e=kt({config:await ns(i!==void 0),d1Binding:i,environment:t.environment,hasConnectionUrl:!!(n.TURSO_DATABASE_URL??n.DATABASE_URL)});if(e)return rs(e,t,n)}let a;switch(r){case`postgres`:a=await b({env:n});break;case`sqlite`:a=await x({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let{appliedMigrations:o,pendingMigrations:s}=await fs(a);return await ds(s,o.size,"Move unsafe statements to held migrations and apply them with `pnpm db migrate-held`."),await ms(t,s)?{kind:`drizzle`}:{kind:`none`}}async function ns(e){try{return await Tt()}catch(t){if(e)throw t;return{}}}async function rs(e,t,n){if(t.skipMigrations)return V.log.info(`Skipping D1 migration checks for binding "${e.binding}" (--skip-migrations). Apply pending migrations separately with \`wrangler d1 migrations apply ${e.binding} --remote --env ${t.environment}\`.`),{kind:`none`};let r=await v(),i=await is(e,t.environment,n),a=r.filter(t=>{let n=os(t,e);return n===void 0||!i.has(n)}),o=a.filter(t=>os(t,e)===void 0);return o.length>0&&V.log.warn(`Deploy migrations are outside the D1 binding's migrations_dir and Wrangler will not apply them:\n${E(o)}`),await ds(a,i.size,`Move unsafe statements to held migrations and apply them to the D1 database for ${t.environment} separately.`),await ms(t,a)?{kind:`d1`,database:e}:{kind:`none`}}async function is(e,t,n){let r=`select name from ${ls(e.migrationsTable)} order by id`,i;try{i=(await I(`pnpm`,ss(t,[`d1`,`execute`,e.binding,`--remote`,`--json`,`--command`,r]),{env:cs(n),stdin:`ignore`})).stdout}catch(n){let r=us(n);if(/no such table|does not exist/iu.test(r))return new Set;throw Error(`Could not read applied D1 migrations for binding "${e.binding}" in ${t}. Check Wrangler credentials and the D1 binding configuration.\n${r}`)}return new Set(as(i,e))}function as(e,t){let n;try{n=JSON.parse(e)}catch{throw Error(`Could not parse Wrangler D1 migration output for binding "${t.binding}".`)}if(!Array.isArray(n))throw Error(`Could not parse Wrangler D1 migration output for binding "${t.binding}".`);let r=[];for(let e of n)if(!(!ws(e)||!Array.isArray(e.results)))for(let t of e.results)ws(t)&&typeof t.name==`string`&&r.push(t.name);return r}function os(e,t){let n=t.migrationsDir.replaceAll(`\\`,`/`).replace(/^\.\/|\/+$/gu,``),r=e.relativePath.split(ye).join(`/`);return r.startsWith(`${n}/`)?r.slice(n.length+1):void 0}function ss(e,t){return[`exec`,`wrangler`,`--config`,Ze,`--env`,e,...t]}function cs(e){let t={...e};return delete t.CLOUDFLARE_ENV,t}function ls(e){return`"${e.replaceAll(`"`,`""`)}"`}function us(e){if(typeof e==`object`&&e){let{output:t,stdout:n,stderr:r}=e,i=[t,n,r].filter(e=>typeof e==`string`&&e.length>0).join(`
|
|
18
|
+
`);if(i)return i}return e instanceof Error?e.message:String(e)}async function ds(e,t,n){let r=await se(e);if(r.length!==0){if(t>0)throw Error(`Pending deploy migrations contain unsafe SQL. ${n}\n${ee(r)}`);V.log.warn(`Pending deploy migrations contain SQL that is unsafe for an existing deployment, but the target database has no applied migrations, so no deployed app version can depend on the current schema. Proceeding with deploy migrations.\n${ee(r)}`)}}async function fs(e){try{return await ps(e)}finally{await e.close?.()}}async function ps(e){let t=await v(),n=await re(e);return{appliedMigrations:n,pendingMigrations:w(t,n)}}async function ms(e,t){if(t.length===0)return V.log.info(`No pending deploy migrations.`),!1;if(V.note(E(t),`Pending deploy migrations`),e.runMigrations)return!0;if(e.skipMigrations)return!1;if(!process.stdout.isTTY)throw Error(`Pending migrations require --run-migrations or --skip-migrations in noninteractive deploys.`);let n=await V.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(V.isCancel(n))throw V.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function hs(){let{stdout:e}=await I(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function gs(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function _s(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function vs(e,t,n=ft){return e.url?ys(e.url,t):t===`staging`&&e.stagingHostname?ys(await n(),t):ys(void 0,t)}function ys(e,t){if(!e)throw Error(`Missing ${t} deploy URL. Set DEPLOY_URL or deploy.environments.${t}.url in coreframe.config.ts.`);let n;try{n=new URL(e)}catch{throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Invalid ${t} deploy URL "${e}". Expected an HTTP(S) URL.`);return n.toString()}async function bs(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await V.confirm({initialValue:!1,message:`Deploy to production?`});if(V.isCancel(t)||!t)throw V.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}async function xs(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Rt(await U(`.env`,`utf8`))}catch(e){throw Cs(e)&&e.code===`ENOENT`?Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`):e}let i=r.DASHBOARD_PASSWORD?.trim();if(!i)throw Error(`Missing ${t} dashboard password. Set DASHBOARD_PASSWORD in ".env".`);return i}async function Ss(e){let t=await We(P(Ae(),`coreframe-deploy-secrets-`)),n=P(t,`secrets.json`);return await G(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>W(t,{force:!0,recursive:!0})}}function Cs(e){return e instanceof Error&&`code`in e}function ws(e){return typeof e==`object`&&!!e}function Ts(e,t,n,r,i){return{...e,CLOUDFLARE_ENV:t,DEPLOY_ENV:t,POSTHOG_RELEASE:n,POSTHOG_RELEASE_NAME:e.POSTHOG_RELEASE_NAME??r,POSTHOG_RELEASE_VERSION:e.POSTHOG_RELEASE_VERSION??i}}function Es(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function Ds(){let e=await ks();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function Os(e){let t=await ks(),n=As();await ai.mkdir(M.dirname(n),{recursive:!0}),await ai.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function ks(){try{let e=await ai.readFile(As(),`utf8`),t=JSON.parse(e);return js(t)?t:{}}catch{return{}}}function As(){return M.join(si.homedir(),`.coreframe`,`preferences.json`)}function js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Ms({env:e=J.env,interactive:t=J.stdin.isTTY===!0,platform:n,target:r}){let i=await zs(n,e).catch(()=>[]),a=r?rc(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Rs(i,n,t);let o=r?rc(await Vs(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Hs(o,n,e,t);let s=await Bs(n,e),c=r?rc(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Rs(s,n,t);let l=n===`ios`?`iOS`:`Android`;throw Error(r?`Could not find a ${l} device matching "${r}".`:`No connected ${l} devices or available ${l} ${n===`ios`?`simulators`:`emulators`} were detected.`)}async function Ns(e){let{device:t,host:n,interactive:r=J.stdin.isTTY===!0}=e;if(!t.physical&&n===void 0)return;if(typeof n==`string`&&n!==`0.0.0.0`&&n!==`::`)return n;let i=ac();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await Is();if(a&&i.includes(a))return a;if(i.length===1)return await Ls(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await V.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(V.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await Ls(o),o}async function Ps({device:e,env:t=J.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await Xs(e.id,a,t)}catch{V.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:Fs(i,await Ns({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function Fs(e,t,n){let r=t??(e===`android`?`10.0.2.2`:`127.0.0.1`);return`http://${r.includes(`:`)&&!r.startsWith(`[`)?`[${r}]`:r}:${n}`}async function Is(){return(await Ds()).mobileDevHost}async function Ls(e){try{await Os({mobileDevHost:e})}catch(e){V.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Rs(e,t,n){if(e.length===1)return e[0];if(!n)throw Error(`Multiple ${t===`ios`?`iOS`:`Android`} devices were detected. Pass a device name explicitly.`);let r=await V.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(V.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function zs(e,t){return e===`android`?Ws(t):Ks(t)}async function Bs(e,t){return e===`android`?Gs(t):qs(t)}async function Vs(e){let{stdout:t}=await I(`flutter`,[`emulators`],{env:e});return t.split(/\r?\n/).flatMap(e=>{let[t,n,,r]=e.split(/\s*•\s*/).map(e=>e.trim());return t&&n&&(r===`android`||r===`ios`)?[{id:t,label:n,name:n,physical:!1,platform:r}]:[]})}async function Hs(e,t,n,r){let i=await Us(t,n).catch(()=>[]),{stdout:a}=await I(`flutter`,[`emulators`,`--launch`,e.id],{env:n});if(/No emulator found|More than one emulator matches/i.test(a))throw Error(a.trim());let o=Date.now()+3e4;do{let a=await Us(t,n).catch(()=>[]),o=rc(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Rs(s,t,r);if(a.length===1)return a[0];await Zt(250)}while(Date.now()<o);let s=t===`ios`?`iOS simulator`:`Android emulator`;throw Error(`Flutter launched "${e.id}", but no ${s} became available.`)}async function Us(e,t){return e===`ios`?qs(t,`booted`):(await Ws(t)).filter(e=>!e.physical)}async function Ws(e){let t=await Ys(e,`platform-tools`,J.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await I(t,[`devices`],{env:e}),r=n.split(/\r?\n/).map(e=>e.match(/^(\S+)\s+device(?:\s|$)/)?.[1]).filter(e=>e!==void 0);return(await Promise.all(r.map(async n=>{let r=await Qs(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await ec(t,e,n,r):await tc(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(oc)}async function Gs(e){let{stdout:t}=await I(await Ys(e,`emulator`,J.platform===`win32`?`emulator.exe`:`emulator`),[`-list-avds`],{env:e});return t.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!/^(INFO|WARNING|ERROR)\s+\|/.test(e)).map(e=>({id:e,label:e,name:e,physical:!1}))}async function Ks(e){let t=await ai.mkdtemp(M.join(si.tmpdir(),`coreframe-ios-devices-`)),n=M.join(t,`devices.json`);try{return await ai.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await ai.readFile(n,`utf8`)).result?.devices??[]).filter(Js).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(oc)}finally{await ai.rm(t,{force:!0,recursive:!0})}}async function qs(e,t=`available`){let{stdout:n}=await I(`xcrun`,[`simctl`,`list`,`--json`,`devices`,t],{env:e}),r=JSON.parse(n);return Object.entries(r.devices??{}).filter(([e])=>e.includes(`iOS-`)).flatMap(([,e])=>e).flatMap(e=>e.name&&e.udid?[{id:e.udid,label:e.name,name:e.name,physical:!1}]:[]).sort(oc)}function Js(e){return e.connectionProperties?.tunnelState!==`unavailable`&&typeof e.hardwareProperties?.platform==`string`&&(e.hardwareProperties.platform.includes(`iOS`)||e.hardwareProperties.platform.includes(`xrOS`))&&typeof e.deviceProperties?.name==`string`&&typeof e.hardwareProperties.productType==`string`&&typeof e.hardwareProperties.udid==`string`}async function Ys(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:Zs(e);for(let e of i){let r=M.join(e,t,n);try{return await ai.access(r),r}catch{}}return n}async function Xs(e,t,n){let r=await Ys(n,`platform-tools`,J.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await I(r,[`-s`,e,`reverse`,`tcp:0`,`tcp:${t}`],{env:n,timeout:3e3}),a=Number(i.trim());if(!Number.isInteger(a)||a<1||a>65535)throw Error(`ADB did not return a valid reverse TCP port.`);let o=`tcp:${a}`,s=!1;return{async close(){s||(s=!0,await I(r,[`-s`,e,`reverse`,`--remove`,o],{env:n,timeout:3e3}).catch(()=>void 0))},serverUrl:`http://127.0.0.1:${a}`,viteHost:`127.0.0.1`}}function Zs(e){return J.platform===`darwin`?[M.join(si.homedir(),`Library`,`Android`,`sdk`)]:J.platform===`win32`&&e.LOCALAPPDATA?[M.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[M.join(si.homedir(),`Android`,`Sdk`)]}async function Qs(e,t,n,r){return(await $s(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function $s(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function ec(e,t,n,r){return $s(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function tc(e,t,n,r){return $s(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>nc(e)||r).catch(()=>r)}function nc(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function rc(e,t){let n=e.map(e=>({device:e,score:Math.max(ic(t,e.name),ic(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function ic(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(r===n)return 1e4;let i=r.indexOf(n);if(i>=0)return 5e3-i;let a=0,o=0;for(let e of n){let t=r.indexOf(e,o);if(t<0)return 0;a+=t===o?2:1,o=t+1}return a}function ac(){return[...new Set(Object.values(si.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function oc(e,t){return e.label.localeCompare(t.label)}var sc=class{#e;#t=new Map;#n=new Set;#r;#i;#a;#o;#s=0;constructor({onEvent:e,verbose:t=!1,write:n}){this.#e=e,this.#r=t,this.#i=n}async handleLine(e){let t;try{t=JSON.parse(e)}catch{return $(e,`debug`)}if(!Array.isArray(t))return $(e,`debug`);let n=[];for(let e of t){if(!fc(e)){n.push(...$(JSON.stringify(e),`debug`));continue}if(e.id!==void 0&&(`result`in e||`error`in e)){this.#c(e);continue}if(typeof e.event!=`string`)continue;let t={event:e.event,params:fc(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...lc(t,this.#r))}return n}async restart({debounce:e=!1,fullRestart:t,reason:n}){let r=await this.#d();if(!r.supportsRestart)throw Error(`The running Flutter application does not support hot restart or reload.`);let i=await this.#u(`app.restart`,{appId:r.id,debounce:e,fullRestart:t,reason:n});if(!fc(i)||typeof i.code!=`number`)throw Error(`Flutter returned an invalid restart response.`);let a={code:i.code,message:typeof i.message==`string`?i.message:``};if(a.code!==0)throw Error(a.message||`Flutter restart failed with code ${a.code}.`);return a}async stop(){let e=await this.#d();if(await this.#u(`app.stop`,{appId:e.id})!==!0)throw Error(`Flutter did not stop the running application.`)}close(e=Error(`The Flutter machine connection closed.`)){if(this.#o)return;let t=mc(e);this.#o=t;for(let e of this.#t.values())e.reject(t);this.#t.clear(),this.#f(t)}#c(e){let t=String(e.id),n=this.#t.get(t);n&&(this.#t.delete(t),`error`in e?n.reject(Error(pc(e.error))):n.resolve(e.result))}#l({event:e,params:t}){let n=typeof t.appId==`string`?t.appId:void 0;if(e===`app.start`&&n){this.#a={id:n,started:!1,supportsRestart:t.supportsRestart===!0};return}if(e===`app.started`&&n&&this.#a?.id===n){let e={...this.#a,started:!0};this.#a=e;for(let t of this.#n)t.resolve(e);this.#n.clear();return}e===`app.stop`&&n&&this.#a?.id===n&&(this.#a=void 0,this.#f(Error(`The Flutter application stopped before it was ready.`)))}async#u(e,t){if(this.#o)throw this.#o;let n=String(++this.#s),r,i,a=new Promise((e,t)=>{r=t,i=e});this.#t.set(n,{reject:r,resolve:i});try{await this.#i(`${JSON.stringify([{id:n,method:e,params:t}])}\n`)}catch(e){this.#t.delete(n),r(mc(e))}return a}#d(){return this.#o?Promise.reject(this.#o):this.#a?.started?Promise.resolve(this.#a):new Promise((e,t)=>{this.#n.add({reject:t,resolve:e})})}#f(e){for(let t of this.#n)t.reject(e);this.#n.clear()}};async function*cc(e,t){try{for await(let n of e)yield*await t.handleLine(n)}catch(e){throw t.close(e),e}finally{t.close()}}function lc({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(dc(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=uc(t.level);return!n&&e===`debug`?[]:[...$(dc(t.message),e),...n?$(dc(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(dc(t.message),uc(t.level)):e===`app.warning`?$(dc(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(dc(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(pc(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function uc(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function dc(e){return typeof e==`string`&&e.length>0?e:void 0}function fc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function pc(e){if(typeof e==`string`)return e;if(fc(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function mc(e){return e instanceof Error?e:Error(pc(e))}async function hc(e,t){if(!e)return()=>void 0;Se(M.dirname(e),{recursive:!0}),B(e,``,{flag:`a`});let n;try{n=z(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=De(e,{persistent:!1},()=>{if(i)return;let a=++r;U(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function gc(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const _c=J.platform===`win32`?`portless.cmd`:`portless`,vc=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),yc=/^Proxy is already running on port (\d+)\.$/,bc=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function xc(e){let t=e.split(/(\r\n|\n)/),n=[];for(let e=0;e<t.length;){let r=t[e],i=t[e+2],a=r?.replace(vc,``).trim().match(yc);if(a?.[1]!==void 0&&i!==void 0&&bc.test(i.replace(vc,``).trim())){n.push(`Portless proxy is running on port ${a[1]}.`),t[e+1]!==void 0&&n.push(t[e+1]),e+=t[e+3]===void 0?3:4;continue}n.push(t[e]??``),e+=1}return n.join(``)}function Sc(e){let t=xc(e);t&&J.stdout.write(t.endsWith(`
|
|
19
|
+
`)?t:`${t}\n`)}async function Cc({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await Qt()).isAgent?!1:Gt(e)}async function wc({cwd:e,env:t,lan:n=!1}){let r=M.join(`node_modules`,`.bin`,_c),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(M.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Sc(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Sc(e.stdout),e}}function Tc({host:e,lan:t=!1,port:n}){return[...t?[`--lan`]:[],`run`,...n===void 0?[]:[`--app-port`,String(n)],`react-router`,`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e]]}const Ec=M.join(`.coreframe`,`dev`,`session.json`);async function Dc({appOrigin:e,cwd:t,device:n,flutterMcp:r,flutterMode:i,id:a,localOrigin:o,now:s=new Date,pid:c=process.pid,platform:l}){let u=M.resolve(t,Ec),d=M.dirname(u),f={version:2,id:a,pid:c,projectRoot:M.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:M.resolve(t,`.leylines`,`logs.sqlite`),scopes:{browser:`browser`,...i===void 0?void 0:{flutter:`dev.flutter`},vite:`dev.vite`}},...i===void 0?void 0:{flutter:{mode:i,mcp:r,state:`starting`,...n===void 0?void 0:{device:n}}}},p=Promise.resolve(),m=()=>{let e=`${JSON.stringify(f,void 0,2)}\n`;return p=p.then(async()=>{await H(d,{recursive:!0});let t=M.join(d,`.session-${a}.json`);await G(t,e,{mode:384}),await Ve(t,384),await Ke(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=Ac(t.appId),i;if(e===`daemon.connected`){let e=jc(t.pid),r=Ac(t.version);i={...Oc(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...Oc(n),appId:r,state:`starting`,supportsRestart:t.supportsRestart===!0};else if(e===`app.started`&&r===n.appId)i={...n,state:`running`};else if(e===`app.debugPort`&&r===n.appId){let e=Ac(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=Ac(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=Ac(t.uri);e&&(i={...n,dtdUri:e})}else e===`app.stop`&&r===n.appId&&(i=kc(n));i&&(f={...f,flutter:i},await m())},async recordFlutterExit(){!f.flutter||f.flutter.state===`stopped`||(f={...f,flutter:kc(f.flutter)},await m())},async close(){await p;try{JSON.parse(await U(u,`utf8`)).id===a&&await W(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function Oc(e){return{mode:e.mode,mcp:e.mcp,...e.device===void 0?void 0:{device:e.device},...e.daemonPid===void 0?void 0:{daemonPid:e.daemonPid},...e.protocolVersion===void 0?void 0:{protocolVersion:e.protocolVersion}}}function kc(e){return{...Oc(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function Ac(e){return typeof e==`string`?e:void 0}function jc(e){return typeof e==`number`?e:void 0}const Mc=`extension:dev`;function Nc(e){if(!R(P(e,`src-webext/wxt.config.ts`)))throw Error("No WXT configuration found at src-webext/wxt.config.ts. Apply the wxt recipe or add that convention before running `coreframe dev webext`.");let t=P(e,`package.json`),n;try{n=JSON.parse(z(t,`utf8`))}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}if(!n||typeof n!=`object`||!(`scripts`in n)||!n.scripts||typeof n.scripts!=`object`||!(`extension:dev`in n.scripts)||typeof n.scripts[`extension:dev`]!=`string`)throw Error(`package.json must define scripts.${Mc} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function Pc({host:e,port:t}){let n=[...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)]];return[`run`,Mc,...n.length>0?[`--`,...n]:[]]}const Fc=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],Ic=[`managed-dev-overlay`],Lc=M.resolve(`node_modules`,`.bin`),Rc=J.platform===`win32`?`pnpm.cmd`:`pnpm`,zc=J.platform===`win32`?`portless.cmd`:`portless`,Bc=J.platform===`win32`?`react-router.cmd`:`react-router`,Vc=`Lost connection to device.`;async function Hc({cwd:e=J.cwd(),debug:t,device:n,env:r=J.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=J.stdin.isTTY===!0,lan:u=!1,managed:d=!1,noCodesign:f=!1,noManaged:p=!1,noDevJobs:m=!1,platform:h=`web`,verbose:g=!1,webPort:_}={}){let v=Vt({env:r}),y=r.PATH??r.Path??``,b=tl(h)?h:void 0,x=an(i||a),S=el(_??r.COREFRAME_WEB_PORT),C,w,T,E,ee,te,ne,re,ae,oe,se,ce,le,D=!1,de,O=r;if(d&&p)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&d)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&b===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(a&&b===void 0)throw Error(`The --flutter-mcp option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(f&&h!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(o===`full`&&b===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(h===`webext`){if(d||p||t!==void 0||g)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);Nc(e)}if(c&&h!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&h!==`ios`&&h!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let fe=await v.measure(`routing`,()=>Cc({cwd:e,env:r,platform:h}));fe&&await v.measure(`portless`,()=>wc({cwd:e,env:r,lan:u}));let k=b===void 0?h===`web`?S??await oi.getAvailablePort():h===`webext`?S:void 0:S??await oi.getAvailablePort(),A,me=new Promise(e=>{A=e}),j=()=>{D||(D=!0,A(),w?.kill(`SIGTERM`),te?.kill(`SIGTERM`),ne?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),re?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ae?.close().catch(()=>void 0),C?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ge().catch(()=>void 0))},ge=()=>E?(ee??=E[Symbol.asyncDispose](),ee):Promise.resolve(),N=e=>{de??=e,j()},_e=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>N(e);return J.on(e,t),{handler:t,signal:e}}),P=async e=>{let t=nt(e);w=t;try{await t.expectSuccess()}catch(e){if(!D)throw e}finally{w===t&&(w=void 0)}};try{se=b?Xt({path:M.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await Ms({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&on({device:_,mode:x,platform:i});let S=b?se?.logger({scope:`dev.flutter`,properties:{platform:b,..._?{deviceId:_.id}:void 0}}):void 0;oe=i&&_&&k!==void 0?await Ps({device:_,env:r,host:s,interactive:l,platform:i,port:k}):void 0;let w=oe?.viteHost??(b?i?!0:`127.0.0.1`:s),ee=k===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${k}`,de=b===void 0?ee:oe?.serverUrl??Fs(b,void 0,k),A={},ge=!1,N;[A,ge]=await Promise.all([v.measure(`config`,()=>K({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await Wt(e))]),await v.measure(`i18n`,()=>Or({cwd:e,projectConfig:A})),N=h!==`webext`&&A.dashboard?.enabled!==!1&&pi(e)?await oi.getAvailablePort():void 0;let _e=await v.measure(`https`,async()=>c&&!fe?Kt({cwd:e}):void 0),ve=gc(r,h);O={...ve,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[qt]:q()}:void 0,...b?{COREFRAME_PLATFORM:b,[Yt]:M.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,..._e?{[Ht]:_e.cert,[Ut]:_e.key}:void 0,...N?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${N}`}:void 0},ee!==void 0&&de!==void 0&&(ce=await Dc({appOrigin:de,cwd:e,device:_,flutterMcp:a,flutterMode:b===void 0?void 0:x,id:q(),localOrigin:ee,platform:h}));let F=async()=>{if(!N)return;let t=mi({cwd:e,env:O,port:N});ae=t;try{await t.listen(),await t.wait()}finally{await t.close(),ae===t&&(ae=void 0)}},ye=async()=>{let t=tt({label:`web`}),n=tt({color:`red`,label:`web`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),ne=I(fe?zc:Bc,fe?Tc({host:w,lan:u,port:k}):$c({host:w,port:k,strictPort:h===`web`||b!==void 0}),{cwd:e,env:{...O,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[O.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Lc+M.delimiter+y},stdin:`inherit`});let r=Promise.allSettled([Yc(ne.stdout,t),Yc(ne.stderr,n)]);try{await ne;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([et(t),et(n)]),ne=void 0}},L=async()=>{let t=tt({label:`webext`}),n=tt({color:`red`,label:`webext`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),re=I(Rc,Pc({host:s,port:k}),{cwd:e,env:O,stdin:`inherit`});let r=Promise.allSettled([Yc(re.stdout,t),Yc(re.stderr,n)]);try{await re;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!D)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([et(t),et(n)]),re=void 0}},be=async t=>{let n,r,i=!1,s,c=hc(O[Yt],()=>{if(D||!n||!r||s||x!==`debug`&&i)return;let e=n,t=r;s=(async()=>{if(x===`debug`){await t.restart({debounce:!0,fullRestart:!0,reason:`manual`});return}i=!0;try{await t.stop()}catch(t){let n=t instanceof Error?t.message:String(t);S?.write(`warn`,`Flutter stop failed; terminating it: ${n}`,{properties:{stream:`control`}}),J.stderr.write(`Flutter stop failed; terminating it: ${n}\n`),await e.nodeChildProcess.then(e=>e.kill(`SIGTERM`))}})().catch(e=>{let t=e instanceof Error?e.message:String(e);S?.write(`error`,`Flutter restart failed: ${t}`,{properties:{stream:`control`}}),J.stderr.write(`Flutter restart failed: ${t}\n`)}).finally(()=>{s=void 0})});try{for(;!D;){i=!1;let s=!1,c=h===`android`&&o===`filtered`&&!g?await he():void 0,u=I(`flutter`,sn({device:_??{id:h},flutterDriver:a,mode:x,serverUrl:de,verbose:g}),{cwd:M.join(e,`src-flutter`),env:rn(ve,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new sc({onEvent:async e=>{Gc(e.params.message)&&(s=!0),await ce?.recordFlutterEvent(e)},verbose:g,write:async e=>{let t=await u.nodeChildProcess;if(!t.stdin)throw Error(`Flutter machine input is unavailable.`);t.stdin.write(e)===!1&&await zt(t.stdin,`drain`)}}),p=e=>Wc(cc(e,d),()=>s=!0);C=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(Jc(p(u),S,`output`)):Promise.all([qc(p(u.stdout),J.stdout,S,`stdout`),Uc(u.stderr,J.stderr,S,`stderr`)]);await Promise.all([u,e])}catch{e=!0}if(i&&!D)continue;if(D)return;let n=l?await V.confirm({initialValue:!0,message:s?`${Vc} Restart Flutter?`:e?`Flutter failed. Retry?`:`Flutter exited unexpectedly. Restart Flutter?`}):!1;if(V.isCancel(n)||!n){if(!e&&!s){V.log.warn(`Flutter exited unexpectedly.`);return}V.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??me);return}}finally{C===u&&(C=void 0),n===u&&(n=void 0),r===d&&(r=void 0),d.close(),ce?.recordFlutterExit().catch(e=>{let t=e instanceof Error?e.message:String(e);S?.write(`error`,`Failed to record Flutter exit: ${t}`,{properties:{stream:`control`}})})}}}finally{(await c)()}},R=async()=>{if(h===`web`){await ye();return}let t=ye().then(()=>{if(!D)throw Error(`The Vite development server stopped while Flutter was still running.`)});await pe({cwd:e});try{await Promise.race([t,be(t)])}finally{j(),await Promise.allSettled([t,C]),C=void 0}},xe=async()=>{let t=nt({name:`panda`,command:Rc,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:O});te=t;try{if(await t.expectSuccess(),!D)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!D)throw e}finally{te===t&&(te=void 0)}},Se=async()=>{if(h===`webext`){await L();return}let e=xe(),t=R(),n=N?F():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),D&&await t}finally{j(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(ge&&(O={...O,[Jt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(le=await v.measure(`supervisor`,()=>Bt({cwd:e,env:r})))),D)return;if(h===`webext`){v.report(),await Se();return}if(A.database?.dialect===`sqlite`){if(await v.measure(`database`,async()=>{let t=await ue({config:A,cwd:e,env:r,tursoOutput:J.stdout,useSupervisorLease:!0});E=t,O={...O,...t.env}}),await v.measure(`schema`,()=>P({name:`db`,command:Rc,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),D)return;ie({cwd:e,env:O,dialect:`sqlite`})}if(Qc(A)){let t=tt({label:`postgres`});t.pipe(J.stdout,{end:!1});try{let n=await v.measure(`database`,()=>Zc({config:A,cwd:e,env:O,failIfRunning:!0,interactive:l,isStopping:()=>D,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;T=n,O={...O,...n.env};try{D||await v.measure(`schema`,()=>P({name:`db`,command:Rc,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),D||(ie({cwd:e,env:O,dialect:`postgres`}),v.report(),await Se())}finally{await n[Symbol.asyncDispose](),T===n&&(T=void 0)}}finally{t.end()}return}v.report(),await Se()}finally{j(),await oe?.close(),oe=void 0;let e;try{await T?.[Symbol.asyncDispose]()}catch(t){e=t}finally{try{await ge()}finally{try{await ce?.close()}finally{le?.close(),se?.close();for(let{handler:e,signal:t}of _e)J.off(t,e)}}de&&(J.exitCode??=de===`SIGINT`?130:143)}Xc(e)}}async function Uc(e,t,n,r){for await(let i of Kc(e,n,r))t.write(`${i}\n`)||await zt(t,`drain`)}async function*Wc(e,t){for await(let n of e)Gc(n.message)&&t(),yield n}function Gc(e){return typeof e==`string`&&e.trim()===Vc}async function*Kc(e,t,n){for await(let r of e){let e=fe(r);e.message&&t?.write(e.level,e.message,{properties:{stream:n}}),yield r}}async function qc(e,t,n,r){for await(let i of Jc(e,n,r))t.write(`${i}\n`)||await zt(t,`drain`)}async function*Jc(e,t,n){for await(let r of e)r.message&&t?.write(r.level,r.message,{properties:{stream:n}}),yield r.message}async function Yc(e,t){for await(let n of e)t.write(`${n}\n`)||await zt(t,`drain`)}function Xc(e){if(e)throw e}async function Zc({interactive:e,isStopping:t,...n}){try{return await D(n)}catch(r){if(!(r instanceof h)||!e)throw r;let i=await V.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(V.isCancel(i)||!i){V.cancel(`Keeping the existing PostgreSQL process.`);return}return await de(r),t()?void 0:D(n)}}function Qc(e){return(e.database?.dialect??`postgres`)===`postgres`}function $c({host:e,port:t,strictPort:n=!1}){return[`dev`,...e===void 0?[]:[`--host`,e===!0?`0.0.0.0`:e],...t===void 0?[]:[`--port`,String(t)],...n?[`--strictPort`]:[]]}function el(e){if(e===void 0)return;let t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw Error(`COREFRAME_WEB_PORT must be a valid TCP port.`);return t}function tl(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function nl(e={}){let t=e.cwd??J.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Be(M.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Ye(n,t);if(!e.default||typeof e.default!=`object`)throw Error(`scripts/preview.ts must default-export preview hooks.`);for(let t of[`beforeBuild`,`afterBuild`])if(e.default[t]!==void 0&&typeof e.default[t]!=`function`)throw Error(`scripts/preview.ts ${t} must be a function.`);r=e.default}return $t({...e,cwd:t},r)}const rl=`worker-configuration.d.ts`;async function il({check:e=!1,cwd:t=process.cwd()}={}){let n=await K({cwd:t}),r=await gt({coreframeConfig:n,cwd:t}),i=F(t,rl),a=F(t,`.coreframe-worker-types-${q()}.d.ts`);try{try{await I(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw al(e),e}let o=ol(await U(a,`utf8`)),s=Qe(r.config),c=Xe(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${sl(c)}\n`;if(e){if(await U(i,`utf8`).catch(()=>``)!==l)throw Error(`${rl} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await U(i,`utf8`).catch(()=>``);return u!==l&&await G(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await W(a,{force:!0})}}function al(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
20
|
+
`)?t:`${t}\n`)}function ol(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
21
|
+
`)}function sl(e){return[`// Coreframe application string inventory declaration-merges with Wrangler's generated Env.`,`interface Env {`,...e.map(e=>` /** ${e.description.replaceAll(`*/`,`*\\/`)} */\n ${JSON.stringify(e.name)}?: string`),`}`].join(`
|
|
22
|
+
`)}const cl=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),ll=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],ul=[`dashboard`,`node_modules/@coreframe/dashboard/dist/package/app`,`node_modules/@coreframe/dashboard/package.json`,`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`],dl=[`coreframe.config.ts`,`node_modules/@coreframe/config/dist`,`node_modules/@coreframe/config/package.json`,`node_modules/@coreframe/deploy/dist`,`node_modules/@coreframe/deploy/package.json`,`node_modules/wrangler/package.json`,`package.json`,`pnpm-lock.yaml`,`src/api`,`wrangler.jsonc`],fl=`.coreframe/typegen.json`,pl=[`web`,`dashboard`,`worker`];async function ml({checkWorker:e=!1,cwd:t=J.cwd(),runners:n={}}={}){let r=await vl(t)??{generators:{},schemaVersion:1},i=[];return i.push(await gl({cwd:t,inputPaths:ll,name:`web`,outputPath:`.react-router`,run:()=>(n.web??_l)(t),state:r})),i.push(await gl({cwd:t,inputPaths:ul,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??ei)(t),state:r})),i.push(await gl({cwd:t,inputPaths:dl,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??il)({check:e,cwd:t}),state:r})),i}function hl(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function gl({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await bl(e,t),s=await xl(e,r),c=a.generators[n];if(s&&c?.inputFingerprint===o&&c.outputFingerprint===s)return{changed:!1,name:n,ran:!1};await i();let l=await xl(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await yl(e,a),{changed:s!==l,name:n,ran:!0}}async function _l(e){let t=J.platform===`win32`?`react-router.cmd`:`react-router`,n=J.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:M.resolve(e,`node_modules/.bin`)+M.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function vl(e){try{let t=JSON.parse(await U(M.resolve(e,fl),`utf8`));if(!Tl(t)||t.schemaVersion!==1)return;let n={};if(!Tl(t.generators))return;for(let e of pl){let r=t.generators[e];Tl(r)&&typeof r.inputFingerprint==`string`&&typeof r.outputFingerprint==`string`&&(n[e]={inputFingerprint:r.inputFingerprint,outputFingerprint:r.outputFingerprint})}return{generators:n,schemaVersion:1}}catch{return}}async function yl(e,t){let n=M.resolve(e,fl);await H(M.dirname(n),{recursive:!0}),await G(n,`${JSON.stringify(t)}\n`,{mode:384})}async function bl(e,t){let n=$e(`sha256`);for(let r of[...t].sort()){let t=M.resolve(e,r),i=await Cl(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Sl(t)){let i=M.join(t,r),a=M.relative(e,i).split(M.sep).join(`/`);n.update(`${a}\0`),n.update(await U(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await U(t)))}return n.digest(`hex`)}async function xl(e,t){if(await Cl(M.resolve(e,t)))return bl(e,[t])}async function Sl(e){let t=[];async function n(e,r){let i=await Ge(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(cl.has(a.name))continue;await n(M.join(e,a.name),M.join(r,a.name))}else a.isFile()&&t.push(M.join(r,a.name))}return await n(e,``),t.sort()}async function Cl(e){try{return await qe(e)}catch(e){if(wl(e))return;throw e}}function wl(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const El=M.resolve(`node_modules`,`.bin`);J.env.PATH=El+M.delimiter+J.env.PATH;const Dl=J.platform===`win32`?`tsc.cmd`:`tsc`,Ol=[{name:`scripts`,path:`scripts/tsconfig.json`},{name:`shared`,path:`src/shared/tsconfig.json`},{name:`api`,path:`src/api/tsconfig.json`},{name:`worker`,path:`src/api/worker/tsconfig.json`},{name:`web`,path:`src/web/tsconfig.json`},{name:`dashboard`,path:`dashboard/tsconfig.json`}];async function kl(){await ml({checkWorker:!0});let e=[];for(let t of Ol)try{await Be(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>nt({name:e.name,command:Dl,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(J.exitCode=n[0].exitCode)}const Al=r(s(Ic),{displayName:`feature`,from:async e=>e}),jl=r(s(nn),{displayName:`filtered|full`,from:async e=>e}),Ml=[`Cookies and sessions are origin-scoped.`,`Exact-host passkeys may require re-registration unless a stable eligible parent RP ID was configured in advance.`,`External OAuth callbacks such as Google may need updating.`,`Database data and private backend resources are unchanged.`],Nl=n({name:`deploy`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:i({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:i({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:i({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:i({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Xo([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Pl=m({name:`staging`,cmds:{reassign:n({name:`reassign`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await Et();if(e){console.log(JSON.stringify({...t,notices:Ml}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Ml.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ft();console.log(e?JSON.stringify({url:t}):t)}})}}),Fl=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:i({long:`yes`,short:`y`,description:`Confirm immediate signing-secret replacement and invalidation of outstanding access JWTs.`,defaultValue:()=>!1})},handler:async({environment:e,yes:t})=>{if(!t)throw Error(`Access-token signing-secret rotation requires --yes because it immediately invalidates outstanding access JWTs.`);await jt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:n({name:`status`,args:{environment:u({type:l(s(ut)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await pt({environment:e});console.log(t?JSON.stringify(n):Vl(n))}}),set:n({name:`set`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:u({type:l(p),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:i({long:`bulk`,description:`Queue known secrets from pasted or piped dotenv-formatted contents.`,defaultValue:()=>!1})},handler:async({environment:e,name:t,bulk:n})=>{if(n&&t)throw Error(`Use either a secret name or --bulk, not both.`);if(t){await bt({environment:e,name:t,value:await Hl(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await St(),i=n?await Wl(r):await Ul(r,e);await xt({environment:e,values:i});let a=Object.keys(i).sort();console.log(a.length>0?`Queued ${a.join(`, `)} for ${e}. Run coreframe deploy ${e} to apply.`:`No ${e} Worker secret updates were queued.`)}}),discard:n({name:`discard`,args:{environment:u({type:s(ut),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:u({type:p,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await dt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),Il=n({name:`typecheck`,args:{},handler:kl}),Ll=m({name:`worker`,cmds:{typegen:n({name:`typegen`,args:{check:i({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await il({check:e});console.log(e?`${Kl(t.path)} is current.`:`${Kl(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Rl=n({name:`dev`,args:{debug:c({long:`debug`,type:l(Al),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:i({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:i({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:c({long:`flutter-output`,type:jl,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:i({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:c({long:`host`,type:l(p),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:i({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:i({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:i({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:i({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:i({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:i({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:u({type:l(s(Fc)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:u({type:l(p),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:c({long:`port`,type:l(o),description:`Port for the web development server.`}),verbose:i({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,flutterDebug:n,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,simulator:m,verbose:h})=>{let g=zl({device:t,flutterDebug:n,platform:f,simulator:m});return Hc({debug:e,device:g.device,flutterDebug:g.flutterDebug,flutterMcp:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f??`web`,verbose:h,webPort:p})}});function zl({device:e,flutterDebug:t,platform:n,simulator:r}){if(!r)return{device:e,flutterDebug:t};if(n!==`ios`)throw Error(`The --simulator flag is only supported for the iOS development target.`);if(e!==void 0)throw Error(`The --simulator flag cannot be combined with an explicit device.`);return{device:`apple_ios_simulator`,flutterDebug:!0}}const Bl=n({name:`preview`,args:{host:c({long:`host`,type:l(p),description:`Host address for the preview server.`}),port:c({long:`port`,type:l(o),description:`Port for the preview server.`})},handler:({host:e,port:t})=>nl({host:e,port:t})});function Vl(e){if(e.entries.length===0)return`No Worker environment values are declared in coreframe.config.ts.`;let t=e.entries.map(e=>[e.name,e.kind,e.local===`override`?`override`:`built-in default`,e.deployed.staging.replaceAll(`_`,` `),e.deployed.production.replaceAll(`_`,` `)]),n=[`Name`,`Kind`,`Local`,`Staging`,`Production`],r=n.map((e,n)=>Math.max(e.length,...t.map(e=>e[n].length))),i=(e,t=` `)=>e.map((e,n)=>e.padEnd(r[n],t)).join(` | `).trimEnd();return[i(n),i(r.map(e=>``.padEnd(e,`-`)),`-`),...t.map(e=>i(e))].join(`
|
|
23
|
+
`)}async function Hl(e){if(!J.stdin.isTTY){let e=``;for await(let t of J.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await V.password({message:`Enter the new value for ${e}`});if(V.isCancel(t))throw V.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function Ul(e,t){if(!J.stdin.isTTY)throw Error(`Interactive secret setup requires a terminal. Provide a secret name or use --bulk with piped dotenv contents.`);if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let n={};for(let r of e){let e=r.requiredIn.includes(t),i=await V.password({message:`${r.name}: ${r.description}${e?` (required)`:` (optional; leave blank to skip)`}`,validate:n=>e&&!n?.trim()?`${r.name} is required in ${t}.`:void 0});if(V.isCancel(i))throw V.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function Wl(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=J.stdin.isTTY?await V.multiline({message:`Paste dotenv-formatted Worker secrets. Press Enter twice to submit.`,validate:e=>e?.trim()?void 0:`Paste at least one dotenv entry.`}):await Gl();if(V.isCancel(t))throw V.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=_t(t,e);return n.length>0&&V.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function Gl(){let e=``;for await(let t of J.stdin)e+=t.toString();return e}function Kl(e){return e.split(/[\\/]/).at(-1)??e}const ql=n({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await ml();for(let t of e)console.log(hl(t))}});function Jl(e,{formatMessage:t,temporaryDirectory:n=Ae(),write:r=e=>console.error(e)}={}){let i=eu(e),a=ru(Xl(e,t),i);try{let t=P(Ce(P(n,`coreframe-error-`)),`error.log`);return B(t,`${ru(Zl(e),i)}\n`,{mode:384}),r(`Error: ${a}\nFull diagnostic: ${t}`),t}catch{r(`Error: ${a}\nThe full diagnostic could not be written to the temporary directory.`);return}}function Yl(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,Jl(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function Xl(e,t){try{return t?.(e)||(e instanceof Error?e.message:String(e)).split(/\r?\n/,1)[0]||`Unknown error`}catch{return`Unknown error`}}function Zl(e){try{let t=Ql(e);if(!(e instanceof Error)||!$l(t))return Lt(t,{customInspect:!1,depth:10});let n=typeof t.stack==`string`?t.stack:`${e.name}: ${e.message}`;return delete t.name,delete t.message,delete t.stack,`${n}${Reflect.ownKeys(t).length?`\n${Lt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function Ql(e,t=new WeakMap){if((typeof e!=`object`||!e)&&typeof e!=`function`)return e;let n=e,r=t.get(n);if(r)return r;if(typeof e==`function`)return`[Function${e.name?`: ${e.name}`:``}]`;let i=Array.isArray(e)?[]:{};t.set(n,i),e instanceof Error&&(i.name=e.name,i.message=e.message,i.stack=e.stack??`${e.name}: ${e.message}`);for(let r of Reflect.ownKeys(n)){if(typeof r!=`string`||r.toLowerCase()===`env`||Array.isArray(e)&&r===`length`||e instanceof Error&&(r===`name`||r===`message`||r===`stack`))continue;let a=Object.getOwnPropertyDescriptor(n,r);!a||!(`value`in a)||Object.defineProperty(i,r,{configurable:!0,enumerable:!0,value:Ql(a.value,t),writable:!0})}return i}function $l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eu(e,t=new WeakSet){let n=new Set;function r(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let i=e;if(!t.has(i)){t.add(i);for(let e of Reflect.ownKeys(i)){if(typeof e!=`string`)continue;let t=Object.getOwnPropertyDescriptor(i,e);!t||!(`value`in t)||(e.toLowerCase()===`env`?tu(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function tu(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&nu(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function nu(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function ru(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const iu=m({name:`coreframe`,cmds:{build:bn,conflicts:Un,dashboard:_i,assets:Yr,flutter:Xr,i18n:Zr,jobs:Fi,deploy:Nl,staging:Pl,secrets:Fl,typegen:ql,typecheck:Il,worker:Ll,dev:Rl,preview:Bl,upgrade:Ko,recipes:qo,db:Jo}});import.meta.main&&Yl(iu,{formatMessage:process.argv[2]===`db`?T:void 0});export{iu as coreframeCli};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/scripts",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.44",
|
|
4
4
|
"description": "Coreframe project workflow CLI and automation scripts",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
"nano-spawn": "^2.1.0",
|
|
30
30
|
"procband": "^0.3.9",
|
|
31
31
|
"yaml": "^2.9.0",
|
|
32
|
-
"@coreframe/assets": "^0.1.
|
|
33
|
-
"@coreframe/
|
|
34
|
-
"@coreframe/dev": "^0.1.
|
|
32
|
+
"@coreframe/assets": "^0.1.20",
|
|
33
|
+
"@coreframe/db": "^0.1.24",
|
|
34
|
+
"@coreframe/dev": "^0.1.29",
|
|
35
35
|
"@coreframe/dev-contracts": "^0.1.10",
|
|
36
|
-
"@coreframe/flutter-tools": "^0.1.
|
|
36
|
+
"@coreframe/flutter-tools": "^0.1.28",
|
|
37
37
|
"@coreframe/jobs": "^0.1.1",
|
|
38
38
|
"@coreframe/object-storage": "^0.1.4",
|
|
39
|
-
"@coreframe/preview": "^0.1.
|
|
40
|
-
"@coreframe/
|
|
41
|
-
"@coreframe/
|
|
39
|
+
"@coreframe/preview": "^0.1.24",
|
|
40
|
+
"@coreframe/deploy": "^0.1.18",
|
|
41
|
+
"@coreframe/config": "^0.1.17"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"@types/node": "^26.1.0",
|