@coreframe/scripts 0.2.24 → 0.2.26
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 +4 -1
- package/dist/coreframe.d.ts +4 -8
- package/dist/coreframe.js +15 -26
- package/package.json +12 -11
package/bin/coreframe.js
CHANGED
|
@@ -12,7 +12,10 @@ const forwardedSignals =
|
|
|
12
12
|
|
|
13
13
|
function runChild(command, args, options = {}) {
|
|
14
14
|
return new Promise((resolve) => {
|
|
15
|
-
const child = spawn(command, args, {
|
|
15
|
+
const child = spawn(command, args, {
|
|
16
|
+
...options,
|
|
17
|
+
stdio: "inherit",
|
|
18
|
+
})
|
|
16
19
|
let settled = false
|
|
17
20
|
const signalHandlers = new Map()
|
|
18
21
|
const cleanup = () => {
|
package/dist/coreframe.d.ts
CHANGED
|
@@ -29,18 +29,16 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
29
29
|
args: {
|
|
30
30
|
debug: "managed-dev-overlay" | undefined;
|
|
31
31
|
flutterDebug: boolean;
|
|
32
|
+
flutterMcp: boolean;
|
|
32
33
|
flutterOutput: "filtered" | "full";
|
|
33
34
|
https: boolean;
|
|
34
|
-
fresh: boolean;
|
|
35
35
|
host: string | undefined;
|
|
36
36
|
lan: boolean;
|
|
37
37
|
managed: boolean;
|
|
38
38
|
noCodesign: boolean;
|
|
39
39
|
noManaged: boolean;
|
|
40
40
|
noDevJobs: boolean;
|
|
41
|
-
reuseVite: boolean;
|
|
42
41
|
simulator: boolean;
|
|
43
|
-
stop: boolean;
|
|
44
42
|
platform: "web" | "ios" | "android" | "macos" | "windows" | "linux" | "webext" | undefined;
|
|
45
43
|
device: string | undefined;
|
|
46
44
|
port: number | undefined;
|
|
@@ -336,18 +334,16 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
336
334
|
args: {
|
|
337
335
|
debug: "managed-dev-overlay" | undefined;
|
|
338
336
|
flutterDebug: boolean;
|
|
337
|
+
flutterMcp: boolean;
|
|
339
338
|
flutterOutput: "filtered" | "full";
|
|
340
339
|
https: boolean;
|
|
341
|
-
fresh: boolean;
|
|
342
340
|
host: string | undefined;
|
|
343
341
|
lan: boolean;
|
|
344
342
|
managed: boolean;
|
|
345
343
|
noCodesign: boolean;
|
|
346
344
|
noManaged: boolean;
|
|
347
345
|
noDevJobs: boolean;
|
|
348
|
-
reuseVite: boolean;
|
|
349
346
|
simulator: boolean;
|
|
350
|
-
stop: boolean;
|
|
351
347
|
platform: "web" | "ios" | "android" | "macos" | "windows" | "linux" | "webext" | undefined;
|
|
352
348
|
device: string | undefined;
|
|
353
349
|
port: number | undefined;
|
|
@@ -630,7 +626,7 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
630
626
|
};
|
|
631
627
|
} | {
|
|
632
628
|
command: "dev";
|
|
633
|
-
value: Promise<void
|
|
629
|
+
value: Promise<void>;
|
|
634
630
|
} | {
|
|
635
631
|
command: "typegen";
|
|
636
632
|
value: Promise<void>;
|
|
@@ -805,7 +801,7 @@ declare const coreframeCli: Partial<import("@alloc/cmd-ts/dist/cjs/argparser").R
|
|
|
805
801
|
};
|
|
806
802
|
} | {
|
|
807
803
|
command: "dev";
|
|
808
|
-
value: Promise<void
|
|
804
|
+
value: Promise<void>;
|
|
809
805
|
} | {
|
|
810
806
|
command: "typegen";
|
|
811
807
|
value: Promise<void>;
|
package/dist/coreframe.js
CHANGED
|
@@ -1,29 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as e from"@alloc/cmd-ts";import{command as t,extendType as n,flag as r,number as i,oneOf as a,option as o,optional as s,positional as c,rest as l,string as u,subcommands as d}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as f,checkDeployMigrations as p,checkSchemaPush as m,collectDeployMigrationFiles as h,createProjectPostgresDatabaseAdapter as g,createProjectSqliteDatabaseAdapter as _,ensureLocalDb as v,filterPendingMigrations as
|
|
3
|
-
`)}function
|
|
2
|
+
import*as e from"@alloc/cmd-ts";import{command as t,extendType as n,flag as r,number as i,oneOf as a,option as o,optional as s,positional as c,rest as l,string as u,subcommands as d}from"@alloc/cmd-ts";import{ProjectPostgresAlreadyRunningError as f,checkDeployMigrations as p,checkSchemaPush as m,collectDeployMigrationFiles as h,createProjectPostgresDatabaseAdapter as g,createProjectSqliteDatabaseAdapter as _,ensureLocalDb as v,filterPendingMigrations as ee,formatDbErrorMessage as y,formatMigrationList as b,formatMigrationScanFailures as x,migrateHeldMigrations as S,migrateLocalDb as C,readAppliedMigrationNames as w,resetLocalDb as te,runDrizzleKitCommand as T,scanDeployMigrationFiles as ne,seedLocalDb as re,setupLocalDb as ie,startProjectPostgres as ae,startProjectTurso as oe,stopProjectPostgres as se}from"@coreframe/db";import{checkFlutterClient as ce,classifyFlutterDevOutputLine as le,ensureFlutterDevAssetDirectories as ue,flutterPlatforms as E,generateFlutterNativeBridge as de,prepareFlutterClient as D,prepareFlutterDevOutput as fe,productionApiOrigin as O,runFlutterAcceptance as k}from"@coreframe/flutter-tools";import A,{dirname as j,isAbsolute as pe,join as M,posix as N,resolve as P,sep as F}from"node:path";import I from"nano-spawn";import*as L from"@clack/prompts";import{addAsset as me,backupAssets as he,buildAssets as ge,checkAssets as _e,printAssetResult as ve,publishAssets as ye}from"@coreframe/assets";import{assertAssetCredentialProfile as be,configureAssetCredentials as xe,createB2PrivateObjectStore as Se}from"@coreframe/object-storage";import{access as Ce,chmod as we,copyFile as Te,cp as Ee,mkdir as R,mkdtemp as De,readFile as z,readdir as Oe,rename as ke,rm as B,stat as Ae,writeFile as V}from"node:fs/promises";import{homedir as je,networkInterfaces as Me,tmpdir as Ne}from"node:os";import{importProjectDependency as Pe,importProjectModule as Fe,normalizeWorkerEnvironment as Ie,readProjectConfig as H,wranglerEnvironmentNames as Le}from"@coreframe/config";import{createHash as Re,randomUUID as U}from"node:crypto";import W from"node:process";import{chmodSync as ze,existsSync as G,lstatSync as Be,mkdirSync as Ve,mkdtempSync as He,readFileSync as K,readlinkSync as Ue,rmSync as We,symlinkSync as Ge,watch as Ke,writeFileSync as q}from"node:fs";import{finished as qe}from"node:stream/promises";import{createPrefixStream as J,supervise as Je}from"procband";import{createConnection as Ye,createServer as Xe}from"node:net";import{spawnSync as Y}from"node:child_process";import{parse as Ze,stringify as Qe}from"yaml";import{accessTokenSigningSecretName as $e,clearAppliedPendingWorkerSecrets as et,deployEnvironments as tt,discardPendingWorkerSecret as nt,discoverStagingUrl as rt,inspectWorkerEnvironment as it,materializeBuiltClientDeployConfig as at,materializePrimaryWorkerConfig as ot,materializePrimaryWorkerTypeConfig as st,parseDeclaredWorkerSecretEnv as ct,prepareAccessTokenSigningSecret as lt,queueWorkerSecret as ut,queueWorkerSecrets as dt,readDeclaredWorkerSecrets as ft,readPackageJson as pt,readPendingWorkerSecretSnapshot as mt,reassignStagingHostname as ht,releaseName as gt,resolveDeployConfig as _t,resolveReleaseVersion as vt,rotateAccessTokenSigningSecret as yt,runAfterWorkerDeploy as bt,runPostDeployChecks as xt,validateWorkerEnvironmentForDeploy as St,verifyAccessTokenSigningSecret as Ct,writePackageVersion as wt}from"@coreframe/deploy";import{inspect as Tt,parseEnv as Et}from"node:util";import{once as Dt}from"node:events";import{createDevStartupTiming as Ot,devHttpsCertEnv as kt,devHttpsKeyEnv as At,isManagedDevCheckout as jt,isPrimaryCheckout as Mt,prepareDevHttps as Nt}from"@coreframe/dev";import{devJobsEnv as Pt}from"@coreframe/dev-contracts/dev-jobs";import{managedDevEnv as Ft,managedDevFlutterRestartFileEnv as It}from"@coreframe/dev-contracts/managed-dev";import{openScopedLogs as Lt}from"leylines";import{setTimeout as Rt}from"node:timers/promises";import{determineAgent as zt}from"@vercel/detect-agent";import{runPreview as Bt}from"@coreframe/preview";const Vt=`FLUTTER_XCODE_COREFRAME_BUNDLE_IDENTIFIER_SUFFIX`,Ht=`COREFRAME_FLUTTER_DEVELOPMENT`,Ut=[`filtered`,`full`];function Wt(e,{noCodesign:t=!1}={}){return{...e,[Vt]:`.dev`,[Ht]:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function Gt(e=!1){return e?`debug`:`profile`}function Kt({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 qt({device:e,flutterDriver:t,mode:n,serverUrl:r,verbose:i}){return[`run`,`--${n}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${r}`,...t?[`--dart-define=ENABLE_FLUTTER_DRIVER=true`]:[],...i?[`--verbose`]:[]]}const Jt=[`web`,...E];function Yt(e=`web`,{apiOrigin:t,cwd:n=process.cwd(),profile:r=!1,simulator:i=!1}={}){if(nn(e,{profile:r,simulator:i}),e===`web`)return[an(`pnpm`,[`build`],n,{COREFRAME_PLATFORM:`web`})];let a=O(t);return[{kind:`prepare`,platform:e},an(`flutter`,Xt(e,a,{profile:r,simulator:i}),P(n,`src-flutter`),{COREFRAME_API_ORIGIN:a})]}function Xt(e,t,{noCodesign:n=e===`macos`,profile:r=!1,simulator:i=!1}={}){nn(e,{profile:r,simulator:i});let a=O(t);return[`build`,e===`android`?`apk`:e,r?`--profile`:`--release`,...i?[`--simulator`]:[],...n?[`--no-codesign`]:[],`--dart-define=COREFRAME_API_ORIGIN=${a}`]}function Zt(e,{profile:t=!1}={}){let n=t?`profile`:`release`,r=P(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 Qt(e,{profile:t=!1,simulator:n=!1}={}){let r=t?`profile`:`release`,i=P(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 Yt({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=oe,runCommand:s=Zt}={}){Xt(r,{profile:i,simulator:a});let c={...n};delete c.COREFRAME_FLUTTER_DEVELOPMENT,delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:M(e??n.COREFRAME_API_ORIGIN);for(let e of Ut(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(Gt(t,{profile:i})):r===`ios`?console.log(Kt(t,{profile:i,simulator:a})):r===`windows`?console.log(qt(t)):r===`linux`&&console.log(Jt(t))}function Xt(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 Zt(e,t,{cwd:n,env:r}){await V(e,t,{cwd:n,env:r,stdio:`inherit`})}function Qt(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const $t=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return M(e)}}),en=t({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:c({type:s(a(Ht)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:o({long:`api-origin`,type:s($t),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:r({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>Yt({apiOrigin:e,platform:t,profile:n,simulator:r})}),tn=/^[a-f0-9]{64}$/,nn=/^[a-f0-9]{40}$/,rn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function an(e){if(!tn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function on(e){if(!nn.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function sn(e,t){if(!rn.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function cn(e){return`projects/${sn(e,`Project ID`)}/i18n/v1`}function ln(e,t){return an(t),`${cn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function un(e,t){return on(t),`${cn(e)}/commits/${t}.json`}function dn(e,t){return fn(t),`${cn(e)}/releases/${encodeURIComponent(t)}.json`}function fn(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 Q(e,t){if(!t||t.startsWith(`/`)||t.includes(`\0`))throw Error(`Unsafe i18n artifact path "${t}".`);let n=z(e),r=z(n,t);if(r!==n&&!r.startsWith(`${n}${B}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function $(e,t,n){return`${e.directory}/${t}/${n}.json`}function pn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function mn(e){await V(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function hn({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=Q(t,$(e,n,a)),s=await bn(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=L(r,`${n}-${a}.json`);await G(F(l),{recursive:!0}),await _e(o,l),i.push({path:o,backup:l}),await xn(o,c)}await V(`pnpm`,[`exec`,`lingui`,`compile`,...n?[`--strict`]:[]],{cwd:t,stdio:`inherit`})}finally{try{for(let{path:e,backup:t}of i)await _e(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await q(Q(t,pn(e,n,r)),{force:!0})}}}async function gn({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 bn(Q(t,$(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)=>En(e).localeCompare(En(t)))}async function _n({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 Sn(await Cn({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function vn({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[En(e),e])),a=new Map;for(let e of r.translations){let t=En(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 ke(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(En(e));wn({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=Q(t,$(e,n,r)),o=await bn(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(En({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 xn(i,o)}}async function yn({config:e,cwd:t}){let n=await gn({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await ke(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await bn(Q(t,$(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}.`);wn({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function bn(e){let t=JSON.parse(await K(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 xn(e,t){await G(F(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await J(n,`${JSON.stringify(t,null,2)}\n`),await Ce(n,e)}function Sn(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 Cn({args:e,command:t,cwd:n,env:r,input:i}){return V(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 wn({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=Tn(a),c=Tn(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 Tn(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 En(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Dn(e){return Pe(`sha256`).update(e).digest(`hex`)}async function On(e){return Dn(await K(e))}function kn(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function An({bucket:e,digest:t,projectId:n,source:r,store:i}){if(an(t),await On(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=ln(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${Y()}.verify`;try{if(await i.download(e,a,o),await On(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await q(o,{force:!0})}}async function jn({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=kn(n),o=L(i,`reference-${Y()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await K(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await q(o,{force:!0})}await J(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await q(o,{force:!0})}let s=L(i,`reference-${Y()}.verify.json`);try{if(await r.download(e,t,s),!(await K(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await q(s,{force:!0})}}async function Mn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=kn(t),o=Dn(a),s=L(i,`manifest-${o}.json`);await J(s,a,{flag:`wx`});try{await An({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await q(s,{force:!0})}return o}async function Nn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=L(r,`reference-${Y()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await K(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return on(r.revision),an(r.snapshot),r}finally{await q(i,{force:!0})}}async function Pn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await Nn({bucket:e,key:un(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 Fn({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await jn({bucket:e,key:un(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await jn({bucket:e,key:dn(t,i),reference:n,store:r,temporaryDirectory:a})}async function In({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){an(n);let o=L(z(t),`v1`,`sha256`,n.slice(0,2),n);if(await Rn(o,n)===!1){await G(F(o),{recursive:!0});let t=`${o}.${process.pid}.${Y()}.tmp`;try{if(await i.download(e,ln(r,n),t),await On(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await q(o,{force:!0}),await Ce(t,o)}finally{await q(t,{force:!0})}}await G(F(a),{recursive:!0});let s=`${a}.${process.pid}.${Y()}.tmp`;try{if(await _e(o,s),await On(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await q(a,{force:!0}),await Ce(s,a)}finally{await q(s,{force:!0})}}async function Ln({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=L(a,`manifest-${n}.json`);await In({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await K(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}.`);on(s.revision),s.baseline!==void 0&&an(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}.`);an(e.digest)}return s}async function Rn(e,t){try{return(await we(e)).isFile()&&await On(e)===t}catch{return!1}}async function zn({cwd:e=process.cwd(),env:t=process.env}={}){if((await Me({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await Hn({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await mn(e)}}async function Bn({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await Me({cwd:e});if(!n.i18n)return;let r=Un(n.i18n),i=Q(e,r.directory);try{if(!(await we(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await mn(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await we(Q(e,$(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 mn(e);return}}async function Vn({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){fn(r);let i=await Wn({cwd:e,env:t,store:n});await Qn(e);let a=await Zn(e);await $n(e,r,a);let o=await be(L(Oe(),`coreframe-i18n-prepare-`));try{let n=await Pn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Ln({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return Xn(i,e,a),await Kn(i,e),await Fn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await Yn(i,o,async()=>{let n=await Gn(i,a,o);n||await Jn(i),await mn(e);let s=await gn({config:i.config,cwd:e}),c=await _n({config:i.config,cwd:e,env:t,messages:s});await vn({config:i.config,cwd:e,missing:s,response:c}),await yn({config:i.config,cwd:e}),await hn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await qn(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await er(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await Mn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Fn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:{revision:a,snapshot:d,version:1},store:i.store,tag:r,temporaryDirectory:o}),{reused:!1,snapshot:d}})}finally{await q(o,{force:!0,recursive:!0})}}async function Hn({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await Me({cwd:e});if(!i.i18n)return;let a=await Wn({cwd:e,env:t,store:r,projectConfig:i}),o=on(n??await Zn(e)),s=await be(L(Oe(),`coreframe-i18n-materialize-`));try{let e=await Pn({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 Ln({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return Xn(a,t,o),await Kn(a,t),{revision:o,snapshot:e.snapshot}}finally{await q(s,{force:!0,recursive:!0})}}function Un(e){let t=sn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>sn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>sn(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 Wn({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await Me({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:z(e,`.coreframe`,`i18n`,`cache`),config:Un(i.i18n),cwd:z(e),env:t,store:r??me({config:a,env:t})}}async function Gn(e,t,n){let{stdout:r}=await V(`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 Pn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:on(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Ln({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return Xn(e,i,t),await Kn(e,i),r.snapshot}}async function Kn(e,t){for(let n of t.files)if(await In({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:Q(e.cwd,n.path)}),(await we(Q(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function qn(e){let t=[];for(let n of e.config.locales)for(let r of e.config.catalogs){let i=$(e.config,n,r),a=Q(e.cwd,i),o=await On(a);await An({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await we(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function Jn(e){let{stdout:t}=await V(`git`,[`rev-parse`,`--show-prefix`],{cwd:e.cwd,stdin:`ignore`}),n=t.trim(),{stdout:r}=await V(`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 ke(`@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 V(`git`,[`show`,`${i}:${s}`],{cwd:e.cwd,stdin:`ignore`});await xn(Q(e.cwd,$(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function Yn(e,t,n){let r=[];for(let n of e.config.locales)for(let i of e.config.catalogs){let a=$(e.config,n,i),o=Q(e.cwd,a);try{await he(o)}catch{continue}let s=L(t,`previous-catalogs`,a);await G(F(s),{recursive:!0}),await Ce(o,s),r.push({backup:s,path:o})}try{let e=await n();return await q(L(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 q(Q(e.cwd,$(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await G(F(t),{recursive:!0}),await Ce(e,t);throw t}}function Xn(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=>$(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 Zn(e){let{stdout:t}=await V(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return on(t.trim())}async function Qn(e){let{stdout:t}=await V(`git`,[`status`,`--porcelain`],{cwd:e,stdin:`ignore`});if(t.trim())throw Error(`Tagged i18n preparation requires a clean Git tree.`)}async function $n(e,t,n){let{stdout:r}=await V(`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 er(e){let{stdout:t}=await V(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const tr=[`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(` `),nr=n(u,{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}}),rr=n(u,{displayName:`profile`,async from(e){return fe(e)}}),ir=n(u,{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}}),ar=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return M(e)}}),or=d({name:`assets`,cmds:{configure:t({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${tr}`,args:{profile:c({type:rr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{H.note(tr,`Required B2 key access`);let t=await H.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(H.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await H.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(H.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await pe({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:t({name:`add`,args:{file:c({type:u,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:o({long:`id`,type:u,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:o({long:`alt`,type:s(u),description:`Required alt text for raster image and SVG assets.`}),pack:o({long:`pack`,type:s(ir),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:o({long:`widths`,type:s(nr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>W(await U({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:t({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:o({long:`branch`,type:u,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await ce({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:t({name:`build`,args:{id:o({long:`id`,type:s(u),description:`Build only one logical asset ID.`}),pack:o({long:`pack`,type:s(ir),description:`Build only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>W(await le({id:e,pack:n}),t,{kind:`build`})}),check:t({name:`check`,args:{fix:r({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:o({long:`pack`,type:s(ir),description:`Check only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await ue({fix:e,pack:n});W(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:t({name:`publish`,args:{pack:o({long:`pack`,type:s(ir),description:`Publish only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await de({pack:t});W(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:t({name:`status`,args:{pack:o({long:`pack`,type:s(ir),description:`Report status for only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await ue({pack:t});W(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),sr=d({name:`flutter`,cmds:{acceptance:t({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:ar,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>N({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:t({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:r({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>j({check:e})}),prepare:t({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:c({type:a(A),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:ar,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>oe({apiOrigin:e,platform:t})}),check:t({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:c({type:a(A),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:ar,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>k({apiOrigin:e,platform:t})})}}),cr=d({name:`i18n`,cmds:{build:t({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await zn()}}),materialize:t({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:o({long:`revision`,type:s(u),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Hn({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:t({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot.`,args:{tag:o({long:`tag`,type:u,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await Vn({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),lr=X.platform===`win32`?`react-router.cmd`:`react-router`,ur=X.platform===`win32`?`panda.cmd`:`panda`;async function dr(e=X.cwd()){await mr(e),await pr(e,[`typegen`])}async function fr(e=X.cwd(),t=X.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=P.resolve(e,`.coreframe/dashboard-build`),i=P.join(r,`client`),a=P.resolve(e,`dist/client/__dashboard`);await q(r,{force:!0,recursive:!0}),await hr(e,ur,[`build`],t),await pr(e,[`build`,...n?[`--mode`,n]:[]],t),await q(a,{force:!0,recursive:!0}),await G(P.dirname(a),{recursive:!0}),await ve(i,a,{recursive:!0})}async function pr(e,t,n=X.env){await hr(e,lr,t,n)}async function mr(e){await q(P.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function hr(e,t,n,r=X.env){await V(t,n,{cwd:P.resolve(e,`dashboard`),env:{...r,PATH:P.resolve(e,`node_modules/.bin`)+P.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const gr={access:he,chmod:ge,mkdir:G,mkdtemp:be,readFile:K,readFileSync:Be,rm:q,writeFile:J},_r={getAvailablePort:yr},vr={homedir:Ee,kill:X.kill,networkInterfaces:De,tmpdir:Oe};async function yr(){let e=Xe();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 br({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 xr(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=Xe(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 xr(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await Sr(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 Sr({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=Ye({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 Cr=X.platform===`win32`?`react-router.cmd`:`react-router`;function wr(e){return Ie(P.resolve(e,`dashboard/dashboard.config.ts`))}function Tr(e){return[`exec`,`coreframe`,`dashboard`,`dev`,`--port`,String(e)]}function Er({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 X.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([Ke(t.stdout),Ke(t.stderr)]),i===e&&(i=void 0)}};a=br({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await _r.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=qe({label:`dashboard`}),s=qe({color:`red`,label:`dashboard`});a.pipe(X.stdout,{end:!1}),s.pipe(X.stderr,{end:!1});let l=V(Cr,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:P.resolve(e,`dashboard`),env:{...t,PATH:P.resolve(e,`node_modules/.bin`)+P.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Or(l.stdout,a),Or(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)X.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function Dr({cwd:e=X.cwd(),env:t=X.env,port:n}){let r=Er({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Or(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const kr=d({name:`dashboard`,cmds:{dev:t({name:`dev`,args:{port:o({long:`port`,type:i,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>Dr({port:e})}),build:t({name:`build`,args:{mode:o({long:`mode`,type:s(u),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>fr(void 0,void 0,e)}),typegen:t({name:`typegen`,args:{},handler:()=>dr()})}}),Ar=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function jr(e,t){let n=Nr(e,t);if(!Pr(n)||!Fr(n,[`description`,`requires`,`routes`,`verifier`])||!Lr(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Lr))||n.verifier!==void 0&&!Lr(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=>Mr(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Pr(e)||!Ir(e,[`path`,`router`,`when`])||!Lr(e.path)||!Lr(e.router)||!Lr(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 Mr(e){if(!Ar.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Nr(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Pr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fr(e,t){return Object.keys(e).every(e=>t.includes(e))}function Ir(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Lr(e){return typeof e==`string`&&e.length>0}const Rr=`https://github.com/airlock-labs/coreframe.git`;function zr(e,t){return Z(`git`,e,{cwd:t,encoding:`utf8`})}function Br(e,t){let n=zr(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 Vr(e,t){let n=zr([`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 Hr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Br([`rev-parse`,`--show-toplevel`],e);let r=Vr(n,e);if(r===null)Br([`remote`,`add`,n,Rr],e),console.log(`Added ${n} remote: ${Rr}`);else if(r===Rr)console.log(`${n} remote already points at ${Rr}`);else throw Error(`${n} remote points at ${r}, not ${Rr}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(Br([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const Ur=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function Wr(e){return Ur.test(e)?`v${e}`:e}function Gr(e){return`${Wr(e)}:template`}function Kr(e,t){return`${Gr(e)}/${t}`}function qr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=Zr(e),a=ti(i,[`rev-parse`,`--show-toplevel`]),o=Wr(r??Qr(i));return Hr({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function Jr(e,t,n){return Yr(e,t,n).toString(`utf8`)}function Yr(e,t,n){let r=`${t}:${n}`,i=Z(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${ni([`show`,r],i)}`);return i.stdout}function Xr(e,t,n){let r=Z(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(ni([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function Zr(e){let t=z(e);for(;;){let e=L(t,`package.json`),n=ei(e);if(n!==void 0&&$r(n,e).engines?.coreframe)return t;let r=F(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function Qr(e){let t=L(e,`package.json`),n=ei(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=$r(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function $r(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ei(e){try{return Be(e,`utf8`)}catch(e){if(ri(e)&&e.code===`ENOENT`)return;throw e}}function ti(e,t){let n=Z(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ni(t,n));return n.stdout.trim()}function ni(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 ri(e){return e instanceof Error&&`code`in e}const ii=[{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:si},{path:`src/api/client/app-origin.ts`,requirement:`allow the Flutter shell to provide its exact API origin`,test:e=>oi(e,[`@coreframe/flutter-js/client`,`resolveAppOrigin`,`browserOrigin: location?.origin`])},{path:`src/api/worker/auth-config.ts`,requirement:`trust the exact Flutter authentication origins`,test:e=>oi(e,[`appendFlutterAuthOrigins`,`appendFlutterAuthOrigins([], development)`])},{path:`src/api/worker/middleware/auth.ts`,requirement:`broker Flutter access tokens and accept Flutter bearer origins`,test:e=>oi(e,[`createFlutterAccessTokenResponse`,`isFlutterAuthOrigin(origin, import.meta.env.DEV)`,`readFlutterBearerToken(request, import.meta.env.DEV, developmentOrigin)`,`native && ctx.request.method !== "GET"`])&&!e.includes(`isNativeOrigin`)},{path:`src/api/worker/middleware/flutter-cors.ts`,requirement:`provide the Flutter packaged-origin CORS boundary`,test:e=>oi(e,[`applyFlutterCors`,`handleFlutterCorsPreflight`,`flutterCorsMiddleware`])},{path:`src/api/worker/middleware/index.ts`,requirement:`apply Flutter CORS to ordinary Worker responses`,test:e=>e.includes(`flutterCorsMiddleware`)},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>oi(e,[`configureShellQueryFocus`,`authSessionHint`])},{path:`src/web/entry.client.tsx`,requirement:`load the package-owned Flutter development tools only for non-browser development`,test:e=>oi(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}];function ai(e){let t=[];for(let n of ii){let r=L(e,n.path);if(!Ie(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=Be(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}return t}function oi(e,t){return t.every(t=>e.includes(t))}function si(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 ci({name:e,...t}){let n=qr(t),r=`recipes/${e}/recipe.yaml`,i=di(jr(Jr(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(`
|
|
8
|
-
`)}`);return{name:e,ref:n.ref}}function
|
|
9
|
-
`)}\nApply and verify ${n} before continuing.`)}}function
|
|
10
|
-
`)])),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
|
|
5
|
+
`)}function $t(e){return[`Windows release build succeeded.`,``,`The unpackaged application bundle is at ${JSON.stringify(P(e,`src-flutter/build/windows/x64/runner/Release`))}.`,`Create and sign an installer with the Windows packaging workflow for distribution.`].join(`
|
|
6
|
+
`)}function en(e){return[`Linux release build succeeded.`,``,`The application bundle is at ${JSON.stringify(P(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 tn({apiOrigin:e,cwd:t=process.cwd(),environment:n=process.env,platform:r=`web`,profile:i=!1,simulator:a=!1,prepareClient:o=D,runCommand:s=rn}={}){nn(r,{profile:i,simulator:a});let c={...n};delete c[Vt],delete c[Ht],delete c.COREFRAME_PLATFORM,delete c.TAURI_ENV_PLATFORM;let l=r===`web`?void 0:O(e??n.COREFRAME_API_ORIGIN);for(let e of Yt(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(Zt(t,{profile:i})):r===`ios`?console.log(Qt(t,{profile:i,simulator:a})):r===`windows`?console.log($t(t)):r===`linux`&&console.log(en(t))}function nn(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 rn(e,t,{cwd:n,env:r}){await I(e,t,{cwd:n,env:r,stdio:`inherit`})}function an(e,t,n,r){return{kind:`command`,command:e,args:t,cwd:n,...r===void 0?{}:{environment:r}}}const on=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in a packaged Flutter client.`,async from(e){return O(e)}}),sn=t({name:`build`,description:`Build the web client or a Flutter app (release by default). Tauri is not built.`,args:{platform:c({type:s(a(Jt)),displayName:`platform`,description:`Build target: web, iOS, Android, macOS, Windows, or Linux. Defaults to web.`}),apiOrigin:o({long:`api-origin`,type:s(on),description:`Exact production HTTPS API origin for a Flutter build. Defaults to COREFRAME_API_ORIGIN.`}),profile:r({long:`profile`,description:`Build a Flutter profile app instead of the default release app.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Build iOS for the simulator instead of a physical device.`,defaultValue:()=>!1})},handler:({apiOrigin:e,platform:t,profile:n,simulator:r})=>tn({apiOrigin:e,platform:t,profile:n,simulator:r})}),cn=/^[a-f0-9]{64}$/,ln=/^[a-f0-9]{40}$/,un=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function dn(e){if(!cn.test(e))throw Error(`Invalid SHA-256 digest "${e}".`);return e}function fn(e){if(!ln.test(e))throw Error(`Invalid full Git revision "${e}".`);return e}function pn(e,t){if(!un.test(e))throw Error(`${t} must contain only letters, numbers, dots, underscores, or hyphens.`);return e}function mn(e){return`projects/${pn(e,`Project ID`)}/i18n/v1`}function hn(e,t){return dn(t),`${mn(e)}/objects/sha256/${t.slice(0,2)}/${t}`}function gn(e,t){return fn(t),`${mn(e)}/commits/${t}.json`}function _n(e,t){return vn(t),`${mn(e)}/releases/${encodeURIComponent(t)}.json`}function vn(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=P(e),r=P(n,t);if(r!==n&&!r.startsWith(`${n}${F}`))throw Error(`Unsafe i18n artifact path "${t}".`);return r}function Z(e,t,n){return`${e.directory}/${t}/${n}.json`}function yn(e,t,n){return`${e.directory}/${t}/${n}.mjs`}async function bn(e){await I(`pnpm`,[`exec`,`lingui`,`extract`],{cwd:e,stdio:`inherit`})}async function xn({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 En(o),c=Object.fromEntries(Object.entries(s).filter(([,e])=>!e.obsolete)),l=M(r,`${n}-${a}.json`);await R(j(l),{recursive:!0}),await Te(o,l),i.push({path:o,backup:l}),await Dn(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 Te(t,e)}finally{for(let n of e.locales)for(let r of e.catalogs)await B(X(t,yn(e,n,r)),{force:!0})}}}async function Sn({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 En(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)=>Mn(e).localeCompare(Mn(t)))}async function Cn({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 On(await kn({args:e.generator.args??[],command:e.generator.command,cwd:t,env:r,input:JSON.stringify(i)}))}async function wn({config:e,cwd:t,missing:n,response:r}){let i=new Map(n.map(e=>[Mn(e),e])),a=new Map;for(let e of r.translations){let t=Mn(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 Pe(`@lingui/message-utils/compileMessage`,t);for(let e of n){let t=a.get(Mn(e));An({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 En(i),s=!1;for(let[e,t]of Object.entries(o)){let i=a.get(Mn({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 Dn(i,o)}}async function Tn({config:e,cwd:t}){let n=await Sn({config:e,cwd:t});if(n.length>0)throw Error(`I18n catalogs remain incomplete: ${n.length} translations are missing.`);let r=await Pe(`@lingui/message-utils/compileMessage`,t);for(let n of e.locales)if(n!==e.sourceLocale)for(let i of e.catalogs){let a=await En(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}.`);An({compileMessage:r,id:e,locale:n,source:t.message,translation:t.translation})}}}async function En(e){let t=JSON.parse(await z(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 Dn(e,t){await R(j(e),{recursive:!0});let n=`${e}.${process.pid}.tmp`;await V(n,`${JSON.stringify(t,null,2)}\n`),await ke(n,e)}function On(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 kn({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 An({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=jn(a),c=jn(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 jn(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 Mn(e){return`${e.locale}\0${e.catalog}\0${e.id}`}function Nn(e){return Re(`sha256`).update(e).digest(`hex`)}async function Pn(e){return Nn(await z(e))}function Fn(e){return Buffer.from(`${JSON.stringify(e,null,2)}\n`)}async function In({bucket:e,digest:t,projectId:n,source:r,store:i}){if(dn(t),await Pn(r)!==t)throw Error(`I18n object source does not match declared SHA-256 digest ${t}.`);let a=hn(n,t);await i.has(e,a)||await i.upload(e,a,r,`application/octet-stream`);let o=`${r}.${process.pid}.${U()}.verify`;try{if(await i.download(e,a,o),await Pn(o)!==t)throw Error(`Existing immutable i18n object ${a} failed integrity verification.`)}finally{await B(o,{force:!0})}}async function Ln({bucket:e,key:t,reference:n,store:r,temporaryDirectory:i}){let a=Fn(n),o=M(i,`reference-${U()}.json`);if(await r.has(e,t))try{if(await r.download(e,t,o),!(await z(o)).equals(a))throw Error(`Immutable i18n reference ${t} already resolves to different snapshot data.`);return}finally{await B(o,{force:!0})}await V(o,a,{flag:`wx`});try{await r.upload(e,t,o,`application/json`)}finally{await B(o,{force:!0})}let s=M(i,`reference-${U()}.verify.json`);try{if(await r.download(e,t,s),!(await z(s)).equals(a))throw Error(`Uploaded immutable i18n reference ${t} failed verification.`)}finally{await B(s,{force:!0})}}async function Rn({bucket:e,manifest:t,projectId:n,store:r,temporaryDirectory:i}){let a=Fn(t),o=Nn(a),s=M(i,`manifest-${o}.json`);await V(s,a,{flag:`wx`});try{await In({bucket:e,digest:o,projectId:n,source:s,store:r})}finally{await B(s,{force:!0})}return o}async function zn({bucket:e,key:t,store:n,temporaryDirectory:r}){if(!await n.has(e,t))return;let i=M(r,`reference-${U()}.json`);try{await n.download(e,t,i);let r=JSON.parse(await z(i,`utf8`));if(r.version!==1||typeof r.revision!=`string`||typeof r.snapshot!=`string`)throw Error(`Invalid i18n reference at ${t}.`);return fn(r.revision),dn(r.snapshot),r}finally{await B(i,{force:!0})}}async function Bn({bucket:e,projectId:t,revision:n,store:r,temporaryDirectory:i}){let a=await zn({bucket:e,key:gn(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 Vn({bucket:e,projectId:t,reference:n,store:r,tag:i,temporaryDirectory:a}){await Ln({bucket:e,key:gn(t,n.revision),reference:n,store:r,temporaryDirectory:a}),i&&await Ln({bucket:e,key:_n(t,i),reference:n,store:r,temporaryDirectory:a})}async function Hn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:a}){dn(n);let o=M(P(t),`v1`,`sha256`,n.slice(0,2),n);if(await Wn(o,n)===!1){await R(j(o),{recursive:!0});let t=`${o}.${process.pid}.${U()}.tmp`;try{if(await i.download(e,hn(r,n),t),await Pn(t)!==n)throw Error(`Downloaded i18n object failed SHA-256 verification: ${n}.`);await B(o,{force:!0}),await ke(t,o)}finally{await B(t,{force:!0})}}await R(j(a),{recursive:!0});let s=`${a}.${process.pid}.${U()}.tmp`;try{if(await Te(o,s),await Pn(s)!==n)throw Error(`Cached i18n object failed SHA-256 verification: ${n}.`);await B(a,{force:!0}),await ke(s,a)}finally{await B(s,{force:!0})}}async function Un({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,temporaryDirectory:a}){let o=M(a,`manifest-${n}.json`);await Hn({bucket:e,cacheRoot:t,digest:n,projectId:r,store:i,target:o});let s=JSON.parse(await z(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}.`);fn(s.revision),s.baseline!==void 0&&dn(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}.`);dn(e.digest)}return s}async function Wn(e,t){try{return(await Ae(e)).isFile()&&await Pn(e)===t}catch{return!1}}async function Gn({cwd:e=process.cwd(),env:t=process.env}={}){if((await H({cwd:e})).i18n){if(t.COREFRAME_I18N_RELEASE_REVISION){await Jn({cwd:e,env:t,revision:t.COREFRAME_I18N_RELEASE_REVISION});return}await bn(e)}}async function Kn({cwd:e=process.cwd(),projectConfig:t}={}){let n=t??await H({cwd:e});if(!n.i18n)return;let r=Yn(n.i18n),i=X(e,r.directory);try{if(!(await Ae(i)).isDirectory())throw Error(`I18n catalog path is not a directory: ${i}.`)}catch(t){if(t.code!==`ENOENT`)throw t;await bn(e);return}for(let t of r.locales)for(let n of r.catalogs)try{if(!(await Ae(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 bn(e);return}}async function qn({cwd:e=process.cwd(),env:t=process.env,store:n,tag:r}){vn(r);let i=await Xn({cwd:e,env:t,store:n});await ir(e);let a=await rr(e);await ar(e,r,a);let o=await De(M(Ne(),`coreframe-i18n-prepare-`));try{let n=await Bn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,revision:a,store:i.store,temporaryDirectory:o});if(n){let e=await Un({bucket:i.assets.sourceBucket,cacheRoot:i.cacheRoot,digest:n.snapshot,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return nr(i,e,a),await Qn(i,e),await Vn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:n,store:i.store,tag:r,temporaryDirectory:o}),{reused:!0,snapshot:n.snapshot}}return await tr(i,o,async()=>{let n=await Zn(i,a,o);n||await er(i),await bn(e);let s=await Sn({config:i.config,cwd:e}),c=await Cn({config:i.config,cwd:e,env:t,messages:s});await wn({config:i.config,cwd:e,missing:s,response:c}),await Tn({config:i.config,cwd:e}),await xn({config:i.config,cwd:e,strict:!0,temporaryDirectory:o});let l=await $n(i),u={...n?{baseline:n}:{},catalogs:i.config.catalogs,files:l,generator:s.length>0?i.config.generator?.id??`unconfigured`:`none`,linguiVersion:await or(e),locales:i.config.locales,projectId:i.assets.projectId,revision:a,sourceLocale:i.config.sourceLocale,version:1},d=await Rn({bucket:i.assets.sourceBucket,manifest:u,projectId:i.assets.projectId,store:i.store,temporaryDirectory:o});return await Vn({bucket:i.assets.sourceBucket,projectId:i.assets.projectId,reference:{revision:a,snapshot:d,version:1},store:i.store,tag:r,temporaryDirectory:o}),{reused:!1,snapshot:d}})}finally{await B(o,{force:!0,recursive:!0})}}async function Jn({cwd:e=process.cwd(),env:t=process.env,revision:n,store:r}={}){let i=await H({cwd:e});if(!i.i18n)return;let a=await Xn({cwd:e,env:t,store:r,projectConfig:i}),o=fn(n??await rr(e)),s=await De(M(Ne(),`coreframe-i18n-materialize-`));try{let e=await Bn({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 Un({bucket:a.assets.sourceBucket,cacheRoot:a.cacheRoot,digest:e.snapshot,projectId:a.assets.projectId,store:a.store,temporaryDirectory:s});return nr(a,t,o),await Qn(a,t),{revision:o,snapshot:e.snapshot}}finally{await B(s,{force:!0,recursive:!0})}}function Yn(e){let t=pn(e.sourceLocale,`Source locale`),n=[...new Set(e.locales.map(e=>pn(e,`Locale`)))],r=[...new Set(e.catalogs.map(e=>pn(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 Xn({cwd:e=process.cwd(),env:t=process.env,projectConfig:n,store:r}){let i=n??await H({cwd:e});if(!i.i18n)throw Error(`Missing i18n configuration in coreframe.config.ts.`);if(!i.assets)throw Error(`I18n snapshots require the existing private build bucket configured under assets.`);let a=i.assets;return{assets:a,cacheRoot:P(e,`.coreframe`,`i18n`,`cache`),config:Yn(i.i18n),cwd:P(e),env:t,store:r??Se({config:a,env:t})}}async function Zn(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 Bn({bucket:e.assets.sourceBucket,projectId:e.assets.projectId,revision:fn(t),store:e.store,temporaryDirectory:n});if(!r)continue;let i=await Un({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:r.snapshot,projectId:e.assets.projectId,store:e.store,temporaryDirectory:n});return nr(e,i,t),await Qn(e,i),r.snapshot}}async function Qn(e,t){for(let n of t.files)if(await Hn({bucket:e.assets.sourceBucket,cacheRoot:e.cacheRoot,digest:n.digest,projectId:e.assets.projectId,store:e.store,target:X(e.cwd,n.path)}),(await Ae(X(e.cwd,n.path))).size!==n.size)throw Error(`Materialized i18n artifact size does not match manifest: ${n.path}.`)}async function $n(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 Pn(a);await In({bucket:e.assets.sourceBucket,digest:o,projectId:e.assets.projectId,source:a,store:e.store}),t.push({digest:o,path:i,size:(await Ae(a)).size})}return t.sort((e,t)=>e.path.localeCompare(t.path))}async function er(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 Pe(`@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 Dn(X(e.cwd,Z(e.config,t,r)),a.parse(n)),o=!0}catch{}}return o}async function tr(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 Ce(o)}catch{continue}let s=M(t,`previous-catalogs`,a);await R(j(s),{recursive:!0}),await ke(o,s),r.push({backup:s,path:o})}try{let e=await n();return await B(M(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 B(X(e.cwd,Z(e.config,t,n)),{force:!0});for(let{backup:e,path:t}of r)await R(j(t),{recursive:!0}),await ke(e,t);throw t}}function nr(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 rr(e){let{stdout:t}=await I(`git`,[`rev-parse`,`HEAD`],{cwd:e,stdin:`ignore`});return fn(t.trim())}async function ir(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 ar(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 or(e){let{stdout:t}=await I(`pnpm`,[`exec`,`lingui`,`--version`],{cwd:e,stdin:`ignore`});return t.trim()}const sr=[`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(` `),cr=n(u,{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}}),lr=n(u,{displayName:`profile`,async from(e){return be(e)}}),ur=n(u,{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}}),dr=n(u,{displayName:`origin`,description:`Exact production HTTPS API origin embedded in the packaged Flutter client.`,async from(e){return O(e)}}),fr=d({name:`assets`,cmds:{configure:t({name:`configure`,description:`Store a Backblaze B2 private build-object key in the operating system credential store. ${sr}`,args:{profile:c({type:lr,displayName:`profile`,description:`Credential profile named by coreframe.config.ts.`})},handler:async({profile:e})=>{L.note(sr,`Required B2 key access`);let t=await L.text({message:`Backblaze B2 application key ID`,validate:e=>e?.trim()?void 0:`The application key ID is required.`});if(L.isCancel(t))throw Error(`Asset credential configuration was cancelled.`);let n=await L.password({message:`Backblaze B2 application key`,validate:e=>e?void 0:`The application key is required.`});if(L.isCancel(n))throw Error(`Asset credential configuration was cancelled.`);await xe({applicationKey:n,applicationKeyId:t.trim(),profile:e}),console.log(`Stored Coreframe asset credential profile "${e}".`)}}),add:t({name:`add`,args:{file:c({type:u,displayName:`file`,description:`Source raster image, SVG, MP3, MP4, or Lottie JSON to add to the asset library.`}),id:o({long:`id`,type:u,description:`Logical asset ID, such as blog/my-post/hero.`}),alt:o({long:`alt`,type:s(u),description:`Required alt text for raster image and SVG assets.`}),pack:o({long:`pack`,type:s(ur),description:`Place the asset in a named, lazily loaded pack.`}),variantWidths:o({long:`widths`,type:s(cr),description:`Generate exactly these raster-image widths instead of the default ladder.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({alt:e,file:t,id:n,json:r,pack:i,variantWidths:a})=>ve(await me({alt:e,file:t,id:n,pack:i,variantWidths:a}),r,{kind:`add`,assetId:n})}),backup:t({name:`backup`,description:`Back up every object in both configured asset buckets to a new Git branch.`,args:{branch:o({long:`branch`,type:u,description:`Name of the new local Git branch that will contain the backup.`})},handler:async({branch:e})=>{let t=await he({branch:e});console.log(`Backed up ${t.objects} objects (${t.bytes} bytes) to branch "${t.branch}" at ${t.commit}.`)}}),build:t({name:`build`,args:{id:o({long:`id`,type:s(u),description:`Build only one logical asset ID.`}),pack:o({long:`pack`,type:s(ur),description:`Build only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({id:e,json:t,pack:n})=>ve(await ge({id:e,pack:n}),t,{kind:`build`})}),check:t({name:`check`,args:{fix:r({long:`fix`,description:`Migrate asset state and build missing generated output when possible.`,defaultValue:()=>!1}),pack:o({long:`pack`,type:s(ur),description:`Check only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({fix:e,json:t,pack:n})=>{let r=await _e({fix:e,pack:n});ve(r,t,{kind:`check`}),r.ok||(process.exitCode=1)}}),publish:t({name:`publish`,args:{pack:o({long:`pack`,type:s(ur),description:`Publish only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await ye({pack:t});ve(n,e,{kind:`publish`}),n.ok||(process.exitCode=1)}}),status:t({name:`status`,args:{pack:o({long:`pack`,type:s(ur),description:`Report status for only one named asset pack.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e,pack:t})=>{let n=await _e({pack:t});ve(n,e,{kind:`status`}),n.ok||(process.exitCode=1)}})}}),pr=d({name:`flutter`,cmds:{acceptance:t({name:`acceptance`,description:`Run the complete packaged Flutter conformance gate on macOS.`,args:{apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e})=>k({environment:{...process.env,COREFRAME_API_ORIGIN:e}})}),codegen:t({name:`codegen`,description:`Generate Flutter bridge contracts and Panda-backed Mix theme tokens.`,args:{check:r({long:`check`,description:`Fail when generated Flutter artifacts are missing or stale.`,defaultValue:()=>!1})},handler:({check:e})=>de({check:e})}),prepare:t({name:`prepare`,description:`Build and package the React client for one Flutter platform.`,args:{platform:c({type:a(E),displayName:`platform`,description:`Flutter platform whose packaged client should be prepared.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>D({apiOrigin:e,platform:t})}),check:t({name:`check`,description:`Reject missing, stale, modified, or incorrectly targeted Flutter assets.`,args:{platform:c({type:a(E),displayName:`platform`,description:`Flutter platform whose packaged client should be checked.`}),apiOrigin:o({long:`api-origin`,env:`COREFRAME_API_ORIGIN`,type:dr,description:`Defaults to COREFRAME_API_ORIGIN.`})},handler:({apiOrigin:e,platform:t})=>ce({apiOrigin:e,platform:t})})}}),mr=d({name:`i18n`,cmds:{build:t({name:`build`,description:`Extract source messages or materialize an exact release catalog snapshot.`,args:{},handler:async()=>{await Gn()}}),materialize:t({name:`materialize`,description:`Materialize the immutable i18n snapshot for an exact commit.`,args:{revision:o({long:`revision`,type:s(u),description:`Full commit SHA. Defaults to the checked-out commit.`})},handler:async({revision:e})=>{let t=await Jn({revision:e});t&&console.log(`Materialized i18n snapshot ${t.snapshot}.`)}}),prepare:t({name:`prepare`,description:`Fill missing translations, strictly compile, and publish an immutable tagged snapshot.`,args:{tag:o({long:`tag`,type:u,description:`Pushed v* release tag that points to the checked-out commit.`})},handler:async({tag:e})=>{let t=await qn({tag:e});console.log(`${t.reused?`Reused`:`Published`} i18n snapshot ${t.snapshot}.`)}})}}),hr=W.platform===`win32`?`react-router.cmd`:`react-router`,gr=W.platform===`win32`?`panda.cmd`:`panda`;async function _r(e=W.cwd()){await br(e),await yr(e,[`typegen`])}async function vr(e=W.cwd(),t=W.env,n){if((t.COREFRAME_PLATFORM??`web`)!==`web`)return;let r=A.resolve(e,`.coreframe/dashboard-build`),i=A.join(r,`client`),a=A.resolve(e,`dist/client/__dashboard`);if(await B(r,{force:!0,recursive:!0}),(await H({cwd:e})).deploy?.mode===`client`){await B(a,{force:!0,recursive:!0});return}await xr(e,gr,[`build`],t),await yr(e,[`build`,...n?[`--mode`,n]:[]],t),await B(a,{force:!0,recursive:!0}),await R(A.dirname(a),{recursive:!0}),await Ee(i,a,{recursive:!0})}async function yr(e,t,n=W.env){await xr(e,hr,t,n)}async function br(e){await B(A.resolve(e,`dashboard/.react-router`),{force:!0,recursive:!0})}async function xr(e,t,n,r=W.env){await I(t,n,{cwd:A.resolve(e,`dashboard`),env:{...r,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(r.PATH??r.Path??``)},stdio:`inherit`})}const Q={access:Ce,chmod:we,mkdir:R,mkdtemp:De,readFile:z,readFileSync:K,rm:B,writeFile:V},Sr={getAvailablePort:wr},Cr={homedir:je,kill:W.kill,networkInterfaces:Me,tmpdir:Ne};async function wr(){let e=Xe();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 Tr({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 Er(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=Xe(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 Er(e,t){let n=Date.now()+1e4,r;for(;!t();)try{return await Dr(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 Dr({host:e=`127.0.0.1`,port:t}){return new Promise((n,r)=>{let i=Ye({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 Or=W.platform===`win32`?`react-router.cmd`:`react-router`;function kr(e){return G(A.resolve(e,`dashboard/dashboard.config.ts`))}function Ar({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 W.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([qe(t.stdout),qe(t.stderr)]),i===e&&(i=void 0)}};a=Tr({port:n,start:async()=>{if(o)throw Error(`The dashboard development server was stopped before it started.`);let n=await Sr.getAvailablePort();if(o)throw Error(`The dashboard development server was stopped before it started.`);let a=J({label:`dashboard`}),s=J({color:`red`,label:`dashboard`});a.pipe(W.stdout,{end:!1}),s.pipe(W.stderr,{end:!1});let l=I(Or,[`dev`,`--host`,`127.0.0.1`,`--port`,String(n)],{cwd:A.resolve(e,`dashboard`),env:{...t,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+r},stdin:`inherit`});i=l;let d=Promise.allSettled([Mr(l.stdout,a),Mr(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)W.off(t,e)})(),s);return{close:d,listen:()=>a.listen(),wait:()=>a.wait()}}async function jr({cwd:e=W.cwd(),env:t=W.env,port:n}){let r=Ar({cwd:e,env:t,port:n});try{await r.listen(),await r.wait()}finally{await r.close()}}async function Mr(e,t){for await(let n of e)t.write(`${n}\n`)||await new Promise(e=>t.once(`drain`,e))}const Nr=d({name:`dashboard`,cmds:{dev:t({name:`dev`,args:{port:o({long:`port`,type:i,description:`Local TCP port for the dashboard proxy.`})},handler:({port:e})=>jr({port:e})}),build:t({name:`build`,args:{mode:o({long:`mode`,type:s(u),description:`Vite environment mode used for the dashboard build.`})},handler:({mode:e})=>vr(void 0,void 0,e)}),typegen:t({name:`typegen`,args:{},handler:()=>_r()})}}),Pr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Fr(e,t){let n=Lr(e,t);if(!Rr(n)||!zr(n,[`description`,`requires`,`routes`,`verifier`])||!Vr(n.description)||n.requires!==void 0&&(!Array.isArray(n.requires)||!n.requires.every(Vr))||n.verifier!==void 0&&!Vr(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=>Ir(e));if(new Set(r).size!==r.length)throw Error(`${t} contains duplicate recipe requirements.`);let i=n.routes.map((e,n)=>{if(!Rr(e)||!Br(e,[`path`,`router`,`when`])||!Vr(e.path)||!Vr(e.router)||!Vr(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 Ir(e){if(!Pr.test(e))throw Error(`Recipe names use lowercase letters, numbers, and single hyphens.`);return e}function Lr(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Rr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zr(e,t){return Object.keys(e).every(e=>t.includes(e))}function Br(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Vr(e){return typeof e==`string`&&e.length>0}const Hr=`https://github.com/coreframe-js/coreframe.git`;function Ur(e,t){return Y(`git`,e,{cwd:t,encoding:`utf8`})}function Wr(e,t){let n=Ur(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 Gr(e,t){let n=Ur([`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 Kr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`}={}){if(n.length===0)throw Error(`Remote name must not be empty.`);Wr([`rev-parse`,`--show-toplevel`],e);let r=Gr(n,e);if(r===null)Wr([`remote`,`add`,n,Hr],e),console.log(`Added ${n} remote: ${Hr}`);else if(r===Hr)console.log(`${n} remote already points at ${Hr}`);else throw Error(`${n} remote points at ${r}, not ${Hr}.\nChoose the intended template source before continuing, then update or rename the remote manually.`);t&&(Wr([`fetch`,n,`--tags`,`--prune`],e),console.log(`Fetched ${n}.`))}const qr=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;function $(e){return qr.test(e)?`v${e}`:e}function Jr(e){return`${$(e)}:template`}function Yr(e,t){return`${Jr(e)}/${t}`}function Xr({cwd:e=process.cwd(),fetch:t=!0,remote:n=`template`,target:r}={}){let i=ei(e),a=ii(i,[`rev-parse`,`--show-toplevel`]),o=$(r??ti(i));return Kr({cwd:a,fetch:t,remote:n}),{projectRoot:i,ref:o,repositoryRoot:a}}function Zr(e,t,n){return Qr(e,t,n).toString(`utf8`)}function Qr(e,t,n){let r=`${t}:${n}`,i=Y(`git`,[`show`,r],{cwd:e,encoding:`buffer`});if(i.status!==0)throw Error(`Could not read ${r}. ${ai([`show`,r],i)}`);return i.stdout}function $r(e,t,n){let r=Y(`git`,[`ls-tree`,`-r`,`--name-only`,`-z`,t,`--`,n],{cwd:e,encoding:`buffer`});if(r.status!==0)throw Error(ai([`ls-tree`,t,n],r));return r.stdout.toString(`utf8`).split(`\0`).filter(Boolean)}function ei(e){let t=P(e);for(;;){let e=M(t,`package.json`),n=ri(e);if(n!==void 0&&ni(n,e).engines?.coreframe)return t;let r=j(t);if(r===t)throw Error(`Could not find a package.json with engines.coreframe.`);t=r}}function ti(e){let t=M(e,`package.json`),n=ri(t);if(n===void 0)throw Error(`Required file package.json does not exist.`);let r=ni(n,t).engines?.coreframe;if(!r)throw Error(`package.json must declare an exact engines.coreframe recipe baseline.`);return r}function ni(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function ri(e){try{return K(e,`utf8`)}catch(e){if(oi(e)&&e.code===`ENOENT`)return;throw e}}function ii(e,t){let n=Y(`git`,t,{cwd:e,encoding:`utf8`});if(n.status!==0)throw Error(ai(t,n));return n.stdout.trim()}function ai(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 oi(e){return e instanceof Error&&`code`in e}const si=[{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:gi},{path:`src-flutter/pubspec.yaml`,requirement:`declare flutter_driver as a Flutter SDK dependency`,test:_i},{path:`src-flutter/lib/main.dart`,requirement:`gate Flutter Driver behind kDebugMode and ENABLE_FLUTTER_DRIVER before starting Coreframe`,test:vi},{path:`src/web/app/flutter-shell/application.ts`,requirement:`configure the Flutter shell's app-owned query and session hooks`,test:e=>hi(e,[`configureShellQueryFocus`,`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=>hi(e,[`@coreframe/vite/flutter-devtools`,`import.meta.env.PLATFORM !== "web"`])}],ci=`src-flutter/lib/application.dart`,li=`src/api/worker/auth-origin.ts`;function ui(e){let t=[];for(let n of si){let r=M(e,n.path);if(!G(r)){t.push(`${n.path} is missing; it must ${n.requirement}.`);continue}let i=K(r,`utf8`);n.test(i)||t.push(`${n.path} must ${n.requirement}.`)}let n=di(e,t),r=fi(e,t);return n!==void 0&&r!==void 0&&n!==r&&t.push(`${ci} loopbackPort (${n}) must match ${li} FLUTTER_LOOPBACK_ORIGIN (${r}).`),t}function di(e,t){let n=pi(e,ci,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=mi(r??a);return o===void 0&&t.push(`${ci} must configure loopbackPort as a fixed integer port.`),o}function fi(e,t){let n=pi(e,li,t);if(n===void 0)return;let r=mi(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(`${li} must define FLUTTER_LOOPBACK_ORIGIN as an exact localhost origin with a fixed integer port.`),r}function pi(e,t,n){let r=M(e,t);if(!G(r)){n.push(`${t} is missing; it must define the Flutter loopback origin contract.`);return}return K(r,`utf8`)}function mi(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535?t:void 0}function hi(e,t){return t.every(t=>e.includes(t))}function gi(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 _i(e){try{let t=Ze(e);if(!yi(t)||!yi(t.dependencies))return!1;let n=t.dependencies.flutter_driver;return yi(n)&&n.sdk===`flutter`}catch{return!1}}function vi(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 yi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bi({name:e,...t}){let n=Xr(t),r=`recipes/${e}/recipe.yaml`,i=Ci(Fr(Zr(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(`
|
|
8
|
+
`)}`);return{name:e,ref:n.ref}}function xi(e){console.log(`Verified Coreframe recipe ${e.name} from ${e.ref}.`)}function Si(e,t){for(let n of e){let e=`recipes/${n}/recipe.yaml`,r=Ci(Fr(Zr(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(`
|
|
9
|
+
`)}\nApply and verify ${n} before continuing.`)}}function Ci(e,t){if(!e)throw Error(`Required recipe does not declare a verifier.`);if(e===`flutter`)return ui(t);throw Error(`Unknown recipe verifier ${JSON.stringify(e)}.`)}function wi({cwd:e=process.cwd(),fetch:t=!0,name:n,remote:r=`template`,target:i}){Ir(n);let a=Xr({cwd:e,fetch:t,remote:r,target:i}),{projectRoot:o,ref:s,repositoryRoot:c}=a,l=`recipes/${n}`,u=`${l}/recipe.yaml`,d=Fr(Zr(c,s,u),u);Si(d.requires,a);let f=Zr(c,s,`${l}/RECIPE.md`),p=$r(c,s,`${l}/files`),m=$r(c,s,`${l}/patches`),h=$r(c,s,`${l}/.agents`),g=new Map,_=new Map,v=[],ee=[],y=[],b=[],x=[],S=[];for(let e of p){let t=e.slice(`${l}/files/`.length);if(ji(t,`Recipe file ${e}`),t.startsWith(`.agents/`))throw Error(`Recipe file ${e} must be stored in the recipe's .agents directory.`);g.set(t,Qr(c,s,e)),_.set(t,e)}for(let e of h){let t=e.slice(`${l}/`.length);if(Oi(t,`Recipe asset ${e}`),g.has(t))throw Error(`Recipe declares ${t} as both a file and an agent asset.`);g.set(t,Qr(c,s,e)),_.set(t,e)}for(let e of m){let t=Mi(e,l);if(g.has(t))throw Error(`Recipe declares ${t} as both a file and a patch.`);let n=Qr(c,s,e);Ni(n.toString(`utf8`),t,e),Ai(o,t),Pi(o,n,!1)?(v.push({contents:n,destinationPath:t}),b.push(t)):Pi(o,n,!0)?x.push(t):y.push({destination:t,source:e})}let C=new Map;for(let[e,t]of g){let r=Li(Ai(o,e));if(r===void 0)C.set(e,t),ee.push(e);else if(r.equals(t))x.push(e);else if(e.startsWith(`.agents/`))throw Error(`Recipe ${n} cannot replace modified ${e}. Reconcile that agent asset manually.`);else y.push({destination:e,source:_.get(e)})}let w=new Map;for(let e of d.routes){if(Oi(e.router,`Recipe route router`),ki(e.path,`Recipe route path`),g.has(e.router))throw Error(`Recipe cannot replace its destination router ${e.router}.`);if(!g.has(e.path)&&!G(Ai(o,e.path)))throw Error(`Recipe route target ${e.path} does not exist.`);let t=w.get(e.router)??Ei(Ri(Ai(o,e.router),e.router),e.router);w.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 w){t.routes.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path));let n=Ri(Ai(o,e),e),r=Qe(t,{lineWidth:0});r===n?x.push(e):(C.set(e,r),S.push(e))}for(let{destinationPath:e}of v)if(C.has(e))throw Error(`Recipe cannot both write and patch ${e}.`);for(let[e,t]of C){let n=Ai(o,e);Ve(j(n),{recursive:!0}),q(n,t)}return v.length>0&&Fi(o,v.map(({contents:e})=>e)),{created:ee.sort(),instructions:f,mergeRequired:y.sort((e,t)=>e.destination.localeCompare(t.destination)),name:n,patched:b.sort(),ref:s,unchanged:[...new Set(x)].sort(),updated:S.sort()}}function Ti(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 Ei(e,t){let n=Di(e,t);if(!zi(n)||!Bi(n,[`routes`,`rules`])||!Array.isArray(n.rules)||!n.rules.every(Vi)||!Array.isArray(n.routes))throw Error(`${t} must contain only string rules and a routes array.`);let r=n.routes.map((e,n)=>{if(!zi(e)||!Bi(e,[`path`,`when`])||!Vi(e.path)||!Vi(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 Di(e,t){try{return Ze(e)}catch(e){throw Error(`Could not parse ${t}.`,{cause:e})}}function Oi(e,t){if(!e.startsWith(`.agents/`))throw Error(`${t} must be a normalized project-relative path beneath .agents/.`);ji(e,t)}function ki(e,t){if(ji(e,t),!/(?:^|\/)\.agents\/rules\/.+\.md$/u.test(e))throw Error(`${t} must point to a Markdown rule beneath an .agents/rules directory.`)}function Ai(e,t){ji(t,`Recipe destination`);let n=M(e,t),r=e;for(let e of t.split(`/`))if(r=M(r,e),G(r)&&Be(r).isSymbolicLink())throw Error(`Recipe destination ${t} crosses symbolic link ${r}.`);return n}function ji(e,t){if(e.length===0||pe(e)||e===`..`||e.startsWith(`../`)||e.includes(`\\`)||N.normalize(e)!==e)throw Error(`${t} must be a normalized project-relative path.`)}function Mi(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 ji(r,`Recipe patch ${e}`),r}function Ni(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 Pi(e,t,n){let r=[`apply`,`--check`,`--whitespace=nowarn`];return n&&r.push(`--reverse`),r.push(`-`),Y(`git`,r,{cwd:e,input:t}).status===0}function Fi(e,t){let n=Y(`git`,[`apply`,`--whitespace=nowarn`,`-`],{cwd:e,input:Buffer.concat(t.flatMap(e=>[e,Buffer.from(e.at(-1)===10?``:`
|
|
10
|
+
`)])),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 Ii(e){return Li(e)?.toString(`utf8`)}function Li(e){try{return K(e)}catch(e){if(Hi(e)&&e.code===`ENOENT`)return;throw e}}function Ri(e,t){let n=Ii(e);if(n===void 0)throw Error(`Required file ${t} does not exist.`);return n}function zi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bi(e,t){let n=Object.keys(e).sort();return n.length===t.length&&n.every((e,n)=>e===t[n])}function Vi(e){return typeof e==`string`&&e.length>0}function Hi(e){return e instanceof Error&&`code`in e}function Ui(e={}){let{ref:t,repositoryRoot:n}=Xr(e),r=$r(n,t,`recipes`).filter(e=>/^recipes\/[^/]+\/recipe\.yaml$/u.test(e)).map(e=>{let r=e.split(`/`)[1];return Ir(r),{description:Fr(Zr(n,t,e),e).description,name:r}});return r.sort((e,t)=>e.name.localeCompare(t.name)),{recipes:r,ref:t}}function Wi(e){console.log(`Coreframe recipes at ${e.ref}:`);for(let t of e.recipes)console.log(`${t.name} — ${t.description}`)}const Gi=`.agents/skills/coreframe-upgrade/SKILL.md`;function Ki(e,t={}){return Y(`git`,e,t)}function qi(e){return e.stderr.toString(`utf8`).trim()||e.stdout.toString(`utf8`).trim()}function Ji(e,t){let n=Yr(e,t),r=Ki([`show`,n],{encoding:`utf8`});if(r.status!==0){let e=qi(r);throw Error(`Could not read ${n}.${e?` ${e}`:``}`)}return r.stdout.toString()}function Yi(){let e=Ki([`rev-parse`,`--show-toplevel`],{encoding:`utf8`});if(e.status!==0){let t=qi(e);throw Error(`Could not find git repository root.${t?` ${t}`:``}`)}return e.stdout.toString().trim()}function Xi(e,t){let n=He(M(Ne(),`coreframe-upgrade-skill-`)),r=M(n,`SKILL.md`);try{q(r,t);let n=qi(Ki([`--no-pager`,`diff`,`--no-index`,`--color=never`,`--`,e,r]));n&&console.log(n)}finally{We(n,{force:!0,recursive:!0})}}function Zi({apply:e,target:t}){let n=M(Yi(),Gi),r=$(t);if(!G(n))throw Error(`Local ${Gi} does not exist.`);let i=K(n,`utf8`),a=Ji(t,Gi);return i===a?(console.log(`Coreframe upgrade skill matches ${r}:template/${Gi}.`),0):e?(q(n,a),console.error(`Updated ${Gi} from ${r}:template. Reread it before continuing the upgrade.`),20):(console.error(`Coreframe upgrade skill differs from ${r}:template/${Gi}.`),console.error(`Run again with --apply to update it, then reread ${Gi} before continuing.`),Xi(n,a),20)}const Qi=[{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`}],$i=[{matches:e=>e===`src-tauri`||e.startsWith(`src-tauri/`),reason:`legacy Tauri shell removed by breaking host migration`}],ea=new Set([`100644`,`100755`,`120000`]);function ta(e,t={}){return Y(`git`,e,t)}function na(e){let t=ta(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 ra(e){let t=ta(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 ia(){return na([`rev-parse`,`--show-toplevel`]).trim()}function aa(e){let t=M(e,`package.json`);if(!G(t))throw Error(`Missing --base <git-ref>, and package.json does not exist.`);let n=JSON.parse(K(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 oa(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 sa(e,t){let n=oa(ra([`diff`,`--name-status`,`-z`,`--no-renames`,Jr(e),Jr(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 ca(e,t){let n=ra([`ls-tree`,`-z`,`-r`,Jr(e),`--`,t]);if(n.length===0)return null;let r=oa(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 la(e){return ra([`cat-file`,`blob`,e.object])}function ua(e,t){let n=P(e,t),r=e.endsWith(F)?e:`${e}${F}`;if(n!==e&&!n.startsWith(r))throw Error(`Refusing to access path outside repository: ${t}`);return n}function da(e){try{return Be(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}function fa(e){return(e.mode&73)!=0}function pa(e){return e===null||e.type===`blob`&&ea.has(e.mode)}function ma(e){return Qi.find(t=>t.matches(e))?.reason}function ha(e){return $i.find(t=>t.matches(e))?.reason}function ga(e,t,n){let r=ua(e,t);if(n===null)return{matches:!da(r)};if(!pa(n))return{matches:!1,reason:`unsupported template entry mode ${n.mode} ${n.type}`};let i;try{i=Be(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=la(n);return n.mode===`120000`?i.isSymbolicLink()?{matches:Buffer.from(Ue(r),`utf8`).equals(a)}:{matches:!1,reason:`worktree path is not a symlink`}:i.isFile()?(n.mode===`100755`?fa(i):!fa(i))?{matches:K(r).equals(a)}:{matches:!1,reason:`worktree executable bit differs from template`}:{matches:!1,reason:`worktree path is not a regular file`}}function _a(e){da(e)&&We(e,{force:!0,recursive:!1})}function va(e,t,n){let r=ua(e,t);if(n===null){_a(r);return}if(Ve(j(r),{recursive:!0}),n.mode===`120000`){_a(r),Ge(la(n).toString(`utf8`),r);return}let i=da(r)?Be(r):null;i&&!i.isFile()&&_a(r),q(r,la(n)),ze(r,n.mode===`100755`?493:420)}function ya(e,t){return e===null&&t!==null?`add`:e!==null&&t===null?`delete`:`update`}function ba(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 xa(e){let t=ia(),n=$(e.base??aa(t)),r=$(e.target),i=sa(n,r),a=[],o=[],s=[],c=[];for(let e of i){let i=ma(e.path);if(i){o.push({action:`ignored`,path:e.path,reason:i});continue}let l=ca(n,e.path),u=ca(r,e.path),d=ya(l,u),f=u===null?ha(e.path):void 0;if(f){a.push({action:d,path:e.path,reason:f,targetEntry:u});continue}if(!pa(l)||!pa(u)){s.push({action:d,path:e.path,reason:`unsupported template entry type`});continue}if(ga(t,e.path,u).matches){c.push({action:`unchanged`,path:e.path});continue}let p=ga(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)va(t,e.path,e.targetEntry??null);console.log(`Coreframe template fast-forward: ${n} -> ${r}`),console.log(``),ba(e.apply?`Applied clean template updates`:`Would apply clean template updates`,a),ba(`Ignored downstream-owned paths`,o),ba(`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).`))}const Sa=[`dependencies`,`devDependencies`];function Ca(e){let t=Y(`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 wa(e,t){try{return JSON.parse(e)}catch(e){throw Error(`Could not parse ${t}: ${e instanceof Error?e.message:e}`)}}function Ta(e,t){let n=`${$(e)}:${t}`;return wa(Ca([`show`,n]),n)}function Ea(e){return e.startsWith(`@coreframe/`)}function Da(e){return e.startsWith(`file:`)||e.startsWith(`link:`)||e.startsWith(`workspace:`)}function Oa(e){return e.startsWith(`file:`)||e.startsWith(`link:`)}function ka(e,t){let n=e.indexOf(`:`),r=e.slice(n+1),i=N.normalize(N.join(`template`,r,`package.json`));if(r.length===0||N.isAbsolute(r)||i===`..`||i.startsWith(`../`))throw Error(`Invalid local template dependency for ${t}: ${e}`);return i}function Aa(e){let t=Ta(e,`template/package.json`),n=[],r=new Set;for(let i of Sa)for(let[a,o]of Object.entries(t[i]??{})){if(!Ea(a)||!Oa(o))continue;if(r.has(a))throw Error(`Target template declares ${a} more than once.`);let t=ka(o,a),s=Ta(e,t);if(s.name!==a||typeof s.version!=`string`)throw Error(`${$(e)}:${t} must declare ${a} with a version.`);n.push({group:i,name:a,spec:`^${s.version}`}),r.add(a)}return n}function ja(e,t){for(let n of Sa){let r=e[n]?.[t];if(r)return{group:n,spec:r}}}function Ma(e,t,n){let r=t.match(/\n([\t ]+)"/u)?.[1]??` `,i=t.endsWith(`
|
|
11
11
|
`)?`
|
|
12
|
-
`:``;
|
|
13
|
-
`),`Pending Worker secret updates`),u.provisioned&&H.log.info(`Provisioning Coreframe-managed access-token signing material.`),await Ra(n);let x=a.database?.dialect??`postgres`,C;switch(x){case`postgres`:C=await g({env:t});break;case`sqlite`:C=await _({env:t});break;default:throw Error(`Unsupported database dialect "${x}".`)}let w=await ja(C),T=await O(w);if(T.length>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations.\n${S(T)}`);let E=await Na(n,w);try{v&&await Ct(Da,r,p),H.log.step(`Running pre-deploy build`),await V(`pnpm`,[`build`],{env:Wa(h),stdio:`inherit`}),H.log.step(`Running release build and uploading PostHog source maps`),y=!0,await V(`pnpm`,[`build`],{env:h,stdio:`inherit`}),E&&(H.log.step(`Running deploy-safe database migrations`),await V(`pnpm`,[`db`,`migrate`],{env:h,stdio:`inherit`})),H.log.step(`Deploying Worker and static assets to Cloudflare`);let e={...l?{DASHBOARD_PASSWORD:l}:{},...u.value?{[$e]:u.value}:{},...c.values},t=Object.keys(e).length>0?await Va(e):void 0,i=await at({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:m}}});try{await V(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,i.path,`--env`,n.environment,`--strict`,`--keep-vars`,`--tag`,m,`--message`,`Deploy ${m}`,...t?[`--secrets-file`,t.path]:[]],{env:h,stdio:`inherit`}),await et(c),await St({environment:n.environment})}finally{await i.dispose(),await t?.dispose()}let d={environment:n.environment,releaseName:m,url:s,version:p};o.afterWorkerDeploy&&(H.log.step(`Running required after-Worker deploy hook`),await yt(o,d)),n.skipPostDeployChecks||(H.log.step(`Running post-deploy checks`),await bt(o,d)),H.outro(`Deployed ${m} to ${n.environment}`)}catch(e){throw!y&&v&&await J(Da,i),e}}function ka(e){return{environment:Aa(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Aa(e){if(e&&tt.includes(e))return e;throw Error(`Deploy environment must be one of: ${tt.join(`, `)}.`)}async function ja(e){try{return await Ma(e)}finally{await e.close?.()}}async function Ma(e){return y(await h(),await T(e))}async function Na(e,t){if(t.length===0)return H.log.info(`No pending deploy migrations.`),!1;if(H.note(x(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 H.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(H.isCancel(n))throw H.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function Pa(){let{stdout:e}=await V(`git`,[`status`,`--porcelain`],{stdin:`ignore`});if(e.trim().length>0)throw Error(`Deploy requires a clean git tree.`);let{stdout:t}=await V(`git`,[`rev-parse`,`HEAD`],{stdin:`ignore`});return t.trim()}function Fa(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}async function Ia(e,t,n=rt){return e.url?La(e.url,t):t===`staging`&&e.stagingHostname?La(await n(),t):La(void 0,t)}function La(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 Ra(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await H.confirm({initialValue:!1,message:`Deploy to production?`});if(H.isCancel(t)||!t)throw H.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}function za(e,t){let n=t.filter(t=>!e[t]);if(n.length>0)throw Error(`Missing required deploy environment variables: ${n.join(`, `)}`);return Object.fromEntries(t.map(t=>[t,e[t]]))}async function Ba(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Nt(await K(`.env`,`utf8`))}catch(e){throw Ha(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 Va(e){let t=await be(L(Oe(),`coreframe-deploy-secrets-`)),n=L(t,`secrets.json`);return await J(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>q(t,{force:!0,recursive:!0})}}function Ha(e){return e instanceof Error&&`code`in e}function Ua(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 Wa(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function Ga(){let e=await qa();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function Ka(e){let t=await qa(),n=Ja();await gr.mkdir(P.dirname(n),{recursive:!0}),await gr.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function qa(){try{let e=await gr.readFile(Ja(),`utf8`),t=JSON.parse(e);return Ya(t)?t:{}}catch{return{}}}function Ja(){return P.join(vr.homedir(),`.coreframe`,`preferences.json`)}function Ya(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function Xa({env:e=X.env,interactive:t=X.stdin.isTTY===!0,platform:n,target:r}){let i=await ro(n,e).catch(()=>[]),a=r?So(i,r):void 0;if(a)return a;if(!r&&i.length>0)return no(i,n,t);let o=r?So(await ao(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return oo(o,n,e,t);let s=await io(n,e),c=r?So(s,r):void 0;if(c)return c;if(!r&&s.length>0)return no(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 Za(e){let{device:t,host:n,interactive:r=X.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=wo();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await eo();if(a&&i.includes(a))return a;if(i.length===1)return await to(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await H.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(H.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await to(o),o}async function Qa({device:e,env:t=X.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await ho(e.id,a,t)}catch{H.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:$a(i,await Za({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function $a(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 eo(){return(await Ga()).mobileDevHost}async function to(e){try{await Ka({mobileDevHost:e})}catch(e){H.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function no(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 H.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(H.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function ro(e,t){return e===`android`?co(t):uo(t)}async function io(e,t){return e===`android`?lo(t):fo(t)}async function ao(e){let{stdout:t}=await V(`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 oo(e,t,n,r){let i=await so(t,n).catch(()=>[]),{stdout:a}=await V(`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 so(t,n).catch(()=>[]),o=So(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return no(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 so(e,t){return e===`ios`?fo(t,`booted`):(await co(t)).filter(e=>!e.physical)}async function co(e){let t=await mo(e,`platform-tools`,X.platform===`win32`?`adb.exe`:`adb`),{stdout:n}=await V(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 _o(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await yo(t,e,n,r):await bo(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(To)}async function lo(e){let{stdout:t}=await V(await mo(e,`emulator`,X.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 uo(e){let t=await gr.mkdtemp(P.join(vr.tmpdir(),`coreframe-ios-devices-`)),n=P.join(t,`devices.json`);try{return await gr.writeFile(n,``),await V(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await gr.readFile(n,`utf8`)).result?.devices??[]).filter(po).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(To)}finally{await gr.rm(t,{force:!0,recursive:!0})}}async function fo(e,t=`available`){let{stdout:n}=await V(`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(To)}function po(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 mo(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:go(e);for(let e of i){let r=P.join(e,t,n);try{return await gr.access(r),r}catch{}}return n}async function ho(e,t,n){let r=await mo(n,`platform-tools`,X.platform===`win32`?`adb.exe`:`adb`),{stdout:i}=await V(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 V(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 go(e){return X.platform===`darwin`?[P.join(vr.homedir(),`Library`,`Android`,`sdk`)]:X.platform===`win32`&&e.LOCALAPPDATA?[P.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[P.join(vr.homedir(),`Android`,`Sdk`)]}async function _o(e,t,n,r){return(await vo(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function vo(e,t,n){return(await V(e,n,{env:t,timeout:3e3})).stdout}async function yo(e,t,n,r){return vo(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function bo(e,t,n,r){return vo(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>xo(e)||r).catch(()=>r)}function xo(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function So(e,t){let n=e.map(e=>({device:e,score:Math.max(Co(t,e.name),Co(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function Co(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 wo(){return[...new Set(Object.values(vr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function To(e,t){return e.label.localeCompare(t.label)}async function Eo(e,t){if(!e)return()=>void 0;await G(P.dirname(e),{recursive:!0}),await J(e,``,{flag:`a`});let n=await K(e,`utf8`).catch(()=>void 0),r=0,i=!1,a=We(e,{persistent:!1},()=>{if(i)return;let a=++r;K(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}const Do=[`filtered`,`full`];function Oo(e,{noCodesign:t=!1}={}){return{...e,COREFRAME_FLUTTER_DEVELOPMENT:`1`,...t?{FLUTTER_XCODE_CODE_SIGNING_ALLOWED:`NO`,FLUTTER_XCODE_CODE_SIGNING_REQUIRED:`NO`,FLUTTER_XCODE_CODE_SIGN_IDENTITY:``}:void 0}}function ko({enabled:e,env:t=X.env,input:n=X.stdin,onInterrupt:r,onQuit:i,onRestart:a,output:o=X.stdout}){if(!e)return()=>void 0;let s=n.readableFlowing,c=n.isRaw,l=e=>{for(let t of e.toString())t===``?r():t===`R`?a():t===`q`?i():t===`h`?o.write(`
|
|
14
|
-
Coreframe Flutter commands:
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
q Quit.
|
|
18
|
-
`):t
|
|
19
|
-
Coreframe: Press "R" to restart the Flutter process.
|
|
20
|
-
`),()=>{n.off(`data`,l),c||n.setRawMode?.(!1),s!==!0&&n.pause()}}function Ao(e=!1){return e?`debug`:`profile`}function jo({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 Mo({device:e,mode:t,serverUrl:n,verbose:r}){return[`run`,`--${t}`,`-d`,e.id,`--dart-define=COREFRAME_DEV_SERVER_URL=${n}`,...r?[`--verbose`]:[]]}const No={command:Yo,isRunning:Bo,stop(e){try{X.kill(e,`SIGTERM`)}catch(e){if(!Uo(e))throw e}},waitForExit:Vo};async function Po({confirmStop:e=Lo,cwd:t=X.cwd(),interactive:n=X.stdin.isTTY===!0,pid:r=X.pid,platform:i=`web`,processes:a=No}={}){let o=await Qo(t,i),s=o.file,c={pid:r,platform:i,repository:o.repository,token:Y()},l=`${JSON.stringify(c)}\n`,u=`${s}.${c.token}.tmp`,d=await Go({confirmStop:e,file:P.resolve(t,`.coreframe/dev.lock`),interactive:n,owner:c,processes:a});if(d===void 0)return;let f=d;await G(P.dirname(s),{recursive:!0}),await J(u,l,{flag:`wx`,mode:384});try{for(;;){try{return await ye(u,s),{owner:c,async release(){await zo(s,l)},takeoverApproved:f}}catch(e){if(!Ho(e))throw e}let t=await Io({confirmStop:e,file:s,interactive:n,owner:c,processes:a});if(t===void 0)return;f||=t}}finally{await Te(u).catch(()=>void 0)}}async function Fo({cwd:e=X.cwd(),platform:t=`web`}={}){let{file:n}=await Qo(e,t);return(await Ro(n))?.owner}async function Io({confirmStop:e,file:t,interactive:n,owner:r,processes:i}){let a=await Ro(t);if(!a||!ns(a.owner,r)||!i.isRunning(a.owner.pid))return await zo(t,a?.source),!1;if(!n)throw Error(`Coreframe dev is already running for this project (PID ${a.owner.pid}). Stop it before starting another.`);if(await e(a.owner.pid))return i.stop(a.owner.pid),await i.waitForExit(a.owner.pid),await zo(t,a.source),!0}async function Lo(e){let t=await H.confirm({initialValue:!1,message:`Coreframe dev is already running for this project (PID ${e}). Stop it and start here?`});return H.isCancel(t)||!t?(H.cancel(`Keeping the existing Coreframe dev process.`),!1):!0}async function Ro(e){try{let t=await K(e,`utf8`),n=JSON.parse(t);return!Number.isSafeInteger(n.pid)||Number(n.pid)<=0||typeof n.platform!=`string`||n.platform.length===0||typeof n.repository!=`string`||n.repository.length===0||typeof n.token!=`string`||n.token.length===0?void 0:{owner:n,source:t}}catch{return}}async function zo(e,t){let n=await K(e,`utf8`).catch(()=>void 0);(t===void 0||n===t)&&await Te(e).catch(()=>void 0)}function Bo(e){try{return X.kill(e,0),!0}catch(e){return!Uo(e)}}async function Vo(e){let t=Date.now()+1e4;for(;Bo(e);){if(Date.now()>=t)throw Error(`Coreframe dev process ${e} did not stop within 10 seconds.`);await new Promise(e=>setTimeout(e,50))}}function Ho(e){return Wo(e)&&e.code===`EEXIST`}function Uo(e){return Wo(e)&&e.code===`ESRCH`}function Wo(e){return e instanceof Error}async function Go({confirmStop:e,file:t,interactive:n,owner:r,processes:i}){let a=await Ko(t);if(!a||!i.isRunning(a.owner.pid))return await zo(t,a?.source),!1;let o=i.command?.(a.owner.pid);if(!o||!qo(o,r.platform))return!1;if(!n)throw Error(`Coreframe dev is already running for this project (PID ${a.owner.pid}). Stop it before starting another.`);if(await e(a.owner.pid))return i.stop(a.owner.pid),await i.waitForExit(a.owner.pid),await zo(t,a.source),!0}async function Ko(e){try{let t=await K(e,`utf8`),n=JSON.parse(t);return!Number.isSafeInteger(n.pid)||Number(n.pid)<=0||typeof n.token!=`string`||n.token.length===0?void 0:{owner:n,source:t}}catch{return}}function qo(e,t){let n=e.trim().split(/\s+/u),r=n.findIndex(e=>{let t=e.split(/[\\/]/u).at(-1);return t===`coreframe`||t===`coreframe.js`||t===`coreframe.ts`});if(r<0)return!1;let i=n.indexOf(`dev`,r+1);return i<0?!1:Jo(n.slice(i+1))===t}function Jo(e){let t=new Set([`android`,`ios`,`linux`,`macos`,`web`,`windows`]),n=new Set([`--debug`,`--host`,`--port`]),r=!1;for(let i of e){if(r){r=!1;continue}if(n.has(i)){r=!0;continue}if(!i.startsWith(`-`))return t.has(i)?i:`web`}return`web`}function Yo(e){let t=X.platform===`win32`?Zo(e):Xo(e);if(t.status===0)return t.stdout.trim()||void 0}function Xo(e){return Z(`ps`,[`-p`,String(e),`-o`,`command=`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})}function Zo(e){return Z(`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance Win32_Process -Filter 'ProcessId = ${e}').CommandLine`],{encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]})}async function Qo(e,t){let n=await $o(P.resolve(e)),r=n.gitCommonDir?P.join(n.path,`coreframe-dev`):P.join(n.path,`.coreframe`);return{file:P.join(r,`dev.${t}.lock`),repository:n.path}}async function $o(e){let t=es(e);return t?{gitCommonDir:!0,path:await ts(P.resolve(e,t))}:{gitCommonDir:!1,path:await ts(e)}}function es(e){let t=Z(`git`,[`rev-parse`,`--git-common-dir`],{cwd:e,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`]});if(t.status===0)return t.stdout.trim()||void 0}async function ts(e){return Se(e).catch(()=>P.resolve(e))}function ns(e,t){return e.platform===t.platform&&e.repository===t.repository}function rs(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const is=X.platform===`win32`?`portless.cmd`:`portless`,as=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),os=/^Proxy is already running on port (\d+)\.$/,ss=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function cs(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(as,``).trim().match(os);if(a?.[1]!==void 0&&i!==void 0&&ss.test(i.replace(as,``).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 ls(e){let t=cs(e);t&&X.stdout.write(t.endsWith(`
|
|
21
|
-
`)?t:`${t}\n`)}async function us({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await Bt()).isAgent?!1:kt(e)}async function ds({cwd:e,env:t,lan:n=!1}){let r=P.join(`node_modules`,`.bin`,is),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await V(P.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});ls(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&ls(e.stdout),e}}function fs({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]]}async function ps({cwd:e=X.cwd(),platform:t}){let n=await ms({cwd:e});if(!n||!Cs(n.platform)||!ws(n.platform,t)||!Es(n.owner.pid))return;let r=await Fo({cwd:e,platform:n.platform});if(!(!r||!Ds(n.owner,r))&&!(n.postgres?.pid!==void 0&&!Es(n.postgres.pid)))return n}async function ms({cwd:e=X.cwd()}={}){let t;try{t=JSON.parse(await K(_s(e),`utf8`))}catch{return}return vs(t)&&t.cwd===P.resolve(e)?t:void 0}async function hs({cwd:e=X.cwd(),owner:t,platform:n,postgres:r,vitePort:i}){let a=_s(e),o=P.dirname(a),s=`${a}.${Y()}.tmp`,c={cwd:P.resolve(e),owner:t,platform:n,...r?{postgres:r}:void 0,version:1,vite:{port:i}};await G(o,{recursive:!0});try{await J(s,`${JSON.stringify(c)}\n`,{flag:`wx`,mode:384}),await Ce(s,a)}finally{await Te(s).catch(()=>void 0)}}async function gs({cwd:e=X.cwd(),owner:t}){let n=_s(e),r=await ms({cwd:e});!r||!Ds(r.owner,t)||await Te(n).catch(()=>void 0)}function _s(e){return P.resolve(e,`.coreframe/dev.session.json`)}function vs(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.cwd==`string`&&ys(t.owner)&&xs(t.platform)&&Ts(t.vite?.port)&&(t.postgres===void 0||bs(t.postgres))}function ys(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.pid;return typeof n==`number`&&Number.isSafeInteger(n)&&n>0&&typeof t.token==`string`}function bs(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.dataDir==`string`&&(t.pid===void 0||Number.isSafeInteger(t.pid)&&t.pid>0)}function xs(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`web`||e===`windows`}function Ss(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}function Cs(e){return e===`web`||Ss(e)}function ws(e,t){return t===void 0?Ss(e):e===t}function Ts(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0&&e<=65535}function Es(e){try{return X.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Ds(e,t){return e.pid===t.pid&&e.token===t.token}const Os=X.platform===`win32`?`pnpm.cmd`:`pnpm`,ks=X.platform===`win32`?`portless.cmd`:`portless`,As=X.platform===`win32`?`react-router.cmd`:`react-router`;async function js({cwd:e=X.cwd(),debug:t,device:n,env:r=X.env,flutterDebug:i=!1,flutterOutput:a=`filtered`,host:o,https:s=!1,interactive:c=X.stdin.isTTY===!0,lan:l=!1,managed:u=!1,noCodesign:d=!1,noManaged:f=!1,noDevJobs:p=!1,platform:m=`web`,portless:h,fresh:g=!1,reuseVite:_=!1,verbose:v=!1,webPort:y,supervisor:b}){let x=Tt({env:r}),S=Ls(m)?m:void 0,C=Ao(i);if(i&&S===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);let w=Rs(m),T=m===`ios`||m===`android`?m:void 0,E=T?await Xa({env:r,interactive:c,platform:T,target:n}):void 0;T&&E&&jo({device:E,mode:C,platform:T});let D=S?!0:o,O=await x.measure(`config`,()=>Me({cwd:e})),ee=await x.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(u||c&&!f)&&await Ot(e));await x.measure(`i18n`,()=>Bn({cwd:e,projectConfig:O}));let te=await x.measure(`routing`,async()=>h??await us({cwd:e,env:r,platform:m})),ne=await x.measure(`https`,async()=>s&&!te?At({cwd:e}):void 0),re=rs(r,m),ie=!_&&wr(e),k,A={...re,...x.environment,...ee?{[Ft]:`1`,[Lt]:`1`}:void 0,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!p&&m!==`webext`?{[It]:Y()}:void 0,...S?{COREFRAME_PLATFORM:S,[Rt]:P.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...ne?{[Et]:ne.cert,[Dt]:ne.key}:void 0},j=!1,oe,se,M,N,F,I,L,R,z,B=new Promise(e=>{z=e}),V=new Map,H=[`postgres`,`sqlite`,w];for(let e of H){let t=e===`postgres`||e===`sqlite`?e:e.startsWith(`vite:flutter`)?`flutter`:`web`,n=qe({label:t}),r=qe({color:`red`,label:t});n.pipe(X.stdout,{end:!1}),r.pipe(X.stderr,{end:!1}),V.set(e,{stderr:r,stdout:n})}let U=b.onEvent(e=>{e.event===`log`?(V.get(e.resource)?.[e.stream])?.write(e.data):e.event===`service`&&e.resource===w&&(e.state===`failed`||e.state===`stopped`)&&(e.state===`failed`&&(R=Error(e.error??`${w} development failed.`)),ce())}),ce=()=>{j||(j=!0,z(),M?.kill(`SIGTERM`),se?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))},le=e=>{oe??=e,ce()},ue=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>le(e);return X.on(e,t),{handler:t,signal:e}}),W=async e=>{let t=Je(e);M=t;try{await t.expectSuccess()}catch(e){if(!j)throw e}finally{M===t&&(M=void 0)}};try{if(await b.subscribe(H),Is(O)){let e=await b.acquirePostgres({config:O,env:A});F=e.leaseId,A={...A,...e.env}}if(O.database?.dialect===`sqlite`){let e=await b.acquireSqlite({config:O,env:A});I=e.leaseId,A={...A,...e.env}}(Is(O)||O.database?.dialect===`sqlite`)&&await x.measure(`schema`,()=>W({name:`db`,command:Os,args:[`db`,`ensure`],cwd:e,env:A,prefix:!1}));let t=Fs(y??r.COREFRAME_WEB_PORT),n=await b.status(),i=n.resources?.find(e=>e.resource===w),u=i!==void 0&&!g,f=u&&t===void 0?void 0:t??(_?5173:await _r.getAvailablePort()),p=f??i?.endpoint?.port??5173;if(f!==void 0&&n.resources?.some(e=>e.resource!==w&&e.endpoint?.port===p)){if(t!==void 0)throw Error(`Port ${p} is already used by another Coreframe development shell.`);p=await _r.getAvailablePort()}if(ie&&!u&&(k=await _r.getAvailablePort(),k===p&&(k=await _r.getAvailablePort()),A={...A,COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${k}`}),T&&E&&(N=await Qa({device:E,env:r,host:o,interactive:c,platform:T,port:p}),D=N.viteHost),!_){let t={...A,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[A.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:P.join(e,`node_modules`,`.bin`)+P.delimiter+(A.PATH??``)},n=[{args:te?fs({host:D,lan:l,port:p}):[`dev`,...D===void 0?[]:[`--host`,D===!0?`0.0.0.0`:D],`--port`,String(p),...m===`web`||S?[`--strictPort`]:[]],command:te?ks:As,cwd:e,env:t},{args:[`exec`,`panda`,`dev`,`--no-color`],command:Os,cwd:e,env:A},...k?[{args:Tr(k),command:Os,cwd:e,env:A}]:[]],r=await b.acquireVite({configFingerprint:Ps({cwd:e,host:D,lan:l,https:s,portless:te,resource:w}),endpoint:{host:D===!0?`0.0.0.0`:D??`127.0.0.1`,port:p},processes:n,resource:w},g);L=r.leaseId,p=r.endpoint.port}if(x.report(),j)return;if(m===`web`?await Promise.race([Ns(b,w,()=>R),B]):(await ae({cwd:e}),await Ms({cwd:e,env:re,interactive:c,platform:m,requestStop:ce,selectedDevice:E,serverUrl:N?.serverUrl??$a(m,void 0,p),mode:C,noCodesign:d,output:a,flutterRestartFile:A[Rt],handleShutdown:le,isStopping:()=>j,stopRequested:B,setActiveNative:e=>{se=e},verbose:v})),R)throw R}finally{ce(),await N?.close(),N=void 0,L&&await b.release(L).catch(()=>void 0),F&&await b.release(F).catch(()=>void 0),I&&await b.release(I).catch(()=>void 0),U();for(let{handler:e,signal:t}of ue)X.off(t,e);for(let e of V.values())e.stdout.end(),e.stderr.end();oe&&(X.exitCode??=oe===`SIGINT`?130:143),b.close()}}async function Ms({cwd:e,env:t,interactive:n,platform:r,requestStop:i,selectedDevice:a,serverUrl:o,mode:s,noCodesign:c,output:l,flutterRestartFile:u,handleShutdown:d,isStopping:f,stopRequested:p,setActiveNative:m,verbose:h}){let g,_=!1,v=()=>{_||f()||!g||(_=!0,t.CI!==`true`&&X.stdout.write(`
|
|
22
|
-
Restarting Flutter process...
|
|
23
|
-
`),g.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))},y=Eo(u,v);try{for(;;){_=!1;let u=r===`android`&&l===`filtered`&&!h?await se():void 0,y=n&&s===`profile`,b=V(`flutter`,Mo({device:a??{id:r},mode:s,serverUrl:o,verbose:h}),{cwd:P.join(e,`src-flutter`),env:Oo(t,{noCodesign:c}),stdio:u?[y?`pipe`:`inherit`,`pipe`,`pipe`]:y?[`pipe`,`inherit`,`inherit`]:`inherit`});m(b),g=b;let x=ko({enabled:y,env:t,onInterrupt:()=>d(`SIGINT`),onQuit:i,onRestart:v});try{if(await Promise.all([b,u?.capture(b)]),!_||f())return}catch{if(_&&!f())continue;if(f())return;let e=n?await H.confirm({initialValue:!0,message:`Flutter failed. Retry?`}):!1;if(H.isCancel(e)||!e){H.log.warn(`Flutter stopped. Web development is still running.`),await p;return}}finally{x(),m(void 0),g===b&&(g=void 0)}}}finally{(await y)()}}async function Ns(e,t,n){await e.waitForServiceExit(t);let r=n();if(r)throw r}function Ps({cwd:e,host:t,lan:n,https:r,portless:i,resource:a}){return Pe(`sha256`).update(JSON.stringify({cwd:P.resolve(e),host:t??null,lan:n,https:r,portless:i,resource:a})).digest(`hex`)}function Fs(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 Is(e){return(e.database?.dialect??`postgres`)===`postgres`}function Ls(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}function Rs(e){if(e===`web`)return`vite:web`;if(Ls(e))return`vite:flutter:${e}`;throw Error(`Unsupported supervised development platform: ${e}.`)}const zs=`extension:dev`;function Bs(e){if(!Ie(L(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=L(e,`package.json`),n;try{n=JSON.parse(Be(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.${zs} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function Vs({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`,zs,...n.length>0?[`--`,...n]:[]]}const Hs=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],Us=[`managed-dev-overlay`],Ws=P.resolve(`node_modules`,`.bin`),Gs=X.platform===`win32`?`pnpm.cmd`:`pnpm`,Ks=X.platform===`win32`?`portless.cmd`:`portless`,qs=X.platform===`win32`?`react-router.cmd`:`react-router`;async function Js({cwd:e=X.cwd(),debug:t,device:n,env:r=X.env,flutterDebug:i=!1,flutterOutput:a=`filtered`,host:o,https:s=!1,interactive:c=X.stdin.isTTY===!0,lan:l=!1,managed:u=!1,noCodesign:d=!1,noManaged:f=!1,noDevJobs:p=!1,platform:m=`web`,fresh:h=!1,reuseVite:g=!1,supervisor:_,verbose:v=!1,webPort:y}={}){let b=Tt({env:r}),x=r.PATH??r.Path??``,S=nc(m)?m:void 0,C=Ao(i),w=m===`web`||S!==void 0;if(h&&g)throw Error(`Cannot use --fresh and --reuse-vite together.`);let T=!h&&(S||m===`web`)?await b.measure(`dev-session`,()=>ps({cwd:e,platform:m})):void 0,E=g||T!==void 0,D=tc(y??r.COREFRAME_WEB_PORT);if(T&&D!==void 0&&D!==T.vite.port)throw Error(`The active development session uses port ${T.vite.port}. Omit --port or use that port when reusing it.`);let O,ee,te,ne,ie,k,A,j,oe,M,N=!1,F,I=r,L,R;if(u&&f)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&u)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&S===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(d&&m!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(a===`full`&&S===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(g&&S===void 0)throw Error(`The --reuse-vite option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(m===`webext`){if(u||f||t!==void 0||v)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);Bs(e)}if(s&&m!==`web`)throw Error(`Local HTTPS is only supported for the web development platform.`);if(n!==void 0&&m!==`ios`&&m!==`android`)throw Error(`A device name or ID is only supported for iOS or Android development.`);let z=await b.measure(`routing`,()=>us({cwd:e,env:r,platform:m}));if(z&&await b.measure(`portless`,()=>ds({cwd:e,env:r,lan:l})),w&&r.COREFRAME_DEV_SUPERVISOR!==`0`){let b=_??await wt({cwd:e,env:r});if(b)return js({cwd:e,debug:t,device:n,env:r,flutterDebug:i,flutterOutput:a,fresh:h,host:o,https:s,interactive:c,lan:l,managed:u,noCodesign:d,noManaged:f,noDevJobs:p,platform:m,portless:z,reuseVite:g,supervisor:b,verbose:v,webPort:y})}let B=E?void 0:await b.measure(`dev-lock`,()=>Po({cwd:e,interactive:c,platform:m}));if(!E&&!B)return;let U=S===void 0?m===`web`||m===`webext`?T?.vite.port??D:void 0:T?.vite.port??D??(g?5173:await _r.getAvailablePort()),ce,le=new Promise(e=>{ce=e}),ue=()=>{N||(N=!0,ce(),ee?.kill(`SIGTERM`),k?.kill(`SIGTERM`),A?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),j?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),oe?.close().catch(()=>void 0),O?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),W().catch(()=>void 0))},W=()=>ne?(ie??=ne[Symbol.asyncDispose](),ie):Promise.resolve(),de=e=>{F??=e,ue()},fe=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>de(e);return X.on(e,t),{handler:t,signal:e}}),pe=async e=>{let t=Je(e);ee=t;try{await t.expectSuccess()}catch(e){if(!N)throw e}finally{ee===t&&(ee=void 0)}};try{let i=m===`ios`||m===`android`?m:void 0,h=i?await Xa({env:r,interactive:c,platform:i,target:n}):void 0;i&&h&&jo({device:h,mode:C,platform:i}),M=i&&h&&U!==void 0?await Qa({device:h,env:r,host:o,interactive:c,platform:i,port:U}):void 0;let g=M?.viteHost??(S?!0:o),_={},y=!1,w;E||([_,y]=await Promise.all([b.measure(`config`,()=>Me({cwd:e})),b.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(u||c&&!f)&&await Ot(e))]),await b.measure(`i18n`,()=>Bn({cwd:e,projectConfig:_})),w=m!==`webext`&&wr(e)?await _r.getAvailablePort():void 0);let T=E?void 0:await b.measure(`https`,async()=>s&&!z?At({cwd:e}):void 0),D=rs(r,m);I={...D,...b.environment,...y?{[Ft]:`1`}:void 0,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!p&&m!==`webext`?{[It]:Y()}:void 0,...S&&(y||E)?{COREFRAME_PLATFORM:S,[Rt]:P.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...T?{[Et]:T.cert,[Dt]:T.key}:void 0,...w?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${w}`}:void 0};let ee=async()=>{if(!w)return;let t=Er({cwd:e,env:I,port:w});oe=t;try{await t.listen(),await t.wait()}finally{await t.close(),oe===t&&(oe=void 0)}},ie=async()=>{let t=qe({label:`web`}),n=qe({color:`red`,label:`web`});t.pipe(X.stdout,{end:!1}),n.pipe(X.stderr,{end:!1}),A=V(z?Ks:qs,z?fs({host:g,lan:l,port:U}):ec({host:g,port:U,strictPort:S!==void 0}),{cwd:e,env:{...I,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[I.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:Ws+P.delimiter+x},stdin:`inherit`});let r=Promise.allSettled([Ys(A.stdout,t),Ys(A.stderr,n)]);try{await A;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!N)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([Ke(t),Ke(n)]),A=void 0}},F=async()=>{let t=qe({label:`webext`}),n=qe({color:`red`,label:`webext`});t.pipe(X.stdout,{end:!1}),n.pipe(X.stderr,{end:!1}),j=V(Gs,Vs({host:o,port:U}),{cwd:e,env:I,stdin:`inherit`});let r=Promise.allSettled([Ys(j.stdout,t),Ys(j.stderr,n)]);try{await j;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!N)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([Ke(t),Ke(n)]),j=void 0}},ce=async t=>{let n,i=!1,o=()=>{i||N||!n||(i=!0,r.CI!==`true`&&X.stdout.write(`
|
|
24
|
-
Restarting Flutter process...
|
|
25
|
-
`),n.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))},s=Eo(I[Rt],o);try{for(;!N;){i=!1;let s=m===`android`&&a===`filtered`&&!v?await se():void 0,l=c&&C===`profile`,u=V(`flutter`,Mo({device:h??{id:m},mode:C,serverUrl:M?.serverUrl??$a(m,void 0,U),verbose:v}),{cwd:P.join(e,`src-flutter`),env:Oo(D,{noCodesign:d}),stdio:s?[l?`pipe`:`inherit`,`pipe`,`pipe`]:l?[`pipe`,`inherit`,`inherit`]:`inherit`});O=u,n=u;let f=ko({enabled:l,env:r,onInterrupt:()=>de(`SIGINT`),onQuit:ue,onRestart:o});try{if(await Promise.all([u,s?.capture(u)]),!i||N)return}catch{if(i&&!N)continue;if(N)return;let e=c?await H.confirm({initialValue:!0,message:`Flutter failed. Retry?`}):!1;if(H.isCancel(e)||!e){H.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??le);return}}finally{f(),O===u&&(O=void 0),n===u&&(n=void 0)}}}finally{(await s)()}},W=async()=>{if(E){if(m===`web`)return;await ae({cwd:e}),await ce();return}if(m===`web`){await ie();return}let t=ie().then(()=>{if(!N)throw Error(`The Vite development server stopped while Flutter was still running.`)});await ae({cwd:e});try{await Promise.race([t,ce(t)])}finally{ue(),await Promise.allSettled([t,O]),O=void 0}},fe=async()=>{let t=Je({name:`panda`,command:Gs,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:I});k=t;try{if(await t.expectSuccess(),!N)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!N)throw e}finally{k===t&&(k=void 0)}},me=async()=>{if(m===`webext`){await F();return}if(E){await W();return}let e=fe(),t=W(),n=w?ee():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),N&&await t}finally{ue(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}},he=async()=>{E||!B?.owner||U===void 0||(await hs({cwd:e,owner:B.owner,platform:m,postgres:R,vitePort:U}),L=B.owner)};if(y&&(I={...I,[Lt]:`1`}),N)return;if(m===`webext`){b.report(),await me();return}if(E){b.report(),await me();return}if(_.database?.dialect===`sqlite`&&(await b.measure(`database`,async()=>{let t=await re({config:_,cwd:e,env:r,tursoOutput:X.stdout,useSupervisorLease:!0});ne=t,I={...I,...t.env}}),await b.measure(`schema`,()=>pe({name:`db`,command:Gs,args:[`db`,`ensure`],cwd:e,env:I,prefix:!1})),N))return;if($s(_)){let t=qe({label:`postgres`});t.pipe(X.stdout,{end:!1});try{let n=await b.measure(`database`,()=>Qs({config:_,cwd:e,env:I,failIfRunning:!0,interactive:c,isStopping:()=>N,postgresOutput:t,takeoverApproved:B?.takeoverApproved??!1,useSupervisorLease:!0}));if(!n)return;te=n,I=n.env,R=await Zs(n.env);try{N||await b.measure(`schema`,()=>pe({name:`db`,command:Gs,args:[`db`,`ensure`],cwd:e,env:I,prefix:!1})),N||(await he(),b.report(),await me())}finally{await n[Symbol.asyncDispose](),te===n&&(te=void 0)}}finally{t.end()}return}await he(),b.report(),await me()}finally{ue(),await M?.close(),M=void 0,L&&=(await gs({cwd:e,owner:L}),void 0);let t;try{await te?.[Symbol.asyncDispose]()}catch(e){t=e}finally{await W();for(let{handler:e,signal:t}of fe)X.off(t,e);F&&(X.exitCode??=F===`SIGINT`?130:143)}Xs(t),await B?.release()}}async function Ys(e,t){for await(let n of e)t.write(`${n}\n`)||await Pt(t,`drain`)}function Xs(e){if(e)throw e}async function Zs(e){let t=e.PGDATA;if(!t)return;let n=Number((await gr.readFile(P.join(t,`postmaster.pid`),`utf8`).catch(()=>``)).split(/\r?\n/,1)[0]);return{dataDir:P.resolve(t),...Number.isSafeInteger(n)&&n>0?{pid:n}:void 0}}async function Qs({interactive:e,isStopping:t,takeoverApproved:n,...r}){try{return await ne(r)}catch(i){if(!(i instanceof f)||!e)throw i;if(!n){let e=await H.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${i.pid}). Stop it and start here?`});if(H.isCancel(e)||!e){H.cancel(`Keeping the existing PostgreSQL process.`);return}}return await ie(i),t()?void 0:ne(r)}}function $s(e){return(e.database?.dialect??`postgres`)===`postgres`}function ec({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 tc(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 nc(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function rc(e={}){let t=e.cwd??X.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await he(P.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Ae(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 Vt({...e,cwd:t},r)}const ic=`worker-configuration.d.ts`;async function ac({check:e=!1,cwd:t=process.cwd()}={}){let n=await Me({cwd:t}),r=await ot({coreframeConfig:n,cwd:t}),i=z(t,ic),a=z(t,`.coreframe-worker-types-${Y()}.d.ts`);try{try{await V(`pnpm`,[`exec`,`wrangler`,`types`,a,`--config`,r.path,`--strict-vars=false`,`--include-runtime=false`],{cwd:t,stdio:[`ignore`,`pipe`,`pipe`]})}catch(e){throw oc(e),e}let o=sc(await K(a,`utf8`)),s=Ne(r.config),c=je(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${cc(c)}\n`;if(e){if(await K(i,`utf8`).catch(()=>``)!==l)throw Error(`${ic} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await K(i,`utf8`).catch(()=>``);return u!==l&&await J(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await q(a,{force:!0})}}function oc(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
26
|
-
`)?t:`${t}\n`)}function sc(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
27
|
-
`)}function cc(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(`
|
|
28
|
-
`)}const lc=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),uc=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],dc=[`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`],fc=[`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`],pc=`.coreframe/typegen.json`,mc=[`web`,`dashboard`,`worker`];async function hc({checkWorker:e=!1,cwd:t=X.cwd(),runners:n={}}={}){let r=await yc(t)??{generators:{},schemaVersion:1},i=[];return i.push(await _c({cwd:t,inputPaths:uc,name:`web`,outputPath:`.react-router`,run:()=>(n.web??vc)(t),state:r})),i.push(await _c({cwd:t,inputPaths:dc,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??dr)(t),state:r})),i.push(await _c({cwd:t,inputPaths:fc,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??ac)({check:e,cwd:t}),state:r})),i}function gc(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function _c({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await xc(e,t),s=await Sc(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 Sc(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await bc(e,a),{changed:s!==l,name:n,ran:!0}}async function vc(e){let t=X.platform===`win32`?`react-router.cmd`:`react-router`,n=X.env;await V(t,[`typegen`],{cwd:e,env:{...n,PATH:P.resolve(e,`node_modules/.bin`)+P.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function yc(e){try{let t=JSON.parse(await K(P.resolve(e,pc),`utf8`));if(!Ec(t)||t.schemaVersion!==1)return;let n={};if(!Ec(t.generators))return;for(let e of mc){let r=t.generators[e];Ec(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 bc(e,t){let n=P.resolve(e,pc);await G(P.dirname(n),{recursive:!0}),await J(n,`${JSON.stringify(t)}\n`,{mode:384})}async function xc(e,t){let n=Pe(`sha256`);for(let r of[...t].sort()){let t=P.resolve(e,r),i=await wc(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Cc(t)){let i=P.join(t,r),a=P.relative(e,i).split(P.sep).join(`/`);n.update(`${a}\0`),n.update(await K(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await K(t)))}return n.digest(`hex`)}async function Sc(e,t){if(await wc(P.resolve(e,t)))return xc(e,[t])}async function Cc(e){let t=[];async function n(e,r){let i=await xe(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(lc.has(a.name))continue;await n(P.join(e,a.name),P.join(r,a.name))}else a.isFile()&&t.push(P.join(r,a.name))}return await n(e,``),t.sort()}async function wc(e){try{return await we(e)}catch(e){if(Tc(e))return;throw e}}function Tc(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ec(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Dc=P.resolve(`node_modules`,`.bin`);X.env.PATH=Dc+P.delimiter+X.env.PATH;const Oc=X.platform===`win32`?`tsc.cmd`:`tsc`,kc=[{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 Ac(){await hc({checkWorker:!0});let e=[];for(let t of kc)try{await he(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>Je({name:e.name,command:Oc,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(X.exitCode=n[0].exitCode)}const jc=n(a(Us),{displayName:`feature`,from:async e=>e}),Mc=n(a(Do),{displayName:`filtered|full`,from:async e=>e}),Nc=[`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.`],Pc=t({name:`deploy`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:r({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:r({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:r({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:r({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Oa([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),Fc=d({name:`staging`,cmds:{reassign:t({name:`reassign`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await mt();if(e){console.log(JSON.stringify({...t,notices:Nc}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Nc.join(` `)}`)}}),url:t({name:`url`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await rt();console.log(e?JSON.stringify({url:t}):t)}})}}),Ic=d({name:`secrets`,cmds:{"rotate-access-token":t({name:`rotate-access-token`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:r({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 vt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:t({name:`status`,args:{environment:c({type:s(a(tt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await it({environment:e});console.log(t?JSON.stringify(n):Uc(n))}}),set:t({name:`set`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:c({type:s(u),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:r({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 lt({environment:e,name:t,value:await Wc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await dt(),i=n?await Kc(r):await Gc(r,e);await ut({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:t({name:`discard`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:c({type:u,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await nt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),Lc=t({name:`typecheck`,args:{},handler:Ac}),Rc=d({name:`worker`,cmds:{typegen:t({name:`typegen`,args:{check:r({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await ac({check:e});console.log(e?`${Jc(t.path)} is current.`:`${Jc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),zc=t({name:`dev`,args:{debug:o({long:`debug`,type:s(jc),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:r({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterOutput:o({long:`flutter-output`,type:Mc,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:r({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),fresh:r({long:`fresh`,description:`Start a new directory-scoped development session instead of attaching to one.`,defaultValue:()=>!1}),host:o({long:`host`,type:s(u),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:r({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:r({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:r({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:r({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:r({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),reuseVite:r({long:`reuse-vite`,description:`Use an existing Vite development server instead of starting another one for Flutter.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),stop:r({long:`stop`,description:`Stop the Vite development server for the selected platform.`,defaultValue:()=>!1}),platform:c({type:s(a(Hs)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:c({type:s(u),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:o({long:`port`,type:s(i),description:`Port for the web development server.`}),verbose:r({long:`verbose`,description:`Show the full native development output.`,defaultValue:()=>!1})},handler:({debug:e,device:t,fresh:n,flutterDebug:r,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f,port:p,reuseVite:m,simulator:h,stop:g,verbose:_})=>{if(g)return jt({cwd:X.cwd(),resource:Vc(f??`web`)});let v=Bc({device:t,flutterDebug:r,platform:f,simulator:h});return Js({debug:e,device:v.device,fresh:n,flutterDebug:v.flutterDebug,flutterOutput:i,host:a,https:o,lan:s,managed:c,noCodesign:l,noManaged:u,noDevJobs:d,platform:f??`web`,reuseVite:m,verbose:_,webPort:p})}});function Bc({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}}function Vc(e){if(e===`web`)return`vite:web`;if(e===`ios`||e===`android`||e===`macos`||e===`windows`||e===`linux`)return`vite:flutter:${e}`;throw Error(`The --stop option is only supported for web, iOS, Android, macOS, Windows, and Linux development targets.`)}const Hc=t({name:`preview`,args:{host:o({long:`host`,type:s(u),description:`Host address for the preview server.`}),port:o({long:`port`,type:s(i),description:`Port for the preview server.`})},handler:({host:e,port:t})=>rc({host:e,port:t})});function Uc(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=>e.map((e,t)=>e.padEnd(r[t])).join(` `).trimEnd();return[i(n),i(r.map(e=>`-`.repeat(e))),...t].join(`
|
|
29
|
-
`)}async function Wc(e){if(!X.stdin.isTTY){let e=``;for await(let t of X.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await H.password({message:`Enter the new value for ${e}`});if(H.isCancel(t))throw H.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function Gc(e,t){if(!X.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 H.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(H.isCancel(i))throw H.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function Kc(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=X.stdin.isTTY?await H.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 qc();if(H.isCancel(t))throw H.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=st(t,e);return n.length>0&&H.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function qc(){let e=``;for await(let t of X.stdin)e+=t.toString();return e}function Jc(e){return e.split(/[\\/]/).at(-1)??e}const Yc=t({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await hc();for(let t of e)console.log(gc(t))}});function Xc(e,{formatMessage:t,temporaryDirectory:n=Oe(),write:r=e=>console.error(e)}={}){let i=nl(e),a=al(Qc(e,t),i);try{let t=L(ze(L(n,`coreframe-error-`)),`error.log`);return Ge(t,`${al($c(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 Zc(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,Xc(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function Qc(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 $c(e){try{let t=el(e);if(!(e instanceof Error)||!tl(t))return Mt(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${Mt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function el(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:el(a.value,t),writable:!0})}return i}function tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nl(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`?rl(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function rl(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&il(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function il(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function al(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const ol=d({name:`coreframe`,cmds:{build:en,dashboard:kr,assets:or,flutter:sr,i18n:cr,deploy:Pc,staging:Fc,secrets:Ic,typegen:Yc,typecheck:Lc,worker:Rc,dev:zc,preview:Hc,upgrade:wa,recipes:Ta,db:Ea}});import.meta.main&&Zc(ol,{formatMessage:process.argv[2]===`db`?b:void 0});export{ol as coreframeCli};
|
|
12
|
+
`:``;q(e,`${JSON.stringify(n,null,r)}${i}`)}function Na(e,t){if(t.length!==0){console.log(`${e}:`);for(let e of t)console.log(` ${e}`);console.log(``)}}function Pa(e){let t=P(Ca([`rev-parse`,`--show-toplevel`]).trim(),`package.json`),n=K(t,`utf8`),r=wa(n,t),i=$(e.target),a=Aa(i),o=new Set(a.map(({name:e})=>e)),s=[],c=[],l=[],u=0;for(let e of a){let t=ja(r,e.name);if(!t){c.push(`missing: ${e.name} ${e.spec} (${e.group})`);continue}if(Da(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=Sa.flatMap(e=>Object.entries(r[e]??{}).filter(([e])=>Ea(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;Ma(t,n,r)}console.log(`Coreframe package sync: ${i}`),console.log(``),Na(e.apply?`Updated Coreframe packages`:`Would update Coreframe packages`,s.map(({currentSpec:e,name:t,spec:n})=>`update: ${t} ${e} -> ${n}`)),Na(`Missing target Coreframe packages`,c),Na(`Locally linked Coreframe packages`,l),Na(`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 Fa={...u,displayName:`recipe`,description:`Coreframe recipe name, such as yam-db.`,async from(e){return Ir(e)}},Ia=d({name:`upgrade`,cmds:{"ensure-template-remote":t({name:`ensure-template-remote`,args:{remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Remote name to ensure.`}),noFetch:r({long:`no-fetch`,description:`Do not fetch the remote after ensuring it exists.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t})=>Kr({fetch:!e,remote:t})}),"check-skill-current":t({name:`check-skill-current`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Replace the local upgrade skill with the target version when it differs.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>{process.exitCode=Zi({apply:e,target:t})}}),"fast-forward-template-files":t({name:`fast-forward-template-files`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),base:o({long:`base`,type:s(u),description:`Previous Coreframe template git ref. Defaults to package.json engines.coreframe.`}),apply:r({long:`apply`,description:`Write clean fast-forwards to the worktree.`,defaultValue:()=>!1})},handler:({apply:e,base:t,target:n})=>xa({apply:e,base:t,target:n})}),"sync-coreframe-packages":t({name:`sync-coreframe-packages`,args:{target:o({long:`target`,type:u,description:`Target Coreframe template git ref.`}),apply:r({long:`apply`,description:`Update existing published Coreframe dependency specifications.`,defaultValue:()=>!1})},handler:({apply:e,target:t})=>Pa({apply:e,target:t})})}}),La=d({name:`recipes`,cmds:{apply:t({name:`apply`,args:{recipe:c({type:Fa,displayName:`recipe`,description:`Recipe to prepare and apply.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>Ti(wi({fetch:!e,name:t,remote:n,target:r}))}),list:t({name:`list`,args:{target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,remote:t,target:n})=>Wi(Ui({fetch:!e,remote:t,target:n}))}),verify:t({name:`verify`,args:{recipe:c({type:Fa,displayName:`recipe`,description:`Recipe adoption to verify.`}),target:o({long:`target`,type:s(u),description:`Coreframe Git ref. Defaults to package.json engines.coreframe.`}),remote:o({long:`remote`,type:u,defaultValue:()=>`template`,description:`Coreframe Git remote name.`}),noFetch:r({long:`no-fetch`,description:`Use already-fetched recipe refs without fetching the remote.`,defaultValue:()=>!1})},handler:({noFetch:e,recipe:t,remote:n,target:r})=>xi(bi({fetch:!e,name:t,remote:n,target:r}))})}}),Ra=d({name:`db`,cmds:{ensure:t({name:`ensure`,args:{},handler:v}),generate:t({name:`generate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit generate.`})},handler:({args:e})=>T(`generate`,e)}),migrate:t({name:`migrate`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit migrate.`})},handler:({args:e})=>T(`migrate`,e)}),"migrate-held":t({name:`migrate-held`,args:{local:r({long:`local`,description:`Run held migrations against the Coreframe-managed local PostgreSQL database.`,defaultValue:()=>!1})},handler:({local:e})=>S({target:e?`local`:`deployment`})}),"migrate-local":t({name:`migrate-local`,args:{},handler:C}),"migrations-check":t({name:`migrations-check`,args:{},handler:p}),reset:t({name:`reset`,args:{},handler:te}),seed:t({name:`seed`,args:{},handler:()=>re()}),"schema-check":t({name:`schema-check`,args:{seed:r({long:`seed`,description:`Run the configured project seed against the throwaway database.`,defaultValue:()=>!1})},handler:({seed:e})=>m({seed:e})}),setup:t({name:`setup`,args:{},handler:()=>ie()}),studio:t({name:`studio`,args:{args:l({displayName:`drizzle-kit args`,description:`Additional arguments passed to drizzle-kit studio.`})},handler:({args:e})=>T(`studio`,e)})}}),za=`package.json`;async function Ba(e=process.argv.slice(2),t=process.env){let n=Va(e);Ya(n);let{packageJson:r,source:i}=await pt(za),a=await H(),o=_t(a.deploy,n.environment,t);Xa(n,o.mode),eo(t,[`POSTHOG_API_KEY`,`POSTHOG_PROJECT_ID`]);let s=await Za(o,n.environment,()=>rt({env:t})),c=o.mode===`full`?await Ua(n.environment,t):void 0,l=await Ja();await Jn({env:t,revision:l});let u=l.slice(0,12),d=vt(n.environment,r.version,u),f=gt(r.name,d),p={...io(t,n.environment,f,r.name,d),COREFRAME_I18N_RELEASE_REVISION:l},m=n.environment===`production`,h=!1;L.intro(`Deploy ${f} to ${n.environment}`);let g=Object.keys(c?.pendingWorkerSecrets.values??{}).sort();g.length>0&&L.note(g.join(`
|
|
13
|
+
`),`Pending Worker secret updates`),c?.accessTokenSigningSecret.provisioned&&L.log.info(`Provisioning Coreframe-managed access-token signing material.`),await $a(n);let _=o.mode===`full`?await Wa(a,n,t):!1;try{m&&await wt(za,r,d),L.log.step(`Running pre-deploy build`),await I(`pnpm`,[`build`],{env:ao(p),stdio:`inherit`}),L.log.step(`Running release build and uploading PostHog source maps`),h=!0,await I(`pnpm`,[`build`],{env:p,stdio:`inherit`}),_&&(L.log.step(`Running deploy-safe database migrations`),await I(`pnpm`,[`db`,`migrate`],{env:p,stdio:`inherit`})),L.log.step(o.mode===`full`?`Deploying Worker and static assets to Cloudflare`:`Deploying static assets to Cloudflare`);let e={...c?.dashboardPassword?{DASHBOARD_PASSWORD:c.dashboardPassword}:{},...c?.accessTokenSigningSecret.value?{[$e]:c.accessTokenSigningSecret.value}:{},...c?.pendingWorkerSecrets.values},t=Object.keys(e).length>0?await no(e):void 0,i=o.mode===`full`?await ot({coreframeConfig:a,environment:n.environment,contributions:{generatedValues:{DEPLOY_ENV:n.environment,POSTHOG_RELEASE:f}}}):await at(process.cwd());try{await I(`pnpm`,[`exec`,`wrangler`,`deploy`,`--config`,i.path,...o.mode===`full`?[`--env`,n.environment]:[],`--strict`,`--keep-vars`,`--tag`,f,`--message`,`Deploy ${f}`,...t?[`--secrets-file`,t.path]:[]],{env:p,stdio:`inherit`}),c&&(await et(c.pendingWorkerSecrets),await Ct({environment:n.environment}))}finally{await i.dispose(),await t?.dispose()}let l={environment:n.environment,releaseName:f,url:s,version:d};o.mode===`full`&&o.afterWorkerDeploy&&(L.log.step(`Running required after-Worker deploy hook`),await bt(o,l)),n.skipPostDeployChecks||(L.log.step(`Running post-deploy checks`),await xt(o,l)),L.outro(`Deployed ${f} to ${n.environment}`)}catch(e){throw!h&&m&&await V(za,i),e}}function Va(e){return{environment:Ha(e[0]),runMigrations:e.includes(`--run-migrations`),skipMigrations:e.includes(`--skip-migrations`),skipPostDeployChecks:e.includes(`--skip-post-deploy-checks`),yes:e.includes(`--yes`)}}function Ha(e){if(e&&tt.includes(e))return e;throw Error(`Deploy environment must be one of: ${tt.join(`, `)}.`)}async function Ua(e,t){let n=await mt({environment:e}),r=n.values.DASHBOARD_PASSWORD??await to(t,e);return St(await it({environment:e}),e,{availableNames:[...Object.keys(n.values),...r?[`DASHBOARD_PASSWORD`]:[]]}),{accessTokenSigningSecret:await lt({environment:e}),dashboardPassword:r,pendingWorkerSecrets:n}}async function Wa(e,t,n){let r=e.database?.dialect??`postgres`,i;switch(r){case`postgres`:i=await g({env:n});break;case`sqlite`:i=await _({env:n});break;default:throw Error(`Unsupported database dialect "${r}".`)}let a=await Ga(i),o=await ne(a);if(o.length>0)throw Error(`Pending deploy migrations contain unsafe SQL. Move unsafe statements to held migrations.\n${x(o)}`);return qa(t,a)}async function Ga(e){try{return await Ka(e)}finally{await e.close?.()}}async function Ka(e){return ee(await h(),await w(e))}async function qa(e,t){if(t.length===0)return L.log.info(`No pending deploy migrations.`),!1;if(L.note(b(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 L.confirm({initialValue:!0,message:`Run these deploy-safe database migrations before Cloudflare deploy?`});if(L.isCancel(n))throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`);return n}async function Ja(){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 Ya(e){if(e.runMigrations&&e.skipMigrations)throw Error(`Use only one of --run-migrations or --skip-migrations.`)}function Xa(e,t){if(t===`client`&&(e.runMigrations||e.skipMigrations))throw Error(`Migration flags are not available when deploy.mode is "client".`)}async function Za(e,t,n=rt){return e.url?Qa(e.url,t):t===`staging`&&e.stagingHostname?Qa(await n(),t):Qa(void 0,t)}function Qa(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 $a(e){if(e.environment!==`production`||e.yes)return;if(!process.stdout.isTTY)throw Error(`Production deploys require --yes in noninteractive environments.`);let t=await L.confirm({initialValue:!1,message:`Deploy to production?`});if(L.isCancel(t)||!t)throw L.cancel(`Deploy cancelled.`),Error(`Deploy cancelled.`)}function eo(e,t){let n=t.filter(t=>!e[t]);if(n.length>0)throw Error(`Missing required deploy environment variables: ${n.join(`, `)}`);return Object.fromEntries(t.map(t=>[t,e[t]]))}async function to(e,t){let n=e.DASHBOARD_PASSWORD?.trim();if(n)return n;let r;try{r=Et(await z(`.env`,`utf8`))}catch(e){throw ro(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 no(e){let t=await De(M(Ne(),`coreframe-deploy-secrets-`)),n=M(t,`secrets.json`);return await V(n,JSON.stringify(e),{mode:384}),{path:n,dispose:()=>B(t,{force:!0,recursive:!0})}}function ro(e){return e instanceof Error&&`code`in e}function io(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 ao(e){let{POSTHOG_API_KEY:t,POSTHOG_PROJECT_ID:n,...r}=e;return r}async function oo(){let e=await co();return typeof e.mobileDevHost==`string`?{mobileDevHost:e.mobileDevHost}:{}}async function so(e){let t=await co(),n=lo();await Q.mkdir(A.dirname(n),{recursive:!0}),await Q.writeFile(n,`${JSON.stringify({...t,...e},void 0,2)}\n`)}async function co(){try{let e=await Q.readFile(lo(),`utf8`),t=JSON.parse(e);return uo(t)?t:{}}catch{return{}}}function lo(){return A.join(Cr.homedir(),`.coreframe`,`preferences.json`)}function uo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function fo({env:e=W.env,interactive:t=W.stdin.isTTY===!0,platform:n,target:r}){let i=await yo(n,e).catch(()=>[]),a=r?Lo(i,r):void 0;if(a)return a;if(!r&&i.length>0)return vo(i,n,t);let o=r?Lo(await xo(e).catch(()=>[]),r):void 0;if(o&&o.platform===n)return So(o,n,e,t);let s=await bo(n,e),c=r?Lo(s,r):void 0;if(c)return c;if(!r&&s.length>0)return vo(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 po(e){let{device:t,host:n,interactive:r=W.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=zo();if(i.length===0)throw Error(`No external IP address was detected. Pass one explicitly with --host.`);let a=await go();if(a&&i.includes(a))return a;if(i.length===1)return await _o(i[0]),i[0];if(!r)throw Error(`Multiple external IP addresses were detected (${i.join(`, `)}). Pass one explicitly with --host.`);let o=await L.select({message:`Which IP address should the mobile device use to reach the development server?`,options:i.map(e=>({label:e,value:e}))});if(L.isCancel(o))throw Error(`Mobile development IP selection was cancelled.`);return await _o(o),o}async function mo({device:e,env:t=W.env,host:n,interactive:r,platform:i,port:a}){if(i===`android`&&e.physical&&n===void 0)try{return await Ao(e.id,a,t)}catch{L.log.warn(`Could not establish Android ADB port forwarding. Using the LAN development address instead.`)}return{close:async()=>void 0,serverUrl:ho(i,await po({device:e,host:n,interactive:r,platform:i}),a),viteHost:!0}}function ho(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 go(){return(await oo()).mobileDevHost}async function _o(e){try{await so({mobileDevHost:e})}catch(e){L.log.warn(`Could not remember the mobile development IP address: ${e instanceof Error?e.message:String(e)}`)}}async function vo(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 L.select({message:`Which ${t===`ios`?`iOS`:`Android`} device should Coreframe use?`,options:e.map(e=>({label:e.label,value:e,hint:e.id}))});if(L.isCancel(r))throw Error(`Mobile development device selection was cancelled.`);return r}async function yo(e,t){return e===`android`?wo(t):Eo(t)}async function bo(e,t){return e===`android`?To(t):Do(t)}async function xo(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 So(e,t,n,r){let i=await Co(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 Co(t,n).catch(()=>[]),o=Lo(a,e.id);if(o)return o;let s=a.filter(e=>!i.some(t=>t.id===e.id));if(s.length>0)return vo(s,t,r);if(a.length===1)return a[0];await Rt(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 Co(e,t){return e===`ios`?Do(t,`booted`):(await wo(t)).filter(e=>!e.physical)}async function wo(e){let t=await ko(e,`platform-tools`,W.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 Mo(t,e,n,`ro.product.model`),i=n.startsWith(`emulator-`),a=i?await Po(t,e,n,r):await Fo(t,e,n,r);return{id:n,label:a===r?a:`${a} (${r})`,name:a,physical:!i}}))).sort(Bo)}async function To(e){let{stdout:t}=await I(await ko(e,`emulator`,W.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 Eo(e){let t=await Q.mkdtemp(A.join(Cr.tmpdir(),`coreframe-ios-devices-`)),n=A.join(t,`devices.json`);try{return await Q.writeFile(n,``),await I(`xcrun`,[`devicectl`,`list`,`devices`,`--json-output`,n],{env:e}),(JSON.parse(await Q.readFile(n,`utf8`)).result?.devices??[]).filter(Oo).map(e=>({id:e.hardwareProperties.udid,label:`${e.deviceProperties.name} (${e.hardwareProperties.productType})`,name:e.deviceProperties.name,physical:!0})).sort(Bo)}finally{await Q.rm(t,{force:!0,recursive:!0})}}async function Do(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(Bo)}function Oo(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 ko(e,t,n){let r=e.ANDROID_HOME??e.ANDROID_SDK_ROOT,i=r?[r]:jo(e);for(let e of i){let r=A.join(e,t,n);try{return await Q.access(r),r}catch{}}return n}async function Ao(e,t,n){let r=await ko(n,`platform-tools`,W.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 jo(e){return W.platform===`darwin`?[A.join(Cr.homedir(),`Library`,`Android`,`sdk`)]:W.platform===`win32`&&e.LOCALAPPDATA?[A.join(e.LOCALAPPDATA,`Android`,`Sdk`)]:[A.join(Cr.homedir(),`Android`,`Sdk`)]}async function Mo(e,t,n,r){return(await No(e,t,[`-s`,n,`shell`,`getprop`,r])).trim()}async function No(e,t,n){return(await I(e,n,{env:t,timeout:3e3})).stdout}async function Po(e,t,n,r){return No(e,t,[`-s`,n,`emu`,`avd`,`name`]).then(e=>e.split(/\r?\n/)[0]?.trim()||r).catch(()=>r)}async function Fo(e,t,n,r){return No(e,t,[`-s`,n,`shell`,`dumpsys`,`bluetooth_manager`]).then(e=>Io(e)||r).catch(()=>r)}function Io(e){return e.match(/\bname: (.+)/)?.[1]?.trim()}function Lo(e,t){let n=e.map(e=>({device:e,score:Math.max(Ro(t,e.name),Ro(t,e.id))})).sort((e,t)=>t.score-e.score)[0];return n&&n.score>0?n.device:void 0}function Ro(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 zo(){return[...new Set(Object.values(Cr.networkInterfaces()).flatMap(e=>e??[]).filter(e=>!e.internal&&e.family===`IPv4`).map(e=>e.address))].sort()}function Bo(e,t){return e.label.localeCompare(t.label)}async function Vo(e,t){if(!e)return()=>void 0;Ve(A.dirname(e),{recursive:!0}),q(e,``,{flag:`a`});let n;try{n=K(e,`utf8`)}catch{n=void 0}let r=0,i=!1,a=Ke(e,{persistent:!1},()=>{if(i)return;let a=++r;z(e,`utf8`).then(e=>{i||a!==r||e===n||(n=e,t())},()=>void 0)});return()=>{i=!0,a.close()}}function Ho(e,t){let n={...e};return t===`web`||t===`webext`?n.COREFRAME_PLATFORM=`web`:n.COREFRAME_PLATFORM=t,n}const Uo=W.platform===`win32`?`portless.cmd`:`portless`,Wo=RegExp(`\x1B\\[[0-?]*[ -/]*[@-~]`,`g`),Go=/^Proxy is already running on port (\d+)\.$/,Ko=/^To restart: portless proxy stop(?: (?:-p|--port) \d+)? && portless proxy start(?: (?:-p|--port) \d+)?$/;function qo(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(Wo,``).trim().match(Go);if(a?.[1]!==void 0&&i!==void 0&&Ko.test(i.replace(Wo,``).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 Jo(e){let t=qo(e);t&&W.stdout.write(t.endsWith(`
|
|
14
|
+
`)?t:`${t}\n`)}async function Yo({cwd:e,env:t,platform:n}){return n!==`web`||t.PORTLESS===`0`||(await zt()).isAgent?!1:Mt(e)}async function Xo({cwd:e,env:t,lan:n=!1}){let r=A.join(`node_modules`,`.bin`,Uo),i=[`proxy`,`start`,...n?[`--lan`]:[]];try{let{stdout:n}=await I(A.resolve(e,r),i,{cwd:e,env:t,stdin:`inherit`,stdout:`pipe`,stderr:`inherit`});Jo(n)}catch(e){throw typeof e==`object`&&e&&`stdout`in e&&typeof e.stdout==`string`&&Jo(e.stdout),e}}function Zo({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 Qo=/A Dart VM Service on .+ is available at: (https?:\/\/\S+)/u,$o=/The Flutter DevTools debugger and profiler on .+ is available at: (https?:\/\/\S+)/u,es=A.join(`.coreframe`,`dev`,`session.json`);async function ts({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=A.resolve(t,es),d=A.dirname(u),f={version:1,id:a,pid:c,projectRoot:A.resolve(t),startedAt:s.toISOString(),platform:l,vite:{localOrigin:o,appOrigin:e},logs:{path:A.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,...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 R(d,{recursive:!0});let t=A.join(d,`.session-${a}.json`);await V(t,e),await ke(t,u)}),p};return await m(),{path:u,async recordFlutterOutput(e){let t=e.match(Qo)?.[1],n=e.match($o)?.[1];f.flutter===void 0||t===void 0&&n===void 0||(f={...f,flutter:{...f.flutter,...t===void 0?void 0:{vmServiceUri:t},...n===void 0?void 0:{devToolsUri:n}}},await m())},async close(){await p;try{JSON.parse(await z(u,`utf8`)).id===a&&await B(u,{force:!0})}catch(e){if(e.code!==`ENOENT`)throw e}}}}const ns=`extension:dev`;function rs(e){if(!G(M(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=M(e,`package.json`),n;try{n=JSON.parse(K(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.${ns} for \`coreframe dev webext\`. Apply the wxt recipe and add its named extension lifecycle scripts.`)}function is({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`,ns,...n.length>0?[`--`,...n]:[]]}const as=[`web`,`webext`,`ios`,`android`,`macos`,`windows`,`linux`],os=[`managed-dev-overlay`],ss=A.resolve(`node_modules`,`.bin`),cs=W.platform===`win32`?`pnpm.cmd`:`pnpm`,ls=W.platform===`win32`?`portless.cmd`:`portless`,us=W.platform===`win32`?`react-router.cmd`:`react-router`;async function ds({cwd:e=W.cwd(),debug:t,device:n,env:r=W.env,flutterDebug:i=!1,flutterMcp:a=!1,flutterOutput:o=`filtered`,host:s,https:c=!1,interactive:l=W.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=Ot({env:r}),ee=r.PATH??r.Path??``,y=bs(h)?h:void 0,b=Gt(i||a),x=ys(_??r.COREFRAME_WEB_PORT),S,C,w,te,T,ne,re,ie,ae,se,ce,le,E=!1,de,D=r;if(d&&p)throw Error(`Cannot use --managed and --no-managed together.`);if(t===`managed-dev-overlay`&&d)throw Error(`Cannot use --managed with --debug managed-dev-overlay.`);if(i&&y===void 0)throw Error(`The --flutter-debug option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(a&&y===void 0)throw Error(`The --flutter-mcp option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(f&&h!==`macos`)throw Error(`The --no-codesign option is only supported for macOS Flutter development.`);if(o===`full`&&y===void 0)throw Error(`The --flutter-output option is only supported for Flutter development platforms (iOS, Android, macOS, Windows, and Linux).`);if(h===`webext`){if(d||p||t!==void 0||g)throw Error(`Managed development, debug features, and verbose native output are only supported for the main web or native development platforms.`);rs(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 O=await v.measure(`routing`,()=>Yo({cwd:e,env:r,platform:h}));O&&await v.measure(`portless`,()=>Xo({cwd:e,env:r,lan:u}));let k=y===void 0?h===`web`?x??await Sr.getAvailablePort():h===`webext`?x:void 0:x??await Sr.getAvailablePort(),j,pe=new Promise(e=>{j=e}),M=()=>{E||(E=!0,j(),C?.kill(`SIGTERM`),ne?.kill(`SIGTERM`),re?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ie?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),ae?.close().catch(()=>void 0),S?.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0),N().catch(()=>void 0))},N=()=>te?(T??=te[Symbol.asyncDispose](),T):Promise.resolve(),P=e=>{de??=e,M()},F=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>P(e);return W.on(e,t),{handler:t,signal:e}}),me=async e=>{let t=Je(e);C=t;try{await t.expectSuccess()}catch(e){if(!E)throw e}finally{C===t&&(C=void 0)}};try{ce=y?Lt({path:A.resolve(e,`.leylines`,`logs.sqlite`)}):void 0;let i=h===`ios`||h===`android`?h:void 0,_=i?await fo({env:r,interactive:l,platform:i,target:n}):void 0;i&&_&&Kt({device:_,mode:b,platform:i});let x=y?ce?.logger({scope:`dev.flutter`,properties:{platform:y,..._?{deviceId:_.id}:void 0}}):void 0;se=i&&_&&k!==void 0?await mo({device:_,env:r,host:s,interactive:l,platform:i,port:k}):void 0;let C=se?.viteHost??(y?i?!0:`127.0.0.1`:s),T=k===void 0?void 0:`${c?`https`:`http`}://127.0.0.1:${k}`,de=y===void 0?T:se?.serverUrl??ho(y,void 0,k),j={},N=!1,P;[j,N]=await Promise.all([v.measure(`config`,()=>H({cwd:e})),v.measure(`managed`,async()=>t!==`managed-dev-overlay`&&(d||l&&!p)&&await jt(e))]),await v.measure(`i18n`,()=>Kn({cwd:e,projectConfig:j})),P=h!==`webext`&&kr(e)?await Sr.getAvailablePort():void 0;let F=await v.measure(`https`,async()=>c&&!O?Nt({cwd:e}):void 0),he=Ho(r,h);D={...he,...v.environment,...t===`managed-dev-overlay`?{VITE_COREFRAME_MANAGED_DEV_OVERLAY_DEBUG:`1`}:void 0,...!m&&h!==`webext`?{[Pt]:U()}:void 0,...y?{COREFRAME_PLATFORM:y,[It]:A.resolve(e,`.coreframe`,`managed-dev-flutter-restart`)}:void 0,...F?{[kt]:F.cert,[At]:F.key}:void 0,...P?{COREFRAME_DASHBOARD_ORIGIN:`http://127.0.0.1:${P}`}:void 0},T!==void 0&&de!==void 0&&(le=await ts({appOrigin:de,cwd:e,device:_,flutterMcp:a,flutterMode:y===void 0?void 0:b,id:U(),localOrigin:T,platform:h}));let ge=async()=>{if(!P)return;let t=Ar({cwd:e,env:D,port:P});ae=t;try{await t.listen(),await t.wait()}finally{await t.close(),ae===t&&(ae=void 0)}},_e=async()=>{let t=J({label:`web`}),n=J({color:`red`,label:`web`});t.pipe(W.stdout,{end:!1}),n.pipe(W.stderr,{end:!1}),re=I(O?ls:us,O?Zo({host:C,lan:u,port:k}):vs({host:C,port:k,strictPort:h===`web`||y!==void 0}),{cwd:e,env:{...D,CLOUDFLARE_ENV:`development`,NODE_OPTIONS:[D.NODE_OPTIONS,`--conditions=development`].filter(Boolean).join(` `),PATH:ss+A.delimiter+ee},stdin:`inherit`});let r=Promise.allSettled([ms(re.stdout,t),ms(re.stderr,n)]);try{await re;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([qe(t),qe(n)]),re=void 0}},ve=async()=>{let t=J({label:`webext`}),n=J({color:`red`,label:`webext`});t.pipe(W.stdout,{end:!1}),n.pipe(W.stderr,{end:!1}),ie=I(cs,is({host:s,port:k}),{cwd:e,env:D,stdin:`inherit`});let r=Promise.allSettled([ms(ie.stdout,t),ms(ie.stderr,n)]);try{await ie;let e=(await r).find(e=>e.status===`rejected`);if(e)throw e.reason}catch(e){if(!E)throw e}finally{await r,t.end(),n.end(),await Promise.allSettled([qe(t),qe(n)]),ie=void 0}},ye=async t=>{let n,r=!1,i=Vo(D[It],()=>{if(!(E||!n)){if(b===`debug`){n.nodeChildProcess.then(e=>e.stdin?.write(`R`)).catch(()=>void 0);return}r||(r=!0,n.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0))}});try{for(;!E;){r=!1;let i=h===`android`&&o===`filtered`&&!g?await fe():void 0,s=I(`flutter`,qt({device:_??{id:h},flutterDriver:a,mode:b,serverUrl:de,verbose:g}),{cwd:A.join(e,`src-flutter`),env:Wt(he,{noCodesign:f}),stdio:[b===`debug`?`pipe`:`ignore`,`pipe`,`pipe`]});S=s,n=s;try{let e=i?i.capture(ps(s,x,`output`,le?.recordFlutterOutput)):Promise.all([fs(s.stdout,W.stdout,x,`stdout`,le?.recordFlutterOutput),fs(s.stderr,W.stderr,x,`stderr`,le?.recordFlutterOutput)]);if(await Promise.all([s,e]),!r||E)return}catch{if(r&&!E)continue;if(E)return;let e=l?await L.confirm({initialValue:!0,message:`Flutter failed. Retry?`}):!1;if(L.isCancel(e)||!e){L.log.warn(t?`Flutter stopped. Web development is still running.`:`Flutter stopped.`),await(t??pe);return}}finally{S===s&&(S=void 0),n===s&&(n=void 0)}}}finally{(await i)()}},be=async()=>{if(h===`web`){await _e();return}let t=_e().then(()=>{if(!E)throw Error(`The Vite development server stopped while Flutter was still running.`)});await ue({cwd:e});try{await Promise.race([t,ye(t)])}finally{M(),await Promise.allSettled([t,S]),S=void 0}},xe=async()=>{let t=Je({name:`panda`,command:cs,args:[`exec`,`panda`,`dev`,`--no-color`],cwd:e,env:D});ne=t;try{if(await t.expectSuccess(),!E)throw Error(`The Panda CSS watcher stopped while development was still running.`)}catch(e){if(!E)throw e}finally{ne===t&&(ne=void 0)}},Se=async()=>{if(h===`webext`){await ve();return}let e=xe(),t=be(),n=P?ge():void 0;try{await Promise.race([e,t,n].filter(e=>e!==void 0)),E&&await t}finally{M(),await Promise.allSettled([e,t,n].filter(e=>e!==void 0))}};if(N&&(D={...D,[Ft]:`1`}),E)return;if(h===`webext`){v.report(),await Se();return}if(j.database?.dialect===`sqlite`&&(await v.measure(`database`,async()=>{let t=await oe({config:j,cwd:e,env:r,tursoOutput:W.stdout,useSupervisorLease:!0});te=t,D={...D,...t.env}}),await v.measure(`schema`,()=>me({name:`db`,command:cs,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E))return;if(_s(j)){let t=J({label:`postgres`});t.pipe(W.stdout,{end:!1});try{let n=await v.measure(`database`,()=>gs({config:j,cwd:e,env:D,failIfRunning:!0,interactive:l,isStopping:()=>E,postgresOutput:t,useSupervisorLease:!0}));if(!n)return;w=n,D={...D,...n.env};try{E||await v.measure(`schema`,()=>me({name:`db`,command:cs,args:[`db`,`ensure`],cwd:e,env:D,prefix:!1})),E||(v.report(),await Se())}finally{await n[Symbol.asyncDispose](),w===n&&(w=void 0)}}finally{t.end()}return}v.report(),await Se()}finally{M(),await se?.close(),se=void 0;let e;try{await w?.[Symbol.asyncDispose]()}catch(t){e=t}finally{await N();try{await le?.close()}finally{ce?.close();for(let{handler:e,signal:t}of F)W.off(t,e)}de&&(W.exitCode??=de===`SIGINT`?130:143)}hs(e)}}async function fs(e,t,n,r,i){for await(let a of ps(e,n,r,i))t.write(`${a}\n`)||await Dt(t,`drain`)}async function*ps(e,t,n,r){for await(let i of e){let e=le(i);e.message&&(t?.write(e.level,e.message,{properties:{stream:n}}),await r?.(e.message)),yield i}}async function ms(e,t){for await(let n of e)t.write(`${n}\n`)||await Dt(t,`drain`)}function hs(e){if(e)throw e}async function gs({interactive:e,isStopping:t,...n}){try{return await ae(n)}catch(r){if(!(r instanceof f)||!e)throw r;let i=await L.confirm({initialValue:!1,message:`PostgreSQL is already running for this project (PID ${r.pid}). Stop it and start here?`});if(L.isCancel(i)||!i){L.cancel(`Keeping the existing PostgreSQL process.`);return}return await se(r),t()?void 0:ae(n)}}function _s(e){return(e.database?.dialect??`postgres`)===`postgres`}function vs({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 ys(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 bs(e){return e===`android`||e===`ios`||e===`linux`||e===`macos`||e===`windows`}async function xs(e={}){let t=e.cwd??W.cwd(),n=`scripts/preview.ts`,r={},i=!0;try{await Ce(A.resolve(t,n))}catch(e){if(e.code===`ENOENT`)i=!1;else throw e}if(i){let e=await Fe(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 Bt({...e,cwd:t},r)}const Ss=`worker-configuration.d.ts`;async function Cs({check:e=!1,cwd:t=process.cwd()}={}){let n=await H({cwd:t}),r=await st({coreframeConfig:n,cwd:t}),i=P(t,Ss),a=P(t,`.coreframe-worker-types-${U()}.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 ws(e),e}let o=Ts(await z(a,`utf8`)),s=Le(r.config),c=Ie(n.worker?.environment).filter(e=>!s.has(e.name)),l=`${o.trimEnd()}\n\n${Es(c)}\n`;if(e){if(await z(i,`utf8`).catch(()=>``)!==l)throw Error(`${Ss} is stale. Run "coreframe worker typegen" and commit the result.`);return{changed:!1,path:i}}let u=await z(i,`utf8`).catch(()=>``);return u!==l&&await V(i,l),{changed:u!==l,path:i}}finally{await r.dispose(),await B(a,{force:!0})}}function ws(e){if(typeof e!=`object`||!e||!(`output`in e))return;let{output:t}=e;typeof t!=`string`||t===``||process.stderr.write(t.endsWith(`
|
|
15
|
+
`)?t:`${t}\n`)}function Ts(e){return e.split(/\r?\n/).filter(e=>!e.startsWith(`// Generated by Wrangler by running `)).join(`
|
|
16
|
+
`)}function Es(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(`
|
|
17
|
+
`)}const Ds=new Set([`.coreframe`,`.git`,`.react-router`,`.wrangler`,`.wxt`,`build`,`dist`,`node_modules`,`styled-system`,`target`]),Os=[`node_modules/@react-router/dev/package.json`,`node_modules/react-router/package.json`,`package.json`,`pnpm-lock.yaml`,`react-router.config.ts`,`src/web`],ks=[`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`],As=[`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`],js=`.coreframe/typegen.json`,Ms=[`web`,`dashboard`,`worker`];async function Ns({checkWorker:e=!1,cwd:t=W.cwd(),runners:n={}}={}){let r=await Ls(t)??{generators:{},schemaVersion:1},i=[];return i.push(await Fs({cwd:t,inputPaths:Os,name:`web`,outputPath:`.react-router`,run:()=>(n.web??Is)(t),state:r})),i.push(await Fs({cwd:t,inputPaths:ks,name:`dashboard`,outputPath:`dashboard/.react-router`,run:()=>(n.dashboard??_r)(t),state:r})),i.push(await Fs({cwd:t,inputPaths:As,name:`worker`,outputPath:`worker-configuration.d.ts`,run:()=>(n.worker??Cs)({check:e,cwd:t}),state:r})),i}function Ps(e){return`${{dashboard:`Dashboard route types`,web:`Web route types`,worker:`Worker types`}[e.name]} ${e.changed?`generated`:`unchanged`}.`}async function Fs({cwd:e,inputPaths:t,name:n,outputPath:r,run:i,state:a}){let o=await zs(e,t),s=await Bs(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 Bs(e,r);if(!l)throw Error(`Coreframe ${n} typegen did not produce ${r}.`);return a.generators[n]={inputFingerprint:o,outputFingerprint:l},await Rs(e,a),{changed:s!==l,name:n,ran:!0}}async function Is(e){let t=W.platform===`win32`?`react-router.cmd`:`react-router`,n=W.env;await I(t,[`typegen`],{cwd:e,env:{...n,PATH:A.resolve(e,`node_modules/.bin`)+A.delimiter+(n.PATH??n.Path??``)},stdio:`inherit`})}async function Ls(e){try{let t=JSON.parse(await z(A.resolve(e,js),`utf8`));if(!Ws(t)||t.schemaVersion!==1)return;let n={};if(!Ws(t.generators))return;for(let e of Ms){let r=t.generators[e];Ws(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 Rs(e,t){let n=A.resolve(e,js);await R(A.dirname(n),{recursive:!0}),await V(n,`${JSON.stringify(t)}\n`,{mode:384})}async function zs(e,t){let n=Re(`sha256`);for(let r of[...t].sort()){let t=A.resolve(e,r),i=await Hs(t);if(!i){n.update(`missing:${r}\0`);continue}if(i.isDirectory()){n.update(`directory:${r}\0`);for(let r of await Vs(t)){let i=A.join(t,r),a=A.relative(e,i).split(A.sep).join(`/`);n.update(`${a}\0`),n.update(await z(i))}continue}i.isFile()&&(n.update(`file:${r}\0`),n.update(await z(t)))}return n.digest(`hex`)}async function Bs(e,t){if(await Hs(A.resolve(e,t)))return zs(e,[t])}async function Vs(e){let t=[];async function n(e,r){let i=await Oe(e,{withFileTypes:!0});i.sort((e,t)=>e.name.localeCompare(t.name));for(let a of i)if(a.isDirectory()){if(Ds.has(a.name))continue;await n(A.join(e,a.name),A.join(r,a.name))}else a.isFile()&&t.push(A.join(r,a.name))}return await n(e,``),t.sort()}async function Hs(e){try{return await Ae(e)}catch(e){if(Us(e))return;throw e}}function Us(e){return e instanceof Error&&`code`in e&&e.code===`ENOENT`}function Ws(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Gs=A.resolve(`node_modules`,`.bin`);W.env.PATH=Gs+A.delimiter+W.env.PATH;const Ks=W.platform===`win32`?`tsc.cmd`:`tsc`,qs=[{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 Js(){await Ns({checkWorker:!0});let e=[];for(let t of qs)try{await Ce(t.path),e.push(t)}catch(e){if(!(e instanceof Error&&`code`in e&&e.code===`ENOENT`))throw e}let t=e.map(e=>Je({name:e.name,command:Ks,args:[`-p`,e.path]})),n=(await Promise.all(t.map(e=>e.wait()))).filter(e=>e.exitCode!==0);n.length>0&&(W.exitCode=n[0].exitCode)}const Ys=n(a(os),{displayName:`feature`,from:async e=>e}),Xs=n(a(Ut),{displayName:`filtered|full`,from:async e=>e}),Zs=[`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.`],Qs=t({name:`deploy`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Deploy to the staging or production environment.`}),runMigrations:r({long:`run-migrations`,description:`Run pending deploy-safe database migrations before deploying.`,defaultValue:()=>!1}),skipMigrations:r({long:`skip-migrations`,description:`Deploy without running pending deploy-safe database migrations.`,defaultValue:()=>!1}),skipPostDeployChecks:r({long:`skip-post-deploy-checks`,description:`Skip post-deploy checks after Cloudflare deployment.`,defaultValue:()=>!1}),yes:r({long:`yes`,short:`y`,description:`Approve the production deployment confirmation.`,defaultValue:()=>!1})},handler:({environment:e,runMigrations:t,skipMigrations:n,skipPostDeployChecks:r,yes:i})=>Ba([e,...t?[`--run-migrations`]:[],...n?[`--skip-migrations`]:[],...r?[`--skip-post-deploy-checks`]:[],...i?[`--yes`]:[]])}),$s=d({name:`staging`,cmds:{reassign:t({name:`reassign`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await ht();if(e){console.log(JSON.stringify({...t,notices:Zs}));return}console.log(t.url),console.error(`Staging hostname reassigned. ${Zs.join(` `)}`)}}),url:t({name:`url`,args:{json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({json:e})=>{let t=await rt();console.log(e?JSON.stringify({url:t}):t)}})}}),ec=d({name:`secrets`,cmds:{"rotate-access-token":t({name:`rotate-access-token`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment whose access JWTs should be invalidated.`}),yes:r({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 yt({environment:e}),console.log(`Rotated Coreframe access-token signing material for ${e}. Clients must remint outstanding access JWTs.`)}}),status:t({name:`status`,args:{environment:c({type:s(a(tt)),displayName:`environment`,description:`Inspect staging, production, or both when omitted.`}),json:r({long:`json`,description:`Print machine-readable JSON.`,defaultValue:()=>!1})},handler:async({environment:e,json:t})=>{let n=await it({environment:e});console.log(t?JSON.stringify(n):oc(n))}}),set:t({name:`set`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment to update on its next deploy.`}),name:c({type:s(u),displayName:`name`,description:`Declared Worker secret name; omit to configure known secrets.`}),bulk:r({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 ut({environment:e,name:t,value:await sc(t)}),console.log(`Queued ${t} for ${e}. Run coreframe deploy ${e} to apply.`);return}let r=await ft(),i=n?await lc(r):await cc(r,e);await dt({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:t({name:`discard`,args:{environment:c({type:a(tt),displayName:`environment`,description:`Worker environment with a queued secret update.`}),name:c({type:u,displayName:`name`,description:`Declared Worker secret name.`})},handler:async({environment:e,name:t})=>{let n=await nt({environment:e,name:t});console.log(n?`Discarded the queued ${t} update for ${e}.`:`No ${t} update is queued for ${e}.`)}})}}),tc=t({name:`typecheck`,args:{},handler:Js}),nc=d({name:`worker`,cmds:{typegen:t({name:`typegen`,args:{check:r({long:`check`,description:`Fail when the committed primary Worker declarations are stale.`,defaultValue:()=>!1})},handler:async({check:e})=>{let t=await Cs({check:e});console.log(e?`${dc(t.path)} is current.`:`${dc(t.path)} ${t.changed?`generated`:`is unchanged`}.`)}})}}),rc=t({name:`dev`,args:{debug:o({long:`debug`,type:s(Ys),description:`Launch a development feature in isolated debug mode.`}),flutterDebug:r({long:`flutter-debug`,description:`Run Flutter in debug mode instead of profile mode.`,defaultValue:()=>!1}),flutterMcp:r({long:`flutter-mcp`,description:`Enable the app-side Flutter MCP QA bridge and imply Flutter debug mode.`,defaultValue:()=>!1}),flutterOutput:o({long:`flutter-output`,type:Xs,description:`Choose filtered Android diagnostics (default) or full standard Flutter output.`,defaultValue:()=>`filtered`}),https:r({long:`https`,description:`Serve the web app over locally trusted HTTPS.`,defaultValue:()=>!1}),host:o({long:`host`,type:s(u),implicitValue:`0.0.0.0`,description:`Host address for the web development server. Pass without an address to use 0.0.0.0.`}),lan:r({long:`lan`,description:`Expose the Portless development proxy to devices on the local network.`,defaultValue:()=>!1}),managed:r({long:`managed`,description:`Run managed checkout synchronization even without an interactive terminal.`,defaultValue:()=>!1}),noCodesign:r({long:`no-codesign`,description:`Disable Xcode code signing for macOS Flutter development.`,defaultValue:()=>!1}),noManaged:r({long:`no-managed`,description:`Run without managed checkout synchronization for this invocation.`,defaultValue:()=>!1}),noDevJobs:r({long:`no-dev-jobs`,description:`Skip automatic local development jobs for this invocation.`,defaultValue:()=>!1}),simulator:r({long:`simulator`,description:`Run iOS in Flutter debug mode on the Apple iOS Simulator.`,defaultValue:()=>!1}),platform:c({type:s(a(as)),displayName:`platform`,description:`Development target platform. Defaults to web.`}),device:c({type:s(u),displayName:`device`,description:`Device name or ID for iOS or Android development.`}),port:o({long:`port`,type:s(i),description:`Port for the web development server.`}),verbose:r({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=ic({device:t,flutterDebug:n,platform:f,simulator:m});return ds({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 ic({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 ac=t({name:`preview`,args:{host:o({long:`host`,type:s(u),description:`Host address for the preview server.`}),port:o({long:`port`,type:s(i),description:`Port for the preview server.`})},handler:({host:e,port:t})=>xs({host:e,port:t})});function oc(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=>e.map((e,t)=>e.padEnd(r[t])).join(` `).trimEnd();return[i(n),i(r.map(e=>`-`.repeat(e))),...t].join(`
|
|
18
|
+
`)}async function sc(e){if(!W.stdin.isTTY){let e=``;for await(let t of W.stdin)e+=t.toString();return e.replace(/\r?\n$/,``)}let t=await L.password({message:`Enter the new value for ${e}`});if(L.isCancel(t))throw L.cancel(`Secret update cancelled.`),Error(`Secret update cancelled.`);return t}async function cc(e,t){if(!W.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 L.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(L.isCancel(i))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);i.trim()&&(n[r.name]=i)}return n}async function lc(e){if(e.length===0)throw Error(`No Worker secrets are declared in coreframe.config.ts.`);let t=W.stdin.isTTY?await L.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 uc();if(L.isCancel(t))throw L.cancel(`Secret setup cancelled.`),Error(`Secret setup cancelled.`);let{ignoredNames:n,values:r}=ct(t,e);return n.length>0&&L.log.info(`Ignored non-secret or undeclared names: ${n.join(`, `)}.`),r}async function uc(){let e=``;for await(let t of W.stdin)e+=t.toString();return e}function dc(e){return e.split(/[\\/]/).at(-1)??e}const fc=t({name:`typegen`,description:`Generate Coreframe route and Worker type declarations.`,args:{},handler:async()=>{let e=await Ns();for(let t of e)console.log(Ps(t))}});function pc(e,{formatMessage:t,temporaryDirectory:n=Ne(),write:r=e=>console.error(e)}={}){let i=yc(e),a=Sc(hc(e,t),i);try{let t=M(He(M(n,`coreframe-error-`)),`error.log`);return q(t,`${Sc(gc(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 mc(t,n={}){let r=typeof t==`function`?t:()=>e.run(e.binary(t),process.argv),i=!1,a=e=>{i||(i=!0,pc(e,n),process.exit(1))};process.once(`uncaughtException`,a),process.once(`unhandledRejection`,a),Promise.resolve().then(r).catch(a)}function hc(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 gc(e){try{let t=_c(e);if(!(e instanceof Error)||!vc(t))return Tt(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${Tt(t,{customInspect:!1,depth:10})}`:``}`}catch{return`The thrown value could not be inspected.`}}function _c(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:_c(a.value,t),writable:!0})}return i}function vc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yc(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`?bc(t.value,n):r(t.value))}}}try{r(e)}catch{}return n}function bc(e,t){if(!(typeof e!=`object`||!e))for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);typeof n==`string`&&xc(n)&&r&&`value`in r&&typeof r.value==`string`&&r.value&&t.add(r.value)}}function xc(e){return/(?:^|_)(?:AUTH|CERT|COOKIE|CREDENTIALS?|DATABASE_URL|DSN|KEY|PASS(?:WORD)?|PRIVATE|SECRET|SESSION|TOKEN)(?:_|$)/i.test(e)}function Sc(e,t){return[...t].sort((e,t)=>t.length-e.length).reduce((e,t)=>e.replaceAll(t,`[redacted environment value]`),e)}const Cc=d({name:`coreframe`,cmds:{build:sn,dashboard:Nr,assets:fr,flutter:pr,i18n:mr,deploy:Qs,staging:$s,secrets:ec,typegen:fc,typecheck:tc,worker:nc,dev:rc,preview:ac,upgrade:Ia,recipes:La,db:Ra}});import.meta.main&&mc(Cc,{formatMessage:process.argv[2]===`db`?y:void 0});export{Cc as coreframeCli};
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreframe/scripts",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.26",
|
|
4
4
|
"description": "Coreframe project workflow CLI and automation scripts",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/
|
|
7
|
+
"url": "git+https://github.com/coreframe-js/coreframe.git",
|
|
8
8
|
"directory": "node/scripts"
|
|
9
9
|
},
|
|
10
10
|
"bin": {
|
|
@@ -25,18 +25,19 @@
|
|
|
25
25
|
"@alloc/cmd-ts": "0.17.1",
|
|
26
26
|
"@clack/prompts": "^1.6.0",
|
|
27
27
|
"@vercel/detect-agent": "^1.2.3",
|
|
28
|
+
"leylines": "^0.3.8",
|
|
28
29
|
"nano-spawn": "^2.1.0",
|
|
29
30
|
"procband": "^0.3.8",
|
|
30
31
|
"yaml": "^2.9.0",
|
|
31
|
-
"@coreframe/assets": "^0.1.
|
|
32
|
-
"@coreframe/
|
|
33
|
-
"@coreframe/
|
|
34
|
-
"@coreframe/
|
|
35
|
-
"@coreframe/
|
|
36
|
-
"@coreframe/
|
|
37
|
-
"@coreframe/
|
|
38
|
-
"@coreframe/preview": "^0.1.
|
|
39
|
-
"@coreframe/
|
|
32
|
+
"@coreframe/assets": "^0.1.13",
|
|
33
|
+
"@coreframe/db": "^0.1.14",
|
|
34
|
+
"@coreframe/deploy": "^0.1.10",
|
|
35
|
+
"@coreframe/dev": "^0.1.17",
|
|
36
|
+
"@coreframe/flutter-tools": "^0.1.19",
|
|
37
|
+
"@coreframe/config": "^0.1.10",
|
|
38
|
+
"@coreframe/object-storage": "^0.1.4",
|
|
39
|
+
"@coreframe/preview": "^0.1.13",
|
|
40
|
+
"@coreframe/dev-contracts": "^0.1.8"
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
43
|
"@types/node": "^26.1.0",
|