@webority/mobile-tools 0.130.0 → 0.130.2
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/README.md +10 -6
- package/lib/build.js +1 -1
- package/lib/cli.js +1 -1
- package/lib/doctor.js +1 -1
- package/lib/platform.js +1 -1
- package/lib/run.js +1 -1
- package/lib/sync.js +1 -1
- package/lib/xos.js +1 -1
- package/package.json +3 -4
package/README.md
CHANGED
|
@@ -12,6 +12,8 @@ Node 24. Run every command from the app's root folder, where `appsettings.json`
|
|
|
12
12
|
|
|
13
13
|
## Commands
|
|
14
14
|
|
|
15
|
+
`<command> --help` prints that command's usage and exits 0; `help` alone prints every command.
|
|
16
|
+
|
|
15
17
|
### `prebuild`
|
|
16
18
|
|
|
17
19
|
```bash
|
|
@@ -104,7 +106,7 @@ npx mobile-tools run --env <Environment> [--platform android|ios] [--device <ser
|
|
|
104
106
|
|
|
105
107
|
**iOS** (macOS only, for the Simulator):
|
|
106
108
|
|
|
107
|
-
`--app <path.app>` is required.
|
|
109
|
+
`--app <path.app>` is required. Build it on a host that has xOS Tools with `build --artifact ios-sim --debug --arch arm64` (Apple silicon), copy the `.app` to the Mac, then pass it here. `run` never builds, and it checks only node_modules, not the iOS pods.
|
|
108
110
|
|
|
109
111
|
1. Installs the `--app` app on the booted simulator with `xcrun simctl`.
|
|
110
112
|
2. Starts Metro on 8081, where the iOS app looks, or reuses one already serving this app.
|
|
@@ -125,23 +127,24 @@ Every program is started by absolute path with an argument list, never through a
|
|
|
125
127
|
### `build`
|
|
126
128
|
|
|
127
129
|
```bash
|
|
128
|
-
npx mobile-tools build --env <Environment> --artifact apk|aab|ios-sim [--debug] [--ota-test] [--arch
|
|
130
|
+
npx mobile-tools build --env <Environment> --artifact apk|aab|ios-sim [--debug] [--ota-test] [--arch <value>] [--json] [-- <gradle args>]
|
|
129
131
|
```
|
|
130
132
|
|
|
131
133
|
`--ota-test` appends `-otatest` to the OTA runtime version, so only builds of this artifact receive an update published for that version. A later plain build restamps the native files.
|
|
132
134
|
|
|
133
135
|
1. Stops on a stale tree, as `run` does.
|
|
134
136
|
2. Runs `prebuild` for the environment and platform.
|
|
135
|
-
3. Android: checks that `android/app/build.gradle` exists, then runs one Gradle task for the environment's flavor, the artifact and the build type, with every ABI.
|
|
137
|
+
3. Android: checks that `android/app/build.gradle` exists, then runs one Gradle task for the environment's flavor, the artifact and the build type, with every ABI unless `--arch` names some. On Windows, a folder path over 90 characters prints a warning first: the Android native build can fail with CreateProcess error=2 beyond that length.
|
|
136
138
|
4. iOS (`ios-sim`): runs `xos build --pods` then `xos app` for the simulator, into `ios/build/xos/<Configuration>-iphonesimulator`. `<Configuration>` is `Debug` with `--debug` and `Release` otherwise.
|
|
137
139
|
5. Collects the artifact: every `.apk` or `.aab` in the Gradle output folder, or the simulator `.app`. Release builds also report the mapping file when it exists.
|
|
138
140
|
|
|
139
141
|
Notes:
|
|
140
142
|
|
|
141
|
-
- `apk` and `aab` are Android release builds of every ABI unless `--debug` is given.
|
|
143
|
+
- `apk` and `aab` are Android release builds of every ABI unless `--debug` is given, or of the ABIs `--arch` names.
|
|
144
|
+
- `--arch` for `apk` and `aab` takes `arm64-v8a`, `armeabi-v7a`, `x86_64` or `x86`, one value or a comma list (`--arch arm64-v8a,x86_64`), with `arm64` as an alias for `arm64-v8a`. Each ABI is listed once, in the order given. Gradle gets it as `-PreactNativeArchitectures`, so a `-PreactNativeArchitectures` argument after `--` cannot be combined with it.
|
|
142
145
|
- `aab` is release only.
|
|
143
146
|
- `ios-sim` runs on any host with `xos` on `PATH`, and is unsigned.
|
|
144
|
-
- `--arch`
|
|
147
|
+
- `--arch` for `ios-sim` takes `x86_64` or `arm64`, and defaults to `x86_64`. Use `arm64` for an Apple-silicon Mac. A wrong architecture fails at `simctl install` with Apple's own message.
|
|
145
148
|
- Store `ipa` builds are not this command's job: iOS store builds run on the build server through xOS Tools.
|
|
146
149
|
- Arguments after `--` go to Gradle unchanged for apk and aab (for example `-- --no-daemon --max-workers=3`); each must be a plain token, and ios-sim refuses them.
|
|
147
150
|
- With CI=true, a failed build also prints the whole log to stderr, so a CI job log carries it.
|
|
@@ -210,6 +213,7 @@ Checks the toolchain and the app tree, one check per code:
|
|
|
210
213
|
- `buildTools`: the build-tools version in `android/build.gradle` is installed.
|
|
211
214
|
- `androidPlatform`: the compile SDK platform in `android/build.gradle` is installed.
|
|
212
215
|
- `ninja`: on Windows, ninja 1.11 or newer is on `PATH`.
|
|
216
|
+
- `appPath`: on Windows, the app folder path is 90 characters or fewer. A longer path is reported as a warning and does not fail doctor.
|
|
213
217
|
- `install`: `node_modules` matches the lockfile.
|
|
214
218
|
- `autolinkingCache`: the Android autolinking cache was made for this tree.
|
|
215
219
|
- `ndkHook`: `android/build.gradle` gives library modules the app's NDK.
|
|
@@ -391,6 +395,6 @@ It returns Expo's `getDefaultConfig` for the app, with `console` calls dropped f
|
|
|
391
395
|
}
|
|
392
396
|
```
|
|
393
397
|
|
|
394
|
-
There is no `ios` script: an iOS run takes two steps on two hosts. On a host
|
|
398
|
+
There is no `ios` script: an iOS run takes two steps on two hosts. On a host that has `xos`, run `npx mobile-tools build --env <Env> --artifact ios-sim --debug --arch arm64`; then on the Mac, run `npx mobile-tools run --env <Env> --platform ios --app <path.app>`.
|
|
395
399
|
|
|
396
400
|
`postinstall` keeps the stamp accurate after any install. After a pull, `npx mobile-tools sync` is still the one command to run: it also resets native codegen when a native package moved, which a plain install does not.
|
package/lib/build.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{gradleOutputDir,gradleTask,loadToolsConfig,mappingFile,resolveIosProjectName}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{gradleInvocation}from"./platform.js";import{prebuild}from"./prebuild.js";import{ensurePods,requireSynced}from"./sync.js";import{prependXosShims,xosPath,xosSimulatorBuild}from"./xos.js";const buildAndroid=async(o,a,i)=>{const{appRoot:
|
|
1
|
+
import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{gradleOutputDir,gradleTask,loadToolsConfig,mappingFile,resolveIosProjectName}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{gradleInvocation,warnLongWindowsPath}from"./platform.js";import{prebuild}from"./prebuild.js";import{ensurePods,requireSynced}from"./sync.js";import{prependXosShims,xosPath,xosSimulatorBuild}from"./xos.js";const buildAndroid=async(o,a,i)=>{const{appRoot:t,env:r}=o;requireSynced(t,{pods:!1});const s=loadToolsConfig(t),e=path.join(t,"android");existsSync(path.join(e,"app","build.gradle"))||fail("appConfigInvalid",`android/app/build.gradle not found in ${t}`),void 0!==o.abis&&o.gradleArgs.some(o=>o.startsWith("-PreactNativeArchitectures"))&&fail("badInput","--arch and a -PreactNativeArchitectures argument after -- both set the Android ABIs: pass only one"),prebuild({appRoot:t,env:r,platform:"android",otaTest:o.otaTest});const n=gradleTask(r,s.flavors,a,i),l=path.join(logDir(t),`gradle-${r}-${logStamp()}.log`),p=void 0===o.abis?[]:[`-PreactNativeArchitectures=${o.abis.join(",")}`];warnLongWindowsPath(t),await buildOrFail(gradleInvocation(e,[`:app:${n}`,...p,...o.gradleArgs],process.platform,process.env),e,l,`gradle ${n}`);const d=gradleOutputDir(t,r,s.flavors,a,i),c=existsSync(d)?readdirSync(d,{withFileTypes:!0}).filter(o=>o.isFile()&&o.name.endsWith(`.${a}`)).map(o=>path.resolve(d,o.name)).sort():[];0===c.length&&fail("artifactMissing",`the build produced no ${a} in ${d}`);const g=mappingFile(t,r,s.flavors);return{artifacts:c,mapping:"release"===i&&existsSync(g)?g:null,log:l}},buildIos=async(o,a)=>{o.gradleArgs.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const{appRoot:i,env:t}=o,r=xosPath(process.env,process.platform);requireSynced(i,{pods:!0});const s=loadToolsConfig(i),e=resolveIosProjectName(i,s)??fail("appConfigInvalid",`no ios/ folder in ${i}`);prebuild({appRoot:i,env:t,platform:"ios",otaTest:o.otaTest}),prependXosShims(r,i),ensurePods(i,process.platform);const n="release"===a?"Release":"Debug",l=path.join(logDir(i),`xos-${t}-${logStamp()}.log`);return{artifacts:[await xosSimulatorBuild(r,{appRoot:i,projectName:e,configuration:n,arch:o.arch??"x86_64"},l)],mapping:null,log:l}};export const build=async o=>{const a=o.debug?"debug":"release",i="ios-sim"===o.artifact?await buildIos(o,a):await buildAndroid(o,o.artifact,a);if(isJsonOutput())sayJson({artifacts:i.artifacts,mapping:i.mapping,log:i.log});else{for(const o of i.artifacts)say(`build: ${o}`);null!==i.mapping&&say(`build: mapping ${i.mapping}`)}};
|
package/lib/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{parseArgs}from"node:util";import{build}from"./build.js";import{cache}from"./cache.js";import{parseEnvironment}from"./config.js";import{devices}from"./devices.js";import{doctor}from"./doctor.js";import{installHooks}from"./hooks.js";import{icons}from"./icons.js";import{restartMetro}from"./metro.js";import{CliError,fail,reportFailure,say,setJsonOutput,warn}from"./output.js";import{prebuild}from"./prebuild.js";import{run}from"./run.js";import{checkSync,sync,writeStamp}from"./sync.js";import{SIMULATOR_ARCHS}from"./xos.js";const
|
|
2
|
+
import{parseArgs}from"node:util";import{build}from"./build.js";import{cache}from"./cache.js";import{parseEnvironment}from"./config.js";import{devices}from"./devices.js";import{doctor}from"./doctor.js";import{installHooks}from"./hooks.js";import{icons}from"./icons.js";import{restartMetro}from"./metro.js";import{CliError,fail,reportFailure,say,setJsonOutput,warn}from"./output.js";import{parseAndroidAbis}from"./platform.js";import{prebuild}from"./prebuild.js";import{run}from"./run.js";import{checkSync,sync,writeStamp}from"./sync.js";import{SIMULATOR_ARCHS}from"./xos.js";const COMMAND_USAGE={prebuild:" prebuild --env <Development|Staging|Production> [--platform android|ios]\n prebuild --same-env [--platform android|ios]\n Compile appsettings into appsettings.Compiled.json and stamp the native projects.",sync:" sync [--check | --stamp]\n --check: exit 1 with the fix command when node_modules (or ios/Pods) is stale.\n --stamp: record that node_modules matches the lockfile now (run it from postinstall).\n Without either: install from the lockfile, stamp, and reset native codegen when needed.",hooks:" hooks install\n Add git post-merge and post-checkout hooks that run sync --check.",run:" run --env <Environment> [--platform android|ios] [--device <serial|name>] [--rebuild] [--profiling] [--app <path.app>]\n Build for one device's ABI (or install the cached build with the same native fingerprint), install it there, reuse or start Metro, and launch. --rebuild skips the cache.\n iOS (macOS): installs the simulator app --app names on a booted simulator, starts Metro and launches it; it never builds.\n --profiling serves production JavaScript with React's profiling renderer; a Metro serving development JavaScript must be stopped first.",build:" build --env <Environment> --artifact apk|aab|ios-sim [--debug] [--ota-test] [--arch <value>] [--json] [-- <gradle args>]\n Prebuild, then build a release APK or App Bundle (Android, every ABI unless --arch) or an iOS simulator app through xOS Tools (xos on PATH).\n --arch for ios-sim: x86_64 (the default) or arm64. For apk and aab: arm64-v8a, armeabi-v7a, x86_64 or x86, as one value or a comma list; arm64 means arm64-v8a.\n --debug builds the debug variant (apk or ios-sim only).\n --ota-test suffixes the OTA runtime version with -otatest, so only this build receives an update published for it.\n Arguments after -- go to Gradle unchanged (apk and aab only), for example -- --no-daemon --max-workers=3.",devices:" devices [--platform android|ios] [--json]\n Connect local MuMu emulators, then list every ready device once (simulators for iOS).",doctor:" doctor [--platform android|ios] [--fix] [--json]\n Check the toolchain and the app tree; exit 1 while a problem remains. --fix removes a stale autolinking cache.",cache:" cache list|clear [--json]\n List or remove this app's cached builds.",metro:" metro restart\n Stop the Metro mobile-tools started for this app and start it again on the same port.",icons:" icons [--source <png|svg>]\n Render per-environment launcher icons for Android flavors and iOS AppIcon-<Env> sets."},USAGE=`mobile-tools <command> [options] (run from the app's root folder)\n\n${Object.values(COMMAND_USAGE).join("\n\n")}`,knownCommand=e=>Object.hasOwn(COMMAND_USAGE,e),commandUsage=e=>`usage:\n${COMMAND_USAGE[e]}`,parse=(e,o,t,a=!1)=>{try{const{values:e,positionals:n}=parseArgs({args:o,options:t,allowPositionals:a,strict:!0});return{values:e,positionals:n}}catch(o){return fail("badInput",`${o.message}\n\n${commandUsage(e)}`)}},envOption=e=>"string"==typeof e?parseEnvironment(e):void 0,platformOption=e=>{if(void 0!==e)return"android"!==e&&"ios"!==e?fail("badInput",`--platform must be android or ios, not ${String(e)}`):e},JSON_COMMANDS=new Set(["build","cache","devices","doctor"]),artifactOption=e=>"apk"===e||"aab"===e||"ios-sim"===e?e:fail("badInput","build needs --artifact apk, aab or ios-sim"),main=async e=>{const[o,...t]=e,a=process.cwd(),n=t.indexOf("--"),s=n<0?t:t.slice(0,n);if(void 0!==o&&knownCommand(o)&&(s.includes("--help")||s.includes("-h")))say(commandUsage(o));else switch(setJsonOutput(JSON_COMMANDS.has(o??"")&&s.includes("--json")),o){case"prebuild":{const{values:e}=parse(o,t,{env:{type:"string"},"same-env":{type:"boolean"},platform:{type:"string"}});return void prebuild({appRoot:a,env:envOption(e.env),sameEnv:!0===e["same-env"],platform:platformOption(e.platform)})}case"sync":{const{values:e}=parse(o,t,{check:{type:"boolean"},stamp:{type:"boolean"}});if(e.check&&e.stamp&&fail("badInput","use --check or --stamp, not both"),e.stamp)return writeStamp(a),void say("sync --stamp: recorded node_modules as matching the lockfile");if(e.check){const e=checkSync(a,process.platform);return e.length>0&&fail("installStale",e.join("\n")),void say("sync --check: node_modules matches the lockfile")}return void sync(a,process.platform)}case"hooks":{const{positionals:e}=parse(o,t,{},!0);return"install"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools hooks install\n\n${USAGE}`),void installHooks(a)}case"run":{const{values:e}=parse(o,t,{env:{type:"string"},platform:{type:"string"},device:{type:"string"},rebuild:{type:"boolean"},profiling:{type:"boolean"},app:{type:"string"}}),n=envOption(e.env)??fail("badInput","run needs --env <Development|Staging|Production>");return void await run({appRoot:a,env:n,platform:platformOption(e.platform)??"android",device:"string"==typeof e.device?e.device:void 0,rebuild:!0===e.rebuild,profiling:!0===e.profiling,app:"string"==typeof e.app?e.app:void 0})}case"build":{const e=t.indexOf("--"),n=e<0?t:t.slice(0,e),s=e<0?[]:t.slice(e+1),{values:i}=parse(o,n,{env:{type:"string"},artifact:{type:"string"},debug:{type:"boolean"},"ota-test":{type:"boolean"},json:{type:"boolean"},arch:{type:"string"}}),r=envOption(i.env)??fail("badInput","build needs --env <Development|Staging|Production>"),p=artifactOption(i.artifact);!0===i.debug&&"aab"===p&&fail("badInput","--debug builds an apk or an ios-sim app; an App Bundle is release only"),"ios-sim"===p&&s.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const l="string"==typeof i.arch?i.arch:void 0,c="ios-sim"===p?SIMULATOR_ARCHS.find(e=>e===(l??"x86_64"))??fail("badInput","--arch must be x86_64 or arm64"):void 0,d="ios-sim"===p||void 0===l?void 0:parseAndroidAbis(l);return void await build({appRoot:a,env:r,artifact:p,debug:!0===i.debug,otaTest:!0===i["ota-test"],gradleArgs:s,arch:c,abis:d})}case"devices":{const{values:e}=parse(o,t,{platform:{type:"string"},json:{type:"boolean"}});return void await devices({appRoot:a,platform:platformOption(e.platform)??"android"})}case"doctor":{const{values:e}=parse(o,t,{platform:{type:"string"},fix:{type:"boolean"},json:{type:"boolean"}});return void await doctor({appRoot:a,platform:platformOption(e.platform),fix:!0===e.fix})}case"cache":{const{positionals:e}=parse(o,t,{json:{type:"boolean"}},!0),n=e[0];return(1!==e.length||"list"!==n&&"clear"!==n)&&fail("badInput",`usage: mobile-tools cache list|clear\n\n${USAGE}`),void await cache({appRoot:a,action:n})}case"metro":{const{positionals:e}=parse(o,t,{},!0);return"restart"===e[0]&&1===e.length||fail("badInput",`usage: mobile-tools metro restart\n\n${USAGE}`),void await restartMetro(a)}case"icons":{const{values:e}=parse(o,t,{source:{type:"string"}});return void await icons({appRoot:a,source:"string"==typeof e.source?e.source:void 0})}case"help":{const e=t[0];return void 0===e?void say(USAGE):(knownCommand(e)||fail("badInput",`unknown command "${e}"\n\n${USAGE}`),void say(commandUsage(e)))}case void 0:case"--help":case"-h":return void say(USAGE);default:fail("badInput",`unknown command "${o}"\n\n${USAGE}`)}};main(process.argv.slice(2)).catch(e=>{e instanceof CliError&&(reportFailure(e),process.exit(e.exitCode)),warn(e instanceof Error?e.stack??e.message:String(e)),process.exit(1)});
|
package/lib/doctor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync,rmSync}from"node:fs";import path from"node:path";import{capture}from"./exec.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{adbPath,findOnPath}from"./platform.js";import{checkNdkHook,usesFirebase}from"./prebuild.js";import{checkSync}from"./sync.js";import{xosPath}from"./xos.js";export const JDK_MAJOR=17;const JDK_FIX="install JDK 17 and set JAVA_HOME",ADB_FIX="set ANDROID_HOME to the Android SDK (adb lives in its platform-tools folder) or put adb on PATH",NINJA_FIX="install ninja 1.11 or newer (scoop install ninja) and put it first on PATH",XCODE_FIX="install Xcode, then xcode-select -s /Applications/Xcode.app",XOS_FIX="install xOS Tools (xos) and put it on PATH",AUTOLINKING_FILE=path.join("android","build","generated","autolinking","autolinking.json"),AUTOLINKING_DIRS=[path.join("android","build","generated","autolinking"),path.join("android","app","build","generated","autolinking")];export const javaMajor=o=>{const e=/version\b[^"]*"([^"]+)"/.exec(o);if(!e)return;const s=e[1].split(/[._+-]/),t=Number(s[0]),n=1===t?Number(s[1]):t;return Number.isInteger(n)?n:void 0};export const gradleSdkVersions=o=>{const e={},s=/ndkVersion\s*=\s*["']([^"']+)["']/.exec(o),t=/buildToolsVersion\s*=\s*["']([^"']+)["']/.exec(o),n=/compileSdkVersion\s*=\s*(\d+)/.exec(o);return s&&(e.ndk=s[1]),t&&(e.buildTools=t[1]),n&&(e.compileSdk=n[1]),e};const samePath=(o,e)=>{const norm=o=>{const e=path.resolve(o).replace(/[\\/]+$/,"");return"win32"===process.platform?e.toLowerCase():e};return norm(o)===norm(e)};export const autolinkingProblem=(o,e,s)=>{let t;try{t=JSON.parse(o)}catch{return"android/build/generated/autolinking/autolinking.json does not parse"}if("string"==typeof t?.root&&!samePath(t.root,e))return`the autolinking cache was made for ${t.root}, not ${e}`;for(const[o,e]of Object.entries(t?.dependencies??{}))if("string"==typeof e?.root&&!s(e.root))return`the autolinking cache names ${o} at ${e.root}, which no longer exists`};const ok=(o,e)=>({code:o,status:"ok",message:e}),skipped=(o,e)=>({code:o,status:"skipped",message:e}),problem=(o,e,s)=>({code:o,status:"problem",message:e,fix:s}),probe=(o,e,s)=>{try{return s()}catch(s){return problem(o,s instanceof Error?s.message:String(s),e)}},outputOf=o=>[o.stdout,o.stderr].join("\n").trim()||`exited with status ${o.status}`,SDK_SPECS=[{code:"ndk",key:"ndkVersion",field:"ndk",folder:(o,e)=>path.join(o,"ndk",e),install:o=>`sdkmanager "ndk;${o}"`},{code:"buildTools",key:"buildToolsVersion",field:"buildTools",folder:(o,e)=>path.join(o,"build-tools",e),install:o=>`sdkmanager "build-tools;${o}"`},{code:"androidPlatform",key:"compileSdkVersion",field:"compileSdk",folder:(o,e)=>path.join(o,"platforms",`android-${e}`),install:o=>`sdkmanager "platforms;android-${o}"`}],sdkCheck=(o,e)=>probe(e.code,"fix the Android SDK under ANDROID_HOME",()=>{const s=path.join(o,"android","build.gradle");if(!existsSync(s))return skipped(e.code,"no android/build.gradle");const t=process.env.ANDROID_HOME;if(!t)return skipped(e.code,"ANDROID_HOME is not set");const n=gradleSdkVersions(readFileSync(s,"utf8"))[e.field];if(void 0===n)return skipped(e.code,`${e.key} is not declared in android/build.gradle`);const r=e.folder(t,n);return existsSync(r)?ok(e.code,r):problem(e.code,`${r} is missing`,e.install(n))}),androidChecks=o=>{const{appRoot:e}=o,s=[];s.push(probe("nodeVersion","install Node 24",()=>{const o=process.versions.node;return 24===Number(o.split(".")[0])?ok("nodeVersion",`Node ${o}`):problem("nodeVersion",`Node ${o} is not Node 24`,"install Node 24")})),s.push(probe("androidHome","set ANDROID_HOME to the Android SDK folder",()=>{const o=process.env.ANDROID_HOME;return o?existsSync(o)?ok("androidHome",o):problem("androidHome",`ANDROID_HOME ${o} does not exist`,"set ANDROID_HOME to the Android SDK folder"):problem("androidHome","ANDROID_HOME is not set","set ANDROID_HOME to the Android SDK folder")}));const t={};s.push(probe("adb",ADB_FIX,()=>{const o=adbPath(process.env,process.platform),s=capture({file:o,args:["version"]},e);if(0!==s.status)return problem("adb",outputOf(s),ADB_FIX);t.path=o;const n=s.stdout.split(/\r?\n/).find(o=>o.startsWith("Version"));return ok("adb",n?`${o}, ${n.trim()}`:o)}));const n=t.path;s.push(void 0===n?skipped("adbServer","adb is not available"):probe("adbServer","use one adb, the SDK platform-tools one: MuMu ships its own adb",()=>{const o=capture({file:n,args:["devices"]},e),s=`${o.stdout}\n${o.stderr}`.split(/\r?\n/).find(o=>o.includes("doesn't match this client"));return void 0===s?ok("adbServer","one adb server version"):problem("adbServer",`another adb restarted the adb server at a different version: ${s.trim()}`,"use one adb, the SDK platform-tools one: MuMu ships its own adb")})),s.push(probe("jdk",JDK_FIX,()=>{const o=process.env.JAVA_HOME,s="win32"===process.platform?"java.exe":"java",t=o?path.join(o,"bin",s):void 0,n=void 0!==t&&existsSync(t)?t:findOnPath("java",process.env,process.platform);if(void 0===n)return problem("jdk","java not found",JDK_FIX);const r=capture({file:n,args:["-version"]},e),i=javaMajor(`${r.stderr}${r.stdout}`);return 17===i?ok("jdk",`Java ${i} at ${n}`):problem("jdk",`Java ${i??"unknown"} at ${n}; React Native builds need Java 17`,JDK_FIX)}));for(const o of SDK_SPECS)s.push(sdkCheck(e,o));s.push("win32"!==process.platform?skipped("ninja","only Windows builds need ninja on PATH"):probe("ninja",NINJA_FIX,()=>{const o=findOnPath("ninja",process.env,process.platform);if(void 0===o)return problem("ninja","ninja not found on PATH",NINJA_FIX);const s=capture({file:o,args:["--version"]},e).stdout.trim(),t=/^(\d+)\.(\d+)/.exec(s);if(!t)return problem("ninja",`ninja --version printed no version at ${o}`,NINJA_FIX);return Number(t[1])>1||1===Number(t[1])&&Number(t[2])>=11?ok("ninja",`ninja ${s} at ${o}`):problem("ninja",`ninja ${s} at ${o} is older than 1.11`,NINJA_FIX)})),s.push(probe("install","npx mobile-tools sync",()=>{const o=checkSync(e,process.platform);return 0===o.length?ok("install","node_modules matches the lockfile"):problem("install",o.join("; "),"npx mobile-tools sync")}));const r="npx mobile-tools doctor --fix";return s.push(probe("autolinkingCache",r,()=>{const s=path.join(e,AUTOLINKING_FILE);if(!existsSync(s))return ok("autolinkingCache","no autolinking cache yet");const t=autolinkingProblem(readFileSync(s,"utf8"),e,existsSync);if(void 0===t)return ok("autolinkingCache","matches this tree");if(!o.fix)return problem("autolinkingCache",t,r);for(const o of AUTOLINKING_DIRS)rmSync(path.join(e,o),{recursive:!0,force:!0});return{code:"autolinkingCache",status:"fixed",message:"removed both autolinking caches; the next build regenerates them"}})),s.push(probe("ndkHook","add the subprojects block the message names to android/build.gradle",()=>(checkNdkHook(e),ok("ndkHook","library modules get the app NDK")))),s.push(probe("firebaseConfig","add the Firebase Android config for this app",()=>{if(!usesFirebase(e))return skipped("firebaseConfig","the app does not use @react-native-firebase");const o=path.join(e,"android","app","google-services.json");return existsSync(o)?ok("firebaseConfig","android/app/google-services.json"):problem("firebaseConfig","android/app/google-services.json is missing","add the Firebase Android config for this app")})),s},xcodeCheck=o=>probe("xcode",XCODE_FIX,()=>{const e=capture({file:"/usr/bin/xcode-select",args:["-p"]},o);return 0===e.status?ok("xcode",e.stdout.trim()):problem("xcode","no Xcode developer directory is selected",XCODE_FIX)}),xosCheck=o=>probe("xos",XOS_FIX,()=>{const e=xosPath(process.env,process.platform),s=capture({file:e,args:["doctor","--json"]},o);return 0===s.status?ok("xos",e):problem("xos",s.stderr.trim().split(/\r?\n/)[0]||`xos doctor exited with status ${s.status}`,"run xos doctor and install what it names")});export const iosChecks=(o,e)=>["darwin"===e?xcodeCheck(o):xosCheck(o),probe("cocoapods","install CocoaPods",()=>{const o=findOnPath("pod",process.env,e);return void 0===o?problem("cocoapods","pod not found on PATH","install CocoaPods"):ok("cocoapods",o)})];export const doctor=async o=>{const e=path.join(o.appRoot,"android"),s=path.join(o.appRoot,"ios");"android"!==o.platform||existsSync(e)||fail("appConfigInvalid",`no android/ folder in ${o.appRoot}`);const t=[];("android"===o.platform||void 0===o.platform&&existsSync(e))&&t.push(...androidChecks(o));const n="darwin"===process.platform||void 0!==findOnPath("xos",process.env,process.platform);("ios"===o.platform||void 0===o.platform&&n&&existsSync(s))&&t.push(...iosChecks(o.appRoot,process.platform));const r=t.filter(o=>"problem"===o.status).length;if(isJsonOutput())sayJson({checks:t,problems:r});else{for(const o of t){const e="problem"===o.status&&o.fix?` Fix: ${o.fix}`:"";say(`doctor: ${o.status} ${o.code}: ${o.message}${e}`)}say(0===r?"doctor: ready":`doctor: ${r} problem(s)`)}r>0&&(process.exitCode=1)};
|
|
1
|
+
import{existsSync,readFileSync,rmSync}from"node:fs";import path from"node:path";import{capture}from"./exec.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{adbPath,findOnPath,longWindowsPathWarning}from"./platform.js";import{checkNdkHook,usesFirebase}from"./prebuild.js";import{checkSync}from"./sync.js";import{xosPath}from"./xos.js";export const JDK_MAJOR=17;const JDK_FIX="install JDK 17 and set JAVA_HOME",ADB_FIX="set ANDROID_HOME to the Android SDK (adb lives in its platform-tools folder) or put adb on PATH",NINJA_FIX="install ninja 1.11 or newer (scoop install ninja) and put it first on PATH",XCODE_FIX="install Xcode, then xcode-select -s /Applications/Xcode.app",XOS_FIX="install xOS Tools (xos) and put it on PATH",APP_PATH_FIX="move the app to a short folder such as C:\\w\\<app>, or map one with subst W: <path>",AUTOLINKING_FILE=path.join("android","build","generated","autolinking","autolinking.json"),AUTOLINKING_DIRS=[path.join("android","build","generated","autolinking"),path.join("android","app","build","generated","autolinking")];export const javaMajor=o=>{const e=/version\b[^"]*"([^"]+)"/.exec(o);if(!e)return;const s=e[1].split(/[._+-]/),t=Number(s[0]),n=1===t?Number(s[1]):t;return Number.isInteger(n)?n:void 0};export const gradleSdkVersions=o=>{const e={},s=/ndkVersion\s*=\s*["']([^"']+)["']/.exec(o),t=/buildToolsVersion\s*=\s*["']([^"']+)["']/.exec(o),n=/compileSdkVersion\s*=\s*(\d+)/.exec(o);return s&&(e.ndk=s[1]),t&&(e.buildTools=t[1]),n&&(e.compileSdk=n[1]),e};const samePath=(o,e)=>{const norm=o=>{const e=path.resolve(o).replace(/[\\/]+$/,"");return"win32"===process.platform?e.toLowerCase():e};return norm(o)===norm(e)};export const autolinkingProblem=(o,e,s)=>{let t;try{t=JSON.parse(o)}catch{return"android/build/generated/autolinking/autolinking.json does not parse"}if("string"==typeof t?.root&&!samePath(t.root,e))return`the autolinking cache was made for ${t.root}, not ${e}`;for(const[o,e]of Object.entries(t?.dependencies??{}))if("string"==typeof e?.root&&!s(e.root))return`the autolinking cache names ${o} at ${e.root}, which no longer exists`};const ok=(o,e)=>({code:o,status:"ok",message:e}),skipped=(o,e)=>({code:o,status:"skipped",message:e}),problem=(o,e,s)=>({code:o,status:"problem",message:e,fix:s}),probe=(o,e,s)=>{try{return s()}catch(s){return problem(o,s instanceof Error?s.message:String(s),e)}},outputOf=o=>[o.stdout,o.stderr].join("\n").trim()||`exited with status ${o.status}`,SDK_SPECS=[{code:"ndk",key:"ndkVersion",field:"ndk",folder:(o,e)=>path.join(o,"ndk",e),install:o=>`sdkmanager "ndk;${o}"`},{code:"buildTools",key:"buildToolsVersion",field:"buildTools",folder:(o,e)=>path.join(o,"build-tools",e),install:o=>`sdkmanager "build-tools;${o}"`},{code:"androidPlatform",key:"compileSdkVersion",field:"compileSdk",folder:(o,e)=>path.join(o,"platforms",`android-${e}`),install:o=>`sdkmanager "platforms;android-${o}"`}],sdkCheck=(o,e)=>probe(e.code,"fix the Android SDK under ANDROID_HOME",()=>{const s=path.join(o,"android","build.gradle");if(!existsSync(s))return skipped(e.code,"no android/build.gradle");const t=process.env.ANDROID_HOME;if(!t)return skipped(e.code,"ANDROID_HOME is not set");const n=gradleSdkVersions(readFileSync(s,"utf8"))[e.field];if(void 0===n)return skipped(e.code,`${e.key} is not declared in android/build.gradle`);const r=e.folder(t,n);return existsSync(r)?ok(e.code,r):problem(e.code,`${r} is missing`,e.install(n))}),androidChecks=o=>{const{appRoot:e}=o,s=[];s.push(probe("nodeVersion","install Node 24",()=>{const o=process.versions.node;return 24===Number(o.split(".")[0])?ok("nodeVersion",`Node ${o}`):problem("nodeVersion",`Node ${o} is not Node 24`,"install Node 24")})),s.push(probe("androidHome","set ANDROID_HOME to the Android SDK folder",()=>{const o=process.env.ANDROID_HOME;return o?existsSync(o)?ok("androidHome",o):problem("androidHome",`ANDROID_HOME ${o} does not exist`,"set ANDROID_HOME to the Android SDK folder"):problem("androidHome","ANDROID_HOME is not set","set ANDROID_HOME to the Android SDK folder")}));const t={};s.push(probe("adb",ADB_FIX,()=>{const o=adbPath(process.env,process.platform),s=capture({file:o,args:["version"]},e);if(0!==s.status)return problem("adb",outputOf(s),ADB_FIX);t.path=o;const n=s.stdout.split(/\r?\n/).find(o=>o.startsWith("Version"));return ok("adb",n?`${o}, ${n.trim()}`:o)}));const n=t.path;s.push(void 0===n?skipped("adbServer","adb is not available"):probe("adbServer","use one adb, the SDK platform-tools one: MuMu ships its own adb",()=>{const o=capture({file:n,args:["devices"]},e),s=`${o.stdout}\n${o.stderr}`.split(/\r?\n/).find(o=>o.includes("doesn't match this client"));return void 0===s?ok("adbServer","one adb server version"):problem("adbServer",`another adb restarted the adb server at a different version: ${s.trim()}`,"use one adb, the SDK platform-tools one: MuMu ships its own adb")})),s.push(probe("jdk",JDK_FIX,()=>{const o=process.env.JAVA_HOME,s="win32"===process.platform?"java.exe":"java",t=o?path.join(o,"bin",s):void 0,n=void 0!==t&&existsSync(t)?t:findOnPath("java",process.env,process.platform);if(void 0===n)return problem("jdk","java not found",JDK_FIX);const r=capture({file:n,args:["-version"]},e),i=javaMajor(`${r.stderr}${r.stdout}`);return 17===i?ok("jdk",`Java ${i} at ${n}`):problem("jdk",`Java ${i??"unknown"} at ${n}; React Native builds need Java 17`,JDK_FIX)}));for(const o of SDK_SPECS)s.push(sdkCheck(e,o));s.push("win32"!==process.platform?skipped("ninja","only Windows builds need ninja on PATH"):probe("ninja",NINJA_FIX,()=>{const o=findOnPath("ninja",process.env,process.platform);if(void 0===o)return problem("ninja","ninja not found on PATH",NINJA_FIX);const s=capture({file:o,args:["--version"]},e).stdout.trim(),t=/^(\d+)\.(\d+)/.exec(s);if(!t)return problem("ninja",`ninja --version printed no version at ${o}`,NINJA_FIX);return Number(t[1])>1||1===Number(t[1])&&Number(t[2])>=11?ok("ninja",`ninja ${s} at ${o}`):problem("ninja",`ninja ${s} at ${o} is older than 1.11`,NINJA_FIX)})),s.push(probe("install","npx mobile-tools sync",()=>{const o=checkSync(e,process.platform);return 0===o.length?ok("install","node_modules matches the lockfile"):problem("install",o.join("; "),"npx mobile-tools sync")})),s.push("win32"!==process.platform?skipped("appPath","only Windows has the long-path limit"):probe("appPath",APP_PATH_FIX,()=>{const o=longWindowsPathWarning(e,process.platform);return void 0===o?ok("appPath","the app folder path is short enough for the Android native build"):{code:"appPath",status:"warning",message:o}}));const r="npx mobile-tools doctor --fix";return s.push(probe("autolinkingCache",r,()=>{const s=path.join(e,AUTOLINKING_FILE);if(!existsSync(s))return ok("autolinkingCache","no autolinking cache yet");const t=autolinkingProblem(readFileSync(s,"utf8"),e,existsSync);if(void 0===t)return ok("autolinkingCache","matches this tree");if(!o.fix)return problem("autolinkingCache",t,r);for(const o of AUTOLINKING_DIRS)rmSync(path.join(e,o),{recursive:!0,force:!0});return{code:"autolinkingCache",status:"fixed",message:"removed both autolinking caches; the next build regenerates them"}})),s.push(probe("ndkHook","add the subprojects block the message names to android/build.gradle",()=>(checkNdkHook(e),ok("ndkHook","library modules get the app NDK")))),s.push(probe("firebaseConfig","add the Firebase Android config for this app",()=>{if(!usesFirebase(e))return skipped("firebaseConfig","the app does not use @react-native-firebase");const o=path.join(e,"android","app","google-services.json");return existsSync(o)?ok("firebaseConfig","android/app/google-services.json"):problem("firebaseConfig","android/app/google-services.json is missing","add the Firebase Android config for this app")})),s},xcodeCheck=o=>probe("xcode",XCODE_FIX,()=>{const e=capture({file:"/usr/bin/xcode-select",args:["-p"]},o);return 0===e.status?ok("xcode",e.stdout.trim()):problem("xcode","no Xcode developer directory is selected",XCODE_FIX)}),xosCheck=o=>probe("xos",XOS_FIX,()=>{const e=xosPath(process.env,process.platform),s=capture({file:e,args:["doctor","--json"]},o);return 0===s.status?ok("xos",e):problem("xos",s.stderr.trim().split(/\r?\n/)[0]||`xos doctor exited with status ${s.status}`,"run xos doctor and install what it names")});export const iosChecks=(o,e)=>["darwin"===e?xcodeCheck(o):xosCheck(o),probe("cocoapods","install CocoaPods",()=>{const o=findOnPath("pod",process.env,e);return void 0===o?problem("cocoapods","pod not found on PATH","install CocoaPods"):ok("cocoapods",o)})];export const doctor=async o=>{const e=path.join(o.appRoot,"android"),s=path.join(o.appRoot,"ios");"android"!==o.platform||existsSync(e)||fail("appConfigInvalid",`no android/ folder in ${o.appRoot}`);const t=[];("android"===o.platform||void 0===o.platform&&existsSync(e))&&t.push(...androidChecks(o));const n="darwin"===process.platform||void 0!==findOnPath("xos",process.env,process.platform);("ios"===o.platform||void 0===o.platform&&n&&existsSync(s))&&t.push(...iosChecks(o.appRoot,process.platform));const r=t.filter(o=>"problem"===o.status).length;if(isJsonOutput())sayJson({checks:t,problems:r});else{for(const o of t){const e="problem"===o.status&&o.fix?` Fix: ${o.fix}`:"";say(`doctor: ${o.status} ${o.code}: ${o.message}${e}`)}say(0===r?"doctor: ready":`doctor: ${r} problem(s)`)}r>0&&(process.exitCode=1)};
|
package/lib/platform.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import path from"node:path";import{fail}from"./output.js";export const pathFor=n=>"win32"===n?path.win32:path.posix;const readEnv=(n,
|
|
1
|
+
import{existsSync}from"node:fs";import path from"node:path";import{fail,warn}from"./output.js";export const ANDROID_ABIS=["arm64-v8a","armeabi-v7a","x86_64","x86"];export const ABI_PATTERN=new RegExp(`^(${ANDROID_ABIS.join("|")})$`);export const parseAndroidAbis=n=>{const o=[];for(const t of n.split(",")){const n="arm64"===t?"arm64-v8a":t;ABI_PATTERN.test(n)||fail("badInput",`--arch must be a comma list of ${ANDROID_ABIS.join(", ")} (arm64 means arm64-v8a), not ${JSON.stringify(t)}`),o.includes(n)||o.push(n)}return o};const LONG_WINDOWS_APP_PATH=90;export const pathFor=n=>"win32"===n?path.win32:path.posix;const readEnv=(n,o)=>{const t=Object.keys(n).find(n=>n.toLowerCase()===o.toLowerCase());return void 0===t?void 0:n[t]};export const childEnv=n=>{const o={};for(const[t,e]of Object.entries(n))"nodefaultcurrentdirectoryinexepath"!==t.toLowerCase()&&(o[t]=e);return o};export const findOnPath=(n,o,t,e=existsSync)=>{const r=pathFor(t),a=readEnv(o,"PATH")??"",i="win32"===t?`${n}.exe`:n;for(const n of a.split("win32"===t?";":":")){if(""===n)continue;const o=r.join(n,i);if(e(o))return o}};export const adbPath=(n,o,t=existsSync)=>{const e=pathFor(o),r=readEnv(n,"ANDROID_HOME");if(r){const n=e.join(r,"platform-tools","win32"===o?"adb.exe":"adb");if(t(n))return n}return findOnPath("adb",n,o,t)??fail("toolMissing","adb not found: set ANDROID_HOME to the Android SDK (adb lives in its platform-tools folder) or put adb on PATH.")};const SAFE_GRADLE_ARG=/^[A-Za-z0-9_:.,=-]+$/;export const gradleInvocation=(n,o,t,e)=>{for(const n of o)SAFE_GRADLE_ARG.test(n)||fail("badInput",`refusing Gradle argument ${JSON.stringify(n)}: only plain task names and -Pkey=value`);const r=pathFor(t);if("win32"!==t)return{file:r.join(n,"gradlew"),args:o};const a=r.join(n,"gradlew.bat");/["%]/.test(a)&&fail("appConfigInvalid",`the app path cannot hold " or %: ${a}`);const i=readEnv(e,"SystemRoot")??"C:\\Windows";return{file:readEnv(e,"ComSpec")??r.join(i,"System32","cmd.exe"),args:["/d","/s","/c",`""${a}" ${o.join(" ")}"`],windowsVerbatimArguments:!0}};export const requireDarwin=(n,o)=>{"darwin"!==n&&fail("platformUnavailable",`${o} needs macOS: the iOS Simulator and xcrun exist only there.`)};export const longWindowsPathWarning=(n,o)=>{const t=path.resolve(n).length;if(!("win32"!==o||t<=90))return`the app folder path is ${t} characters. A Windows tool in the Android native build cannot open a path over 260 characters, and the build adds about 170 under the app folder, so a path over 90 can fail with CreateProcess error=2. Move the app to a short folder such as C:\\w\\<app>, or map one with subst W: <path> and run from W:\\.`};export const warnLongWindowsPath=n=>{const o=longWindowsPathWarning(n,process.platform);void 0!==o&&warn(`Warning: ${o}`)};export const XCRUN="/usr/bin/xcrun";export const npmInvocation=(n,o,t,e,r=existsSync)=>{const a=pathFor(t),i=readEnv(o,"npm_execpath"),s=[i&&/npm-cli\.c?js$/.test(i)?i:void 0,"win32"===t?a.join(a.dirname(e),"node_modules","npm","bin","npm-cli.js"):a.join(a.dirname(e),"..","lib","node_modules","npm","bin","npm-cli.js")].find(n=>void 0!==n&&r(n));return s?{file:e,args:[s,...n]}:fail("toolMissing",`npm not found beside ${e}; install Node 24 with its bundled npm.`)};export const pnpmInvocation=(n,o,t,e,r=existsSync)=>{const a=readEnv(o,"npm_execpath");if(a&&/pnpm\.c?js$/.test(a)&&r(a))return{file:e,args:[a,...n]};const i=findOnPath("pnpm",o,t,r);return i?{file:i,args:n}:fail("toolMissing","pnpm not found on PATH (on Windows, pnpm.exe); install pnpm, or run through pnpm exec.")};
|
package/lib/run.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{findCachedBuild,nativeFingerprint,storeCachedBuild}from"./cache.js";import{applicationId,baseAppId,gradleOutputDir,gradleTask,loadToolsConfig,localApiPort,variantName}from"./config.js";import{connectLocalEmulators,describeDevice,listAndroidDevices,pickDevice}from"./devices.js";import{capture}from"./exec.js";import{appBundleId,describeAppleDevice,listAppleDevices}from"./ios.js";import{ensureMetro}from"./metro.js";import{fail,say}from"./output.js";import{adbPath,gradleInvocation,requireDarwin,XCRUN}from"./platform.js";import{prebuild}from"./prebuild.js";import{requireSynced}from"./sync.js";export const readNamespace=e=>/^\s*namespace\s*=?\s*["']([^"']+)["']/m.exec(e)?.[1];export const
|
|
1
|
+
import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import path from"node:path";import{buildOrFail,logDir,logStamp}from"./buildLog.js";import{findCachedBuild,nativeFingerprint,storeCachedBuild}from"./cache.js";import{applicationId,baseAppId,gradleOutputDir,gradleTask,loadToolsConfig,localApiPort,variantName}from"./config.js";import{connectLocalEmulators,describeDevice,listAndroidDevices,pickDevice}from"./devices.js";import{capture}from"./exec.js";import{appBundleId,describeAppleDevice,listAppleDevices}from"./ios.js";import{ensureMetro}from"./metro.js";import{fail,say}from"./output.js";import{ABI_PATTERN,adbPath,gradleInvocation,requireDarwin,warnLongWindowsPath,XCRUN}from"./platform.js";import{prebuild}from"./prebuild.js";import{requireSynced}from"./sync.js";export const readNamespace=e=>/^\s*namespace\s*=?\s*["']([^"']+)["']/m.exec(e)?.[1];export const chooseApk=(e,a)=>{const i=e.filter(e=>e.endsWith(".apk")).sort();return i.find(e=>e.includes(a))??i.find(e=>e.includes("universal"))??i[0]};const adbOrFail=(e,a,i)=>{const t=capture({file:e,args:a},i);return 0!==t.status?fail("toolFailed",`adb ${a.join(" ")} failed: ${(t.stderr||t.stdout).trim()}`):t.stdout};export const installFailure=e=>/Failure \[[^\]]*\]/.exec(e)?.[0];const UNINSTALL_FIRST=/INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)/;export const installFailureReason=(e,a,i,t)=>{const r=installFailure(`${e}\n${a}`);if(void 0!==r)return UNINSTALL_FIRST.test(r)?`${r}; run \`adb -s ${i} uninstall ${t}\` (this deletes the app's data), then run again`:r;return[e.trim(),a.trim()].filter(Boolean).join("\n")||"adb gave no reason; check the device is still listed by `adb devices`, then run again"};const installOrFail=(e,a,i,t,r)=>{const s=capture({file:e,args:["-s",a,"install","-r","-t",i]},r);0===s.status&&void 0===installFailure(`${s.stderr}\n${s.stdout}`)||fail("toolFailed",`adb install on ${a} failed: ${installFailureReason(s.stderr,s.stdout,a,t)}`)},elapsedSeconds=e=>((Date.now()-e)/1e3).toFixed(1),cachedBuild=(e,a,i)=>{const t=e.fingerprint.slice(0,12),r=a?void 0:findCachedBuild(e);if(r)return say(`cache: hit ${t} (fingerprint ${i} s), installing the cached build`),r;say(a?"cache: skipped (--rebuild), building":`cache: miss ${t} (fingerprint ${i} s), building`)},DEVICE_METRO_PORT=8081,DEV_HOST_ENTRY=/^\s*<string name="debug_http_host">[^<]*<\/string>\s*$\n?/m;export const withDevHost=(e,a)=>{const i=e.includes("</map>")?e.replace(DEV_HOST_ENTRY,""):"<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n<map>\n</map>\n";return void 0===a?i:i.replace("</map>",` <string name="debug_http_host">${a}</string>\n</map>`)};const pointAppAtMetro=(e,a,i,t,r)=>{const s=`shared_prefs/${i}_preferences.xml`;adbOrFail(e,["-s",a,"shell","am","force-stop",i],r);const o=capture({file:e,args:["-s",a,"shell","run-as",i,"cat",s]},r),n=8081===t?void 0:`localhost:${t}`,l=withDevHost(0===o.status?o.stdout:"",n),p=Buffer.from(l,"utf8").toString("base64"),d=capture({file:e,args:["-s",a,"shell",`run-as ${i} sh -c 'mkdir -p shared_prefs && echo ${p} | base64 -d > ${s}'`]},r);0!==d.status&&void 0!==n&&fail("toolFailed",`could not point ${i} at Metro port ${t}: ${(d.stderr||d.stdout).trim()}`),adbOrFail(e,["-s",a,"reverse",`tcp:${t}`,`tcp:${t}`],r)},runAndroid=async e=>{const{appRoot:a,env:i}=e,t=loadToolsConfig(a),r=path.join(a,"android"),s=path.join(r,"app","build.gradle");existsSync(s)||fail("appConfigInvalid",`android/app/build.gradle not found in ${a}`);const o=readNamespace(readFileSync(s,"utf8"))??fail("appConfigInvalid","android/app/build.gradle declares no namespace"),n=adbPath(process.env,process.platform);await connectLocalEmulators(n,a);const l=listAndroidDevices(n,a),p=await pickDevice(l,e.device,describeDevice,!0===process.stdin.isTTY);ABI_PATTERN.test(p.abi)||fail("deviceNotFound",`${describeDevice(p)} reports an ABI this build cannot target: "${p.abi}"`),say(`run: ${describeDevice(p)}`);const d=prebuild({appRoot:a,env:i,platform:"android"}),c=Date.now(),u=await nativeFingerprint(a,"android"),f={appId:baseAppId(a),platform:"android",variant:variantName(i,t.flavors,"debug"),abi:p.abi,fingerprint:u};let m=cachedBuild(f,e.rebuild,elapsedSeconds(c));if(void 0===m){const e=gradleTask(i,t.flavors,"apk","debug"),s=logDir(a);warnLongWindowsPath(a),await buildOrFail(gradleInvocation(r,[`:app:${e}`,`-PreactNativeArchitectures=${p.abi}`],process.platform,process.env),r,path.join(s,`gradle-${i}-${logStamp()}.log`),`gradle ${e}`);const o=gradleOutputDir(a,i,t.flavors,"apk","debug"),n=existsSync(o)?chooseApk(readdirSync(o),p.abi):void 0;n||fail("artifactMissing",`the build produced no APK in ${o}`),m=path.join(o,n),storeCachedBuild(f,m),say(`cache: stored ${u.slice(0,12)}`)}const h=applicationId(d.APP_ID,i);say(`run: installing ${path.basename(m)} on ${p.serial}`),installOrFail(n,p.serial,m,h,a);const b=await ensureMetro(a,path.join(logDir(a),"metro.log"),{fixedPort:!1,profiling:e.profiling});if(pointAppAtMetro(n,p.serial,h,b,a),8081!==b&&say(`run: ${h} loads from Metro on port ${b}; port 8081 belongs to another app`),"Development"===i){const e=localApiPort(String(d.BASE_URL),t);void 0!==e&&(adbOrFail(n,["-s",p.serial,"reverse",`tcp:${e}`,`tcp:${e}`],a),say(`run: device localhost:${e} reaches this machine's API`))}adbOrFail(n,["-s",p.serial,"shell","am","start","-n",`${h}/${o}.MainActivity`],a),say(`run: launched ${h} on ${p.model||p.serial}`)},runIos=async e=>{requireDarwin(process.platform,"run --platform ios");const{appRoot:a,env:i}=e;e.rebuild&&fail("badInput","--rebuild applies to Android; an iOS run installs the app --app names");const t=e.app??fail("badInput","run --platform ios needs --app <path.app>. Build it first with npx mobile-tools build --env <Env> --artifact ios-sim --debug --arch arm64 on a host that has xos, then pass the .app here."),r=path.resolve(a,t);r.endsWith(".app")&&existsSync(r)&&statSync(r).isDirectory()||fail("badInput",`--app must be a simulator .app folder: ${t}`);const s=await pickDevice(listAppleDevices(a),e.device,describeAppleDevice,!0===process.stdin.isTTY);say(`run: ${describeAppleDevice(s)}`);const o=prebuild({appRoot:a,env:i,platform:"ios"}),n=applicationId(o.APP_ID,i),l=appBundleId(r,a);l!==n&&fail("appConfigInvalid",`${r} is ${l}, but --env ${i} runs ${n}: build the simulator app for ${i}`),await ensureMetro(a,path.join(logDir(a),"metro.log"),{fixedPort:!0,profiling:e.profiling});const p=[["simctl","install",s.udid,r],["simctl","launch",s.udid,n]];for(const e of p){const i=capture({file:XCRUN,args:e},a);0!==i.status&&fail("toolFailed",`xcrun ${e.slice(0,3).join(" ")} failed: ${(i.stderr||i.stdout).trim()}`)}say(`run: launched ${n} on ${s.name}`)};export const run=async e=>{"android"===e.platform&&void 0!==e.app&&fail("badInput","--app installs a simulator app; an Android run builds its own"),"ios"===e.platform&&requireDarwin(process.platform,"run --platform ios"),requireSynced(e.appRoot,{pods:!1}),"ios"===e.platform?await runIos(e):await runAndroid(e)};
|
package/lib/sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import path from"node:path";import{runInherit}from"./exec.js";import{fail,say}from"./output.js";import{findOnPath,gradleInvocation,npmInvocation,pnpmInvocation}from"./platform.js";import{prependXosShims,xosPath}from"./xos.js";export const STAMP_FILE=path.join("node_modules",".webority-install.json");export const PODS_RECORD=path.join("ios","Pods",".webority-native.json");const INSTALL_FIELDS=["dependencies","devDependencies","optionalDependencies","peerDependencies","bundleDependencies","overrides","resolutions","pnpm","workspaces"];export const lockfileOf=e=>{const n=path.join(e,"pnpm-lock.yaml"),s=path.join(e,"package-lock.json");return existsSync(n)&&existsSync(s)?fail("appConfigInvalid","both pnpm-lock.yaml and package-lock.json exist: delete the one not in use"):existsSync(n)?{manager:"pnpm",file:n}:existsSync(s)?{manager:"npm",file:s}:fail("appConfigInvalid",`no package-lock.json or pnpm-lock.yaml in ${e}`)};const filesUnder=(e,n="")=>readdirSync(e,{withFileTypes:!0}).flatMap(s=>{const o=""===n?s.name:`${n}/${s.name}`;return s.isDirectory()?filesUnder(path.join(e,s.name),o):[o]}).sort();export const installHash=e=>{const{file:n}=lockfileOf(e),s=JSON.parse(readFileSync(path.join(e,"package.json"),"utf8")),o=createHash("sha256");o.update(`lockfile:${path.basename(n)}\0`),o.update(readFileSync(n)),o.update("\0package.json\0"),o.update(JSON.stringify(INSTALL_FIELDS.map(e=>[e,s[e]??null])));const t=path.join(e,"patches");if(existsSync(t))for(const e of filesUnder(t))o.update(`\0patches/${e}\0`),o.update(readFileSync(path.join(t,...e.split("/"))));return o.digest("hex")};export const readStamp=e=>{const n=path.join(e,STAMP_FILE);if(existsSync(n))try{return JSON.parse(readFileSync(n,"utf8"))}catch{return}};const POD_FIX="cd ios && pod install",hasXos=e=>void 0!==findOnPath("xos",process.env,e),installsPods=e=>"darwin"===e||hasXos(e);export const podsStale=e=>{const n=path.join(e,"ios","Podfile.lock"),s=path.join(e,"ios","Pods","Manifest.lock");return!(!existsSync(n)||!existsSync(s))&&!readFileSync(n).equals(readFileSync(s))};const nodeModulesNewerThanPods=e=>{const n=[path.join(e,"node_modules",".modules.yaml"),path.join(e,"node_modules",".pnpm","lock.yaml")].find(e=>existsSync(e)),s=path.join(e,"ios","Pods","Manifest.lock");return!(!n||!existsSync(s))&&statSync(n).mtimeMs>statSync(s).mtimeMs};export const checkSync=(e,n,s=!0)=>{const o=[],t=readStamp(e),{file:i}=lockfileOf(e);if(t?t.hash!==installHash(e)&&o.push(`node_modules is stale: ${path.basename(i)}, package.json or patches/ changed since the last install. Fix: npx mobile-tools sync`):o.push("node_modules has no install stamp (never installed through mobile-tools). Fix: npx mobile-tools sync"),t){const n=changedNativePackages(t.nativePackages??{},nativePackages(e));n.length>0&&o.push(`node_modules native packages changed since the last install: ${n.join(", ")}. Fix: npx mobile-tools sync`)}const a=s&&installsPods(n);return a&&podsStale(e)&&o.push(`ios/Pods is stale: ios/Podfile.lock differs from ios/Pods/Manifest.lock. Fix: ${POD_FIX}`),a&&existsSync(path.join(e,"ios","Podfile.lock"))&&nodeModulesNewerThanPods(e)&&o.push("node_modules changed after the last pod install; run pod install in ios/ (or mobile-tools sync)"),o};export const requireSynced=(e,n)=>{const s=checkSync(e,process.platform,
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import path from"node:path";import{runInherit}from"./exec.js";import{fail,say}from"./output.js";import{findOnPath,gradleInvocation,npmInvocation,pnpmInvocation}from"./platform.js";import{prependXosShims,xosPath}from"./xos.js";export const STAMP_FILE=path.join("node_modules",".webority-install.json");export const PODS_RECORD=path.join("ios","Pods",".webority-native.json");const INSTALL_FIELDS=["dependencies","devDependencies","optionalDependencies","peerDependencies","bundleDependencies","overrides","resolutions","pnpm","workspaces"];export const lockfileOf=e=>{const n=path.join(e,"pnpm-lock.yaml"),s=path.join(e,"package-lock.json");return existsSync(n)&&existsSync(s)?fail("appConfigInvalid","both pnpm-lock.yaml and package-lock.json exist: delete the one not in use"):existsSync(n)?{manager:"pnpm",file:n}:existsSync(s)?{manager:"npm",file:s}:fail("appConfigInvalid",`no package-lock.json or pnpm-lock.yaml in ${e}`)};const filesUnder=(e,n="")=>readdirSync(e,{withFileTypes:!0}).flatMap(s=>{const o=""===n?s.name:`${n}/${s.name}`;return s.isDirectory()?filesUnder(path.join(e,s.name),o):[o]}).sort();export const installHash=e=>{const{file:n}=lockfileOf(e),s=JSON.parse(readFileSync(path.join(e,"package.json"),"utf8")),o=createHash("sha256");o.update(`lockfile:${path.basename(n)}\0`),o.update(readFileSync(n)),o.update("\0package.json\0"),o.update(JSON.stringify(INSTALL_FIELDS.map(e=>[e,s[e]??null])));const t=path.join(e,"patches");if(existsSync(t))for(const e of filesUnder(t))o.update(`\0patches/${e}\0`),o.update(readFileSync(path.join(t,...e.split("/"))));return o.digest("hex")};export const readStamp=e=>{const n=path.join(e,STAMP_FILE);if(existsSync(n))try{return JSON.parse(readFileSync(n,"utf8"))}catch{return}};const POD_FIX="cd ios && pod install",hasXos=e=>void 0!==findOnPath("xos",process.env,e),installsPods=e=>"darwin"===e||hasXos(e);export const podsStale=e=>{const n=path.join(e,"ios","Podfile.lock"),s=path.join(e,"ios","Pods","Manifest.lock");return!(!existsSync(n)||!existsSync(s))&&!readFileSync(n).equals(readFileSync(s))};const nodeModulesNewerThanPods=e=>{const n=[path.join(e,"node_modules",".modules.yaml"),path.join(e,"node_modules",".pnpm","lock.yaml")].find(e=>existsSync(e)),s=path.join(e,"ios","Pods","Manifest.lock");return!(!n||!existsSync(s))&&statSync(n).mtimeMs>statSync(s).mtimeMs};export const checkSync=(e,n,s=!0)=>{const o=[],t=readStamp(e),{file:i}=lockfileOf(e);if(t?t.hash!==installHash(e)&&o.push(`node_modules is stale: ${path.basename(i)}, package.json or patches/ changed since the last install. Fix: npx mobile-tools sync`):o.push("node_modules has no install stamp (never installed through mobile-tools). Fix: npx mobile-tools sync"),t){const n=changedNativePackages(t.nativePackages??{},nativePackages(e));n.length>0&&o.push(`node_modules native packages changed since the last install: ${n.join(", ")}. Fix: npx mobile-tools sync`)}const a=s&&installsPods(n);return a&&podsStale(e)&&o.push(`ios/Pods is stale: ios/Podfile.lock differs from ios/Pods/Manifest.lock. Fix: ${POD_FIX}`),a&&existsSync(path.join(e,"ios","Podfile.lock"))&&nodeModulesNewerThanPods(e)&&o.push("node_modules changed after the last pod install; run pod install in ios/ (or mobile-tools sync)"),o};export const requireSynced=(e,{pods:n})=>{const s=checkSync(e,process.platform,n);s.length>0&&fail("installStale",s.join("\n"))};export const nativePackages=e=>{const n=path.join(e,"node_modules");if(!existsSync(n))return{};const s=[];for(const e of readdirSync(n,{withFileTypes:!0}))if(!e.name.startsWith(".")&&e.isDirectory())if(e.name.startsWith("@"))for(const o of readdirSync(path.join(n,e.name),{withFileTypes:!0}))o.isDirectory()&&s.push(path.join(n,e.name,o.name));else s.push(path.join(n,e.name));const o={};for(const e of s){const n=path.join(e,"android"),s=path.join(e,"package.json");if(existsSync(n)&&statSync(n).isDirectory()&&existsSync(s))try{const e=JSON.parse(readFileSync(s,"utf8"));e.name&&e.version&&(o[e.name]=e.version)}catch{}}return o};export const changedNativePackages=(e,n)=>[...new Set([...Object.keys(e),...Object.keys(n)])].filter(s=>e[s]!==n[s]).sort();export const writeStamp=e=>{const{manager:n}=lockfileOf(e),s={hash:installHash(e),manager:n,nativePackages:nativePackages(e)};return writeFileSync(path.join(e,STAMP_FILE),`${JSON.stringify(s,null,2)}\n`,"utf8"),s};export const installInvocation=(e,n)=>"pnpm"===e?pnpmInvocation(["install","--frozen-lockfile"],process.env,n,process.execPath):npmInvocation(["ci"],process.env,n,process.execPath);export const ensurePods=(e,n)=>{if(!existsSync(path.join(e,"ios","Podfile")))return;const s=path.join(e,"ios","Pods"),o=path.join(e,PODS_RECORD);let t;if(existsSync(s)?existsSync(path.join(e,"ios","Podfile.lock"))?existsSync(path.join(s,"Manifest.lock"))?podsStale(e)?t="ios/Podfile.lock differs from ios/Pods/Manifest.lock":nodeModulesNewerThanPods(e)?t="node_modules changed after the last pod install":existsSync(o)?readFileSync(o,"utf8")!==JSON.stringify(nativePackages(e))&&(t="native packages changed since the last pod install"):t="no pod install record":t="ios/Pods/Manifest.lock is missing":t="ios/Podfile.lock is missing":t="ios/Pods is missing",void 0===t)return;say(`pods: ${t}; running pod install`);const i=findOnPath("pod",process.env,n);if(!i){const e=hasXos(n)?"check xos doctor --json names its shims folder":"install CocoaPods (brew install cocoapods)";fail("toolMissing",`pod not found on PATH; ${e}, then ${POD_FIX}`)}runInherit({file:i,args:["install"]},path.join(e,"ios"),"pod install");const a=path.join(e,"ios","build","ModuleCache.noindex");existsSync(a)&&(rmSync(a,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,a)}`)),writeFileSync(o,JSON.stringify(nativePackages(e)),"utf8")};export const sync=(e,n)=>{const{manager:s}=lockfileOf(e),o=readStamp(e)?.nativePackages??nativePackages(e);say("sync: "+("pnpm"===s?"pnpm install --frozen-lockfile":"npm ci")),runInherit(installInvocation(s,n),e,`${s} install`);const t=writeStamp(e).nativePackages,i=changedNativePackages(o,t),a=path.join(e,"android"),c=existsSync(path.join(a,"app",".cxx"))||existsSync(path.join(a,"app","build"));if(i.length>0&&c){say(`sync: native packages changed (${i.join(", ")}): regenerating codegen`),runInherit(gradleInvocation(a,["generateCodegenArtifactsFromSchema"],n,process.env),a,"gradlew generateCodegenArtifactsFromSchema");for(const n of[path.join(a,"app",".cxx"),path.join(a,"app","build","generated","autolinking")])rmSync(n,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,n)}`)}installsPods(n)&&existsSync(path.join(e,"ios","Podfile"))&&(hasXos(n)&&prependXosShims(xosPath(process.env,n),e),ensurePods(e,n)),say("sync: done")};
|
package/lib/xos.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail}from"./buildLog.js";import{capture}from"./exec.js";import{fail}from"./output.js";import{findOnPath}from"./platform.js";export const SIMULATOR_ARCHS=["x86_64","arm64"];export const
|
|
1
|
+
import{existsSync,readdirSync}from"node:fs";import path from"node:path";import{buildOrFail}from"./buildLog.js";import{capture}from"./exec.js";import{fail}from"./output.js";import{findOnPath}from"./platform.js";export const SIMULATOR_ARCHS=["x86_64","arm64"];export const XOS_MISSING_MESSAGE="xos not found on PATH. iOS simulator apps build with xOS Tools on a build host, not on this machine. Run npx mobile-tools build --env <Env> --artifact ios-sim --debug --arch arm64 on a host that has xos, copy the resulting .app here, then npx mobile-tools run --env <Env> --platform ios --app <path.app>.";export const xosPath=(o,t)=>findOnPath("xos",o,t)??fail("toolMissing",XOS_MISSING_MESSAGE);export const prependXosShims=(o,t)=>{const i=capture({file:o,args:["doctor","--json"]},t);let s;0!==i.status&&fail("toolMissing",`xos doctor failed: ${i.stderr.trim()}`);try{s=JSON.parse(i.stdout).shims}catch{s=void 0}"string"!=typeof s&&fail("toolFailed","xos doctor --json printed no string field shims: reinstall xOS Tools, then run xos doctor --json and check it prints shims"),process.env.PATH=s+path.delimiter+(process.env.PATH??"")};export const simulatorBuildDir=(o,t)=>path.join(o,"ios","build","xos",`${t}-iphonesimulator`);export const xosSimulatorBuild=async(o,t,i)=>{const{appRoot:s,projectName:a,configuration:r,arch:n}=t,e=simulatorBuildDir(s,r);await buildOrFail({file:o,args:["build","--pods",path.join("ios","Pods"),"--build-dir",e,"--configuration",r,"--platform","iossimulator","--arch",n,"--jobs","0"]},s,i,"xos build --pods"),await buildOrFail({file:o,args:["app","--project",path.join("ios",`${a}.xcodeproj`),"--target",a,"--configuration",r,"--platform","iossimulator","--arch",n,"--build-dir",e,"--assets",path.join("ios",a,"Images.xcassets"),"--jobs","0"]},s,i,"xos app");const subfolders=o=>existsSync(o)?readdirSync(o,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(t=>path.join(o,t.name)):[],p=`${a}.app`,l=subfolders(e),d=[...l,...l.flatMap(subfolders)].find(o=>path.basename(o)===p)??fail("artifactMissing",`the build produced no ${p} in ${e}: read the xos log at ${i}`);return path.resolve(d)};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-tools",
|
|
3
|
-
"version": "0.130.
|
|
3
|
+
"version": "0.130.2",
|
|
4
4
|
"description": "Dev-time CLI for Webority React Native apps: one prebuild, a dependency guard, a device-aware run and per-environment launcher icons, the same on Windows and macOS.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react-native",
|
|
@@ -49,12 +49,11 @@
|
|
|
49
49
|
"@types/node": "25.6.0",
|
|
50
50
|
"@webority/mobile-dev": "0.0.0",
|
|
51
51
|
"jest": "29.7.0",
|
|
52
|
-
"rimraf": "6.1.3",
|
|
53
52
|
"typescript": "5.9.3"
|
|
54
53
|
},
|
|
55
54
|
"scripts": {
|
|
56
|
-
"build": "
|
|
57
|
-
"clean": "
|
|
55
|
+
"build": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node ../mobile-dev/scripts/minify-lib.mjs",
|
|
56
|
+
"clean": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\"",
|
|
58
57
|
"lint": "biome lint ./src",
|
|
59
58
|
"lint:fix": "biome lint --write ./src",
|
|
60
59
|
"test": "jest",
|