@stacksjs/actions 0.75.452 → 0.75.457
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/build/android-config.d.ts +19 -3
- package/dist/build/android-config.js +1 -1
- package/dist/build/android.js +1 -1
- package/dist/build/ios-config.d.ts +17 -44
- package/dist/build/ios-config.js +1 -1
- package/dist/build/ios.js +1 -1
- package/dist/build/native-sensors.d.ts +5 -0
- package/dist/build/native-sensors.js +1 -0
- package/dist/dev/dashboard-utils.d.ts +10 -0
- package/dist/dev/dashboard-utils.js +1 -1
- package/dist/dev/dashboard.js +2 -2
- package/dist/prepublish.js +1 -1
- package/package.json +40 -40
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import type { AndroidMobileConfig } from '@stacksjs/types';
|
|
1
|
+
import type { AndroidMobileConfig, MobileCapabilities } from '@stacksjs/types';
|
|
2
|
+
/** The exact flag map generated for the selected published builder. */
|
|
3
|
+
export declare function androidCapabilityKeys(nativeSensorCapabilities?: readonly string[]): Partial<Record<keyof MobileCapabilities, `enable${string}`>>;
|
|
2
4
|
/** An explicit provider must be implemented by the resolved published builder. */
|
|
3
5
|
export declare function assertCraftSupportsAndroidMapProvider(config: AndroidMobileConfig, providers?: readonly string[]): void;
|
|
4
6
|
/** Which floored features this android config uses. */
|
|
5
7
|
export declare function androidCraftFeatures(config: AndroidMobileConfig, options?: { appBundle?: boolean }): AndroidCraftFeature[];
|
|
6
8
|
/** Refuse to generate an app the resolved Craft would build without what config/mobile.ts asks for. */
|
|
7
9
|
export declare function assertCraftSupportsAndroid(config: AndroidMobileConfig, version: string, source: string, options?: { appBundle?: boolean }): void;
|
|
8
|
-
export declare function toCraftAndroidConfig(config: AndroidMobileConfig): CraftAndroidConfig;
|
|
10
|
+
export declare function toCraftAndroidConfig(config: AndroidMobileConfig, nativeSensorCapabilities?: readonly string[]): CraftAndroidConfig;
|
|
9
11
|
export declare function validateAndroidMobileConfig(config: AndroidMobileConfig): void;
|
|
10
12
|
/** The release an Android build's events name, and so the one its R8 mapping is stored under. */
|
|
11
13
|
export declare function androidRelease(config: Pick<AndroidMobileConfig, 'version' | 'versionCode' | 'crashReporting'>): string;
|
|
@@ -16,6 +18,14 @@ export declare function androidRelease(config: Pick<AndroidMobileConfig, 'versio
|
|
|
16
18
|
* not fail a release build.
|
|
17
19
|
*/
|
|
18
20
|
export declare function uploadAndroidMapping(mappingPath: string, host: string, release: string, token: string | undefined, send?: typeof fetch): Promise<{ ok: boolean, message: string }>;
|
|
21
|
+
/**
|
|
22
|
+
* An app's `android.capabilities` names, and the Craft `enable…` flag each
|
|
23
|
+
* sets. Closed, like ios-config.ts's map, and checked against the installed
|
|
24
|
+
* Craft by tests/craft-capability-parity.test.ts.
|
|
25
|
+
*/
|
|
26
|
+
declare const CAPABILITY_KEYS: Partial<Record<keyof MobileCapabilities, `enable${string}`>>;
|
|
27
|
+
/** Craft Android flags no `android.capabilities` name sets, each with why. */
|
|
28
|
+
export declare const ANDROID_UNMAPPED_CRAFT_FLAGS: Readonly<Record<`enable${string}`, string>>;
|
|
19
29
|
/**
|
|
20
30
|
* The first craft-native release whose Android template honours a feature
|
|
21
31
|
* of `config/mobile.ts`'s android section, the Android sibling of
|
|
@@ -42,7 +52,9 @@ export declare const CRAFT_ANDROID_FLOORS: {
|
|
|
42
52
|
/** CraftCrashReporter.kt: uncaught exceptions, ANRs, JavaScript errors, the outbox. */
|
|
43
53
|
crashReporting: '0.0.179';
|
|
44
54
|
/** A white notification glyph and tint for push, local and recording notifications. */
|
|
45
|
-
notificationIcon: '0.0.241'
|
|
55
|
+
notificationIcon: '0.0.241';
|
|
56
|
+
/** The accelerometer's `shake` event. Tagged at 0.0.427, first published in 0.0.435. */
|
|
57
|
+
shakeGesture: '0.0.435'
|
|
46
58
|
};
|
|
47
59
|
export declare interface CraftAndroidConfig {
|
|
48
60
|
[key: string]: unknown
|
|
@@ -71,6 +83,9 @@ export declare interface CraftAndroidConfig {
|
|
|
71
83
|
mapsApiKey?: string
|
|
72
84
|
enableBluetooth?: boolean
|
|
73
85
|
enableHeartRate?: boolean
|
|
86
|
+
enableShakeGesture?: boolean
|
|
87
|
+
enableHealthServices?: boolean
|
|
88
|
+
enableWallet?: boolean
|
|
74
89
|
enableHealthConnect?: boolean
|
|
75
90
|
renderer?: AndroidMobileConfig['renderer']
|
|
76
91
|
nativeScreens?: Record<string, string>
|
|
@@ -81,3 +96,4 @@ export declare interface CraftAndroidConfig {
|
|
|
81
96
|
privacyPolicyURL?: string
|
|
82
97
|
}
|
|
83
98
|
export type AndroidCraftFeature = keyof typeof CRAFT_ANDROID_FLOORS;
|
|
99
|
+
export { CAPABILITY_KEYS as ANDROID_CAPABILITY_KEYS };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{NATIVE_APP_ROUTE,normalizeMobileUrl,toCraftCrashReporting}from"./ios-config";import{nativeScreenRoutes}from"./native-screens";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",audioRecording:"enableAudioRecording",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",pushNotifications:"enablePushNotifications",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",keepAwake:"enableKeepAwake",deepLinks:"enableDeepLinks",healthConnect:"enableHealthConnect",bluetooth:"enableBluetooth",heartRate:"enableHeartRate",localNetwork:"enableLocalNetwork",localDatabase:"enableLocalDatabase",localNotifications:"enableLocalNotifications"};export const CRAFT_ANDROID_FLOORS={audioRecording:"0.0.324",nativeShell:"0.0.169",appLinks:"0.0.201",bluetooth:"0.0.178",heartRate:"0.0.247",healthConnect:"0.0.169",backgroundRefresh:"0.0.169",appBundle:"0.0.169",crashReporting:"0.0.179",notificationIcon:"0.0.241"};export function assertCraftSupportsAndroidMapProvider(config,providers){if(config.mapProvider&&!providers?.includes(config.mapProvider))throw Error(`The resolved Craft Android builder does not advertise native map provider '${config.mapProvider}'. Upgrade craft-native to a published SDK supporting that provider before building this app.`)}export function androidCraftFeatures(config,options={}){const features=[];if(config.renderer==="native"&&Object.keys(config.nativeScreens??{}).length)features.push("nativeShell");if(config.appLinks?.length&&config.capabilities?.deepLinks)features.push("appLinks");if(config.capabilities?.bluetooth)features.push("bluetooth");if(config.capabilities?.heartRate)features.push("heartRate");if(config.capabilities?.audioRecording)features.push("audioRecording");if(config.capabilities?.healthConnect&&config.renderer==="native")features.push("healthConnect");if(config.backgroundRefresh?.enabled)features.push("backgroundRefresh");if(options.appBundle)features.push("appBundle");if(config.crashReporting?.key)features.push("crashReporting");if(config.notificationIcon||config.notificationColor)features.push("notificationIcon");return features}export function assertCraftSupportsAndroid(config,version,source,options={}){const missing=androidCraftFeatures(config,options).filter((feature)=>!Bun.semver.satisfies(version,`>=${CRAFT_ANDROID_FLOORS[feature]}`));if(!missing.length)return;const needed=missing.map((feature)=>CRAFT_ANDROID_FLOORS[feature]).reduce((max,next)=>Bun.semver.order(next,max)>0?next:max,"0.0.0");throw Error(`The Craft Android builder is craft-native ${version} (${source}), which would build the app without ${missing.map((feature)=>`${feature} (needs >= ${CRAFT_ANDROID_FLOORS[feature]})`).join(", ")}. Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export function toCraftAndroidConfig(config){const devServerURL=normalizeMobileUrl(config.url),trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const native=config.renderer==="native",craft={mapProvider:config.mapProvider,nativeFonts:config.nativeFonts,appName:config.appName,packageName:config.packageName,version:config.version,versionCode:config.versionCode,minSdk:config.minSdk,targetSdk:config.targetSdk,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,devServerURL,trustedOrigins:[...trustedOrigins],urlSchemes:config.urlSchemes,appLinks:config.appLinks,appIconPath:config.appIcon,notificationColor:config.notificationColor,googleServicesFile:config.googleServicesFile,mapsApiKey:config.mapsApiKey,renderer:config.renderer,nativeScreens:native?nativeScreenRoutes(config):void 0,nativeApp:native&&config.nativeApp?NATIVE_APP_ROUTE:void 0,tabs:native?config.tabs:void 0,backgroundRefresh:native?config.backgroundRefresh:void 0,healthConnect:config.capabilities?.healthConnect?config.healthConnect:void 0,privacyPolicyURL:config.privacyPolicyUrl,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(CAPABILITY_KEYS)){const enabled=config.capabilities?.[key];if(enabled!==void 0)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=!0;for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function validateAndroidMobileConfig(config){if(config.mapProvider!==void 0&&config.mapProvider!=="google"&&config.mapProvider!=="maplibre")throw Error(`android.mapProvider must be 'google' or 'maplibre', not ${String(config.mapProvider)}`);if(config.mapProvider&&config.renderer!=="native")throw Error("android.mapProvider configures native map views: set android.renderer to 'native'");if(!config.appName?.trim())throw Error("config/mobile.ts must define android.appName");if(!/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/.test(config.packageName))throw Error(`Invalid Android package name: ${config.packageName}`);if(config.notificationColor!==void 0&&!/^#[0-9a-f]{6}$/i.test(config.notificationColor))throw Error(`android.notificationColor must be #RRGGBB, not ${String(config.notificationColor)}`);if(config.notificationIcon!==void 0&&!/\.(png|xml)$/i.test(config.notificationIcon))throw Error("android.notificationIcon must be an Android vector drawable (.xml) or a white-on-transparent .png");if(config.mapsApiKey!==void 0&&(typeof config.mapsApiKey!=="string"||!config.mapsApiKey.trim()))throw Error("android.mapsApiKey must be a non-empty Google Maps Android SDK key");if(config.renderer!==void 0&&config.renderer!=="web"&&config.renderer!=="native")throw Error(`android.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw Error("android.renderer 'native' draws every screen natively: list them in android.nativeScreens");if(config.webAssets)throw Error("android.renderer 'native' has no web view to show android.webAssets in: set android.url to the app's site instead");if(config.fallbackWebAssets)throw Error("android.fallbackWebAssets is the web view's offline page; android.renderer 'native' has no web view");if(!config.url)throw Error("android.renderer 'native' needs android.url: the app's site, where its API answers")}else{if(config.url&&config.webAssets)throw Error("Choose either android.url or android.webAssets in config/mobile.ts, not both");if(!config.url&&!config.webAssets)throw Error("config/mobile.ts must define android.url or android.webAssets");if(config.fallbackWebAssets&&!config.url)throw Error("android.fallbackWebAssets requires android.url")}if(config.nativeApp&&config.renderer!=="native")throw Error("android.nativeApp runs beside native screens: set android.renderer to 'native'");for(const tab of config.tabs??[])if(!tab.id?.startsWith("/"))throw Error(`An android.tabs entry needs an id that is an app path, like /m (got ${String(tab.id)})`);if(config.url){const normalized=normalizeMobileUrl(config.url),url=new URL(normalized),isLocal=["localhost","127.0.0.1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw Error("android.url must use HTTPS outside local development")}if(config.capabilities?.healthConnect&&(config.minSdk??26)<26)throw Error("Android Health Connect requires android.minSdk 26 or newer");if(config.healthConnect&&!config.capabilities?.healthConnect)throw Error("android.healthConnect lists Health Connect data, but android.capabilities.healthConnect is off");const minutes=config.backgroundRefresh?.minimumIntervalMinutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<15))throw Error("android.backgroundRefresh.minimumIntervalMinutes is at least 15 (WorkManager's shortest period)");for(const scheme of config.urlSchemes??[])if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))throw Error(`Invalid Android URL scheme: ${scheme}`)}export function androidRelease(config){if(config.crashReporting?.release)return config.crashReporting.release;return`${config.version||"1.0.0"}+${config.versionCode||1}`}export async function uploadAndroidMapping(mappingPath,host,release,token,send=fetch){if(!token)return{ok:!1,message:"BUGHQ_UPLOAD_TOKEN is not set, so the R8 mapping was not uploaded and this build's Android crashes will show obfuscated names."};const file=Bun.file(mappingPath);if(!await file.exists())return{ok:!1,message:`No R8 mapping at ${mappingPath}, so nothing was uploaded.`};try{const body=Bun.gzipSync(new Uint8Array(await file.arrayBuffer())),response=await send(`${host.replace(/\/$/,"")}/api/debug-files?kind=proguard&release=${encodeURIComponent(release)}`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/octet-stream"},body});if(!response.ok)return{ok:!1,message:`bughq refused the R8 mapping (${response.status}): ${(await response.text()).slice(0,200)}`};return{ok:!0,message:`Uploaded the R8 mapping for ${release} to bughq.`}}catch(error){return{ok:!1,message:`Could not upload the R8 mapping: ${error instanceof Error?error.message:String(error)}`}}}
|
|
1
|
+
import{assertCraftSupportsNativeSensors,nativeSensorCapabilityKeys}from"./native-sensors";import{NATIVE_APP_ROUTE,normalizeMobileUrl,toCraftCrashReporting}from"./ios-config";import{nativeScreenRoutes}from"./native-screens";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",audioRecording:"enableAudioRecording",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",pushNotifications:"enablePushNotifications",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",keepAwake:"enableKeepAwake",deepLinks:"enableDeepLinks",healthConnect:"enableHealthConnect",bluetooth:"enableBluetooth",heartRate:"enableHeartRate",localNetwork:"enableLocalNetwork",localDatabase:"enableLocalDatabase",localNotifications:"enableLocalNotifications",shakeGesture:"enableShakeGesture",healthServices:"enableHealthServices",wallet:"enableWallet"};export{CAPABILITY_KEYS as ANDROID_CAPABILITY_KEYS};export function androidCapabilityKeys(nativeSensorCapabilities){return{...CAPABILITY_KEYS,...nativeSensorCapabilityKeys("android",nativeSensorCapabilities)}}export const ANDROID_UNMAPPED_CRAFT_FLAGS={enableHealthConnectBackground:"Craft sets it from healthConnect.background, which toCraftAndroidConfig forwards",enableHealthConnectHistory:"Craft sets it from healthConnect.history, which toCraftAndroidConfig forwards"},CRAFT_ANDROID_FLOORS={audioRecording:"0.0.324",nativeShell:"0.0.169",appLinks:"0.0.201",bluetooth:"0.0.178",heartRate:"0.0.247",healthConnect:"0.0.169",backgroundRefresh:"0.0.169",appBundle:"0.0.169",crashReporting:"0.0.179",notificationIcon:"0.0.241",shakeGesture:"0.0.435"};export function assertCraftSupportsAndroidMapProvider(config,providers){if(config.mapProvider&&!providers?.includes(config.mapProvider))throw Error(`The resolved Craft Android builder does not advertise native map provider '${config.mapProvider}'. Upgrade craft-native to a published SDK supporting that provider before building this app.`)}export function androidCraftFeatures(config,options={}){const features=[];if(config.renderer==="native"&&Object.keys(config.nativeScreens??{}).length)features.push("nativeShell");if(config.appLinks?.length&&config.capabilities?.deepLinks)features.push("appLinks");if(config.capabilities?.bluetooth)features.push("bluetooth");if(config.capabilities?.heartRate)features.push("heartRate");if(config.capabilities?.audioRecording)features.push("audioRecording");if(config.capabilities?.shakeGesture)features.push("shakeGesture");if(config.capabilities?.healthConnect&&config.renderer==="native")features.push("healthConnect");if(config.backgroundRefresh?.enabled)features.push("backgroundRefresh");if(options.appBundle)features.push("appBundle");if(config.crashReporting?.key)features.push("crashReporting");if(config.notificationIcon||config.notificationColor)features.push("notificationIcon");return features}export function assertCraftSupportsAndroid(config,version,source,options={}){const missing=androidCraftFeatures(config,options).filter((feature)=>!Bun.semver.satisfies(version,`>=${CRAFT_ANDROID_FLOORS[feature]}`));if(!missing.length)return;const needed=missing.map((feature)=>CRAFT_ANDROID_FLOORS[feature]).reduce((max,next)=>Bun.semver.order(next,max)>0?next:max,"0.0.0");throw Error(`The Craft Android builder is craft-native ${version} (${source}), which would build the app without ${missing.map((feature)=>`${feature} (needs >= ${CRAFT_ANDROID_FLOORS[feature]})`).join(", ")}. Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export function toCraftAndroidConfig(config,nativeSensorCapabilities){assertCraftSupportsNativeSensors("android",config.capabilities,nativeSensorCapabilities);const devServerURL=normalizeMobileUrl(config.url),trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const native=config.renderer==="native",craft={mapProvider:config.mapProvider,nativeFonts:config.nativeFonts,appName:config.appName,packageName:config.packageName,version:config.version,versionCode:config.versionCode,minSdk:config.minSdk,targetSdk:config.targetSdk,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,devServerURL,trustedOrigins:[...trustedOrigins],urlSchemes:config.urlSchemes,appLinks:config.appLinks,appIconPath:config.appIcon,notificationColor:config.notificationColor,googleServicesFile:config.googleServicesFile,mapsApiKey:config.mapsApiKey,renderer:config.renderer,nativeScreens:native?nativeScreenRoutes(config):void 0,nativeApp:native&&config.nativeApp?NATIVE_APP_ROUTE:void 0,tabs:native?config.tabs:void 0,backgroundRefresh:native?config.backgroundRefresh:void 0,healthConnect:config.capabilities?.healthConnect?config.healthConnect:void 0,privacyPolicyURL:config.privacyPolicyUrl,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(androidCapabilityKeys(nativeSensorCapabilities))){const enabled=config.capabilities?.[key];if(enabled!==void 0)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=!0;for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function validateAndroidMobileConfig(config){if(config.mapProvider!==void 0&&config.mapProvider!=="google"&&config.mapProvider!=="maplibre")throw Error(`android.mapProvider must be 'google' or 'maplibre', not ${String(config.mapProvider)}`);if(config.mapProvider&&config.renderer!=="native")throw Error("android.mapProvider configures native map views: set android.renderer to 'native'");if(!config.appName?.trim())throw Error("config/mobile.ts must define android.appName");if(!/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/.test(config.packageName))throw Error(`Invalid Android package name: ${config.packageName}`);if(config.notificationColor!==void 0&&!/^#[0-9a-f]{6}$/i.test(config.notificationColor))throw Error(`android.notificationColor must be #RRGGBB, not ${String(config.notificationColor)}`);if(config.notificationIcon!==void 0&&!/\.(png|xml)$/i.test(config.notificationIcon))throw Error("android.notificationIcon must be an Android vector drawable (.xml) or a white-on-transparent .png");if(config.mapsApiKey!==void 0&&(typeof config.mapsApiKey!=="string"||!config.mapsApiKey.trim()))throw Error("android.mapsApiKey must be a non-empty Google Maps Android SDK key");if(config.renderer!==void 0&&config.renderer!=="web"&&config.renderer!=="native")throw Error(`android.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw Error("android.renderer 'native' draws every screen natively: list them in android.nativeScreens");if(config.webAssets)throw Error("android.renderer 'native' has no web view to show android.webAssets in: set android.url to the app's site instead");if(config.fallbackWebAssets)throw Error("android.fallbackWebAssets is the web view's offline page; android.renderer 'native' has no web view");if(!config.url)throw Error("android.renderer 'native' needs android.url: the app's site, where its API answers")}else{if(config.url&&config.webAssets)throw Error("Choose either android.url or android.webAssets in config/mobile.ts, not both");if(!config.url&&!config.webAssets)throw Error("config/mobile.ts must define android.url or android.webAssets");if(config.fallbackWebAssets&&!config.url)throw Error("android.fallbackWebAssets requires android.url")}if(config.nativeApp&&config.renderer!=="native")throw Error("android.nativeApp runs beside native screens: set android.renderer to 'native'");for(const tab of config.tabs??[])if(!tab.id?.startsWith("/"))throw Error(`An android.tabs entry needs an id that is an app path, like /m (got ${String(tab.id)})`);if(config.url){const normalized=normalizeMobileUrl(config.url),url=new URL(normalized),isLocal=["localhost","127.0.0.1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw Error("android.url must use HTTPS outside local development")}if(config.capabilities?.healthConnect&&(config.minSdk??26)<26)throw Error("Android Health Connect requires android.minSdk 26 or newer");if(config.capabilities?.healthServices&&config.minSdk!==void 0&&config.minSdk<30)throw Error("Android Health Services requires android.minSdk 30 or newer (Android 11), or leave minSdk unset");if(config.healthConnect&&!config.capabilities?.healthConnect)throw Error("android.healthConnect lists Health Connect data, but android.capabilities.healthConnect is off");const minutes=config.backgroundRefresh?.minimumIntervalMinutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<15))throw Error("android.backgroundRefresh.minimumIntervalMinutes is at least 15 (WorkManager's shortest period)");for(const scheme of config.urlSchemes??[])if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))throw Error(`Invalid Android URL scheme: ${scheme}`)}export function androidRelease(config){if(config.crashReporting?.release)return config.crashReporting.release;return`${config.version||"1.0.0"}+${config.versionCode||1}`}export async function uploadAndroidMapping(mappingPath,host,release,token,send=fetch){if(!token)return{ok:!1,message:"BUGHQ_UPLOAD_TOKEN is not set, so the R8 mapping was not uploaded and this build's Android crashes will show obfuscated names."};const file=Bun.file(mappingPath);if(!await file.exists())return{ok:!1,message:`No R8 mapping at ${mappingPath}, so nothing was uploaded.`};try{const body=Bun.gzipSync(new Uint8Array(await file.arrayBuffer())),response=await send(`${host.replace(/\/$/,"")}/api/debug-files?kind=proguard&release=${encodeURIComponent(release)}`,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/octet-stream"},body});if(!response.ok)return{ok:!1,message:`bughq refused the R8 mapping (${response.status}): ${(await response.text()).slice(0,200)}`};return{ok:!0,message:`Uploaded the R8 mapping for ${release} to bughq.`}}catch(error){return{ok:!1,message:`Could not upload the R8 mapping: ${error instanceof Error?error.message:String(error)}`}}}
|
package/dist/build/android.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{androidRelease,assertCraftSupportsAndroid,assertCraftSupportsAndroidMapProvider,toCraftAndroidConfig,uploadAndroidMapping,validateAndroidMobileConfig}from"./android-config";import{assertCraftSupportsChromeFonts,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts}from"./ios-config";import{compileNativeScreens}from"./native-screens";import{writeAndroidIconTable}from"./android-icons";import{reportMobileBuildTarget}from"./mobile-target";process.exitCode=1;function craftAndroidEntry(){const explicit=process.env.CRAFT_ANDROID_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("android",projectPath())}async function loadCraftAndroidBuilder(){try{return await import(craftAndroidEntry())}catch(error){throw Error("Craft Android builder is unavailable. Install the current craft-native package or set CRAFT_ANDROID_SRC to packages/android/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath))throw Error("Missing config/mobile.ts. Add an android section before running `buddy build:android`.");const configModule=await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`),androidSection=configModule.default.android;if(!androidSection)throw Error("config/mobile.ts must define an android section");const config={...androidSection,crashReporting:resolveCrashReporting(configModule.default.crashReporting,androidSection.crashReporting)};validateAndroidMobileConfig(config);const output=resolveMobilePath(projectPath(),config.output)??storagePath("framework/mobile/android"),webAssets=resolveMobilePath(projectPath(),config.webAssets),fallbackWebAssets=resolveMobilePath(projectPath(),config.fallbackWebAssets),craftConfig=toCraftAndroidConfig(config);craftConfig.nativeFonts=resolveNativeFonts(config.nativeFonts,projectPath());craftConfig.appIconPath=resolveMobilePath(projectPath(),config.appIcon);craftConfig.notificationIconPath=resolveMobilePath(projectPath(),config.notificationIcon);craftConfig.googleServicesFile=resolveMobilePath(projectPath(),config.googleServicesFile);if(process.env.NODE_ENV==="production"&&config.capabilities?.pushNotifications&&!craftConfig.googleServicesFile)throw Error("Production Android push notifications require android.googleServicesFile in config/mobile.ts");const appBundle=process.env.STACKS_ANDROID_BUNDLE==="1",release=appBundle||process.env.NODE_ENV==="production",native=config.renderer==="native",
|
|
1
|
+
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{androidRelease,assertCraftSupportsAndroid,assertCraftSupportsAndroidMapProvider,toCraftAndroidConfig,uploadAndroidMapping,validateAndroidMobileConfig}from"./android-config";import{assertCraftSupportsChromeFonts,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts}from"./ios-config";import{compileNativeScreens}from"./native-screens";import{writeAndroidIconTable}from"./android-icons";import{reportMobileBuildTarget}from"./mobile-target";process.exitCode=1;function craftAndroidEntry(){const explicit=process.env.CRAFT_ANDROID_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("android",projectPath())}async function loadCraftAndroidBuilder(){try{return await import(craftAndroidEntry())}catch(error){throw Error("Craft Android builder is unavailable. Install the current craft-native package or set CRAFT_ANDROID_SRC to packages/android/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath))throw Error("Missing config/mobile.ts. Add an android section before running `buddy build:android`.");const configModule=await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`),androidSection=configModule.default.android;if(!androidSection)throw Error("config/mobile.ts must define an android section");const config={...androidSection,crashReporting:resolveCrashReporting(configModule.default.crashReporting,androidSection.crashReporting)};validateAndroidMobileConfig(config);const output=resolveMobilePath(projectPath(),config.output)??storagePath("framework/mobile/android"),webAssets=resolveMobilePath(projectPath(),config.webAssets),fallbackWebAssets=resolveMobilePath(projectPath(),config.fallbackWebAssets),builder=await loadCraftAndroidBuilder(),craftConfig=toCraftAndroidConfig(config,builder.nativeSensorCapabilities);craftConfig.nativeFonts=resolveNativeFonts(config.nativeFonts,projectPath());craftConfig.appIconPath=resolveMobilePath(projectPath(),config.appIcon);craftConfig.notificationIconPath=resolveMobilePath(projectPath(),config.notificationIcon);craftConfig.googleServicesFile=resolveMobilePath(projectPath(),config.googleServicesFile);if(process.env.NODE_ENV==="production"&&config.capabilities?.pushNotifications&&!craftConfig.googleServicesFile)throw Error("Production Android push notifications require android.googleServicesFile in config/mobile.ts");const appBundle=process.env.STACKS_ANDROID_BUNDLE==="1",release=appBundle||process.env.NODE_ENV==="production",native=config.renderer==="native",nativeBundle=native?await compileNativeScreens(config,projectPath(),output,void 0,"android",{routes:builder.nativeRouteBundles===!0,runtime:builder.nativeRouteRuntime===!0,messages:builder.nativeMessages===!0}):null;if(nativeBundle){for(const diagnostic of nativeBundle.diagnostics??[])log.warn(`${diagnostic.file?`${diagnostic.file}: `:""}${diagnostic.message}`);log.info(`Compiled ${Object.keys(config.nativeScreens??{}).length} native screen path(s) into ${nativeBundle.outFile}`)}const{LUCIDE_TO_SF}=native?await import("@stacksjs/stx/native"):{LUCIDE_TO_SF:{}},iconsPath=native?writeAndroidIconTable(projectPath(),output,LUCIDE_TO_SF):null;if(native&&!iconsPath)log.warn("No @iconify-json/lucide in the app: Android draws its own glyphs for the screens' icons.");const craftVersion=craftBuilderVersion(craftAndroidEntry(),projectPath());assertCraftSupportsNativeFonts(config.nativeFonts,craftVersion?.version);assertCraftSupportsChromeFonts(config,craftVersion?.version);if(craftVersion)assertCraftSupportsAndroid(config,craftVersion.version,craftVersion.manifest,{appBundle});else log.warn(`Could not read the craft-native version behind ${craftAndroidEntry()}, so the build cannot check that it supports what config/mobile.ts asks for.`);assertCraftSupportsAndroidMapProvider(config,builder.nativeMapProviders);await builder.init({name:config.appName,packageName:config.packageName,output,config:craftConfig});reportMobileBuildTarget({renderer:config.renderer,site:craftConfig.devServerURL,nativeBundle:nativeBundle?.outFile,webAssets,fallbackWebAssets,production:release},log);await builder.build(native?{output,nativeBundlePath:nativeBundle.outFile,iconsPath:iconsPath??void 0,release,bundle:appBundle,compile:process.env.STACKS_ANDROID_SKIP_GRADLE!=="1"}:{output,htmlPath:webAssets??fallbackWebAssets,devServer:craftConfig.devServerURL,release,bundle:appBundle,compile:process.env.STACKS_ANDROID_SKIP_GRADLE!=="1"});if(release&&config.crashReporting?.key&&config.crashReporting.uploadSymbols!==!1&&process.env.STACKS_ANDROID_SKIP_GRADLE!=="1"){const upload=await uploadAndroidMapping(`${output}/app/build/outputs/mapping/release/mapping.txt`,config.crashReporting.host??"https://bughq.org",androidRelease(config),process.env.BUGHQ_UPLOAD_TOKEN);if(upload.ok)log.info(upload.message);else log.warn(upload.message)}const sourceRevision=Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim(),generatedConfig=JSON.parse(readFileSync(`${output}/craft.config.json`,"utf8"));writeFileSync(`${output}/stacks-mobile.json`,`${JSON.stringify({schemaVersion:"1.0.0",platform:"android",sourceRevision,source:native?{kind:"native",site:craftConfig.devServerURL}:webAssets?{kind:"bundled",path:webAssets}:{kind:"remote",url:craftConfig.devServerURL,fallback:fallbackWebAssets?{kind:"bundled",path:fallbackWebAssets}:void 0},capabilities:config.capabilities??{},builder:resolveCraftBuilderProvenance(process.env.CRAFT_ANDROID_SRC),craft:generatedConfig},null,2)}
|
|
2
2
|
`);log.success(`Built the Craft Android project in ${output}`);await log.flush();process.exitCode=0;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import type { IosMobileConfig, MobileConfig, MobileCrashReportingConfig } from '@stacksjs/types';
|
|
1
|
+
import type { IosMobileConfig, MobileCapabilities, MobileConfig, MobileCrashReportingConfig } from '@stacksjs/types';
|
|
2
|
+
/** The exact flag map generated for the selected published builder. */
|
|
3
|
+
export declare function iosCapabilityKeys(nativeSensorCapabilities?: readonly string[]): Partial<Record<keyof MobileCapabilities, `enable${string}`>>;
|
|
2
4
|
/** The capabilities `config/mobile.ts` turns on that a Craft of `version` would leave out of the app. */
|
|
3
5
|
export declare function unsupportedCraftCapabilities(capabilities: IosMobileConfig['capabilities'], version: string): UnsupportedCraftCapability[];
|
|
4
6
|
/**
|
|
@@ -38,7 +40,7 @@ export declare function resolveMobilePath(root: string, value: string | undefine
|
|
|
38
40
|
* explicit `swipeNavigation` still wins, for an app that set it before.
|
|
39
41
|
*/
|
|
40
42
|
export declare function resolveSwipeNavigation(config: Pick<IosMobileConfig, 'swipeBack' | 'swipeNavigation'>): boolean;
|
|
41
|
-
export declare function toCraftIosConfig(config: IosMobileConfig): CraftIosConfig;
|
|
43
|
+
export declare function toCraftIosConfig(config: IosMobileConfig, nativeSensorCapabilities?: readonly string[]): CraftIosConfig;
|
|
42
44
|
export declare function validateIosMobileConfig(config: IosMobileConfig): void;
|
|
43
45
|
export declare function withActivityTypes(plist: string, types: readonly string[]): string;
|
|
44
46
|
/**
|
|
@@ -61,48 +63,18 @@ export declare function assertCraftSupportsAppShortcuts(shortcuts: IosMobileConf
|
|
|
61
63
|
export declare function assertCraftSupportsNativeFonts(fonts: IosMobileConfig['nativeFonts'], version?: string): void;
|
|
62
64
|
/** The route stx's bundle runs the app script under (`compileNativeBundle`'s `app`). */
|
|
63
65
|
export declare const NATIVE_APP_ROUTE: '__app';
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
calendar: 'enableCalendar';
|
|
77
|
-
localNotifications: 'enableLocalNotifications';
|
|
78
|
-
inAppPurchase: 'enableInAppPurchase';
|
|
79
|
-
keepAwake: 'enableKeepAwake';
|
|
80
|
-
orientationLock: 'enableOrientationLock';
|
|
81
|
-
deepLinks: 'enableDeepLinks';
|
|
82
|
-
qrScanner: 'enableQRScanner';
|
|
83
|
-
localNetwork: 'enableLocalNetwork';
|
|
84
|
-
filePicker: 'enableFilePicker';
|
|
85
|
-
fileDownload: 'enableFileDownload';
|
|
86
|
-
socialAuth: 'enableSocialAuth';
|
|
87
|
-
audioRecording: 'enableAudioRecording';
|
|
88
|
-
videoRecording: 'enableVideoRecording';
|
|
89
|
-
motionSensors: 'enableMotionSensors';
|
|
90
|
-
localDatabase: 'enableLocalDatabase';
|
|
91
|
-
bluetooth: 'enableBluetooth';
|
|
92
|
-
nfc: 'enableNFC';
|
|
93
|
-
healthKit: 'enableHealthKit';
|
|
94
|
-
appleMusic: 'enableAppleMusic';
|
|
95
|
-
heartRate: 'enableHeartRate';
|
|
96
|
-
backgroundAudio: 'enableBackgroundAudio';
|
|
97
|
-
scheduledWorkouts: 'enableScheduledWorkouts';
|
|
98
|
-
liveActivities: 'enableLiveActivities';
|
|
99
|
-
watchApp: 'enableWatchApp';
|
|
100
|
-
backgroundTasks: 'enableBackgroundTasks';
|
|
101
|
-
screenCapture: 'enableScreenCapture';
|
|
102
|
-
pdfViewer: 'enablePDFViewer';
|
|
103
|
-
augmentedReality: 'enableAR';
|
|
104
|
-
machineLearning: 'enableMLKit'
|
|
105
|
-
};
|
|
66
|
+
/**
|
|
67
|
+
* An app's `ios.capabilities` names, and the Craft `enable…` flag each sets.
|
|
68
|
+
*
|
|
69
|
+
* Closed on purpose: the translation iterates this map, so a capability an
|
|
70
|
+
* app misspells is a type error rather than a flag set to nothing. The cost
|
|
71
|
+
* is that a flag Craft ships is unreachable until it is added here, so
|
|
72
|
+
* tests/craft-capability-parity.test.ts fails on any flag the installed Craft
|
|
73
|
+
* declares that is neither here nor in {@link IOS_UNMAPPED_CRAFT_FLAGS}.
|
|
74
|
+
*/
|
|
75
|
+
declare const CAPABILITY_KEYS: Partial<Record<keyof MobileCapabilities, `enable${string}`>>;
|
|
76
|
+
/** Craft iOS flags no `ios.capabilities` name sets, each with why. */
|
|
77
|
+
export declare const IOS_UNMAPPED_CRAFT_FLAGS: Readonly<Record<`enable${string}`, string>>;
|
|
106
78
|
/**
|
|
107
79
|
* The first craft-native release whose iOS template honours a capability.
|
|
108
80
|
*
|
|
@@ -168,3 +140,4 @@ export declare interface UnsupportedCraftCapability {
|
|
|
168
140
|
capability: keyof typeof CRAFT_CAPABILITY_FLOORS
|
|
169
141
|
needs: string
|
|
170
142
|
}
|
|
143
|
+
export { CAPABILITY_KEYS as IOS_CAPABILITY_KEYS };
|
package/dist/build/ios-config.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve}from"node:path";import{spotlightActivityTypes}from"@stacksjs/mobile";import{nativeScreenRoutes}from"./native-screens";export const NATIVE_APP_ROUTE="__app";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",pushNotifications:"enablePushNotifications",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",clipboard:"enableClipboard",contacts:"enableContacts",calendar:"enableCalendar",localNotifications:"enableLocalNotifications",inAppPurchase:"enableInAppPurchase",keepAwake:"enableKeepAwake",orientationLock:"enableOrientationLock",deepLinks:"enableDeepLinks",qrScanner:"enableQRScanner",localNetwork:"enableLocalNetwork",filePicker:"enableFilePicker",fileDownload:"enableFileDownload",socialAuth:"enableSocialAuth",audioRecording:"enableAudioRecording",videoRecording:"enableVideoRecording",motionSensors:"enableMotionSensors",localDatabase:"enableLocalDatabase",bluetooth:"enableBluetooth",nfc:"enableNFC",healthKit:"enableHealthKit",appleMusic:"enableAppleMusic",heartRate:"enableHeartRate",backgroundAudio:"enableBackgroundAudio",scheduledWorkouts:"enableScheduledWorkouts",liveActivities:"enableLiveActivities",watchApp:"enableWatchApp",backgroundTasks:"enableBackgroundTasks",screenCapture:"enableScreenCapture",pdfViewer:"enablePDFViewer",augmentedReality:"enableAR",machineLearning:"enableMLKit"};export const CRAFT_CAPABILITY_FLOORS={audioRecording:"0.0.324",appleMusic:"0.0.144",heartRate:"0.0.152",backgroundAudio:"0.0.162",scheduledWorkouts:"0.0.163"};export function unsupportedCraftCapabilities(capabilities,version){const missing=[];for(const[capability,needs]of Object.entries(CRAFT_CAPABILITY_FLOORS))if(capabilities?.[capability]&&!Bun.semver.satisfies(version,`>=${needs}`))missing.push({capability,needs});return missing}export function assertCraftSupportsCapabilities(capabilities,version,source){const missing=unsupportedCraftCapabilities(capabilities,version);if(missing.length===0)return;const needed=missing.reduce((max,{needs})=>Bun.semver.order(needs,max)>0?needs:max,"0.0.0");throw Error(`The Craft iOS builder is craft-native ${version} (${source}), which would build the app without ${missing.map(({capability,needs})=>`ios.capabilities.${capability} (needs >= ${needs})`).join(", ")}. Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export const CRAFT_CRASH_REPORTING_FLOOR="0.0.179";export function resolveCrashReporting(shared,platform){const set=(config)=>Object.fromEntries(Object.entries(config??{}).filter(([,value])=>value!==void 0&&value!=="")),merged={...set(shared),...set(platform)};if(!merged.key?.trim())return;if(merged.host){const url=new URL(normalizeMobileUrl(merged.host)),local=["localhost","127.0.0.1","::1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!local)throw Error("crashReporting.host must use HTTPS outside local development");merged.host=url.origin}return merged}export function toCraftCrashReporting(config){if(!config?.key)return;const craft={key:config.key,host:config.host,environment:config.environment,release:config.release,sessions:config.sessions};for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function assertCraftSupportsCrashReporting(config,version,source){if(!config?.key||Bun.semver.satisfies(version,`>=${CRAFT_CRASH_REPORTING_FLOOR}`))return;throw Error(`The Craft builder is craft-native ${version} (${source}), which would build the app without crash reporting (crashReporting needs >= ${CRAFT_CRASH_REPORTING_FLOOR}). Install craft-native >= ${CRAFT_CRASH_REPORTING_FLOOR}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export function normalizeMobileUrl(value){const input=value?.trim();if(!input)return;return new URL(/^https?:\/\//i.test(input)?input:`https://${input}`).toString().replace(/\/$/,"")}export function portablePaths(value,projectDir,appRoot){if(typeof value==="string")return isAbsolute(value)&&!relative(appRoot,value).startsWith("..")?relative(projectDir,value)||".":value;if(Array.isArray(value))return value.map((item)=>portablePaths(item,projectDir,appRoot));if(value&&typeof value==="object"){const out={};for(const[key,item]of Object.entries(value))out[key]=typeof item==="string"&&!/(?:path(?:dark)?|bundle)$|^(?:src|license)$/i.test(key)?item:portablePaths(item,projectDir,appRoot);return out}return value}export function resolveMobilePath(root,value){if(!value)return;return isAbsolute(value)?value:resolve(root,value)}export function resolveSwipeNavigation(config){if(config.swipeNavigation!==void 0)return config.swipeNavigation;return config.swipeBack==="webview"}export function toCraftIosConfig(config){const devServerURL=normalizeMobileUrl(config.url),trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const declaresAppBoundDomains=(config.appBoundDomains?.length??0)>0,craft={nativeFonts:config.nativeFonts,appName:config.appName,bundleId:config.bundleId,version:config.version,buildNumber:config.buildNumber,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,tintColor:config.tintColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,swipeNavigation:resolveSwipeNavigation(config),allowsLinkPreview:config.allowsLinkPreview,keyboardAccessory:config.keyboardAccessory,disableZoom:config.disableZoom,splashMaxSeconds:config.splashMaxSeconds,requestTimeoutSeconds:config.requestTimeoutSeconds,backgroundRefresh:config.backgroundRefresh,iosVersion:config.deploymentTarget,watchosVersion:config.watchDeploymentTarget,teamId:config.teamId,devServerURL,urlSchemes:config.urlSchemes,appShortcuts:config.appShortcuts,trustedOrigins:[...trustedOrigins],appBoundDomains:config.appBoundDomains,limitNavigationsToAppBoundDomains:config.limitNavigationsToAppBoundDomains??(declaresAppBoundDomains||void 0),associatedDomains:config.associatedDomains,renderer:config.renderer,nativeScreens:nativeScreenRoutes(config),nativeApp:config.nativeApp?NATIVE_APP_ROUTE:void 0,nativeScriptThread:config.nativeScriptThread,tabs:config.tabs,shareStorage:config.shareStorage,appGroups:config.appGroups,appIconPath:config.appIcon,privacy:config.privacy,usageDescriptions:config.usageDescriptions,orientations:config.orientations,deviceFamilies:config.deviceFamilies,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(CAPABILITY_KEYS)){const enabled=config.capabilities?.[key];if(enabled!==void 0)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=!0;for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function validateIosMobileConfig(config){if(config.tintColor!==void 0&&!/^#[0-9a-f]{6}$/i.test(config.tintColor))throw Error("ios.tintColor must be a #RRGGBB color");if(!config.appName?.trim())throw Error("config/mobile.ts must define ios.appName");if(!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(config.bundleId))throw Error(`Invalid iOS bundle identifier: ${config.bundleId}`);if(config.url&&config.webAssets)throw Error("Choose either ios.url or ios.webAssets in config/mobile.ts, not both");if(!config.url&&!config.webAssets)throw Error("config/mobile.ts must define ios.url or ios.webAssets");if(config.renderer!==void 0&&config.renderer!=="web"&&config.renderer!=="native")throw Error(`ios.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw Error("ios.renderer 'native' draws every screen natively: list them in ios.nativeScreens");if(config.webAssets)throw Error("ios.renderer 'native' has no web view to show ios.webAssets in: set ios.url to the app's site instead");if(config.fallbackWebAssets)throw Error("ios.fallbackWebAssets is the web view's offline page; ios.renderer 'native' has no web view")}if(config.fallbackWebAssets&&!config.url)throw Error("ios.fallbackWebAssets requires ios.url");if(config.deviceFamilies&&(config.deviceFamilies.length===0||config.deviceFamilies.some((family)=>family!=="iphone"&&family!=="ipad")))throw Error("ios.deviceFamilies must contain iphone and/or ipad");if(config.url){const url=new URL(normalizeMobileUrl(config.url)),isLocal=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw Error("ios.url must use HTTPS outside local development")}for(const domain of config.associatedDomains??[])if(!/^(applinks|webcredentials|activitycontinuation):[^/\s]+$/.test(domain))throw Error(`Invalid iOS associated domain: ${domain}`);for(const key of["splashMaxSeconds","requestTimeoutSeconds"]){const value=config[key];if(value!==void 0&&(!Number.isFinite(value)||value<=0))throw Error(`ios.${key} must be a positive number of seconds`)}const refresh=config.backgroundRefresh;if(refresh){if(refresh.identifier!==void 0&&!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(refresh.identifier))throw Error(`Invalid iOS background refresh identifier: ${refresh.identifier}`);if(refresh.minimumIntervalMinutes!==void 0&&(!Number.isFinite(refresh.minimumIntervalMinutes)||refresh.minimumIntervalMinutes<=0))throw Error("ios.backgroundRefresh.minimumIntervalMinutes must be a positive number of minutes")}if(config.capabilities?.watchApp){const target=Number.parseFloat(config.watchDeploymentTarget??"9.0");if(!Number.isFinite(target)||target<9)throw Error("ios.watchDeploymentTarget must be watchOS 9.0 or newer")}}const ACTIVITY_TYPES_BLOCK=/[ \t]*<key>NSUserActivityTypes<\/key>\s*<array>[\s\S]*?<\/array>\n?/;export function withActivityTypes(plist,types){const entries=types.map((type)=>` <string>${escapeXml(type)}</string>`).join(`
|
|
1
|
+
import{assertCraftSupportsNativeSensors,nativeSensorCapabilityKeys}from"./native-sensors";import{existsSync,readFileSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve}from"node:path";import{spotlightActivityTypes}from"@stacksjs/mobile";import{nativeScreenRoutes}from"./native-screens";export const NATIVE_APP_ROUTE="__app";const CAPABILITY_KEYS={speechRecognition:"enableSpeechRecognition",haptics:"enableHaptics",share:"enableShare",camera:"enableCamera",biometric:"enableBiometric",pushNotifications:"enablePushNotifications",secureStorage:"enableSecureStorage",geolocation:"enableGeolocation",backgroundLocation:"enableBackgroundLocation",clipboard:"enableClipboard",contacts:"enableContacts",calendar:"enableCalendar",localNotifications:"enableLocalNotifications",inAppPurchase:"enableInAppPurchase",keepAwake:"enableKeepAwake",orientationLock:"enableOrientationLock",deepLinks:"enableDeepLinks",qrScanner:"enableQRScanner",localNetwork:"enableLocalNetwork",filePicker:"enableFilePicker",fileDownload:"enableFileDownload",socialAuth:"enableSocialAuth",audioRecording:"enableAudioRecording",videoRecording:"enableVideoRecording",motionSensors:"enableMotionSensors",shakeGesture:"enableShakeGesture",wallet:"enableWallet",localDatabase:"enableLocalDatabase",bluetooth:"enableBluetooth",nfc:"enableNFC",healthKit:"enableHealthKit",appleMusic:"enableAppleMusic",heartRate:"enableHeartRate",backgroundAudio:"enableBackgroundAudio",scheduledWorkouts:"enableScheduledWorkouts",liveActivities:"enableLiveActivities",watchApp:"enableWatchApp",backgroundTasks:"enableBackgroundTasks",screenCapture:"enableScreenCapture",pdfViewer:"enablePDFViewer",augmentedReality:"enableAR",machineLearning:"enableMLKit"};export{CAPABILITY_KEYS as IOS_CAPABILITY_KEYS};export function iosCapabilityKeys(nativeSensorCapabilities){return{...CAPABILITY_KEYS,...nativeSensorCapabilityKeys("ios",nativeSensorCapabilities)}}export const IOS_UNMAPPED_CRAFT_FLAGS={enablePasskeys:"no native-screen API calls it yet (stacksjs/stx#2151)"},CRAFT_CAPABILITY_FLOORS={audioRecording:"0.0.324",appleMusic:"0.0.144",heartRate:"0.0.152",backgroundAudio:"0.0.162",scheduledWorkouts:"0.0.163",shakeGesture:"0.0.435"};export function unsupportedCraftCapabilities(capabilities,version){const missing=[];for(const[capability,needs]of Object.entries(CRAFT_CAPABILITY_FLOORS))if(capabilities?.[capability]&&!Bun.semver.satisfies(version,`>=${needs}`))missing.push({capability,needs});return missing}export function assertCraftSupportsCapabilities(capabilities,version,source){const missing=unsupportedCraftCapabilities(capabilities,version);if(missing.length===0)return;const needed=missing.reduce((max,{needs})=>Bun.semver.order(needs,max)>0?needs:max,"0.0.0");throw Error(`The Craft iOS builder is craft-native ${version} (${source}), which would build the app without ${missing.map(({capability,needs})=>`ios.capabilities.${capability} (needs >= ${needs})`).join(", ")}. Install craft-native >= ${needed}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export const CRAFT_CRASH_REPORTING_FLOOR="0.0.179";export function resolveCrashReporting(shared,platform){const set=(config)=>Object.fromEntries(Object.entries(config??{}).filter(([,value])=>value!==void 0&&value!=="")),merged={...set(shared),...set(platform)};if(!merged.key?.trim())return;if(merged.host){const url=new URL(normalizeMobileUrl(merged.host)),local=["localhost","127.0.0.1","::1","10.0.2.2"].includes(url.hostname);if(url.protocol!=="https:"&&!local)throw Error("crashReporting.host must use HTTPS outside local development");merged.host=url.origin}return merged}export function toCraftCrashReporting(config){if(!config?.key)return;const craft={key:config.key,host:config.host,environment:config.environment,release:config.release,sessions:config.sessions};for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function assertCraftSupportsCrashReporting(config,version,source){if(!config?.key||Bun.semver.satisfies(version,`>=${CRAFT_CRASH_REPORTING_FLOOR}`))return;throw Error(`The Craft builder is craft-native ${version} (${source}), which would build the app without crash reporting (crashReporting needs >= ${CRAFT_CRASH_REPORTING_FLOOR}). Install craft-native >= ${CRAFT_CRASH_REPORTING_FLOOR}: look for an older copy nested under @stacksjs/mobile in bun.lock, or raise the app's own craft-native pin.`)}export function normalizeMobileUrl(value){const input=value?.trim();if(!input)return;return new URL(/^https?:\/\//i.test(input)?input:`https://${input}`).toString().replace(/\/$/,"")}export function portablePaths(value,projectDir,appRoot){if(typeof value==="string")return isAbsolute(value)&&!relative(appRoot,value).startsWith("..")?relative(projectDir,value)||".":value;if(Array.isArray(value))return value.map((item)=>portablePaths(item,projectDir,appRoot));if(value&&typeof value==="object"){const out={};for(const[key,item]of Object.entries(value))out[key]=typeof item==="string"&&!/(?:path(?:dark)?|bundle)$|^(?:src|license)$/i.test(key)?item:portablePaths(item,projectDir,appRoot);return out}return value}export function resolveMobilePath(root,value){if(!value)return;return isAbsolute(value)?value:resolve(root,value)}export function resolveSwipeNavigation(config){if(config.swipeNavigation!==void 0)return config.swipeNavigation;return config.swipeBack==="webview"}export function toCraftIosConfig(config,nativeSensorCapabilities){assertCraftSupportsNativeSensors("ios",config.capabilities,nativeSensorCapabilities);const devServerURL=normalizeMobileUrl(config.url),trustedOrigins=new Set(config.trustedOrigins??[]);if(devServerURL)trustedOrigins.add(new URL(devServerURL).origin);const declaresAppBoundDomains=(config.appBoundDomains?.length??0)>0,craft={nativeFonts:config.nativeFonts,appName:config.appName,bundleId:config.bundleId,version:config.version,buildNumber:config.buildNumber,darkMode:config.darkMode,appearance:config.appearance,backgroundColor:config.backgroundColor,tintColor:config.tintColor,backgroundColorDark:config.backgroundColorDark,fontFamily:config.fontFamily,headingFontFamily:config.headingFontFamily,swipeNavigation:resolveSwipeNavigation(config),allowsLinkPreview:config.allowsLinkPreview,keyboardAccessory:config.keyboardAccessory,disableZoom:config.disableZoom,splashMaxSeconds:config.splashMaxSeconds,requestTimeoutSeconds:config.requestTimeoutSeconds,backgroundRefresh:config.backgroundRefresh,iosVersion:config.deploymentTarget,watchosVersion:config.watchDeploymentTarget,teamId:config.teamId,devServerURL,urlSchemes:config.urlSchemes,appShortcuts:config.appShortcuts,trustedOrigins:[...trustedOrigins],appBoundDomains:config.appBoundDomains,limitNavigationsToAppBoundDomains:config.limitNavigationsToAppBoundDomains??(declaresAppBoundDomains||void 0),associatedDomains:config.associatedDomains,renderer:config.renderer,nativeScreens:nativeScreenRoutes(config),nativeApp:config.nativeApp?NATIVE_APP_ROUTE:void 0,nativeScriptThread:config.nativeScriptThread,tabs:config.tabs,shareStorage:config.shareStorage,appGroups:config.appGroups,appIconPath:config.appIcon,privacy:config.privacy,usageDescriptions:config.usageDescriptions,healthKitBackgroundTypes:config.healthKitBackgroundTypes,healthKitBackgroundFrequency:config.healthKitBackgroundFrequency,orientations:config.orientations,deviceFamilies:config.deviceFamilies,crashReporting:toCraftCrashReporting(config.crashReporting)};for(const[key,nativeKey]of Object.entries(iosCapabilityKeys(nativeSensorCapabilities))){const enabled=config.capabilities?.[key];if(enabled!==void 0)craft[nativeKey]=enabled}if(config.capabilities?.backgroundLocation)craft.enableGeolocation=!0;for(const key of Object.keys(craft))if(craft[key]===void 0)delete craft[key];return craft}export function validateIosMobileConfig(config){if(config.tintColor!==void 0&&!/^#[0-9a-f]{6}$/i.test(config.tintColor))throw Error("ios.tintColor must be a #RRGGBB color");if(!config.appName?.trim())throw Error("config/mobile.ts must define ios.appName");if(!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(config.bundleId))throw Error(`Invalid iOS bundle identifier: ${config.bundleId}`);if(config.url&&config.webAssets)throw Error("Choose either ios.url or ios.webAssets in config/mobile.ts, not both");if(!config.url&&!config.webAssets)throw Error("config/mobile.ts must define ios.url or ios.webAssets");if(config.renderer!==void 0&&config.renderer!=="web"&&config.renderer!=="native")throw Error(`ios.renderer must be 'web' or 'native', not ${String(config.renderer)}`);if(config.renderer==="native"){if(!Object.keys(config.nativeScreens??{}).length)throw Error("ios.renderer 'native' draws every screen natively: list them in ios.nativeScreens");if(config.webAssets)throw Error("ios.renderer 'native' has no web view to show ios.webAssets in: set ios.url to the app's site instead");if(config.fallbackWebAssets)throw Error("ios.fallbackWebAssets is the web view's offline page; ios.renderer 'native' has no web view")}if(config.fallbackWebAssets&&!config.url)throw Error("ios.fallbackWebAssets requires ios.url");if(config.deviceFamilies&&(config.deviceFamilies.length===0||config.deviceFamilies.some((family)=>family!=="iphone"&&family!=="ipad")))throw Error("ios.deviceFamilies must contain iphone and/or ipad");if(config.url){const url=new URL(normalizeMobileUrl(config.url)),isLocal=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!isLocal)throw Error("ios.url must use HTTPS outside local development")}for(const domain of config.associatedDomains??[])if(!/^(applinks|webcredentials|activitycontinuation):[^/\s]+$/.test(domain))throw Error(`Invalid iOS associated domain: ${domain}`);for(const key of["splashMaxSeconds","requestTimeoutSeconds"]){const value=config[key];if(value!==void 0&&(!Number.isFinite(value)||value<=0))throw Error(`ios.${key} must be a positive number of seconds`)}const refresh=config.backgroundRefresh;if(refresh){if(refresh.identifier!==void 0&&!/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/.test(refresh.identifier))throw Error(`Invalid iOS background refresh identifier: ${refresh.identifier}`);if(refresh.minimumIntervalMinutes!==void 0&&(!Number.isFinite(refresh.minimumIntervalMinutes)||refresh.minimumIntervalMinutes<=0))throw Error("ios.backgroundRefresh.minimumIntervalMinutes must be a positive number of minutes")}if(config.capabilities?.watchApp){const target=Number.parseFloat(config.watchDeploymentTarget??"9.0");if(!Number.isFinite(target)||target<9)throw Error("ios.watchDeploymentTarget must be watchOS 9.0 or newer")}}const ACTIVITY_TYPES_BLOCK=/[ \t]*<key>NSUserActivityTypes<\/key>\s*<array>[\s\S]*?<\/array>\n?/;export function withActivityTypes(plist,types){const entries=types.map((type)=>` <string>${escapeXml(type)}</string>`).join(`
|
|
2
2
|
`),block=types.length===0?"":` <key>NSUserActivityTypes</key>
|
|
3
3
|
<array>
|
|
4
4
|
${entries}
|
package/dist/build/ios.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{applyWithheldEnv}from"@stacksjs/env";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{assertCraftSupportsAppShortcuts,assertCraftSupportsCapabilities,assertCraftSupportsCrashReporting,portablePaths,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts,toCraftIosConfig,validateIosMobileConfig,writeIosActivityTypes}from"./ios-config";import{generateXcodeProject,resolveXcodegen}from"./ios-toolchain";import{compileNativeScreens}from"./native-screens";import{writeIosShellSupport}from"./ios-shell";import{reportMobileBuildTarget}from"./mobile-target";import{assertCraftSupportsChromeFonts,assertCraftSupportsTint}from"./ios-config";process.exitCode=1;function craftIosEntry(){const explicit=process.env.CRAFT_IOS_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("ios",projectPath())}async function loadCraftIosBuilder(){try{return await import(craftIosEntry())}catch(error){throw Error("Craft iOS builder is unavailable. Install the current craft-native package or set CRAFT_IOS_SRC to packages/ios/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath))throw Error("Missing config/mobile.ts. Add an ios section before running `buddy build:ios`.");applyWithheldEnv();const configModule=await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`),mobile=configModule.default,config=mobile.ios;validateIosMobileConfig(config);if(config.swipeNavigation===!0&&config.swipeBack!=="webview")log.warn("ios.swipeNavigation turns on WebKit's edge swipe alongside the stx router's own. Remove it, or set ios.swipeBack: 'webview' for an app not on the router.");const output=resolveMobilePath(projectPath(),config.output)??storagePath("framework/mobile/ios"),generateProject=process.env.STACKS_IOS_SKIP_XCODEGEN!=="1",xcodegen=generateProject?await resolveXcodegen(projectPath()):null,webAssets=resolveMobilePath(projectPath(),config.webAssets),fallbackWebAssets=resolveMobilePath(projectPath(),config.fallbackWebAssets),crashReporting=resolveCrashReporting(mobile.crashReporting,config.crashReporting),craftConfig=toCraftIosConfig({...config,crashReporting});craftConfig.nativeFonts=resolveNativeFonts(config.nativeFonts,projectPath());craftConfig.appIconPath=resolveMobilePath(projectPath(),config.appIcon);craftConfig.splashImagePath=resolveMobilePath(projectPath(),config.splash?.image);craftConfig.splashImagePathDark=resolveMobilePath(projectPath(),config.splash?.imageDark);const
|
|
1
|
+
import{existsSync,readFileSync,writeFileSync}from"node:fs";import{pathToFileURL}from"node:url";import process from"node:process";import{log}from"@stacksjs/cli";import{applyWithheldEnv}from"@stacksjs/env";import{projectPath,storagePath}from"@stacksjs/path";import{craftBuilderSpecifier,craftBuilderVersion}from"./craft-entry";import{resolveCraftBuilderProvenance}from"./craft-provenance";import{assertCraftSupportsAppShortcuts,assertCraftSupportsCapabilities,assertCraftSupportsCrashReporting,portablePaths,resolveCrashReporting,resolveMobilePath,resolveNativeFonts,assertCraftSupportsNativeFonts,toCraftIosConfig,validateIosMobileConfig,writeIosActivityTypes}from"./ios-config";import{generateXcodeProject,resolveXcodegen}from"./ios-toolchain";import{compileNativeScreens}from"./native-screens";import{writeIosShellSupport}from"./ios-shell";import{reportMobileBuildTarget}from"./mobile-target";import{assertCraftSupportsChromeFonts,assertCraftSupportsTint}from"./ios-config";process.exitCode=1;function craftIosEntry(){const explicit=process.env.CRAFT_IOS_SRC;return explicit?pathToFileURL(explicit).href:craftBuilderSpecifier("ios",projectPath())}async function loadCraftIosBuilder(){try{return await import(craftIosEntry())}catch(error){throw Error("Craft iOS builder is unavailable. Install the current craft-native package or set CRAFT_IOS_SRC to packages/ios/src/index.ts in a Craft checkout.",{cause:error})}}const configPath=projectPath("config/mobile.ts");if(!existsSync(configPath))throw Error("Missing config/mobile.ts. Add an ios section before running `buddy build:ios`.");applyWithheldEnv();const configModule=await import(`${pathToFileURL(configPath).href}?t=${Date.now()}`),mobile=configModule.default,config=mobile.ios;validateIosMobileConfig(config);if(config.swipeNavigation===!0&&config.swipeBack!=="webview")log.warn("ios.swipeNavigation turns on WebKit's edge swipe alongside the stx router's own. Remove it, or set ios.swipeBack: 'webview' for an app not on the router.");const output=resolveMobilePath(projectPath(),config.output)??storagePath("framework/mobile/ios"),generateProject=process.env.STACKS_IOS_SKIP_XCODEGEN!=="1",xcodegen=generateProject?await resolveXcodegen(projectPath()):null,webAssets=resolveMobilePath(projectPath(),config.webAssets),fallbackWebAssets=resolveMobilePath(projectPath(),config.fallbackWebAssets),crashReporting=resolveCrashReporting(mobile.crashReporting,config.crashReporting),builder=await loadCraftIosBuilder(),craftConfig=toCraftIosConfig({...config,crashReporting},builder.nativeSensorCapabilities);craftConfig.nativeFonts=resolveNativeFonts(config.nativeFonts,projectPath());craftConfig.appIconPath=resolveMobilePath(projectPath(),config.appIcon);craftConfig.splashImagePath=resolveMobilePath(projectPath(),config.splash?.image);craftConfig.splashImagePathDark=resolveMobilePath(projectPath(),config.splash?.imageDark);const nativeBundle=await compileNativeScreens(config,projectPath(),output,void 0,"ios",{routes:builder.nativeRouteBundles===!0,runtime:builder.nativeRouteRuntime===!0,messages:builder.nativeMessages===!0});if(nativeBundle){craftConfig.nativeBundle=nativeBundle.outFile;for(const diagnostic of nativeBundle.diagnostics??[])log.warn(`${diagnostic.file?`${diagnostic.file}: `:""}${diagnostic.message}`);log.info(`Compiled ${Object.keys(config.nativeScreens??{}).length} native screen path(s) into ${nativeBundle.outFile}`)}const craftVersion=craftBuilderVersion(craftIosEntry(),projectPath());assertCraftSupportsNativeFonts(config.nativeFonts,craftVersion?.version);assertCraftSupportsTint(config.tintColor,craftVersion?.version);assertCraftSupportsChromeFonts(config,craftVersion?.version);assertCraftSupportsAppShortcuts(config.appShortcuts,craftVersion?.version);if(craftVersion){assertCraftSupportsCapabilities(config.capabilities,craftVersion.version,craftVersion.manifest);assertCraftSupportsCrashReporting(crashReporting,craftVersion.version,craftVersion.manifest)}else log.warn(`Could not read the craft-native version behind ${craftIosEntry()}, so the build cannot check that it supports every capability config/mobile.ts turns on.`);await builder.init({name:config.appName,bundleId:config.bundleId,teamId:config.teamId,output,config:craftConfig});const native=config.renderer==="native";if(native&&!nativeBundle)throw Error("ios.renderer 'native' needs native screens to draw: list them in ios.nativeScreens");reportMobileBuildTarget({renderer:config.renderer,site:craftConfig.devServerURL,nativeBundle:nativeBundle?.outFile,webAssets,fallbackWebAssets,production:process.env.NODE_ENV==="production"},log);await builder.build(native?{output,nativeBundlePath:nativeBundle.outFile,generateProject:!1}:{output,htmlPath:webAssets??fallbackWebAssets,devServer:craftConfig.devServerURL,generateProject:!1});if(xcodegen){generateXcodeProject(xcodegen,output);log.info(`Generated the Xcode project with xcodegen ${xcodegen.version} from Pantry`)}writeIosShellSupport(output,config,void 0,crashReporting);if(crashReporting)log.info(`Crash reporting to ${crashReporting.host??"https://bughq.org"}${crashReporting.uploadSymbols===!1?"":": dSYMs upload from Xcode Cloud when BUGHQ_UPLOAD_TOKEN is set in the workflow"}`);const activityTypes=writeIosActivityTypes(output,mobile);if(activityTypes)log.info(`Declared ${activityTypes.length} activity types, so a tapped Spotlight or Siri entry reaches the app`);const sourceRevision=Bun.spawnSync(["git","rev-parse","HEAD"],{cwd:projectPath()}).stdout.toString().trim(),craftConfigPath=`${output}/craft.config.json`,generatedConfig=portablePaths(JSON.parse(readFileSync(craftConfigPath,"utf8")),output,projectPath());writeFileSync(craftConfigPath,`${JSON.stringify(generatedConfig,null,2)}
|
|
2
2
|
`);writeFileSync(`${output}/stacks-mobile.json`,`${JSON.stringify(portablePaths({schemaVersion:"1.0.0",platform:"ios",sourceRevision,source:native?{kind:"native",site:craftConfig.devServerURL}:webAssets?{kind:"bundled",path:webAssets}:{kind:"remote",url:craftConfig.devServerURL,fallback:fallbackWebAssets?{kind:"bundled",path:fallbackWebAssets}:void 0},capabilities:config.capabilities??{},builder:resolveCraftBuilderProvenance(process.env.CRAFT_IOS_SRC),craft:generatedConfig},output,projectPath()),null,2)}
|
|
3
3
|
`);log.success(`Built the Craft iOS project in ${output}`);await log.flush();process.exitCode=0;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { MobileCapabilities } from '@stacksjs/types';
|
|
2
|
+
/** Only serialize flags the selected builder advertises, including explicit false. */
|
|
3
|
+
export declare function nativeSensorCapabilityKeys(platform: 'ios' | 'android', supported: readonly string[] | undefined): Partial<Record<keyof MobileCapabilities, `enable${string}`>>;
|
|
4
|
+
/** Check the actual builder instead of inventing a version for unreleased support. */
|
|
5
|
+
export declare function assertCraftSupportsNativeSensors(platform: 'ios' | 'android', capabilities: MobileCapabilities | undefined, supported: readonly string[] | undefined): void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const SENSOR_CAPABILITY_KEYS={ios:{barometer:"enableBarometer",pedometer:"enablePedometer",healthKitBackground:"enableHealthKitBackground"},android:{motionSensors:"enableMotionSensors",barometer:"enableBarometer",pedometer:"enablePedometer"}};export function nativeSensorCapabilityKeys(platform,supported){return Object.fromEntries(Object.entries(SENSOR_CAPABILITY_KEYS[platform]).filter(([name])=>supported?.includes(name)))}export function assertCraftSupportsNativeSensors(platform,capabilities,supported){const missing=Object.keys(SENSOR_CAPABILITY_KEYS[platform]).filter((name)=>capabilities?.[name]&&!supported?.includes(name));if(missing.length)throw Error(`The selected Craft ${platform} builder does not support ${missing.join(", ")}. Install a published craft-native builder supporting these capabilities; these flags cannot be silently ignored.`)}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import type { DashboardModelOptions } from '@stacksjs/types';
|
|
2
|
+
/**
|
|
3
|
+
* The discovered models whose feature is on.
|
|
4
|
+
*
|
|
5
|
+
* A framework model whose feature is off is never loaded by the ORM, so its
|
|
6
|
+
* `/models/<id>` page could only answer 404. Sections already collapse when
|
|
7
|
+
* their feature is off (stacksjs/stacks#2928), but a model listed under Data,
|
|
8
|
+
* such as the forms models, still appeared with forms off. An app's own model
|
|
9
|
+
* is always listed: it is loaded whatever the framework features say.
|
|
10
|
+
*/
|
|
11
|
+
export declare function modelsWithEnabledFeatures(models: DiscoveredModel[], featureOf: (name: string) => string | undefined, enabled: (feature: string) => boolean): DiscoveredModel[];
|
|
2
12
|
/** Convert PascalCase model name to kebab-case ID */
|
|
3
13
|
export declare function modelNameToId(name: string): string;
|
|
4
14
|
/** Get the icon for a model name, falling back to the default */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Glob}from"bun";import{randomUUID}from"node:crypto";import{existsSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import path from"node:path";import{pathToFileURL}from"node:url";export const iconMap={user:"person.fill",team:"person.2.fill",subscriber:"envelope.open.fill",subscriberemail:"envelope.fill",post:"doc.text.fill",page:"doc.fill",product:"cube.box.fill",productvariant:"cube.fill",productunit:"scalemass.fill",order:"list.clipboard.fill",orderitem:"list.bullet.clipboard.fill",customer:"person.crop.circle.fill",payment:"creditcard.fill",paymentmethod:"creditcard.and.123",paymentproduct:"creditcard.fill",paymenttransaction:"creditcard.fill",category:"tag.fill",tag:"tag",comment:"bubble.left.fill",author:"person.text.rectangle.fill",notification:"bell.fill",job:"briefcase.fill",log:"list.bullet.rectangle.portrait.fill",campaign:"megaphone.fill",review:"star.fill",coupon:"ticket.fill",giftcard:"giftcard.fill",cart:"cart.fill",cartitem:"cart.badge.plus",taxrate:"percent",transaction:"arrow.left.arrow.right.circle.fill",subscription:"repeat.circle.fill",emaillist:"envelope.badge.person.crop",socialpost:"bubble.left.and.bubble.right.fill",manufacturer:"building.2.fill",shippingmethod:"shippingbox.fill",shippingzone:"map.fill",shippingrate:"dollarsign.circle.fill",deliveryroute:"map.fill",driver:"car.fill",digitaldelivery:"arrow.down.doc.fill",licensekey:"key.fill",loyaltypoint:"star.circle.fill",loyaltyreward:"gift.fill",printdevice:"printer.fill",receipt:"doc.text.fill",waitlistproduct:"clock.fill",waitlistrestaurant:"clock.badge.checkmark.fill",websocket:"antenna.radiowaves.left.and.right",default:"tablecells.fill"},excludeModels=new Set(["activity","request","error","failedjob"]),dedicatedPages=new Set(["user","team","subscriber","post","page","product","order","customer","payment","coupon","category","tag","comment","author","notification","job","campaign","review","gift-card"]);const ROOT_MODEL_CATEGORY={user:"data",team:"data",subscriber:"data",activity:"data",campaign:"marketing",emaillist:"marketing",socialpost:"marketing",subscriberemail:"marketing",comment:"content",tag:"content",paymentmethod:"commerce",paymentproduct:"commerce",paymenttransaction:"commerce",subscription:"commerce",deployment:"system",error:"system",failedjob:"system",job:"system",log:"system",notification:"system",release:"system",request:"system"};export function modelNameToId(name){return name.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}export function getModelIcon(name){return iconMap[name.toLowerCase()]||iconMap.default||"database"}function categorizeModel(relativePath,modelId,defaultCategory){if(defaultCategory)return defaultCategory;const firstSeg=relativePath.includes("/")?(relativePath.split("/")[0]??"").toLowerCase():"";if(firstSeg==="commerce")return"commerce";if(firstSeg==="content")return"content";if(firstSeg==="realtime")return"system";return ROOT_MODEL_CATEGORY[modelId.replace(/-/g,"")]??"data"}async function readModelDashboardConfig(absolutePath){try{const mod=await import(pathToFileURL(absolutePath).href);return(mod.default??mod).dashboard}catch(error){throw Error(`Could not discover dashboard model ${absolutePath}: ${error instanceof Error?error.message:String(error)}`)}}export async function scanModelsDir(dir,seenNames,models,defaultCategory){if(!existsSync(dir))return;const glob=new Glob("**/*.ts");for await(const file of glob.scan({cwd:dir})){if(file.includes("README")||file.includes(".d.ts"))continue;const name=file.replace(/\.ts$/,"").split("/").pop()||"",nameLower=name.toLowerCase();if(name&&!seenNames.has(nameLower)&&!excludeModels.has(nameLower)){seenNames.add(nameLower);const id=modelNameToId(name),absolutePath=path.resolve(dir,file),dashboard=await readModelDashboardConfig(absolutePath);models.push({name,icon:dashboard?.icon??getModelIcon(name),id,category:categorizeModel(file,id,defaultCategory),dashboard})}}}export async function discoverModels(userModelsPath,defaultModelsPath){const models=[],seenNames=new Set;await scanModelsDir(userModelsPath,seenNames,models,"userland");await scanModelsDir(defaultModelsPath,seenNames,models);return models.sort((a,b)=>a.name.localeCompare(b.name))}export function buildManifest(models){return models.map((m)=>{const row={id:m.id,name:m.name,icon:m.icon,hasDedicatedPage:dedicatedPages.has(m.id),category:m.category??"data"};if(m.dashboard)row.dashboard=m.dashboard;return row})}export function writeFileIfChanged(file,content){try{if(readFileSync(file,"utf8")===content)return!1}catch{}const temporary=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(temporary,content,{flag:"wx"});renameSync(temporary,file)}finally{if(existsSync(temporary))unlinkSync(temporary)}return!0}export async function isPortAvailable(port){try{await Bun.serve({port,fetch:()=>new Response}).stop(!0);return!0}catch{return!1}}export async function findAvailablePort(preferred,maxAttempts=20){for(let i=0;i<maxAttempts;i++){const port=preferred+i;if(await isPortAvailable(port))return port}return preferred}function connectsWithin(port,timeoutMs){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(connected)=>{clearTimeout(timer);try{socket.destroy()}catch{}resolve(connected)},timer=setTimeout(()=>finish(!1),timeoutMs);socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1))})}export async function waitForServer(port,maxWait=500){const deadline=Date.now()+maxWait;while(!0){const remaining=deadline-Date.now();if(remaining<=0)return!1;if(await connectsWithin(port,Math.min(remaining,250)))return!0;if(Date.now()>=deadline)return!1;await new Promise((resolve)=>setTimeout(resolve,Math.min(25,Math.max(deadline-Date.now(),0))))}}function effectiveCategory(m){if(m.dashboard?.enabled===!1)return;if(m.dashboard?.section)return m.dashboard.section;return m.category??"data"}function categoryRows(baseRoute,models,category,dedicated){return models.filter((m)=>effectiveCategory(m)===category).filter((m)=>!dedicatedPages.has(m.id)&&!dedicated.has(m.id)).map((m)=>({id:`model-${m.id}`,label:m.dashboard?.label??m.name,icon:m.icon,url:`${baseRoute}/models/${m.id}`,...m.dashboard?.roles&&m.dashboard.roles.length>0?{roles:m.dashboard.roles}:{}}))}export function buildSidebarConfig(baseRoute,discoveredModels,toggles={}){const enabled={library:toggles.library??!0,content:toggles.content??!0,commerce:toggles.commerce??!0,marketing:toggles.marketing??!0,analytics:toggles.analytics??!0,management:toggles.management??!0,utilities:toggles.utilities??!0},dataRow={dashboard:toggles.data?.dashboard??!0,activity:toggles.data?.activity??!0,users:toggles.data?.users??!0,teams:toggles.data?.teams??!0,subscribers:toggles.data?.subscribers??!0,allModels:toggles.data?.allModels??!0},sections=[],homeItems=[{id:"home",label:"Dashboard",icon:"house.fill",url:`${baseRoute}/`},{id:"dependencies",label:"Dependencies",icon:"shippingbox.fill",url:`${baseRoute}/dependencies`},{id:"health",label:"Health",icon:"heart.text.square.fill",url:`${baseRoute}/health`}];if(toggles.ci)homeItems.push({id:"ci",label:"CI",icon:"checkmark.seal.fill",url:`${baseRoute}/ci`});sections.push({id:"home",title:"Home",items:homeItems});if(enabled.library)sections.push({id:"library",title:"Library",items:[{id:"functions",label:"Functions",icon:"function",url:`${baseRoute}/functions`},{id:"packages",label:"Packages",icon:"shippingbox.fill",url:`${baseRoute}/packages`}]});if(enabled.content)sections.push({id:"content",title:"Content",items:[{id:"content-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/content/dashboard`},{id:"files",label:"Files",icon:"folder.fill",url:`${baseRoute}/content/files`},{id:"pages",label:"Pages",icon:"doc.fill",url:`${baseRoute}/content/pages`},{id:"posts",label:"Posts",icon:"text.bubble.fill",url:`${baseRoute}/content/posts`},{id:"categories",label:"Categories",icon:"tag.fill",url:`${baseRoute}/content/categories`},{id:"tags",label:"Tags",icon:"tag",url:`${baseRoute}/content/tags`},{id:"comments",label:"Comments",icon:"bubble.left.fill",url:`${baseRoute}/content/comments`},{id:"authors",label:"Authors",icon:"person.text.rectangle.fill",url:`${baseRoute}/content/authors`},{id:"seo",label:"SEO",icon:"magnifyingglass",url:`${baseRoute}/content/seo`},...categoryRows(baseRoute,discoveredModels,"content",new Set(["page","post","category","tag","comment","author"]))]});sections.push({id:"app",title:"App",items:[{id:"deployments",label:"Deployments",icon:"rocket.fill",url:`${baseRoute}/deployments`},{id:"requests",label:"Requests",icon:"arrow.left.arrow.right",url:`${baseRoute}/requests`},{id:"realtime",label:"Realtime",icon:"link",url:`${baseRoute}/realtime`},{id:"actions",label:"Actions",icon:"bolt.fill",url:`${baseRoute}/actions`},{id:"commands",label:"Commands",icon:"terminal.fill",url:`${baseRoute}/commands`},{id:"queue",label:"Queue",icon:"list.bullet.rectangle.fill",url:`${baseRoute}/queue`},{id:"jobs",label:"Jobs",icon:"briefcase.fill",url:`${baseRoute}/jobs`},{id:"inbox",label:"Inbox",icon:"tray.full.fill",url:`${baseRoute}/inbox`},{id:"queries",label:"Queries",icon:"magnifyingglass.circle.fill",url:`${baseRoute}/queries`},{id:"notifications",label:"Notifications",icon:"bell.fill",url:`${baseRoute}/notifications/dashboard`},...categoryRows(baseRoute,discoveredModels,"system",new Set)]});const dataItems=[];if(dataRow.dashboard)dataItems.push({id:"data-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/data/dashboard`});if(dataRow.activity)dataItems.push({id:"activity",label:"Activity",icon:"waveform.path.ecg",url:`${baseRoute}/data/activity`});if(dataRow.users)dataItems.push({id:"users",label:"Users",icon:"person.crop.circle.fill",url:`${baseRoute}/data/users`});if(dataRow.teams)dataItems.push({id:"teams",label:"Teams",icon:"person.3.fill",url:`${baseRoute}/data/teams`});if(dataRow.subscribers)dataItems.push({id:"subscribers",label:"Subscribers",icon:"envelope.fill",url:`${baseRoute}/data/subscribers`});if(dataRow.allModels)dataItems.push({id:"data-models",label:"All Models",icon:"square.grid.2x2.fill",url:`${baseRoute}/models`});const dynamicRows=discoveredModels.filter((m)=>{const eff=effectiveCategory(m);return eff==="userland"||eff==="data"}).filter((m)=>!dedicatedPages.has(m.id)).map((model)=>({id:`model-${model.id}`,label:model.dashboard?.label??model.name,icon:model.icon,url:`${baseRoute}/models/${model.id}`,...model.dashboard?.roles&&model.dashboard.roles.length>0?{roles:model.dashboard.roles}:{}}));sections.push({id:"data",title:"Data",items:[...dataItems,...dynamicRows]});if(enabled.commerce)sections.push({id:"commerce",title:"Commerce",items:[{id:"commerce-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/commerce/dashboard`},{id:"customers",label:"Customers",icon:"person.crop.circle.fill",url:`${baseRoute}/commerce/customers`},{id:"orders",label:"Orders",icon:"list.clipboard.fill",url:`${baseRoute}/commerce/orders`},{id:"products",label:"Products",icon:"cube.box.fill",url:`${baseRoute}/commerce/products`},{id:"coupons",label:"Coupons",icon:"ticket.fill",url:`${baseRoute}/commerce/coupons`},{id:"gift-cards",label:"Gift Cards",icon:"giftcard.fill",url:`${baseRoute}/commerce/gift-cards`},{id:"payments",label:"Payments",icon:"creditcard.fill",url:`${baseRoute}/commerce/payments`},{id:"delivery",label:"Delivery",icon:"truck.box.fill",url:`${baseRoute}/commerce/delivery`},{id:"taxes",label:"Taxes",icon:"percent",url:`${baseRoute}/commerce/taxes`},...categoryRows(baseRoute,discoveredModels,"commerce",new Set(["customer","order","product","coupon","gift-card","payment","review","category"]))]});if(enabled.marketing)sections.push({id:"marketing",title:"Marketing",items:[{id:"lists",label:"Lists",icon:"list.bullet",url:`${baseRoute}/marketing/lists`},{id:"social-posts",label:"Social Posts",icon:"clock.fill",url:`${baseRoute}/marketing/social-posts`},{id:"campaigns",label:"Campaigns",icon:"megaphone.fill",url:`${baseRoute}/marketing/campaigns`},{id:"marketing-reviews",label:"Reviews",icon:"star.fill",url:`${baseRoute}/marketing/reviews`},...categoryRows(baseRoute,discoveredModels,"marketing",new Set(["campaign"]))]});if(enabled.analytics)sections.push({id:"analytics",title:"Analytics",items:[{id:"analytics-web",label:"Web",icon:"globe",url:`${baseRoute}/analytics/web`},{id:"analytics-blog",label:"Blog",icon:"doc.text.fill",url:`${baseRoute}/analytics/blog`},{id:"analytics-commerce",label:"Commerce",icon:"cart.fill",url:`${baseRoute}/analytics/commerce/web`},{id:"analytics-marketing",label:"Marketing",icon:"megaphone.fill",url:`${baseRoute}/analytics/marketing`}]});if(enabled.management)sections.push({id:"management",title:"Management",items:[{id:"cloud",label:"Cloud",icon:"cloud.fill",url:`${baseRoute}/cloud`},{id:"servers",label:"Servers",icon:"server.rack",url:`${baseRoute}/servers`},{id:"serverless",label:"Serverless",icon:"bolt.horizontal.circle.fill",url:`${baseRoute}/serverless`},{id:"dns",label:"DNS",icon:"network",url:`${baseRoute}/dns`},{id:"mailboxes",label:"Mailboxes",icon:"tray.full.fill",url:`${baseRoute}/mailboxes`},{id:"logs",label:"Logs",icon:"list.bullet.rectangle.portrait.fill",url:`${baseRoute}/logs`},{id:"kanban",label:"Kanban",icon:"rectangle.stack.fill",url:`${baseRoute}/kanban`,roles:["admin","dev"]}]});if(enabled.utilities)sections.push({id:"utilities",title:"Utilities",items:[{id:"buddy",label:"AI Buddy",icon:"bubble.left.and.bubble.right.fill",url:`${baseRoute}/buddy`},{id:"environment",label:"Environment",icon:"key.fill",url:`${baseRoute}/environment`},{id:"access-tokens",label:"Access Tokens",icon:"key.horizontal.fill",url:`${baseRoute}/access-tokens`},{id:"settings",label:"Settings",icon:"gear",url:`${baseRoute}/settings/billing`}]});return{sections,minWidth:200,maxWidth:280}}
|
|
1
|
+
import{Glob}from"bun";import{randomUUID}from"node:crypto";import{existsSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{connect}from"node:net";import path from"node:path";import{pathToFileURL}from"node:url";export const iconMap={user:"person.fill",team:"person.2.fill",subscriber:"envelope.open.fill",subscriberemail:"envelope.fill",post:"doc.text.fill",page:"doc.fill",product:"cube.box.fill",productvariant:"cube.fill",productunit:"scalemass.fill",order:"list.clipboard.fill",orderitem:"list.bullet.clipboard.fill",customer:"person.crop.circle.fill",payment:"creditcard.fill",paymentmethod:"creditcard.and.123",paymentproduct:"creditcard.fill",paymenttransaction:"creditcard.fill",category:"tag.fill",tag:"tag",comment:"bubble.left.fill",author:"person.text.rectangle.fill",notification:"bell.fill",job:"briefcase.fill",log:"list.bullet.rectangle.portrait.fill",campaign:"megaphone.fill",review:"star.fill",coupon:"ticket.fill",giftcard:"giftcard.fill",cart:"cart.fill",cartitem:"cart.badge.plus",taxrate:"percent",transaction:"arrow.left.arrow.right.circle.fill",subscription:"repeat.circle.fill",emaillist:"envelope.badge.person.crop",socialpost:"bubble.left.and.bubble.right.fill",manufacturer:"building.2.fill",shippingmethod:"shippingbox.fill",shippingzone:"map.fill",shippingrate:"dollarsign.circle.fill",deliveryroute:"map.fill",driver:"car.fill",digitaldelivery:"arrow.down.doc.fill",licensekey:"key.fill",loyaltypoint:"star.circle.fill",loyaltyreward:"gift.fill",printdevice:"printer.fill",receipt:"doc.text.fill",waitlistproduct:"clock.fill",waitlistrestaurant:"clock.badge.checkmark.fill",websocket:"antenna.radiowaves.left.and.right",default:"tablecells.fill"},excludeModels=new Set(["activity","request","error","failedjob"]),dedicatedPages=new Set(["user","team","subscriber","post","page","product","order","customer","payment","coupon","category","tag","comment","author","notification","job","campaign","review","gift-card"]);const ROOT_MODEL_CATEGORY={user:"data",team:"data",subscriber:"data",activity:"data",campaign:"marketing",emaillist:"marketing",socialpost:"marketing",subscriberemail:"marketing",comment:"content",tag:"content",paymentmethod:"commerce",paymentproduct:"commerce",paymenttransaction:"commerce",subscription:"commerce",deployment:"system",error:"system",failedjob:"system",job:"system",log:"system",notification:"system",release:"system",request:"system"};export function modelsWithEnabledFeatures(models,featureOf,enabled){return models.filter((model)=>{if(model.category==="userland")return!0;const gate=featureOf(model.name);return gate===void 0||enabled(gate)})}export function modelNameToId(name){return name.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,"")}export function getModelIcon(name){return iconMap[name.toLowerCase()]||iconMap.default||"database"}function categorizeModel(relativePath,modelId,defaultCategory){if(defaultCategory)return defaultCategory;const firstSeg=relativePath.includes("/")?(relativePath.split("/")[0]??"").toLowerCase():"";if(firstSeg==="commerce")return"commerce";if(firstSeg==="content")return"content";if(firstSeg==="realtime")return"system";return ROOT_MODEL_CATEGORY[modelId.replace(/-/g,"")]??"data"}async function readModelDashboardConfig(absolutePath){try{const mod=await import(pathToFileURL(absolutePath).href);return(mod.default??mod).dashboard}catch(error){throw Error(`Could not discover dashboard model ${absolutePath}: ${error instanceof Error?error.message:String(error)}`)}}export async function scanModelsDir(dir,seenNames,models,defaultCategory){if(!existsSync(dir))return;const glob=new Glob("**/*.ts");for await(const file of glob.scan({cwd:dir})){if(file.includes("README")||file.includes(".d.ts"))continue;const name=file.replace(/\.ts$/,"").split("/").pop()||"",nameLower=name.toLowerCase();if(name&&!seenNames.has(nameLower)&&!excludeModels.has(nameLower)){seenNames.add(nameLower);const id=modelNameToId(name),absolutePath=path.resolve(dir,file),dashboard=await readModelDashboardConfig(absolutePath);models.push({name,icon:dashboard?.icon??getModelIcon(name),id,category:categorizeModel(file,id,defaultCategory),dashboard})}}}export async function discoverModels(userModelsPath,defaultModelsPath){const models=[],seenNames=new Set;await scanModelsDir(userModelsPath,seenNames,models,"userland");await scanModelsDir(defaultModelsPath,seenNames,models);return models.sort((a,b)=>a.name.localeCompare(b.name))}export function buildManifest(models){return models.map((m)=>{const row={id:m.id,name:m.name,icon:m.icon,hasDedicatedPage:dedicatedPages.has(m.id),category:m.category??"data"};if(m.dashboard)row.dashboard=m.dashboard;return row})}export function writeFileIfChanged(file,content){try{if(readFileSync(file,"utf8")===content)return!1}catch{}const temporary=`${file}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(temporary,content,{flag:"wx"});renameSync(temporary,file)}finally{if(existsSync(temporary))unlinkSync(temporary)}return!0}export async function isPortAvailable(port){try{await Bun.serve({port,fetch:()=>new Response}).stop(!0);return!0}catch{return!1}}export async function findAvailablePort(preferred,maxAttempts=20){for(let i=0;i<maxAttempts;i++){const port=preferred+i;if(await isPortAvailable(port))return port}return preferred}function connectsWithin(port,timeoutMs){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(connected)=>{clearTimeout(timer);try{socket.destroy()}catch{}resolve(connected)},timer=setTimeout(()=>finish(!1),timeoutMs);socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1))})}export async function waitForServer(port,maxWait=500){const deadline=Date.now()+maxWait;while(!0){const remaining=deadline-Date.now();if(remaining<=0)return!1;if(await connectsWithin(port,Math.min(remaining,250)))return!0;if(Date.now()>=deadline)return!1;await new Promise((resolve)=>setTimeout(resolve,Math.min(25,Math.max(deadline-Date.now(),0))))}}function effectiveCategory(m){if(m.dashboard?.enabled===!1)return;if(m.dashboard?.section)return m.dashboard.section;return m.category??"data"}function categoryRows(baseRoute,models,category,dedicated){return models.filter((m)=>effectiveCategory(m)===category).filter((m)=>!dedicatedPages.has(m.id)&&!dedicated.has(m.id)).map((m)=>({id:`model-${m.id}`,label:m.dashboard?.label??m.name,icon:m.icon,url:`${baseRoute}/models/${m.id}`,...m.dashboard?.roles&&m.dashboard.roles.length>0?{roles:m.dashboard.roles}:{}}))}export function buildSidebarConfig(baseRoute,discoveredModels,toggles={}){const enabled={library:toggles.library??!0,content:toggles.content??!0,commerce:toggles.commerce??!0,marketing:toggles.marketing??!0,analytics:toggles.analytics??!0,management:toggles.management??!0,utilities:toggles.utilities??!0},dataRow={dashboard:toggles.data?.dashboard??!0,activity:toggles.data?.activity??!0,users:toggles.data?.users??!0,teams:toggles.data?.teams??!0,subscribers:toggles.data?.subscribers??!0,allModels:toggles.data?.allModels??!0},sections=[],homeItems=[{id:"home",label:"Dashboard",icon:"house.fill",url:`${baseRoute}/`},{id:"dependencies",label:"Dependencies",icon:"shippingbox.fill",url:`${baseRoute}/dependencies`},{id:"health",label:"Health",icon:"heart.text.square.fill",url:`${baseRoute}/health`}];if(toggles.ci)homeItems.push({id:"ci",label:"CI",icon:"checkmark.seal.fill",url:`${baseRoute}/ci`});sections.push({id:"home",title:"Home",items:homeItems});if(enabled.library)sections.push({id:"library",title:"Library",items:[{id:"functions",label:"Functions",icon:"function",url:`${baseRoute}/functions`},{id:"packages",label:"Packages",icon:"shippingbox.fill",url:`${baseRoute}/packages`}]});if(enabled.content)sections.push({id:"content",title:"Content",items:[{id:"content-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/content/dashboard`},{id:"files",label:"Files",icon:"folder.fill",url:`${baseRoute}/content/files`},{id:"pages",label:"Pages",icon:"doc.fill",url:`${baseRoute}/content/pages`},{id:"posts",label:"Posts",icon:"text.bubble.fill",url:`${baseRoute}/content/posts`},{id:"categories",label:"Categories",icon:"tag.fill",url:`${baseRoute}/content/categories`},{id:"tags",label:"Tags",icon:"tag",url:`${baseRoute}/content/tags`},{id:"comments",label:"Comments",icon:"bubble.left.fill",url:`${baseRoute}/content/comments`},{id:"authors",label:"Authors",icon:"person.text.rectangle.fill",url:`${baseRoute}/content/authors`},{id:"seo",label:"SEO",icon:"magnifyingglass",url:`${baseRoute}/content/seo`},...categoryRows(baseRoute,discoveredModels,"content",new Set(["page","post","category","tag","comment","author"]))]});sections.push({id:"app",title:"App",items:[{id:"deployments",label:"Deployments",icon:"rocket.fill",url:`${baseRoute}/deployments`},{id:"requests",label:"Requests",icon:"arrow.left.arrow.right",url:`${baseRoute}/requests`},{id:"realtime",label:"Realtime",icon:"link",url:`${baseRoute}/realtime`},{id:"actions",label:"Actions",icon:"bolt.fill",url:`${baseRoute}/actions`},{id:"commands",label:"Commands",icon:"terminal.fill",url:`${baseRoute}/commands`},{id:"queue",label:"Queue",icon:"list.bullet.rectangle.fill",url:`${baseRoute}/queue`},{id:"jobs",label:"Jobs",icon:"briefcase.fill",url:`${baseRoute}/jobs`},{id:"inbox",label:"Inbox",icon:"tray.full.fill",url:`${baseRoute}/inbox`},{id:"queries",label:"Queries",icon:"magnifyingglass.circle.fill",url:`${baseRoute}/queries`},{id:"notifications",label:"Notifications",icon:"bell.fill",url:`${baseRoute}/notifications/dashboard`},...categoryRows(baseRoute,discoveredModels,"system",new Set)]});const dataItems=[];if(dataRow.dashboard)dataItems.push({id:"data-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/data/dashboard`});if(dataRow.activity)dataItems.push({id:"activity",label:"Activity",icon:"waveform.path.ecg",url:`${baseRoute}/data/activity`});if(dataRow.users)dataItems.push({id:"users",label:"Users",icon:"person.crop.circle.fill",url:`${baseRoute}/data/users`});if(dataRow.teams)dataItems.push({id:"teams",label:"Teams",icon:"person.3.fill",url:`${baseRoute}/data/teams`});if(dataRow.subscribers)dataItems.push({id:"subscribers",label:"Subscribers",icon:"envelope.fill",url:`${baseRoute}/data/subscribers`});if(dataRow.allModels)dataItems.push({id:"data-models",label:"All Models",icon:"square.grid.2x2.fill",url:`${baseRoute}/models`});const dynamicRows=discoveredModels.filter((m)=>{const eff=effectiveCategory(m);return eff==="userland"||eff==="data"}).filter((m)=>!dedicatedPages.has(m.id)).map((model)=>({id:`model-${model.id}`,label:model.dashboard?.label??model.name,icon:model.icon,url:`${baseRoute}/models/${model.id}`,...model.dashboard?.roles&&model.dashboard.roles.length>0?{roles:model.dashboard.roles}:{}}));sections.push({id:"data",title:"Data",items:[...dataItems,...dynamicRows]});if(enabled.commerce)sections.push({id:"commerce",title:"Commerce",items:[{id:"commerce-dashboard",label:"Dashboard",icon:"gauge.with.dots.needle.33percent",url:`${baseRoute}/commerce/dashboard`},{id:"customers",label:"Customers",icon:"person.crop.circle.fill",url:`${baseRoute}/commerce/customers`},{id:"orders",label:"Orders",icon:"list.clipboard.fill",url:`${baseRoute}/commerce/orders`},{id:"products",label:"Products",icon:"cube.box.fill",url:`${baseRoute}/commerce/products`},{id:"coupons",label:"Coupons",icon:"ticket.fill",url:`${baseRoute}/commerce/coupons`},{id:"gift-cards",label:"Gift Cards",icon:"giftcard.fill",url:`${baseRoute}/commerce/gift-cards`},{id:"payments",label:"Payments",icon:"creditcard.fill",url:`${baseRoute}/commerce/payments`},{id:"delivery",label:"Delivery",icon:"truck.box.fill",url:`${baseRoute}/commerce/delivery`},{id:"taxes",label:"Taxes",icon:"percent",url:`${baseRoute}/commerce/taxes`},...categoryRows(baseRoute,discoveredModels,"commerce",new Set(["customer","order","product","coupon","gift-card","payment","review","category"]))]});if(enabled.marketing)sections.push({id:"marketing",title:"Marketing",items:[{id:"lists",label:"Lists",icon:"list.bullet",url:`${baseRoute}/marketing/lists`},{id:"social-posts",label:"Social Posts",icon:"clock.fill",url:`${baseRoute}/marketing/social-posts`},{id:"campaigns",label:"Campaigns",icon:"megaphone.fill",url:`${baseRoute}/marketing/campaigns`},{id:"marketing-reviews",label:"Reviews",icon:"star.fill",url:`${baseRoute}/marketing/reviews`},...categoryRows(baseRoute,discoveredModels,"marketing",new Set(["campaign"]))]});if(enabled.analytics)sections.push({id:"analytics",title:"Analytics",items:[{id:"analytics-web",label:"Web",icon:"globe",url:`${baseRoute}/analytics/web`},{id:"analytics-blog",label:"Blog",icon:"doc.text.fill",url:`${baseRoute}/analytics/blog`},{id:"analytics-commerce",label:"Commerce",icon:"cart.fill",url:`${baseRoute}/analytics/commerce/web`},{id:"analytics-marketing",label:"Marketing",icon:"megaphone.fill",url:`${baseRoute}/analytics/marketing`}]});if(enabled.management)sections.push({id:"management",title:"Management",items:[{id:"cloud",label:"Cloud",icon:"cloud.fill",url:`${baseRoute}/cloud`},{id:"servers",label:"Servers",icon:"server.rack",url:`${baseRoute}/servers`},{id:"serverless",label:"Serverless",icon:"bolt.horizontal.circle.fill",url:`${baseRoute}/serverless`},{id:"dns",label:"DNS",icon:"network",url:`${baseRoute}/dns`},{id:"mailboxes",label:"Mailboxes",icon:"tray.full.fill",url:`${baseRoute}/mailboxes`},{id:"logs",label:"Logs",icon:"list.bullet.rectangle.portrait.fill",url:`${baseRoute}/logs`},{id:"kanban",label:"Kanban",icon:"rectangle.stack.fill",url:`${baseRoute}/kanban`,roles:["admin","dev"]}]});if(enabled.utilities)sections.push({id:"utilities",title:"Utilities",items:[{id:"buddy",label:"AI Buddy",icon:"bubble.left.and.bubble.right.fill",url:`${baseRoute}/buddy`},{id:"environment",label:"Environment",icon:"key.fill",url:`${baseRoute}/environment`},{id:"access-tokens",label:"Access Tokens",icon:"key.horizontal.fill",url:`${baseRoute}/access-tokens`},{id:"settings",label:"Settings",icon:"gear",url:`${baseRoute}/settings/billing`}]});return{sections,minWidth:200,maxWidth:280}}
|
package/dist/dev/dashboard.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import process from"node:process";import{existsSync,mkdirSync}from"node:fs";import{connect}from"node:net";import{bold,cyan,dim,green}from"@stacksjs/cli";import{defaultsPath,projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{resolveComponentsLibraryRoot}from"./defaults-resources";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{resolveDashboardCraftExecutable}from"./dashboard-native";import{resolveDashboardDomain,resolveDashboardProxyStrategy}from"./dashboard-proxy";import{buildManifest,discoverModels,findAvailablePort,waitForServer,writeFileIfChanged}from"./dashboard-utils";import{runDashboardSupervisor}from"./dashboard-supervisor";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveStxSource}from"../stx-source";if(process.env.STACKS_DASHBOARD_WORKER!=="1"){const exitCode=await runDashboardSupervisor(import.meta.path,process.argv.slice(2));process.exit(exitCode)}const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),{log:originalConsoleLog,warn:originalConsoleWarn}=console,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=defaultsPath("views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),dashboardComponentsPath=defaultsPath("resources/components/Dashboard"),userDashboardComponentsPath=projectPath("resources/components/Dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",dashboardDomain=resolveDashboardDomain(appUrl),sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){const{overridesReady}=await import("@stacksjs/config"),{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports}=await import("@stacksjs/server");await overridesReady;await ensureDiscoveredPackages();if(!existsSync(storagePath("framework/auto-imports/models.ts"))||autoImportsAreStale())await generateAutoImportFiles();await injectGlobalAutoImports();const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")throw Error(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`);let serve;if(serveSource.kind==="override"){serve=(await import(serveSource.path)).serve;console.log(`[Dashboard] bun-plugin-stx from ${serveSource.path}`)}else serve=(await import("bun-plugin-stx/serve")).serve;const stxSource=resolveStxSource({value:process.env.STX_SRC});if(stxSource.kind==="missing")throw Error(`STX_SRC points at ${stxSource.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`);let stxModule;if(stxSource.kind==="override"){stxModule=await import(stxSource.path);console.log(`[Dashboard] stx from ${stxSource.path}`)}const{listConfigFiles,readConfig,updateConfigKeys}=await import(defaultsPath("resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[...localTsChartsRoot?[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`]:[],projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[...localTsChartsRoot?[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`]:[],projectPath("node_modules/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
|
|
1
|
+
import process from"node:process";import{existsSync,mkdirSync}from"node:fs";import{connect}from"node:net";import{bold,cyan,dim,green}from"@stacksjs/cli";import{defaultsPath,projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{resolveComponentsLibraryRoot}from"./defaults-resources";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{resolveDashboardCraftExecutable}from"./dashboard-native";import{resolveDashboardDomain,resolveDashboardProxyStrategy}from"./dashboard-proxy";import{buildManifest,discoverModels,findAvailablePort,modelsWithEnabledFeatures,waitForServer,writeFileIfChanged}from"./dashboard-utils";import{runDashboardSupervisor}from"./dashboard-supervisor";import{ensureDiscoveredPackages}from"../discover-packages";import{resolveStxSource}from"../stx-source";if(process.env.STACKS_DASHBOARD_WORKER!=="1"){const exitCode=await runDashboardSupervisor(import.meta.path,process.argv.slice(2));process.exit(exitCode)}const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),{log:originalConsoleLog,warn:originalConsoleWarn}=console,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=defaultsPath("views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),dashboardComponentsPath=defaultsPath("resources/components/Dashboard"),userDashboardComponentsPath=projectPath("resources/components/Dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",dashboardDomain=resolveDashboardDomain(appUrl),sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){const{overridesReady}=await import("@stacksjs/config"),{autoImportsAreStale,generateAutoImportFiles,injectGlobalAutoImports}=await import("@stacksjs/server");await overridesReady;await ensureDiscoveredPackages();if(!existsSync(storagePath("framework/auto-imports/models.ts"))||autoImportsAreStale())await generateAutoImportFiles();await injectGlobalAutoImports();const serveSource=resolveStxSource({value:process.env.BUN_PLUGIN_STX_SRC});if(serveSource.kind==="missing")throw Error(`BUN_PLUGIN_STX_SRC points at ${serveSource.path}, which does not exist. Unset it to use the installed bun-plugin-stx.`);let serve;if(serveSource.kind==="override"){serve=(await import(serveSource.path)).serve;console.log(`[Dashboard] bun-plugin-stx from ${serveSource.path}`)}else serve=(await import("bun-plugin-stx/serve")).serve;const stxSource=resolveStxSource({value:process.env.STX_SRC});if(stxSource.kind==="missing")throw Error(`STX_SRC points at ${stxSource.path}, which does not exist. Unset it to use the installed @stacksjs/stx.`);let stxModule;if(stxSource.kind==="override"){stxModule=await import(stxSource.path);console.log(`[Dashboard] stx from ${stxSource.path}`)}const{listConfigFiles,readConfig,updateConfigKeys}=await import(defaultsPath("resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[...localTsChartsRoot?[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`]:[],projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[...localTsChartsRoot?[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`]:[],projectPath("node_modules/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
|
|
2
2
|
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCss}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,dashboardComponentsPath,userDashboardComponentsPath],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCss(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router");await router.loadRoutes(await router.appRouteRegistry());const stacksRoute=router.route;serve({root:projectPath("resources"),patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:userDashboardComponentsPath,additionalComponentsDirs:[dashboardComponentsPath],fallbackComponentsDir:resolveComponentsLibraryRoot(),layoutsDir:projectPath("resources/views/dashboard/layouts"),fallbackLayoutsDir:defaultsPath("views/dashboard/layouts"),partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:!1,renderCachePersist:!0,watchDirs:[projectPath("resources/functions"),defaultsPath("resources/functions"),projectPath("config"),storagePath("framework/runtime/dashboard")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
|
|
3
3
|
Failed to start dashboard server: ${err?.message||err}
|
|
4
|
-
`);process.exit(1)})}function portAnswers(port,timeoutMs=800){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(answered)=>{try{socket.destroy()}catch{}resolve(answered)};socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1));setTimeout(()=>finish(!1),timeoutMs).unref?.()})}async function registerWithRpxDaemon(domainToServe){const{writeEntry}=await import("@stacksjs/rpx");await writeEntry({id:`${domainToServe}-dashboard`,from:`localhost:${dashboardPort}`,to:domainToServe,cwd:process.cwd(),createdAt:new Date().toISOString(),pid:process.pid},void 0,verbose);return!0}async function startReverseProxy(){if(!dashboardDomain)return!1;try{let rpx;const loadRpx=async()=>rpx??=await import("@stacksjs/rpx"),strategy=await resolveDashboardProxyStrategy(dashboardDomain,{proxyManagedExternally:Boolean(process.env.STACKS_PROXY_MANAGED),isDaemonRunning:async()=>(await loadRpx()).isDaemonRunning(),httpsPortAnswers:()=>portAnswers(443)});if(strategy==="origin-only")return!1;if(strategy==="parent-managed")return!0;if(strategy==="daemon-route")return await registerWithRpxDaemon(dashboardDomain);await(await loadRpx()).startProxies({proxies:[{from:`localhost:${dashboardPort}`,to:dashboardDomain,cleanUrls:!1}],https:{basePath:sslBasePath,validityDays:825},regenerateUntrustedCerts:!1,verbose});return await portAnswers(443)}catch(error){if(verbose)originalConsoleLog(` ${dim(`Proxy: ${error}`)}`);return!1}}const[,
|
|
4
|
+
`);process.exit(1)})}function portAnswers(port,timeoutMs=800){return new Promise((resolve)=>{const socket=connect({port,host:"127.0.0.1"}),finish=(answered)=>{try{socket.destroy()}catch{}resolve(answered)};socket.once("connect",()=>finish(!0));socket.once("error",()=>finish(!1));setTimeout(()=>finish(!1),timeoutMs).unref?.()})}async function registerWithRpxDaemon(domainToServe){const{writeEntry}=await import("@stacksjs/rpx");await writeEntry({id:`${domainToServe}-dashboard`,from:`localhost:${dashboardPort}`,to:domainToServe,cwd:process.cwd(),createdAt:new Date().toISOString(),pid:process.pid},void 0,verbose);return!0}async function startReverseProxy(){if(!dashboardDomain)return!1;try{let rpx;const loadRpx=async()=>rpx??=await import("@stacksjs/rpx"),strategy=await resolveDashboardProxyStrategy(dashboardDomain,{proxyManagedExternally:Boolean(process.env.STACKS_PROXY_MANAGED),isDaemonRunning:async()=>(await loadRpx()).isDaemonRunning(),httpsPortAnswers:()=>portAnswers(443)});if(strategy==="origin-only")return!1;if(strategy==="parent-managed")return!0;if(strategy==="daemon-route")return await registerWithRpxDaemon(dashboardDomain);await(await loadRpx()).startProxies({proxies:[{from:`localhost:${dashboardPort}`,to:dashboardDomain,cleanUrls:!1}],https:{basePath:sslBasePath,validityDays:825},regenerateUntrustedCerts:!1,verbose});return await portAnswers(443)}catch(error){if(verbose)originalConsoleLog(` ${dim(`Proxy: ${error}`)}`);return!1}}const[,allDiscoveredModels]=await Promise.all([startStxServer(),discoverModels(projectPath("app/Models"),defaultsPath("app/Models"))]),{loadDashboardConfig}=await import(defaultsPath("resources/functions/dashboard/toggles.ts")),{feature:featureEnabled}=await import("@stacksjs/config"),{toggles:dashboardToggles,nav:dashboardNav}=await loadDashboardConfig(projectPath("config/dashboard.ts"),featureEnabled),{frameworkModelFeature}=await import("@stacksjs/orm"),discoveredModels=modelsWithEnabledFeatures(allDiscoveredModels,frameworkModelFeature,(name)=>featureEnabled(name)),manifestDir=storagePath("framework/runtime/dashboard"),manifestPath=storagePath("framework/runtime/dashboard/.discovered-models.json");mkdirSync(manifestDir,{recursive:!0});const manifestPayload={models:buildManifest(discoveredModels),sections:dashboardToggles,nav:dashboardNav};writeFileIfChanged(manifestPath,JSON.stringify(manifestPayload,null,2));const serverReady=await waitForServer(dashboardPort);restoreConsole();const proxyStarted=await startReverseProxy().catch((err)=>{if(verbose)console.warn("[Dashboard] Reverse proxy failed:",err);return!1}),dashboardHttpsUrl=dashboardDomain?`https://${dashboardDomain}`:null,dashboardLocalUrl=`http://localhost:${dashboardPort}`,initialUrl=dashboardHttpsUrl&&proxyStarted?`${dashboardHttpsUrl}/`:`${dashboardLocalUrl}/`,elapsedMs=(Bun.nanoseconds()-startTime)/1e6;console.log();console.log(` ${bold(cyan("stacks dashboard"))}`);console.log();if(dashboardHttpsUrl&&proxyStarted){console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardHttpsUrl)}`);console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(dashboardLocalUrl)}`)}else{console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardLocalUrl)}`);if(dashboardHttpsUrl)console.log(` ${dim("\u279C")} ${dim("Pretty")}: ${dim(`${dashboardHttpsUrl} needs the rpx proxy - run \`buddy dev\``)}`)}console.log(` ${green("\u279C")} ${bold("Window")}: ${dim("Stacks Dashboard")} ${dim("1400\xD7900")}`);console.log(` ${green("\u279C")} ${bold("Models")}: ${dim(`${discoveredModels.length} discovered`)}`);if(dashboardPort!==preferredPort)console.log(` ${dim("\u279C")} ${dim(`Port ${preferredPort} in use, using ${dashboardPort}`)}`);if(!serverReady)console.log(` ${dim("\u26A0")} ${dim("Dev server may not be ready yet")}`);console.log();console.log(` ${dim(`ready in ${elapsedMs.toFixed(0)} ms`)}`);if(verbose){console.log();console.log(` ${dim("\u279C")} ${dim("URL")}: ${dim(initialUrl)}`);if(dashboardDomain){console.log(` ${dim("\u279C")} ${dim("SSL")}: ${dim(sslBasePath)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} \u2192 ${dashboardDomain}`)}`)}if(bufferedLogs.length>0){console.log();for(const line of bufferedLogs)console.log(` ${dim(line)}`)}}console.log();let createApp,resolveCraftBinary;const nativeDisabled=process.env.STACKS_NO_NATIVE==="1",explicitCraftSdk=process.env.CRAFT_SDK_SRC;if(!nativeDisabled&&explicitCraftSdk){if(!existsSync(explicitCraftSdk))throw Error(`CRAFT_SDK_SRC not found: ${explicitCraftSdk}`);try{({createApp,resolveCraftBinary}=await import(explicitCraftSdk));if(!createApp||!resolveCraftBinary)throw Error("CRAFT_SDK_SRC must export createApp and resolveCraftBinary")}catch(error){throw Error(`Could not load CRAFT_SDK_SRC ${explicitCraftSdk}: ${error instanceof Error?error.message:String(error)}`)}}if(!nativeDisabled&&!explicitCraftSdk)try{({createApp,resolveCraftBinary}=await import("craft-native"))}catch{}const craftBinaryPath=createApp&&resolveCraftBinary?resolveDashboardCraftExecutable(resolveCraftBinary):void 0;if(createApp&&craftBinaryPath){const userIconPath=projectPath("resources/assets/images/app-icon.png"),defaultIconPath=defaultsPath("resources/assets/images/app-icon.png"),appIconPath=await Bun.file(userIconPath).exists()?userIconPath:await Bun.file(defaultIconPath).exists()?defaultIconPath:void 0,app=createApp({url:dashboardLocalUrl,quiet:!verbose,craftPath:craftBinaryPath,window:{title:"Stacks Dashboard",width:1400,height:900,titlebarHidden:!0,webSidebarMaterial:!0,webSidebarWidth:250,...appIconPath&&{icon:appIconPath}}});process.on("SIGINT",()=>{app.close();process.exit(0)});process.on("SIGTERM",()=>{app.close();process.exit(0)});try{await app.show();process.exit(0)}catch(error){const fallbackUrl=dashboardHttpsUrl||dashboardLocalUrl;console.log(` ${dim("Native Craft window failed:")} ${dim(error instanceof Error?error.message:String(error))}`);console.log(` ${dim("Dashboard available at:")} ${cyan(fallbackUrl)}
|
|
5
5
|
`);await new Promise(()=>{})}}else{console.log(` ${dim(nativeDisabled?"Native window disabled by STACKS_NO_NATIVE=1. Open the URL above in a browser.":"Native window unavailable. Run pantry install craft, set CRAFT_BIN, or open the URL above in a browser.")}
|
|
6
6
|
`);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));await new Promise(()=>{})}
|
package/dist/prepublish.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{log}from"@stacksjs/logging";log.info("Running prepublish command...");await import("./build/stacks");log.success("Prepublishing completed");
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.457",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -66,54 +66,54 @@
|
|
|
66
66
|
"prepublishOnly": "bun run build"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@stacksjs/action-runner": "0.75.
|
|
70
|
-
"@stacksjs/ai": "0.75.
|
|
71
|
-
"@stacksjs/analytics": "0.75.
|
|
72
|
-
"@stacksjs/api": "0.75.
|
|
73
|
-
"@stacksjs/auth": "0.75.
|
|
74
|
-
"@stacksjs/build": "0.75.
|
|
69
|
+
"@stacksjs/action-runner": "0.75.457",
|
|
70
|
+
"@stacksjs/ai": "0.75.457",
|
|
71
|
+
"@stacksjs/analytics": "0.75.457",
|
|
72
|
+
"@stacksjs/api": "0.75.457",
|
|
73
|
+
"@stacksjs/auth": "0.75.457",
|
|
74
|
+
"@stacksjs/build": "0.75.457",
|
|
75
75
|
"@stacksjs/bumpx": "^0.2.26",
|
|
76
76
|
"@stacksjs/bunpress": "^0.2.15",
|
|
77
|
-
"@stacksjs/cli": "0.75.
|
|
78
|
-
"@stacksjs/cloud": "0.75.
|
|
79
|
-
"@stacksjs/cms": "0.75.
|
|
77
|
+
"@stacksjs/cli": "0.75.457",
|
|
78
|
+
"@stacksjs/cloud": "0.75.457",
|
|
79
|
+
"@stacksjs/cms": "0.75.457",
|
|
80
80
|
"@stacksjs/components": "0.2.794",
|
|
81
|
-
"@stacksjs/config": "0.75.
|
|
82
|
-
"@stacksjs/database": "0.75.
|
|
83
|
-
"@stacksjs/desktop-build": "0.75.
|
|
84
|
-
"@stacksjs/dns": "0.75.
|
|
85
|
-
"@stacksjs/enums": "0.75.
|
|
86
|
-
"@stacksjs/env": "0.75.
|
|
87
|
-
"@stacksjs/error-handling": "0.75.
|
|
88
|
-
"@stacksjs/github": "0.75.
|
|
81
|
+
"@stacksjs/config": "0.75.457",
|
|
82
|
+
"@stacksjs/database": "0.75.457",
|
|
83
|
+
"@stacksjs/desktop-build": "0.75.457",
|
|
84
|
+
"@stacksjs/dns": "0.75.457",
|
|
85
|
+
"@stacksjs/enums": "0.75.457",
|
|
86
|
+
"@stacksjs/env": "0.75.457",
|
|
87
|
+
"@stacksjs/error-handling": "0.75.457",
|
|
88
|
+
"@stacksjs/github": "0.75.457",
|
|
89
89
|
"@stacksjs/gitit": "^0.2.5",
|
|
90
|
-
"@stacksjs/i18n": "0.75.
|
|
91
|
-
"@stacksjs/image": "0.75.
|
|
92
|
-
"@stacksjs/logging": "0.75.
|
|
90
|
+
"@stacksjs/i18n": "0.75.457",
|
|
91
|
+
"@stacksjs/image": "0.75.457",
|
|
92
|
+
"@stacksjs/logging": "0.75.457",
|
|
93
93
|
"@stacksjs/logsmith": "^0.2.11",
|
|
94
|
-
"@stacksjs/mobile": "0.75.
|
|
95
|
-
"@stacksjs/orm": "0.75.
|
|
96
|
-
"@stacksjs/path": "0.75.
|
|
97
|
-
"@stacksjs/payments": "0.75.
|
|
98
|
-
"@stacksjs/queue": "0.75.
|
|
99
|
-
"@stacksjs/registry": "0.75.
|
|
100
|
-
"@stacksjs/router": "0.75.
|
|
94
|
+
"@stacksjs/mobile": "0.75.457",
|
|
95
|
+
"@stacksjs/orm": "0.75.457",
|
|
96
|
+
"@stacksjs/path": "0.75.457",
|
|
97
|
+
"@stacksjs/payments": "0.75.457",
|
|
98
|
+
"@stacksjs/queue": "0.75.457",
|
|
99
|
+
"@stacksjs/registry": "0.75.457",
|
|
100
|
+
"@stacksjs/router": "0.75.457",
|
|
101
101
|
"@stacksjs/rpx": "^0.11.54",
|
|
102
|
-
"@stacksjs/scheduler": "0.75.
|
|
103
|
-
"@stacksjs/search-engine": "0.75.
|
|
104
|
-
"@stacksjs/security": "0.75.
|
|
105
|
-
"@stacksjs/server": "0.75.
|
|
106
|
-
"@stacksjs/sites": "0.75.
|
|
107
|
-
"@stacksjs/storage": "0.75.
|
|
108
|
-
"@stacksjs/strings": "0.75.
|
|
102
|
+
"@stacksjs/scheduler": "0.75.457",
|
|
103
|
+
"@stacksjs/search-engine": "0.75.457",
|
|
104
|
+
"@stacksjs/security": "0.75.457",
|
|
105
|
+
"@stacksjs/server": "0.75.457",
|
|
106
|
+
"@stacksjs/sites": "0.75.457",
|
|
107
|
+
"@stacksjs/storage": "0.75.457",
|
|
108
|
+
"@stacksjs/strings": "0.75.457",
|
|
109
109
|
"@stacksjs/stx": "0.2.794",
|
|
110
110
|
"@stacksjs/tlsx": "^0.13.19",
|
|
111
111
|
"@stacksjs/ts-cloud": "^0.16.91",
|
|
112
112
|
"@stacksjs/ts-md": "^0.1.1",
|
|
113
|
-
"@stacksjs/tunnel": "0.75.
|
|
114
|
-
"@stacksjs/types": "0.75.
|
|
115
|
-
"@stacksjs/utils": "0.75.
|
|
116
|
-
"@stacksjs/whois": "0.75.
|
|
113
|
+
"@stacksjs/tunnel": "0.75.457",
|
|
114
|
+
"@stacksjs/types": "0.75.457",
|
|
115
|
+
"@stacksjs/utils": "0.75.457",
|
|
116
|
+
"@stacksjs/whois": "0.75.457",
|
|
117
117
|
"bun-plugin-stx": "0.2.794"
|
|
118
118
|
},
|
|
119
119
|
"peerDependencies": {
|
|
@@ -129,7 +129,7 @@
|
|
|
129
129
|
}
|
|
130
130
|
},
|
|
131
131
|
"devDependencies": {
|
|
132
|
-
"@stacksjs/validation": "0.75.
|
|
132
|
+
"@stacksjs/validation": "0.75.457",
|
|
133
133
|
"better-dx": "^0.2.24"
|
|
134
134
|
}
|
|
135
135
|
}
|