@coreframe/scripts 0.2.45 → 0.2.47
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/bin/coreframe.js +1 -0
- package/dist/coreframe.js +20 -20
- package/package.json +7 -7
package/bin/coreframe.js
CHANGED
package/dist/coreframe.js
CHANGED
|
@@ -1,23 +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 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,
|
|
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,assetCatalogEntries as Me,backupAssets as Ne,buildAssets as Pe,checkAssets as Fe,formatAssetProblems as Ie,printAssetResult as Le,publishAssets as Re,readAssetCatalog as ze}from"@coreframe/assets";import{assertAssetCredentialProfile as Be,configureAssetCredentials as Ve,createB2PrivateObjectStore as He}from"@coreframe/object-storage";import{access as Ue,chmod as We,copyFile as Ge,cp as Ke,mkdir as H,mkdtemp as qe,readFile as U,readdir as Je,rename as Ye,rm as W,stat as Xe,writeFile as G}from"node:fs/promises";import{importProjectDependency as Ze,importProjectModule as Qe,normalizeWorkerEnvironment as $e,primaryWorkerConfigPath as et,readProjectConfig as K,wranglerEnvironmentNames as tt}from"@coreframe/config";import{createHash as nt,randomUUID as q}from"node:crypto";import J from"node:process";import{finished as rt}from"node:stream/promises";import{createPrefixStream as it,supervise as at}from"procband";import{createConnection as ot,createServer as st}from"node:net";import{inspectDevelopmentJobStates as ct}from"@coreframe/jobs";import{parse as lt,stringify as ut}from"yaml";import{accessTokenSigningSecretName as dt,clearAppliedPendingWorkerSecrets as ft,deployEnvironments as pt,discardPendingWorkerSecret as mt,discoverStagingUrl as ht,inspectWorkerEnvironment as gt,materializeBuiltClientDeployConfig as _t,materializeBuiltWorkerDeployConfig as vt,materializePrimaryWorkerTypeConfig as yt,parseDeclaredWorkerSecretEnv as bt,prepareAccessTokenSigningSecret as xt,prepareReviewerDeploy as St,queueWorkerSecret as Ct,queueWorkerSecrets as wt,readDeclaredWorkerSecrets as Tt,readPackageJson as Et,readPendingWorkerSecretSnapshot as Dt,readPrimaryWorkerConfig as Ot,reassignStagingHostname as kt,releaseName as At,resolveDeployConfig as jt,resolveDeployD1Database as Mt,resolveReleaseVersion as Nt,rotateAccessTokenSigningSecret as Pt,runAfterWorkerDeploy as Ft,runPostDeployChecks as It,validateWorkerEnvironmentForDeploy as Lt,verifyAccessTokenSigningSecret as Rt,writePackageVersion as zt}from"@coreframe/deploy";import{inspect as Bt,parseEnv as Vt}from"node:util";import{once as Ht}from"node:events";import{connectDevSupervisor as Ut,createDevStartupTiming as Wt,devHttpsCertEnv as Gt,devHttpsKeyEnv as Kt,isManagedDevCheckout as qt,isPrimaryCheckout as Jt,prepareDevHttps as Yt}from"@coreframe/dev";import{devJobsEnv as Xt}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Zt,managedDevFlutterRestartFileEnv as Qt}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as $t}from"leylines";import{setTimeout as en}from"node:timers/promises";import{determineAgent as tn}from"@vercel/detect-agent";import{runPreview as nn}from"@coreframe/preview";const rn=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,an=`COREFRAME_FLUTTER_DEVELOPMENT`,on=[`filtered`,`full`];function sn(e,{noCodesign:t=!1}={}){return{...e,[rn]:`.dev`,[an]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function cn(e=!1){return e?`debug`:`profile`}function ln({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 un({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 dn=[`web`,...k];function fn(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(yn(e,{profile:r,simulator:i}),e===`web`)return[xn(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=j(t);return[{kind:`prepare`,platform:e},xn(`flutter`,pn(e,a,{profile:r,simulator:i}),F(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function pn(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){yn(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 mn(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 hn(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 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
|
|
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 gn(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 _n(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 vn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=me,runCommand:s=bn}={}){yn(r,{profile:i,simulator:a});let c={...n};delete c[rn],delete c[an],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 fn(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(mn(t,{profile:i})):r===`ios`?console.log(hn(t,{profile:i,simulator:a})):r===`windows`?console.log(gn(t)):r===`linux`&&console.log(_n(t))}function yn(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 bn(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function xn(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const Sn=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return j(e)}}),Cn=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(dn)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:c({long:`api-origin`,type:l(Sn),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})=>vn({apiOrigin:e,platform:t,profile:n,simulator:r})});function wn(e){return e.apiKey??process.env.TYPESAFE_API_KEY??process.env.JEV_API_KEY}function Tn(e){return e.baseUrl??process.env.TYPESAFE_API_BASE??process.env.JEV_API_BASE??`https://jevtypesafeai.com/api/v1/decide`}function En(){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 Dn(e,t={}){let n=wn(t);if(!n)return{called:!1,approved:!1,reason:`jev_unavailable: no API key`};let r={state:e,questions:En()},i;try{let e=await(t.fetchImpl??fetch)(Tn(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 On(e,t={}){await Promise.all(e.map(async e=>{if(e.tier!==`judgment`)return;let n=await Dn({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 kn=`safe`,An=`judgment`,Y=`unsafe`,jn=new Set([`both_added`,`rename_rename`,`rename_modify`]),Mn=new Set([`both_modified`,`modify_delete`,...jn]);function Nn(e,t,n){let r=L(t,n,{cwd:e,encoding:`utf8`});if(r.error)throw r.error;return r}function Pn(e,t=`git`){let n=Nn(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 Fn(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 In(e,t,n,r=`git`){let i=Nn(e,r,[`show`,`:${t}:${n}`]);return i.status===0?i.stdout:void 0}function Ln(e){return e.collision??[]}function Rn(e){return Ln(e).length>0&&e.ours?.action===`modified`&&e.theirs?.action===`modified`}function zn(e){let t=e.kind??`unknown`,n=e.entity??`(file)`,r=[],i=(e,r)=>({entity:n,kind:t,tier:e,reasons:[r]});if(!Mn.has(t))return i(Y,`unrecognized conflict kind "${t}"`);if(jn.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:An,reasons:r}}return i(Y,`modify_delete with contested hunks: deleted entity was also rewritten`)}let a=e.hunks??[];if(a.every(e=>Ln(e).length===0))return r.push(`both sides wrote adjacent lines only; no shared base statement rewritten`),{entity:n,kind:t,tier:kn,reasons:r};if(a.some(Rn))return i(Y,`collision on the same base statement: both sides rewrote it differently`);let o=a.reduce((e,t)=>e+Ln(t).length,0);return o<=3?(r.push(`contested collision bounded to ${o} statement(s)`),{entity:n,kind:t,tier:An,reasons:r}):i(Y,`contested collision spans ${o} base statements`)}const Bn={[kn]:0,[An]:1,[Y]:2};function Vn(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(zn),r=n.reduce((e,t)=>Bn[t.tier]>Bn[e]?t.tier:e,kn),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 Hn=12e3;function Un(e,t,n,r,i){let a={base:In(e,1,t,r),ours:In(e,2,t,r),theirs:In(e,3,t,r)},o=e=>e===void 0||e.length<=Hn?e:`${e.slice(0,Hn)}\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 Wn(e){let t=e.gitBin??`git`,n=e.weaveBin??process.env.COREFRAME_WEAVE_BIN??`weave`,r=Pn(e.worktree,t).map(r=>{let i=Fn(e.worktree,r,n),a=Vn(r,i);return a.tier===`judgment`&&(a.evidence=Un(e.worktree,r,i.explain,t,n)),a}),i=r.filter(e=>e.tier===An);i.length>0&&await On(i,e.jev??{});let a={total:r.length,safe:r.filter(e=>e.tier===kn).length,judgment:r.filter(e=>e.tier===An).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 Gn(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 Kn=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 Wn({worktree:e??process.cwd()});t?console.log(JSON.stringify(n,void 0,2)):Gn(n),n.recommendation!==`cheap-llm-resolvable`&&(process.exitCode=1)}})}}),qn=/^[a-f0-9]{64}$/,Jn=/^[a-f0-9]{40}$/,Yn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function Xn(e){if(!qn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function Zn(e){if(!Jn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function Qn(e,t){if(!Yn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function $n(e){return`projects/${Qn(e,`Project ID`)}/i18n/v1`}function er(e,t){return Xn(t),`${$n(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function tr(e,t){return Zn(t),`${$n(e)}/commits/${t}.json`}function nr(e,t){return rr(t),`${$n(e)}/releases/${encodeURIComponent(t)}.json`}function rr(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 ir(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function ar(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function or({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 dr(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=P(r,`${n}-${a}.json`);await H(N(l),{recursive:!0}),await Ge(o,l),i.push({path:o,backup:l}),await fr(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 Ge(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await W(X(t,ir(e,n,r)),{force:!0})}}}async function sr({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 dr(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)=>_r(e).localeCompare(_r(t)))}async function cr({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 pr(await mr({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function lr({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[_r(e),e])),a=new Map;for(let e of r.translations){let t=_r(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 Ze(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(_r(e));hr({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 dr(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(_r({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 fr(i,o)}}async function ur({config:e,cwd:t}){let n=await sr({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Ze(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await dr(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}.`);hr({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function dr(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 fr(e,t){await H(N(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await G(n,`${JSON.stringify(t,null,2)}\n`),await Ye(n,e)}function pr(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 mr({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 hr({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=gr(a),c=gr(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 gr(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 _r(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function vr(e){return nt(`sha256`).update(e).digest(`hex`)}async function yr(e){return vr(await U(e))}function br(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function xr({bucket:e,digest:t,projectId:n,source:r,store:i}){if(Xn(t),await yr(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=er(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 yr(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await W(o,{force:!0})}}async function Sr({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=br(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 Cr({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=br(t),o=vr(a),s=P(i,`manifest-${o}.json`);await G(s,a,{flag:`wx`});try{await xr({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await W(s,{force:!0})}return o}async function wr({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 Zn(r.revision),Xn(r.snapshot),r}finally{await W(i,{force:!0})}}async function Tr({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await wr({bucket:e,key:tr(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 Er({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Sr({bucket:e,key:tr(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Sr({bucket:e,key:nr(t,i),reference:n,store:r,temporaryDirectory:a})}async function Dr({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){Xn(n);let o=P(F(t),`v1`,`sha256`,n.slice(0,2),n);if(await kr(o,n)===!1){await H(N(o),{recursive:!0});let t=`${o}.${process.pid}.${q()}.tmp`;try{if(await i.download(e,er(r,n),t),await yr(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await W(o,{force:!0}),await Ye(t,o)}finally{await W(t,{force:!0})}}await H(N(a),{recursive:!0});let s=`${a}.${process.pid}.${q()}.tmp`;try{if(await Ge(o,s),await yr(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await W(a,{force:!0}),await Ye(s,a)}finally{await W(s,{force:!0})}}async function Or({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=P(a,`manifest-${n}.json`);await Dr({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}.`);Zn(s.revision),s.baseline!==void 0&&Xn(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}.`);Xn(e.digest)}return s}async function kr(e,t){try{return(await Xe(e)).isFile()&&await yr(e)===t}catch{return!1}}async function Ar({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(Pr(Fr(n.i18n))===`multilingual`){await Nr({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 ar(e)}async function jr({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await K({cwd:e});if(!n.i18n)return;let r=Fr(n.i18n),i=X(e,r.directory);try{if(!(await Xe(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await ar(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Xe(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 ar(e);return}}async function Mr({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){rr(r),await Wr(e);let i=await Ur(e);await Gr(e,r,i);let a=await K({cwd:e});if(!a.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);let o=Fr(a.i18n);if(Pr(o)===`source-only`)return{mode:`source-only`,sourceLocale:o.sourceLocale};let s=await Ir({cwd:e,env:t,projectConfig:a,store:n}),c=await qe(P(Ae(),`coreframe-i18n-prepare-`));try{let n=await Tr({bucket:s.assets.sourceBucket,projectId:s.assets.projectId,revision:i,store:s.store,temporaryDirectory:c});if(n){let e=await Or({bucket:s.assets.sourceBucket,cacheRoot:s.cacheRoot,digest:n.snapshot,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return Hr(s,e,i),await Rr(s,e),await Er({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 Vr(s,c,async()=>{let n=await Lr(s,i,c);n||await Br(s),await ar(e);let a=await sr({config:s.config,cwd:e}),o=await cr({config:s.config,cwd:e,env:t,messages:a});await lr({config:s.config,cwd:e,missing:a,response:o}),await ur({config:s.config,cwd:e}),await or({config:s.config,cwd:e,strict:!0,temporaryDirectory:c});let l=await zr(s),u={...n?{baseline:n}:{},catalogs:s.config.catalogs,files:l,generator:a.length>0?s.config.generator?.id??`unconfigured`:`none`,linguiVersion:await Kr(e),locales:s.config.locales,projectId:s.assets.projectId,revision:i,sourceLocale:s.config.sourceLocale,version:1},d=await Cr({bucket:s.assets.sourceBucket,manifest:u,projectId:s.assets.projectId,store:s.store,temporaryDirectory:c});return await Er({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 Nr({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 Ir({cwd:e,env:t,store:r,projectConfig:i}),o=Zn(n??await Ur(e)),s=await qe(P(Ae(),`coreframe-i18n-materialize-`));try{let e=await Tr({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 Or({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return Hr(a,t,o),await Rr(a,t),{revision:o,snapshot:e.snapshot}}finally{await W(s,{force:!0,recursive:!0})}}function Pr(e){return e.locales.length===1&&e.locales[0]===e.sourceLocale?`source-only`:`multilingual`}function Fr(e){let t=Qn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>Qn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>Qn(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 Ir({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:Fr(i.i18n),cwd:F(e),env:t,store:r??He({config:a,env:t})}}async function Lr(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 Tr({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:Zn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Or({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return Hr(e,i,t),await Rr(e,i),r.snapshot}}async function Rr(e,t){for(let n of t.files)if(await Dr({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await Xe(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function zr(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 yr(a);await xr({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Xe(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Br(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 Ze(`@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 fr(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Vr(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 Ue(o)}catch{continue}let s=P(t,`previous-catalogs`,a);await H(N(s),{recursive:!0}),await Ye(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 Ye(e,t);throw t}}function Hr(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 Ur(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return Zn(t.trim())}async function Wr(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 Gr(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 Kr(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const qr=[`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(` `),Jr=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}}),Yr=r(p,{displayName:`profile`,async from(e){return Be(e)}}),Xr=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}}),Zr=r(p,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return j(e)}}),Qr=m({name:`assets`,cmds:{configure:n({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${qr}`,args:{profile:u({type:Yr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{V.note(qr,`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 Ve({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(Xr),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:c({long:`widths`,type:l(Jr),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})=>Le(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 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(Xr),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})=>Le(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(Xr),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});Le(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:n({name:`publish`,args:{pack:c({long:`pack`,type:l(Xr),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 Re({pack:t});Le(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:n({name:`status`,args:{pack:c({long:`pack`,type:l(Xr),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});Le(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),$r=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:Zr,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:Zr,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:Zr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>O({apiOrigin:e,platform:t})})}}),ei=m({name:`i18n`,cmds:{build:n({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Ar()}}),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 Nr({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 Mr({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}.`)}})}}),ti=J.platform===`win32`?`react-router.cmd`:`react-router`,ni=J.platform===`win32`?`panda.cmd`:`panda`;async function ri(e=J.cwd()){await oi(e),await ai(e,[`typegen`])}async function ii(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 si(e,ni,[`build`],t),await ai(e,[`build`,...n?[`--mode`,n]:[]],t),await W(a,{force:!0,recursive:!0}),await H(M.dirname(a),{recursive:!0}),await Ke(i,a,{recursive:!0})}async function ai(e,t,n=J.env){await si(e,ti,t,n)}async function oi(e){await W(M.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function si(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 ci={access:Ue,chmod:We,mkdir:H,mkdtemp:qe,readFile:U,readFileSync:z,rm:W,writeFile:G},li={getAvailablePort:di},ui={homedir:Oe,kill:J.kill,networkInterfaces:ke,tmpdir:Ae};async function di(){let e=st();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 fi({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 pi(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=st(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 pi(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await mi(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 mi({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=ot({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 hi=J.platform===`win32`?`react-router.cmd`:`react-router`;function gi(e){return R(M.resolve(e,`dashboard/dashboard.config.ts`))}function _i({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([rt(t.stdout),rt(t.stderr)]),i===e&&(i=void 0)}};a=fi({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await li.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=it({label:`dashboard`}),s=it({color:`red`,label:`dashboard`});a.pipe(J.stdout,{end:!1}),s.pipe(J.stderr,{end:!1});let l=I(hi,[`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([yi(l.stdout,a),yi(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 vi({cwd:e=J.cwd(),env:t=J.env,port:n}){let r=_i({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function yi(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const bi=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})=>vi({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})=>ii(void 0,void 0,e)}),typegen:n({name:`typegen`,args:{},handler:()=>ri()})}});function xi(){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 Si({all:e,cwd:t=process.cwd(),ids:n=[],matches:r=[],now:i=new Date}={}){let a=await Oi(t),o=await ki(a.config,t,async e=>a.module.developmentJobs.createStateAdmin(e).list()),s=ct({jobs:a.module.developmentJobs.jobs,now:i,records:o??[]}),c=Ei(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 Ci({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 Si({all:!0,cwd:n,now:s}),u=Ei(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 ${Ni(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 Oi(n),m=await ki(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 ${Ni(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 wi(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development jobs are configured.`:`${t}${Pi([`Job`,`Status`,`Last success`,`Next eligible`,`Lease`],e.jobs.map(e=>[e.id,e.lease===`active`?`running`:e.registration===`orphaned`?`orphaned`:e.eligibility,ji(e.lastSucceededAt),ji(e.nextEligibleAt),e.lease===`none`?`-`:`${e.lease} until ${ji(e.leaseUntil)}`]))}`}function Ti(e){let t=Mi(e.database);return e.jobs.length===0?`${t}No local development job state matched.`:`${t}${Pi([`Job`,`Result`],e.jobs.map(e=>[e.id,e.status.replaceAll(`-`,` `)]))}`}function Ei(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 ${Ni(o)}.`);let s=new Set(t?a:n);for(let t of r){let n=Di(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 Di(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 Oi(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 Qe(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 ki(e,t,n){try{var r=xi();let a=e.database?.dialect??`postgres`,o=a===`sqlite`?M.resolve(t,`.coreframe/turso.db`):M.resolve(t,`.coreframe/postgres/PG_VERSION`);try{await Xe(o)}catch(e){if(Fi(e)&&e.code===`ENOENT`)return;throw e}if(a===`sqlite`)try{var i=xi();let r=await S({cwd:t,env:i.a(await ue({config:e,cwd:t,useSupervisorLease:!0})).env});try{return await Ai(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 Ai(n,s)}finally{await s.$client.end()}}catch(e){r.e=e}finally{await r.d()}}async function Ai(e,t){try{return await e(t)}catch(e){throw Ii(e)?Error(`The local development job state table is missing. Run coreframe db migrate-local, then retry.`,{cause:e}):e}}function ji(e){return e?.toISOString()??`-`}function Mi(e){return e.state===`missing`?`Local ${e.dialect} database is missing; no database was created.\n\n`:``}function Ni(e){return e.map(e=>JSON.stringify(e)).join(`, `)}function Pi(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 Fi(e){return e instanceof Error&&`code`in e}function Ii(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 Li={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:()=>[]})},Ri=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}),...Li},handler:async({ids:e,json:t,matches:n})=>{let r=await Si({ids:e,matches:n});console.log(t?JSON.stringify(r):wi(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}),...Li},handler:async({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o})=>{let s=await Ci({all:e,breakLeases:t,dryRun:n,ids:r,json:i,matches:a,yes:o});console.log(i?JSON.stringify(s):Ti(s))}})}}),zi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Bi(e,t){let n=Hi(e,t);if(!Ui(n)||!Wi(n,[`description`,`requires`,`routes`,`verifier`])||!Ki(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Ki))||n.verifier!==void 0&&!Ki(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=>Vi(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Ui(e)||!Gi(e,[`path`,`router`,`when`])||!Ki(e.path)||!Ki(e.router)||!Ki(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 Vi(e){if(!zi.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Hi(e,t){try{return lt(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Ui(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wi(e,t){return Object.keys(e).every(e=>t.includes(e))}function Gi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Ki(e){return typeof e==`string`&&e.length>0}const qi=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,Ji=`template`;function Yi(e=Ji){return`refs/remotes/${e}/tags`}function Q(e,t=Ji){return qi.test(e)?`${Yi(t)}/v${e}`:e.startsWith(`v`)&&qi.test(e.slice(1))?`${Yi(t)}/${e}`:e}function Xi(e){return e.startsWith(`refs/remotes/`)?e.slice(13):e}function Zi(e,t=Ji){return`${Q(e,t)}:template`}function Qi(e,t,n=Ji){return`${Zi(e,n)}/${t}`}function $i(e,t){return L(`git`,e,{cwd:t,encoding:`utf8`})}function ea(e,t){let n=$i(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 ta(e,t){let n=$i([`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 na(e,t){$i([`config`,`--get`,`remote.${e}.tagOpt`],t).stdout.trim()!==`--no-tags`&&ea([`config`,`remote.${e}.tagOpt`,`--no-tags`],t);let n=$i([`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/*:${Yi(e)}/*`])r.includes(n)||ea([`config`,`--add`,`remote.${e}.fetch`,n],t)}function ra(e,t){return ea([`for-each-ref`,`--format=%(refname)`,t],e).split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean)}function ia(e,t){return ea([`rev-parse`,`--verify`,`${e}^{commit}`],t).trim()}function aa(e,t){let n=`${Yi(e)}/`,r=new Set(ra(t,Yi(e)).map(e=>e.slice(n.length))),i=[],a=[];for(let e of ra(t,`refs/tags`)){let o=e.slice(10);if(r.has(o)){if(ia(e,t)!==ia(`${n}${o}`,t)){a.push(o);continue}ea([`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 oa({cwd:e=process.cwd(),fetch:t=!0,remote:n=Ji,url:r=`https://github.com/coreframe-js/coreframe.git`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);ea([`rev-parse`,`--show-toplevel`],e);let i=ta(n,e);if(i===null)ea([`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.`);na(n,e),t&&(ea([`fetch`,n,`--prune`],e),console.log(`Fetched ${n}.`)),aa(n,e)}function sa({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=da(e),a=ha(i,[`rev-parse`,`--show-toplevel`]),o=Q(r??fa(i),n);return oa({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,refLabel:Xi(o),repositoryRoot:a}}function ca(e,t,n){return la(e,t,n).toString(`utf8`)}function la(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}. ${ga([`show`,r],i)}`);return i.stdout}function ua(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(ga([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function da(e){let t=F(e);for(;;){let e=P(t,`package.json`),n=ma(e);if(n!==void 0&&pa(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 fa(e){let t=P(e,`package.json`),n=ma(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=pa(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function pa(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ma(e){try{return z(e,`utf8`)}catch(e){if(_a(e)&&e.code===`ENOENT`)return;throw e}}function ha(e,t){let n=L(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ga(t,n));return n.stdout.trim()}function ga(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 _a(e){return e instanceof Error&&`code`in e}const va=[{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:Da},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:Oa},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:ka},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>Ea(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=>Ea(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ya=`src-flutter/lib/application.dart`,ba=`src/api/worker/auth-origin.ts`;function xa(e){let t=[];for(let n of va){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=Sa(e,t),r=Ca(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ya} loopbackPort (${n}) must match ${ba} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function Sa(e,t){let n=wa(e,ya,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=Ta(r??a);return o===void 0&&t.push(`${ya} must configure loopbackPort as a fixed integer port.`),o}function Ca(e,t){let n=wa(e,ba,t);if(n===void 0)return;let r=Ta(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(`${ba} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function wa(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 Ta(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function Ea(e,t){return t.every(t=>e.includes(t))}function Da(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 Oa(e){try{let t=lt(e);if(!Aa(t)||!Aa(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return Aa(n)&&n.sdk===`flutter`}catch{return!1}}function ka(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 Aa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ja({name:e,...t}){let n=sa(t),r=`recipes/${e}/recipe.yaml`,i=Pa(Bi(ca(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 Ma(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Na(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=Pa(Bi(ca(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 Pa(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return xa(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function Fa({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Vi(n);let a=sa({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=Bi(ca(l,s,d),d);Na(f.requires,a);let p=ca(l,s,`${u}/RECIPE.md`),m=ua(l,s,`${u}/files`),h=ua(l,s,`${u}/patches`),g=ua(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(Ha(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);_.set(t,la(l,s,e)),v.set(t,e)}for(let e of g){let t=e.slice(`${u}/`.length);if(za(t,`Recipe asset ${e}`),_.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);_.set(t,la(l,s,e)),v.set(t,e)}for(let e of h){let t=Ua(e,u);if(_.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=la(l,s,e);Wa(n.toString(`utf8`),t,e),Va(o,t),Ga(o,n,!1)?(y.push({contents:n,destinationPath:t}),S.push(t)):Ga(o,n,!0)?C.push(t):x.push({destination:t,source:e})}let T=new Map;for(let[e,t]of _){let r=Ja(Va(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(za(e.router,`Recipe route router`),Ba(e.path,`Recipe route path`),_.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!_.has(e.path)&&!R(Va(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=E.get(e.router)??La(Ya(Va(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=Ya(Va(o,e),e),r=ut(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=Va(o,e);Se(N(n),{recursive:!0}),B(n,t)}return y.length>0&&Ka(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 Ia(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 La(e,t){let n=Ra(e,t);if(!Xa(n)||!Za(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Qa)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!Xa(e)||!Za(e,[`path`,`when`])||!Qa(e.path)||!Qa(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 Ra(e,t){try{return lt(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function za(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);Ha(e,t)}function Ba(e,t){if(Ha(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function Va(e,t){Ha(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 Ha(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 Ua(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 Ha(r,`Recipe patch ${e}`),r}function Wa(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 Ga(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 Ka(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 qa(e){return Ja(e)?.toString(`utf8`)}function Ja(e){try{return z(e)}catch(e){if($a(e)&&e.code===`ENOENT`)return;throw e}}function Ya(e,t){let n=qa(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function Xa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Za(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Qa(e){return typeof e==`string`&&e.length>0}function $a(e){return e instanceof Error&&`code`in e}function eo(e={}){let{ref:t,refLabel:n,repositoryRoot:r}=sa(e),i=ua(r,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let n=e.split(`/`)[1];return Vi(n),{description:Bi(ca(r,t,e),e).description,name:n}});return i.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:i,ref:n}}function to(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const no=`.agents/skills/coreframe-upgrade/SKILL.md`;function ro(e,t={}){return L(`git`,e,t)}function io(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function ao(e,t,n){let r=Qi(e,t,n),i=ro([`show`,r],{encoding:`utf8`});if(i.status!==0){let e=io(i);throw Error(`Could not read ${r}.${e?` ${e}`:``}`)}return i.stdout.toString()}function oo(){let e=ro([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=io(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function so(e,t){let n=Ce(P(Ae(),`coreframe-upgrade-skill-`)),r=P(n,`SKILL.md`);try{B(r,t);let n=io(ro([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{Te(n,{force:!0,recursive:!0})}}function co({apply:e,remote:t,target:n}){let r=P(oo(),no),i=Q(n,t);if(!R(r))throw Error(`Local ${no} does not exist.`);let a=z(r,`utf8`),o=ao(n,no,t),s=Xi(i);return a===o?(console.log(`Coreframe upgrade skill matches ${s}:template/${no}.`),0):e?(B(r,o),console.error(`Updated ${no} from ${s}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${s}:template/${no}.`),console.error(`Run again with --apply to update it, then reread ${no} before continuing.`),so(r,o),20)}const lo=[{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`}],uo=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],fo=new Set([`100644`,`100755`,`120000`]);function po(e,t={}){return L(`git`,e,t)}function mo(e){let t=po(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 ho(e){let t=po(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 go(){return mo([`rev-parse`,`--show-toplevel`]).trim()}function _o(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 vo(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 yo(e,t){let n=vo(ho([`diff`,`--name-status`,`-z`,`--no-renames`,Zi(e),Zi(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 bo(e,t){let n=ho([`ls-tree`,`-z`,`-r`,Zi(e),`--`,t]);if(n.length===0)return null;let r=vo(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 xo(e){return ho([`cat-file`,`blob`,e.object])}function So(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 Co(e){try{return xe(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function wo(e){return(e.mode&73)!=0}function To(e){return e===null||e.type===`blob`&&fo.has(e.mode)}function Eo(e){return lo.find(t=>t.matches(e))?.reason}function Do(e){return uo.find(t=>t.matches(e))?.reason}function Oo(e,t,n){let r=So(e,t);if(n===null)return{matches:!Co(r)};if(!To(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=xo(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`?wo(i):!wo(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 ko(e){Co(e)&&Te(e,{force:!0,recursive:!1})}function Ao(e,t,n){let r=So(e,t);if(n===null){ko(r);return}if(Se(N(r),{recursive:!0}),n.mode===`120000`){ko(r),Ee(xo(n).toString(`utf8`),r);return}let i=Co(r)?xe(r):null;i&&!i.isFile()&&ko(r),B(r,xo(n)),be(r,n.mode===`100755`?493:420)}function jo(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function Mo(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 No(e){let t=go(),n=Q(e.base??_o(t),e.remote),r=Q(e.target,e.remote),i=yo(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=Eo(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=bo(n,e.path),u=bo(r,e.path),d=jo(l,u),f=u===null?Do(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!To(l)||!To(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(Oo(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=Oo(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)Ao(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${Xi(n)} -> ${Xi(r)}`),console.log(``),Mo(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),Mo(`Ignored downstream-owned paths`,o),Mo(`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 Po({base:e,cwd:t=process.cwd(),remote:n=Ji,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(`${Yi(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 Fo=[`dependencies`,`devDependencies`];function Io(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 Lo(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Ro(e,t,n){let r=`${Q(e,n)}:${t}`;return Lo(Io([`show`,r]),r)}function zo(e){return e.startsWith(`@coreframe/`)}function Bo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function Vo(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function Ho(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 Uo(e,t){let n=Ro(e,`template/package.json`,t),r=[],i=new Set;for(let a of Fo)for(let[o,s]of Object.entries(n[a]??{})){if(!zo(o)||!Vo(s))continue;if(i.has(o))throw Error(`Target template declares ${o} more than once.`);let n=Ho(s,o),c=Ro(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 Wo(e,t){for(let n of Fo){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Go(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
|
|
15
15
|
`)?`
|
|
16
|
-
`:``;B(e,`${JSON.stringify(n,null,r)}${i}`)}function
|
|
17
|
-
`),`Pending Worker secret updates`),u?.accessTokenSigningSecret.provisioned&&V.log.info(`Provisioning Coreframe-managed access-token signing material.`),await
|
|
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
|
|
21
|
-
`)}function
|
|
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
|
|
16
|
+
`:``;B(e,`${JSON.stringify(n,null,r)}${i}`)}function Ko(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function qo(e){let t=F(Io([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=z(t,`utf8`),r=Lo(n,t),i=Q(e.target,e.remote),a=Uo(e.target,e.remote),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=Wo(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Bo(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=Fo.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>zo(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;Go(t,n,r)}console.log(`Coreframe package sync: ${Xi(i)}`),console.log(``),Ko(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Ko(`Missing target Coreframe packages`,c),Ko(`Locally linked Coreframe packages`,l),Ko(`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 Jo={...p,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Vi(e)}},Yo=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})=>oa({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=co({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})=>No({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 Po({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})=>qo({apply:e,remote:t,target:n})})}}),Xo=m({name:`recipes`,cmds:{apply:n({name:`apply`,args:{recipe:u({type:Jo,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})=>Ia(Fa({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})=>to(eo({fetch:!e,remote:t,target:n}))}),verify:n({name:`verify`,args:{recipe:u({type:Jo,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})=>Ma(ja({fetch:!e,name:t,remote:n,target:r}))})}}),Zo=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)})}}),Qo=`package.json`;async function $o(e=process.argv.slice(2),t=process.env){let n=ts(e);ys(n),await es(t);let{packageJson:r,source:i}=await Et(Qo),a=await K(),o=jt(a.deploy,n.environment,t);bs(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 xs(o,n.environment,()=>ht({env:t})),l=await St(o,a,c,t),u=o.mode===`full`?await rs(n.environment,t,a):void 0,d=await vs(),f=a.i18n?Fr(a.i18n):void 0;f&&Pr(f)===`source-only`?V.log.info(`I18n source-only mode (${f.sourceLocale}): no prepared translation snapshot is required; source catalogs build directly.`):await Nr({env:t,revision:d});let p=d.slice(0,12),m=Nt(n.environment,r.version,p),h=At(r.name,m),g={...Os(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 Cs(n);let b=o.mode===`full`?await is(a,n,t):{kind:`none`};try{_&&await zt(Qo,r,m);let e=await ze(process.cwd(),{allowMissing:!0});if(a.assets||e.problems.length>0||Me(e.catalog).length>0){let e={config:a.assets,env:g};V.log.step(`Building and validating managed assets`);let t=await Pe({...e,updateManifest:!1});if(!t.ok)throw Error(`Managed asset build failed.\n${Ie(t.problems)}`);let n=await Fe(e);if(!n.ok)throw Error(`Managed asset validation failed.\n${Ie(n.problems)}`);V.log.step(`Publishing managed assets`);let r=await Re(e);if(!r.ok)throw Error(`Managed asset publication failed.\n${Ie(r.problems)}`)}V.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:ks(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 t={...g};delete t.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`,us(n.environment,[`d1`,`migrations`,`apply`,b.database.binding,`--remote`]),{env:t,stdio:`inherit`})),V.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let i={...u?.dashboardPassword?{DASHBOARD_PASSWORD:u.dashboardPassword}:{},...u?.accessTokenSigningSecret.value?{[dt]:u.accessTokenSigningSecret.value}:{},...u?.pendingWorkerSecrets.values},d=Object.keys(i).length>0?await Ts(i):void 0,f=o.mode===`full`?await vt({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:h}}}):await _t(process.cwd());try{await I(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,f.path,`--strict`,`--keep-vars`,`--tag`,h,`--message`,`Deploy ${h}`,...d?[`--secrets-file`,d.path]:[]],{env:t,stdio:`inherit`}),u&&(await ft(u.pendingWorkerSecrets),await Rt({environment:n.environment}))}finally{await f.dispose(),await d?.dispose()}let p={environment:n.environment,releaseName:h,url:c,version:m};o.mode===`full`&&o.afterWorkerDeploy&&(V.log.step(`Running required after-Worker deploy hook`),await Ft(o,p)),l&&(V.log.step(`Provisioning and verifying deployment reviewer`),await l.run(p)),n.skipPostDeployChecks||(V.log.step(`Running post-deploy checks`),await It(o,p)),V.outro(`Deployed ${h} to ${n.environment}`)}catch(e){throw!v&&_&&await G(Qo,i),e}}async function es(e){let t;try{t=await U(`.env.deploy`,`utf8`)}catch(e){if(Es(e)&&e.code===`ENOENT`)return;throw e}for(let[n,r]of Object.entries(Vt(t)))e[n]===void 0&&(e[n]=r)}function ts(e){return{environment:ns(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function ns(e){if(e&&pt.includes(e))return e;throw Error(`Deploy environment must be one of: ${pt.join(`, `)}.`)}async function rs(e,t,n){let r=await Dt({environment:e}),i=n.dashboard?.enabled===!1?void 0:r.values.DASHBOARD_PASSWORD??await ws(t,e);return Lt(await gt({environment:e}),e,{availableNames:[...Object.keys(r.values),...i?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await xt({environment:e}),dashboardPassword:i,pendingWorkerSecrets:r}}async function is(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=Mt({config:await as(i!==void 0),d1Binding:i,environment:t.environment,hasConnectionUrl:!!(n.TURSO_DATABASE_URL??n.DATABASE_URL)});if(e)return os(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 hs(a);return await ms(s,o.size,"Move unsafe statements to held migrations and apply them with `pnpm db migrate-held`."),await _s(t,s)?{kind:`drizzle`}:{kind:`none`}}async function as(e){try{return await Ot()}catch(t){if(e)throw t;return{}}}async function os(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 ss(e,t.environment,n),a=r.filter(t=>{let n=ls(t,e);return n===void 0||!i.has(n)}),o=a.filter(t=>ls(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 ms(a,i.size,`Move unsafe statements to held migrations and apply them to the D1 database for ${t.environment} separately.`),await _s(t,a)?{kind:`d1`,database:e}:{kind:`none`}}async function ss(e,t,n){let r=`select name from ${fs(e.migrationsTable)} order by id`,i;try{i=(await I(`pnpm`,us(t,[`d1`,`execute`,e.binding,`--remote`,`--json`,`--command`,r]),{env:ds(n),stdin:`ignore`})).stdout}catch(n){let r=ps(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(cs(i,e))}function cs(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(!(!Ds(e)||!Array.isArray(e.results)))for(let t of e.results)Ds(t)&&typeof t.name==`string`&&r.push(t.name);return r}function ls(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 us(e,t){return[`exec`,`wrangler`,`--config`,et,`--env`,e,...t]}function ds(e){let t={...e};return delete t.CLOUDFLARE_ENV,t}function fs(e){return`"${e.replaceAll(`"`,`""`)}"`}function ps(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 ms(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 hs(e){try{return await gs(e)}finally{await e.close?.()}}async function gs(e){let t=await v(),n=await re(e);return{appliedMigrations:n,pendingMigrations:w(t,n)}}async function _s(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 vs(){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 ys(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function bs(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function xs(e,t,n=ht){return e.url?Ss(e.url,t):t===`staging`&&e.stagingHostname?Ss(await n(),t):Ss(void 0,t)}function Ss(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 Cs(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 ws(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Vt(await U(`.env`,`utf8`))}catch(e){throw Es(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 Ts(e){let t=await qe(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 Es(e){return e instanceof Error&&`code`in e}function Ds(e){return typeof e==`object`&&!!e}function Os(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 ks(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function As(){let e=await Ms();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function js(e){let t=await Ms(),n=Ns();await ci.mkdir(M.dirname(n),{recursive:!0}),await ci.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function Ms(){try{let e=await ci.readFile(Ns(),`utf8`),t=JSON.parse(e);return Ps(t)?t:{}}catch{return{}}}function Ns(){return M.join(ui.homedir(),`.coreframe`,`preferences.json`)}function Ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Fs({env:e=J.env,interactive:t=J.stdin.isTTY===!0,platform:n,target:r}){let i=await Hs(n,e).catch(()=>[]),a=r?oc(i,r):void 0;if(a)return a;if(!r&&i.length>0)return Vs(i,n,t);let o=r?oc(await Ws(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return Gs(o,n,e,t);let s=await Us(n,e),c=r?oc(s,r):void 0;if(c)return c;if(!r&&s.length>0)return Vs(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 Is(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=cc();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await zs();if(a&&i.includes(a))return a;if(i.length===1)return await Bs(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 Bs(o),o}async function Ls({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 $s(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:Rs(i,await Is({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function Rs(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 zs(){return(await As()).mobileDevHost}async function Bs(e){try{await js({mobileDevHost:e})}catch(e){V.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function Vs(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 Hs(e,t){return e===`android`?qs(t):Ys(t)}async function Us(e,t){return e===`android`?Js(t):Xs(t)}async function Ws(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 Gs(e,t,n,r){let i=await Ks(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 Ks(t,n).catch(()=>[]),o=oc(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return Vs(s,t,r);if(a.length===1)return a[0];await en(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 Ks(e,t){return e===`ios`?Xs(t,`booted`):(await qs(t)).filter(e=>!e.physical)}async function qs(e){let t=await Qs(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 tc(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await rc(t,e,n,r):await ic(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(lc)}async function Js(e){let{stdout:t}=await I(await Qs(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 Ys(e){let t=await ci.mkdtemp(M.join(ui.tmpdir(),`coreframe-ios-devices-`)),n=M.join(t,`devices.json`);try{return await ci.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await ci.readFile(n,`utf8`)).result?.devices??[]).filter(Zs).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(lc)}finally{await ci.rm(t,{force:!0,recursive:!0})}}async function Xs(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(lc)}function Zs(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 Qs(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:ec(e);for(let e of i){let r=M.join(e,t,n);try{return await ci.access(r),r}catch{}}return n}async function $s(e,t,n){let r=await Qs(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 ec(e){return J.platform===`darwin`?[M.join(ui.homedir(),`Library`,`Android`,`sdk`)]:J.platform===`win32`&&e.LOCALAPPDATA?[M.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[M.join(ui.homedir(),`Android`,`Sdk`)]}async function tc(e,t,n,r){return(await nc(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function nc(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function rc(e,t,n,r){return nc(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function ic(e,t,n,r){return nc(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>ac(e)||r).catch(()=>r)}function ac(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function oc(e,t){let n=e.map(e=>({device:e,score:Math.max(sc(t,e.name),sc(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function sc(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 cc(){return[...new Set(Object.values(ui.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function lc(e,t){return e.label.localeCompare(t.label)}var uc=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(!hc(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:hc(e.params)?e.params:{}};this.#l(t),await this.#e?.(t),n.push(...fc(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(!hc(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=_c(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(gc(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(_c(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*dc(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 fc({event:e,params:t},n){if(e===`daemon.log`||e===`app.log`)return $(mc(t.log),t.error===!0?`error`:`debug`);if(e===`daemon.logMessage`){let e=pc(t.level);return!n&&e===`debug`?[]:[...$(mc(t.message),e),...n?$(mc(t.stackTrace),e):[]]}return e===`daemon.showMessage`?$(mc(t.message),pc(t.level)):e===`app.warning`?$(mc(t.warning),`warn`):e===`app.progress`&&t.finished!==!0?$(mc(t.message),`debug`):e===`app.stop`&&t.error!==void 0?$(gc(t.error),`error`):[]}function $(e,t){return e===void 0?[]:e.split(/\r?\n/u).map(e=>({level:t,message:e}))}function pc(e){return e===`error`?`error`:e===`warning`||e===`warn`?`warn`:`debug`}function mc(e){return typeof e==`string`&&e.length>0?e:void 0}function hc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gc(e){if(typeof e==`string`)return e;if(hc(e)&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function _c(e){return e instanceof Error?e:Error(gc(e))}async function vc(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 yc(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const bc=J.platform===`win32`?`portless.cmd`:`portless`,xc=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Sc=/^Proxy is already running on port (\d+)\.$/,Cc=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function wc(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(xc,``).trim().match(Sc);if(a?.[1]!==void 0&&i!==void 0&&Cc.test(i.replace(xc,``).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 Tc(e){let t=wc(e);t&&J.stdout.write(t.endsWith(`
|
|
19
|
+
`)?t:`${t}\n`)}async function Ec({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await tn()).isAgent?!1:Jt(e)}async function Dc({cwd:e,env:t,lan:n=!1}){let r=M.join(`node_modules`,`.bin`,bc),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`});Tc(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Tc(e.stdout),e}}function Oc({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 kc=M.join(`.coreframe`,`dev`,`session.json`);async function Ac({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,kc),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 We(t,384),await Ye(t,u)}),p};return await m(),{path:u,async recordFlutterEvent({event:e,params:t}){let n=f.flutter;if(!n)return;let r=Nc(t.appId),i;if(e===`daemon.connected`){let e=Pc(t.pid),r=Nc(t.version);i={...jc(n),state:`starting`,...e===void 0?void 0:{daemonPid:e},...r===void 0?void 0:{protocolVersion:r}}}else if(e===`app.start`&&r)i={...jc(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=Nc(t.wsUri);e&&(i={...n,vmServiceWsUri:e})}else if(e===`app.devTools`&&r===n.appId){let e=Nc(t.uri);e&&(i={...n,devToolsUri:e})}else if(e===`app.dtd`&&r===n.appId){let e=Nc(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 U(u,`utf8`)).id===a&&await W(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}function jc(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{...jc(e),state:`stopped`,...e.appId===void 0?void 0:{appId:e.appId},...e.supportsRestart===void 0?void 0:{supportsRestart:e.supportsRestart}}}function Nc(e){return typeof e==`string`?e:void 0}function Pc(e){return typeof e==`number`?e:void 0}const Fc=`extension:dev`;function Ic(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.${Fc} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function Lc({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`,Fc,...n.length>0?[`--`,...n]:[]]}const Rc=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],zc=[`managed-dev-overlay`],Bc=M.resolve(`node_modules`,`.bin`),Vc=J.platform===`win32`?`pnpm.cmd`:`pnpm`,Hc=J.platform===`win32`?`portless.cmd`:`portless`,Uc=J.platform===`win32`?`react-router.cmd`:`react-router`,Wc=`Lost connection to device.`;async function Gc({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=Wt({env:r}),y=r.PATH??r.Path??``,b=il(h)?h:void 0,x=cn(i||a),S=rl(_??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.`);Ic(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`,()=>Ec({cwd:e,env:r,platform:h}));fe&&await v.measure(`portless`,()=>Dc({cwd:e,env:r,lan:u}));let k=b===void 0?h===`web`?S??await li.getAvailablePort():h===`webext`?S:void 0:S??await li.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=at(e);w=t;try{await t.expectSuccess()}catch(e){if(!D)throw e}finally{w===t&&(w=void 0)}};try{se=b?$t({path:M.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await Fs({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&ln({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 Ls({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??Rs(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 qt(e))]),await v.measure(`i18n`,()=>jr({cwd:e,projectConfig:A})),N=h!==`webext`&&A.dashboard?.enabled!==!1&&gi(e)?await li.getAvailablePort():void 0;let _e=await v.measure(`https`,async()=>c&&!fe?Yt({cwd:e}):void 0),ve=yc(r,h);O={...ve,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Xt]:q()}:void 0,...b?{COREFRAME_PLATFORM:b,[Qt]:M.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,..._e?{[Gt]:_e.cert,[Kt]:_e.key}:void 0,...N?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${N}`}:void 0},ee!==void 0&&de!==void 0&&(ce=await Ac({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=_i({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=it({label:`web`}),n=it({color:`red`,label:`web`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),ne=I(fe?Hc:Uc,fe?Oc({host:w,lan:u,port:k}):nl({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:Bc+M.delimiter+y},stdin:`inherit`});let r=Promise.allSettled([Qc(ne.stdout,t),Qc(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([rt(t),rt(n)]),ne=void 0}},L=async()=>{let t=it({label:`webext`}),n=it({color:`red`,label:`webext`});t.pipe(J.stdout,{end:!1}),n.pipe(J.stderr,{end:!1}),re=I(Vc,Lc({host:s,port:k}),{cwd:e,env:O,stdin:`inherit`});let r=Promise.allSettled([Qc(re.stdout,t),Qc(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([rt(t),rt(n)]),re=void 0}},be=async t=>{let n,r,i=!1,s,c=vc(O[Qt],()=>{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`,un({device:_??{id:h},flutterDriver:a,mode:x,serverUrl:de,verbose:g}),{cwd:M.join(e,`src-flutter`),env:sn(ve,{noCodesign:f}),stdio:[`pipe`,`pipe`,`pipe`]}),d=new uc({onEvent:async e=>{Jc(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 Ht(t.stdin,`drain`)}}),p=e=>qc(dc(e,d),()=>s=!0);C=u,n=u,r=d;try{let e=!1;try{let e=c?c.capture(Zc(p(u),S,`output`)):Promise.all([Xc(p(u.stdout),J.stdout,S,`stdout`),Kc(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?`${Wc} 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=at({name:`panda`,command:Vc,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,[Zt]:`1`},r.COREFRAME_DEV_SUPERVISOR!==`0`&&(le=await v.measure(`supervisor`,()=>Ut({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:Vc,args:[`db`,`ensure`],cwd:e,env:O,prefix:!1})),D)return;ie({cwd:e,env:O,dialect:`sqlite`})}if(tl(A)){let t=it({label:`postgres`});t.pipe(J.stdout,{end:!1});try{let n=await v.measure(`database`,()=>el({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:Vc,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)}$c(e)}}async function Kc(e,t,n,r){for await(let i of Yc(e,n,r))t.write(`${i}\n`)||await Ht(t,`drain`)}async function*qc(e,t){for await(let n of e)Jc(n.message)&&t(),yield n}function Jc(e){return typeof e==`string`&&e.trim()===Wc}async function*Yc(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 Xc(e,t,n,r){for await(let i of Zc(e,n,r))t.write(`${i}\n`)||await Ht(t,`drain`)}async function*Zc(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 Qc(e,t){for await(let n of e)t.write(`${n}\n`)||await Ht(t,`drain`)}function $c(e){if(e)throw e}async function el({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 tl(e){return(e.database?.dialect??`postgres`)===`postgres`}function nl({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 rl(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 il(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function al(e={}){let t=e.cwd??J.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Ue(M.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Qe(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 nn({...e,cwd:t},r)}const ol=`worker-configuration.d.ts`;async function sl({check:e=!1,cwd:t=process.cwd()}={}){let n=await K({cwd:t}),r=await yt({coreframeConfig:n,cwd:t}),i=F(t,ol),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 cl(e),e}let o=ll(await U(a,`utf8`)),s=tt(r.config),c=$e(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${ul(c)}\n`;if(e){if(await U(i,`utf8`).catch(()=>``)!==l)throw Error(`${ol} 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 cl(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 ll(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
21
|
+
`)}function ul(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 dl=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),fl=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],pl=[`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`],ml=[`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`],hl=`.coreframe/typegen.json`,gl=[`web`,`dashboard`,`worker`];async function _l({checkWorker:e=!1,cwd:t=J.cwd(),runners:n={}}={}){let r=await xl(t)??{generators:{},schemaVersion:1},i=[];return i.push(await yl({cwd:t,inputPaths:fl,name:`web`,outputPath:`.react-router`,run:()=>(n.web??bl)(t),state:r})),i.push(await yl({cwd:t,inputPaths:pl,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??ri)(t),state:r})),i.push(await yl({cwd:t,inputPaths:ml,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??sl)({check:e,cwd:t}),state:r})),i}function vl(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function yl({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await Cl(e,t),s=await wl(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 wl(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Sl(e,a),{changed:s!==l,name:n,ran:!0}}async function bl(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 xl(e){try{let t=JSON.parse(await U(M.resolve(e,hl),`utf8`));if(!Ol(t)||t.schemaVersion!==1)return;let n={};if(!Ol(t.generators))return;for(let e of gl){let r=t.generators[e];Ol(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 Sl(e,t){let n=M.resolve(e,hl);await H(M.dirname(n),{recursive:!0}),await G(n,`${JSON.stringify(t)}\n`,{mode:384})}async function Cl(e,t){let n=nt(`sha256`);for(let r of[...t].sort()){let t=M.resolve(e,r),i=await El(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Tl(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 wl(e,t){if(await El(M.resolve(e,t)))return Cl(e,[t])}async function Tl(e){let t=[];async function n(e,r){let i=await Je(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(dl.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 El(e){try{return await Xe(e)}catch(e){if(Dl(e))return;throw e}}function Dl(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ol(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const kl=M.resolve(`node_modules`,`.bin`);J.env.PATH=kl+M.delimiter+J.env.PATH;const Al=J.platform===`win32`?`tsc.cmd`:`tsc`,jl=[{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 _l({checkWorker:!0});let e=[];for(let t of jl)try{await Ue(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>at({name:e.name,command:Al,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 Nl=r(s(zc),{displayName:`feature`,from:async e=>e}),Pl=r(s(on),{displayName:`filtered|full`,from:async e=>e}),Fl=[`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.`],Il=n({name:`deploy`,args:{environment:u({type:s(pt),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})=>$o([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Ll=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 kt();if(e){console.log(JSON.stringify({...t,notices:Fl}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Fl.join(` `)}`)}}),url:n({name:`url`,args:{json:i({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ht();console.log(e?JSON.stringify({url:t}):t)}})}}),Rl=m({name:`secrets`,cmds:{"rotate-access-token":n({name:`rotate-access-token`,args:{environment:u({type:s(pt),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 Pt({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(pt)),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 gt({environment:e});console.log(t?JSON.stringify(n):Wl(n))}}),set:n({name:`set`,args:{environment:u({type:s(pt),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 Ct({environment:e,name:t,value:await Gl(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await Tt(),i=n?await ql(r):await Kl(r,e);await wt({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(pt),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 mt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),zl=n({name:`typecheck`,args:{},handler:Ml}),Bl=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 sl({check:e});console.log(e?`${Yl(t.path)} is current.`:`${Yl(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),Vl=n({name:`dev`,args:{debug:c({long:`debug`,type:l(Nl),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:Pl,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(Rc)),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=Hl({device:t,flutterDebug:n,platform:f,simulator:m});return Gc({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 Hl({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 Ul=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})=>al({host:e,port:t})});function Wl(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 Gl(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 Kl(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 ql(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 Jl();if(V.isCancel(t))throw V.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=bt(t,e);return n.length>0&&V.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function Jl(){let e=``;for await(let t of J.stdin)e+=t.toString();return e}function Yl(e){return e.split(/[\\/]/).at(-1)??e}const Xl=n({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await _l();for(let t of e)console.log(vl(t))}});function Zl(e,{formatMessage:t,temporaryDirectory:n=Ae(),write:r=e=>console.error(e)}={}){let i=ru(e),a=ou($l(e,t),i);try{let t=P(Ce(P(n,`coreframe-error-`)),`error.log`);return B(t,`${ou(eu(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 Ql(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,Zl(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function $l(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 eu(e){try{let t=tu(e);if(!(e instanceof Error)||!nu(t))return Bt(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${Bt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function tu(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:tu(a.value,t),writable:!0})}return i}function nu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ru(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`?iu(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function iu(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&au(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function au(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function ou(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const su=m({name:`coreframe`,cmds:{build:Cn,conflicts:Kn,dashboard:bi,assets:Qr,flutter:$r,i18n:ei,jobs:Ri,deploy:Il,staging:Ll,secrets:Rl,typegen:Xl,typecheck:zl,worker:Bl,dev:Vl,preview:Ul,upgrade:Yo,recipes:Xo,db:Zo}});import.meta.main&&Ql(su,{formatMessage:process.argv[2]===`db`?T:void 0});export{su 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.47",
|
|
4
4
|
"description": "Coreframe project workflow CLI and automation scripts",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,15 +29,15 @@
|
|
|
29
29
|
"nano-spawn": "^2.1.0",
|
|
30
30
|
"procband": "^0.3.9",
|
|
31
31
|
"yaml": "^2.9.0",
|
|
32
|
-
"@coreframe/
|
|
32
|
+
"@coreframe/db": "^0.1.26",
|
|
33
33
|
"@coreframe/config": "^0.1.18",
|
|
34
|
-
"@coreframe/db": "^0.1.25",
|
|
35
34
|
"@coreframe/deploy": "^0.1.19",
|
|
36
|
-
"@coreframe/dev": "^0.1.
|
|
37
|
-
"@coreframe/
|
|
38
|
-
"@coreframe/
|
|
35
|
+
"@coreframe/dev-contracts": "^0.1.11",
|
|
36
|
+
"@coreframe/flutter-tools": "^0.1.30",
|
|
37
|
+
"@coreframe/dev": "^0.1.32",
|
|
39
38
|
"@coreframe/object-storage": "^0.1.4",
|
|
40
|
-
"@coreframe/
|
|
39
|
+
"@coreframe/assets": "^0.1.21",
|
|
40
|
+
"@coreframe/preview": "^0.1.26",
|
|
41
41
|
"@coreframe/jobs": "^0.1.1"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|