@webority/mobile-tools 0.148.0 → 0.150.0
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/lib/appSettingsRules.d.ts +9 -0
- package/lib/build.d.ts +23 -0
- package/lib/build.js +1 -1
- package/lib/buildLog.d.ts +10 -0
- package/lib/cache.d.ts +30 -0
- package/lib/cache.js +1 -1
- package/lib/cli.d.ts +2 -0
- package/lib/cli.js +1 -1
- package/lib/config.d.ts +57 -0
- package/lib/config.js +1 -1
- package/lib/devices.d.ts +56 -0
- package/lib/doctor.d.ts +35 -0
- package/lib/exec.d.ts +18 -0
- package/lib/hooks.d.ts +17 -0
- package/lib/iconArt.d.ts +32 -0
- package/lib/icons.d.ts +9 -0
- package/lib/ios.d.ts +14 -0
- package/lib/keystore.d.ts +8 -0
- package/lib/metro.d.ts +34 -0
- package/lib/metro.js +1 -1
- package/lib/metroConfig.d.ts +37 -0
- package/lib/otaNative.d.ts +42 -0
- package/lib/output.d.ts +19 -0
- package/lib/platform.d.ts +53 -0
- package/lib/prebuild.d.ts +73 -0
- package/lib/profilingHook.d.ts +16 -0
- package/lib/profilingHook.js +1 -1
- package/lib/rootError.d.ts +7 -0
- package/lib/run.d.ts +28 -0
- package/lib/run.js +1 -1
- package/lib/symbols.d.ts +8 -0
- package/lib/sync.d.ts +57 -0
- package/lib/sync.js +1 -1
- package/lib/xos.d.ts +20 -0
- package/package.json +10 -4
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AppSettings, Environment } from "./config.js";
|
|
2
|
+
/** Set to 1 to make a settings problem stop prebuild. Without it each problem is a warning. */
|
|
3
|
+
export declare const STRICT_SETTINGS_ENV = "MOBILE_TOOLS_STRICT_SETTINGS";
|
|
4
|
+
/** The dependency names in the app's package.json; empty when there is none. */
|
|
5
|
+
export declare const appDependencies: (appRoot: string) => ReadonlySet<string>;
|
|
6
|
+
/** Every way the merged settings break the app settings rules. Pure. */
|
|
7
|
+
export declare const appSettingsProblems: (settings: AppSettings, env: Environment, dependencies: ReadonlySet<string>) => string[];
|
|
8
|
+
/** Warns about each problem, or stops prebuild with all of them when STRICT_SETTINGS_ENV is 1. */
|
|
9
|
+
export declare const checkAppSettings: (appRoot: string, settings: AppSettings, env: Environment) => void;
|
package/lib/build.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type AndroidArtifact, type Environment } from "./config.js";
|
|
2
|
+
import { type SimulatorArch } from "./xos.js";
|
|
3
|
+
export type BuildArtifact = AndroidArtifact | "ios-sim";
|
|
4
|
+
export interface BuildOptions {
|
|
5
|
+
appRoot: string;
|
|
6
|
+
env: Environment;
|
|
7
|
+
artifact: BuildArtifact;
|
|
8
|
+
debug: boolean;
|
|
9
|
+
/** Release apk signed with the debug keystore for staging tests; the app's Gradle file reads -PweborityDebugSigned. */
|
|
10
|
+
debugSigned: boolean;
|
|
11
|
+
/** The runtime version gets the `-otatest` suffix, so only builds of this artifact receive the test update. */
|
|
12
|
+
otaTest: boolean;
|
|
13
|
+
/** Every argument after `--`, passed to Gradle as given; apk and aab only. */
|
|
14
|
+
gradleArgs: readonly string[];
|
|
15
|
+
/** The simulator architecture; set for ios-sim only (default x86_64 from the CLI), undefined for apk and aab. */
|
|
16
|
+
arch: SimulatorArch | undefined;
|
|
17
|
+
/** The Android ABIs from --arch; set for apk and aab only, undefined when --arch is not given (every ABI). */
|
|
18
|
+
abis: readonly string[] | undefined;
|
|
19
|
+
}
|
|
20
|
+
/** Why --debug-signed cannot run with these options, or null when it can (or is not given). */
|
|
21
|
+
export declare const debugSignedProblem: (options: Pick<BuildOptions, "env" | "artifact" | "debug" | "debugSigned">) => string | null;
|
|
22
|
+
/** Guards the install, prebuilds, builds one artifact of every ABI, and prints its paths (or the JSON result). */
|
|
23
|
+
export declare const build: (options: BuildOptions) => Promise<void>;
|
package/lib/build.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{copyFileSync,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 DEBUG_SIGNED_SUFFIX="-debugsigned.apk";export const debugSignedProblem=e=>e.debugSigned?"aab"===e.artifact?"--debug-signed builds an apk; an App Bundle is release only and would need the upload key":"ios-sim"===e.artifact?"--debug-signed signs an Android apk; ios-sim builds have no signing":e.debug?"--debug-signed signs the release build; --debug already builds the debug variant, so use one or the other":"Production"===e.env?"--debug-signed is for staging test builds; a Production build must be signed with the upload key":null:null;const debugSignedCopy=e=>{const o=`${e.slice(0,-4)}-debugsigned.apk`;return copyFileSync(e,o),o},buildAndroid=async(e,o,a)=>{const{appRoot:i,env:s}=e;requireSynced(i,{pods:!1});const t=loadToolsConfig(i),n=path.join(i,"android");existsSync(path.join(n,"app","build.gradle"))||fail("appConfigInvalid",`android/app/build.gradle not found in ${i}`),void 0!==e.abis&&e.gradleArgs.some(e=>e.startsWith("-PreactNativeArchitectures"))&&fail("badInput","--arch and a -PreactNativeArchitectures argument after -- both set the Android ABIs: pass only one"),prebuild({appRoot:i,env:s,platform:"android",otaTest:e.otaTest});const r=gradleTask(s,t.flavors,o,a),d=path.join(logDir(i),`gradle-${s}-${logStamp()}.log`),l=void 0===e.abis?[]:[`-PreactNativeArchitectures=${e.abis.join(",")}`],p=e.debugSigned?["-PweborityDebugSigned=true"]:[];warnLongWindowsPath(i),await buildOrFail(gradleInvocation(n,[`:app:${r}`,...l,...p,...e.gradleArgs],process.platform,process.env),n,d,`gradle ${r}`);const g=gradleOutputDir(i,s,t.flavors,o,a),u=existsSync(g)?readdirSync(g,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.${o}`)&&!e.name.endsWith("-debugsigned.apk")).map(e=>path.resolve(g,e.name)).sort():[];0===u.length&&fail("artifactMissing",`the build produced no ${o} in ${g}`);const c=mappingFile(i,s,t.flavors),b="release"===a&&existsSync(c)?c:null;return{artifacts:e.debugSigned?u.map(debugSignedCopy):u,mapping:b,log:d}},buildIos=async(e,o)=>{e.gradleArgs.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const{appRoot:a,env:i}=e,s=xosPath(process.env,process.platform);requireSynced(a,{pods:!
|
|
1
|
+
import{copyFileSync,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 DEBUG_SIGNED_SUFFIX="-debugsigned.apk";export const debugSignedProblem=e=>e.debugSigned?"aab"===e.artifact?"--debug-signed builds an apk; an App Bundle is release only and would need the upload key":"ios-sim"===e.artifact?"--debug-signed signs an Android apk; ios-sim builds have no signing":e.debug?"--debug-signed signs the release build; --debug already builds the debug variant, so use one or the other":"Production"===e.env?"--debug-signed is for staging test builds; a Production build must be signed with the upload key":null:null;const debugSignedCopy=e=>{const o=`${e.slice(0,-4)}-debugsigned.apk`;return copyFileSync(e,o),o},buildAndroid=async(e,o,a)=>{const{appRoot:i,env:s}=e;requireSynced(i,{pods:!1});const t=loadToolsConfig(i),n=path.join(i,"android");existsSync(path.join(n,"app","build.gradle"))||fail("appConfigInvalid",`android/app/build.gradle not found in ${i}`),void 0!==e.abis&&e.gradleArgs.some(e=>e.startsWith("-PreactNativeArchitectures"))&&fail("badInput","--arch and a -PreactNativeArchitectures argument after -- both set the Android ABIs: pass only one"),prebuild({appRoot:i,env:s,platform:"android",otaTest:e.otaTest});const r=gradleTask(s,t.flavors,o,a),d=path.join(logDir(i),`gradle-${s}-${logStamp()}.log`),l=void 0===e.abis?[]:[`-PreactNativeArchitectures=${e.abis.join(",")}`],p=e.debugSigned?["-PweborityDebugSigned=true"]:[];warnLongWindowsPath(i),await buildOrFail(gradleInvocation(n,[`:app:${r}`,...l,...p,...e.gradleArgs],process.platform,process.env),n,d,`gradle ${r}`);const g=gradleOutputDir(i,s,t.flavors,o,a),u=existsSync(g)?readdirSync(g,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.${o}`)&&!e.name.endsWith("-debugsigned.apk")).map(e=>path.resolve(g,e.name)).sort():[];0===u.length&&fail("artifactMissing",`the build produced no ${o} in ${g}`);const c=mappingFile(i,s,t.flavors),b="release"===a&&existsSync(c)?c:null;return{artifacts:e.debugSigned?u.map(debugSignedCopy):u,mapping:b,log:d}},buildIos=async(e,o)=>{e.gradleArgs.length>0&&fail("badInput","Gradle arguments after -- apply to apk and aab builds only");const{appRoot:a,env:i}=e,s=xosPath(process.env,process.platform);requireSynced(a,{pods:!1});const t=loadToolsConfig(a),n=resolveIosProjectName(a,t)??fail("appConfigInvalid",`no ios/ folder in ${a}`);prebuild({appRoot:a,env:i,platform:"ios",otaTest:e.otaTest}),prependXosShims(s,a),ensurePods(a,process.platform);const r="release"===o?"Release":"Debug",d=path.join(logDir(a),`xos-${i}-${logStamp()}.log`);return{artifacts:[await xosSimulatorBuild(s,{appRoot:a,projectName:n,configuration:r,arch:e.arch??"x86_64"},d)],mapping:null,log:d}};export const build=async e=>{const o=debugSignedProblem(e);null!==o&&fail("badInput",o);const a=e.debug?"debug":"release",i="ios-sim"===e.artifact?await buildIos(e,a):await buildAndroid(e,e.artifact,a);if(isJsonOutput())sayJson({artifacts:i.artifacts,mapping:i.mapping,log:i.log});else{for(const e of i.artifacts)say(`build: ${e}`);null!==i.mapping&&say(`build: mapping ${i.mapping}`)}};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Invocation } from "./platform.js";
|
|
2
|
+
/** Where build and Metro logs go: inside node_modules/.cache, which no repo tracks. */
|
|
3
|
+
export declare const logDir: (appRoot: string) => string;
|
|
4
|
+
/** A file-name-safe UTC stamp for log names. */
|
|
5
|
+
export declare const logStamp: () => string;
|
|
6
|
+
/**
|
|
7
|
+
* Runs a build into its log; on failure fails {buildFailed, "<what> failed:<newline><root error><newline>Full log: <log>"}.
|
|
8
|
+
* In CI (CI=true) a failure also prints the whole log to stderr, so the job log carries it.
|
|
9
|
+
*/
|
|
10
|
+
export declare const buildOrFail: (invocation: Invocation, cwd: string, logFile: string, what: string) => Promise<void>;
|
package/lib/cache.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type Env, type HostPlatform } from "./platform.js";
|
|
2
|
+
import { type MobilePlatform } from "./prebuild.js";
|
|
3
|
+
export interface CacheKey {
|
|
4
|
+
appId: string;
|
|
5
|
+
platform: MobilePlatform;
|
|
6
|
+
variant: string;
|
|
7
|
+
abi: string;
|
|
8
|
+
fingerprint: string;
|
|
9
|
+
}
|
|
10
|
+
export interface CachedBuild extends CacheKey {
|
|
11
|
+
file: string;
|
|
12
|
+
bytes: number;
|
|
13
|
+
storedAtUtc: string;
|
|
14
|
+
}
|
|
15
|
+
/** Builds kept per app, platform, variant and ABI; older ones are deleted on store. */
|
|
16
|
+
export declare const CACHE_KEEP = 5;
|
|
17
|
+
/** The per-user folder cached builds live in, outside node_modules. */
|
|
18
|
+
export declare const buildCacheDir: (env: Env, platform: HostPlatform, home: string) => string;
|
|
19
|
+
/** The native fingerprint of the app as it stands now, through the app's own @expo/fingerprint when it has one, else the copy mobile-tools ships. */
|
|
20
|
+
export declare const nativeFingerprint: (appRoot: string, platform: MobilePlatform) => Promise<string>;
|
|
21
|
+
/** The cached apk file or .app folder for this key, or undefined. root defaults to buildCacheDir(process.env, process.platform, homedir()). */
|
|
22
|
+
export declare const findCachedBuild: (key: CacheKey, root?: string) => string | undefined;
|
|
23
|
+
/** Copies the artifact into the cache atomically, then keeps the newest CACHE_KEEP in the key's ABI folder; returns the stored path. */
|
|
24
|
+
export declare const storeCachedBuild: (key: CacheKey, artifact: string, root?: string) => string;
|
|
25
|
+
export interface CacheOptions {
|
|
26
|
+
appRoot: string;
|
|
27
|
+
action: "list" | "clear";
|
|
28
|
+
}
|
|
29
|
+
/** The cache command: lists or removes this app's cached builds. */
|
|
30
|
+
export declare const cache: (options: CacheOptions) => Promise<void>;
|
package/lib/cache.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{copyFileSync,cpSync,existsSync,mkdirSync,readdirSync,renameSync,rmSync,statSync}from"node:fs";import{createRequire}from"node:module";import{homedir}from"node:os";import path from"node:path";import{pathToFileURL}from"node:url";import{baseAppId}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{pathFor}from"./platform.js";import{nativeBuildInputs}from"./prebuild.js";export const CACHE_KEEP=5;const ARTIFACT_SUFFIXES=[".apk",".app"],BYTES_PER_MB=1048576;export const buildCacheDir=(t,e,o)=>{const r=pathFor(e);return"win32"===e?t.LOCALAPPDATA?r.join(t.LOCALAPPDATA,"Webority","mobile-tools","builds"):fail("toolFailed","LOCALAPPDATA is not set; the build cache lives under it"):"darwin"===e?r.join(o,"Library","Caches","Webority","mobile-tools","builds"):r.join(t.XDG_CACHE_HOME||r.join(o,".cache"),"webority","mobile-tools","builds")};const defaultRoot=()=>buildCacheDir(process.env,process.platform,homedir()),resolveOrUndefined=t=>{try{return t()}catch{return}},fingerprintModuleFile=t=>{const e=createRequire(path.join(t,"package.json"));return resolveOrUndefined(()=>e.resolve("@expo/fingerprint"))??resolveOrUndefined(()=>createRequire(e.resolve("expo/package.json")).resolve("@expo/fingerprint"))},loadFingerprintModule=async t=>{const e=fingerprintModuleFile(t);if(e)return await(import(pathToFileURL(e).href));try{return await(import("@expo/fingerprint"))}catch{return fail("toolMissing","@expo/fingerprint could not be loaded; reinstall @webority/mobile-tools")}};export const nativeFingerprint=async(t,e)=>{const o=await loadFingerprintModule(t),r=o.createProjectHashAsync??o.default?.createProjectHashAsync;let i;try{i=await(r?.(t,{platforms:[e],silent:!0}))}catch(t){return fail("toolFailed",`the native fingerprint could not be computed: ${t.message}`)}return"string"==typeof i&&/^[0-9a-f]{40,64}$/.test(i)?createHash("sha256").update(i).update("\n").update(nativeBuildInputs(t,e)).digest("hex"):fail("toolFailed",`the native fingerprint could not be computed: ${String(i)}`)};const abiDir=(t,e)=>path.join(t,e.appId,e.platform,e.variant,e.abi),artifactName=t=>`${t.fingerprint}${"ios"===t.platform?".app":".apk"}`;export const findCachedBuild=(t,e=defaultRoot())=>{const o=path.join(abiDir(e,t),artifactName(t));return existsSync(o)?o:void 0};const names=t=>existsSync(t)&&statSync(t).isDirectory()?readdirSync(t):[],isArtifact=t=>ARTIFACT_SUFFIXES.some(e=>t.endsWith(e))&&!t.includes(".tmp-"),storedNewestFirst=t=>names(t).filter(isArtifact).map(e=>{const o=path.join(t,e);return{file:o,mtimeMs:statSync(o).mtimeMs}}).sort((t,e)=>e.mtimeMs-t.mtimeMs);export const storeCachedBuild=(t,e,o=defaultRoot())=>{const r=abiDir(o,t);mkdirSync(r,{recursive:!0});const i=path.join(r,artifactName(t)),n=`${i}.tmp-${process.pid}`;rmSync(n,{recursive:!0,force:!0}),statSync(e).isDirectory()?cpSync(e,n,{recursive:!0}):copyFileSync(e,n),rmSync(i,{recursive:!0,force:!0}),renameSync(n,i);for(const t of storedNewestFirst(r).slice(5))rmSync(t.file,{recursive:!0,force:!0});return i};const folderBytes=t=>readdirSync(t,{withFileTypes:!0}).reduce((e,o)=>{const r=path.join(t,o.name);return e+(o.isDirectory()?folderBytes(r):statSync(r).size)},0),listBuilds=(t,e)=>{const o=[];for(const r of names(e))for(const i of names(path.join(e,r)))for(const n of names(path.join(e,r,i))){const s=path.join(e,r,i,n);for(const e of names(s).filter(isArtifact)){const a=path.join(s,e),c=statSync(a);o.push({appId:t,platform:r,variant:i,abi:n,fingerprint:path.parse(e).name,file:a,bytes:c.isDirectory()?folderBytes(a):c.size,storedAtUtc:c.mtime.toISOString()})}}return o.sort((t,e)=>e.storedAtUtc.localeCompare(t.storedAtUtc))};export const cache=async t=>{const e=baseAppId(t.appRoot),o=defaultRoot(),r=path.join(o,e);if("clear"===t.action){const t=listBuilds(e,r).length;return rmSync(r,{recursive:!0,force:!0}),void(isJsonOutput()?sayJson({appId:e,removed:t}):say(`cache: removed ${t} build(s) of ${e}`))}const i=listBuilds(e,r);if(isJsonOutput())sayJson({dir:o,appId:e,builds:i});else if(say(`cache: ${o}`),0!==i.length)for(const t of i){const e=(t.bytes/1048576).toFixed(1);say(`${t.platform} ${t.variant} ${t.abi} ${t.fingerprint.slice(0,12)} ${e} MB ${t.storedAtUtc}`)}else say(`cache: no cached builds for ${e}`)};
|
|
1
|
+
import{createHash}from"node:crypto";import{copyFileSync,cpSync,existsSync,mkdirSync,readdirSync,renameSync,rmSync,statSync}from"node:fs";import{createRequire}from"node:module";import{homedir}from"node:os";import path from"node:path";import{pathToFileURL}from"node:url";import{baseAppId}from"./config.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{pathFor}from"./platform.js";import{nativeBuildInputs}from"./prebuild.js";export const CACHE_KEEP=5;const ARTIFACT_SUFFIXES=[".apk",".app"],BYTES_PER_MB=1048576;export const buildCacheDir=(t,e,o)=>{const r=pathFor(e);return"win32"===e?t.LOCALAPPDATA?r.join(t.LOCALAPPDATA,"Webority","mobile-tools","builds"):fail("toolFailed","LOCALAPPDATA is not set; the build cache lives under it"):"darwin"===e?r.join(o,"Library","Caches","Webority","mobile-tools","builds"):r.join(t.XDG_CACHE_HOME||r.join(o,".cache"),"webority","mobile-tools","builds")};const defaultRoot=()=>buildCacheDir(process.env,process.platform,homedir()),resolveOrUndefined=t=>{try{return t()}catch{return}},fingerprintModuleFile=t=>{const e=createRequire(path.join(t,"package.json"));return resolveOrUndefined(()=>e.resolve("@expo/fingerprint"))??resolveOrUndefined(()=>createRequire(e.resolve("expo/package.json")).resolve("@expo/fingerprint"))},loadFingerprintModule=async t=>{const e=fingerprintModuleFile(t);if(e)return await(import(pathToFileURL(e).href));try{return await(import("@expo/fingerprint"))}catch{return fail("toolMissing","@expo/fingerprint could not be loaded; reinstall @webority/mobile-tools")}};export const nativeFingerprint=async(t,e)=>{const o=await loadFingerprintModule(t),r=o.createProjectHashAsync??o.default?.createProjectHashAsync;let i;try{i=await(r?.(t,{platforms:[e],silent:!0}))}catch(t){return fail("toolFailed",`the native fingerprint could not be computed: ${t instanceof Error?t.message:String(t)}`)}return"string"==typeof i&&/^[0-9a-f]{40,64}$/.test(i)?createHash("sha256").update(i).update("\n").update(nativeBuildInputs(t,e)).digest("hex"):fail("toolFailed",`the native fingerprint could not be computed: ${String(i)}`)};const abiDir=(t,e)=>path.join(t,e.appId,e.platform,e.variant,e.abi),artifactName=t=>`${t.fingerprint}${"ios"===t.platform?".app":".apk"}`;export const findCachedBuild=(t,e=defaultRoot())=>{const o=path.join(abiDir(e,t),artifactName(t));return existsSync(o)?o:void 0};const names=t=>existsSync(t)&&statSync(t).isDirectory()?readdirSync(t):[],isArtifact=t=>ARTIFACT_SUFFIXES.some(e=>t.endsWith(e))&&!t.includes(".tmp-"),storedNewestFirst=t=>names(t).filter(isArtifact).map(e=>{const o=path.join(t,e);return{file:o,mtimeMs:statSync(o).mtimeMs}}).sort((t,e)=>e.mtimeMs-t.mtimeMs);export const storeCachedBuild=(t,e,o=defaultRoot())=>{const r=abiDir(o,t);mkdirSync(r,{recursive:!0});const i=path.join(r,artifactName(t)),n=`${i}.tmp-${process.pid}`;rmSync(n,{recursive:!0,force:!0}),statSync(e).isDirectory()?cpSync(e,n,{recursive:!0}):copyFileSync(e,n),rmSync(i,{recursive:!0,force:!0}),renameSync(n,i);for(const t of storedNewestFirst(r).slice(5))rmSync(t.file,{recursive:!0,force:!0});return i};const folderBytes=t=>readdirSync(t,{withFileTypes:!0}).reduce((e,o)=>{const r=path.join(t,o.name);return e+(o.isDirectory()?folderBytes(r):statSync(r).size)},0),isMobilePlatform=t=>"android"===t||"ios"===t,listBuilds=(t,e)=>{const o=[];for(const r of names(e).filter(isMobilePlatform))for(const i of names(path.join(e,r)))for(const n of names(path.join(e,r,i))){const s=path.join(e,r,i,n);for(const e of names(s).filter(isArtifact)){const a=path.join(s,e),c=statSync(a);o.push({appId:t,platform:r,variant:i,abi:n,fingerprint:path.parse(e).name,file:a,bytes:c.isDirectory()?folderBytes(a):c.size,storedAtUtc:c.mtime.toISOString()})}}return o.sort((t,e)=>e.storedAtUtc.localeCompare(t.storedAtUtc))};export const cache=async t=>{const e=baseAppId(t.appRoot),o=defaultRoot(),r=path.join(o,e);if("clear"===t.action){const t=listBuilds(e,r).length;return rmSync(r,{recursive:!0,force:!0}),void(isJsonOutput()?sayJson({appId:e,removed:t}):say(`cache: removed ${t} build(s) of ${e}`))}const i=listBuilds(e,r);if(isJsonOutput())sayJson({dir:o,appId:e,builds:i});else if(say(`cache: ${o}`),0!==i.length)for(const t of i){const e=(t.bytes/1048576).toFixed(1);say(`${t.platform} ${t.variant} ${t.abi} ${t.fingerprint.slice(0,12)} ${e} MB ${t.storedAtUtc}`)}else say(`cache: no cached builds for ${e}`)};
|
package/lib/cli.d.ts
ADDED
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{initKeystore}from"./keystore.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{uploadSymbols}from"./symbols.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] [--debug-signed] [--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 --debug-signed builds a staging test apk signed with the debug keystore, named *-debugsigned.apk (apk only; not with --debug or Production).\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.",symbols:" symbols upload --env <Environment> --dsym <path>\n Upload an iOS build's dSYM folder or zip to Firebase Crashlytics, with the app id from that environment's GoogleService-Info plist; needs the Firebase CLI.",keystore:' keystore init --out <file.jks> [--alias upload] [--dname "CN=Android Upload Key"] [--validity-days 10000]\n Create the Android upload keystore with the password from MOBILE_TOOLS_KEYSTORE_PASSWORD and print its SHA-256 for store.json.'},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"},"debug-signed":{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,d="ios-sim"===p?SIMULATOR_ARCHS.find(e=>e===(l??"x86_64"))??fail("badInput","--arch must be x86_64 or arm64"):void 0,c="ios-sim"===p||void 0===l?void 0:parseAndroidAbis(l);return void await build({appRoot:a,env:r,artifact:p,debug:!0===i.debug,debugSigned:!0===i["debug-signed"],otaTest:!0===i["ota-test"],gradleArgs:s,arch:d,abis:c})}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
|
|
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{initKeystore}from"./keystore.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{uploadSymbols}from"./symbols.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] [--debug-signed] [--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 --debug-signed builds a staging test apk signed with the debug keystore, named *-debugsigned.apk (apk only; not with --debug or Production).\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.",symbols:" symbols upload --env <Environment> --dsym <path>\n Upload an iOS build's dSYM folder or zip to Firebase Crashlytics, with the app id from that environment's GoogleService-Info plist; needs the Firebase CLI.",keystore:' keystore init --out <file.jks> [--alias upload] [--dname "CN=Android Upload Key"] [--validity-days 10000]\n Create the Android upload keystore with the password from MOBILE_TOOLS_KEYSTORE_PASSWORD and print its SHA-256 for store.json.'},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 instanceof Error?o.message:String(o)}\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"},"debug-signed":{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,d="ios-sim"===p?SIMULATOR_ARCHS.find(e=>e===(l??"x86_64"))??fail("badInput","--arch must be x86_64 or arm64"):void 0,c="ios-sim"===p||void 0===l?void 0:parseAndroidAbis(l);return void await build({appRoot:a,env:r,artifact:p,debug:!0===i.debug,debugSigned:!0===i["debug-signed"],otaTest:!0===i["ota-test"],gradleArgs:s,arch:d,abis:c})}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"symbols":{const{values:e,positionals:n}=parse(o,t,{env:{type:"string"},dsym:{type:"string"}},!0);"upload"===n[0]&&1===n.length||fail("badInput",`usage: mobile-tools symbols upload --env <Environment> --dsym <path>\n\n${USAGE}`);const s=envOption(e.env)??fail("badInput","symbols upload needs --env <Development|Staging|Production>"),i="string"==typeof e.dsym?e.dsym:fail("badInput","symbols upload needs --dsym <path>");return void await uploadSymbols({appRoot:a,env:s,dsym:i})}case"keystore":{const{values:e,positionals:a}=parse(o,t,{out:{type:"string"},alias:{type:"string"},dname:{type:"string"},"validity-days":{type:"string"}},!0);"init"===a[0]&&1===a.length||fail("badInput",`usage: mobile-tools keystore init --out <file.jks>\n\n${USAGE}`);const n="string"==typeof e.out?e.out:fail("badInput","keystore init needs --out <file.jks>"),s="string"==typeof e["validity-days"]?e["validity-days"]:"10000";return/^[1-9][0-9]*$/.test(s)||fail("badInput",`--validity-days must be a positive whole number, not ${s}`),void await initKeystore({out:n,alias:"string"==typeof e.alias?e.alias:"upload",dname:"string"==typeof e.dname?e.dname:"CN=Android Upload Key",validityDays:Number(s)})}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/config.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export declare const ENVIRONMENTS: readonly ["Development", "Staging", "Production"];
|
|
2
|
+
export type Environment = (typeof ENVIRONMENTS)[number];
|
|
3
|
+
export declare const CONFIG_FILE = "mobile-tools.config.json";
|
|
4
|
+
export declare const COMPILED_FILE = "appsettings.Compiled.json";
|
|
5
|
+
export interface ToolsConfig {
|
|
6
|
+
iosProjectName?: string;
|
|
7
|
+
flavors: boolean;
|
|
8
|
+
localApiPort?: number;
|
|
9
|
+
iconSource?: string;
|
|
10
|
+
firebasePlistDir: string;
|
|
11
|
+
/** Setting keys the app reads beyond REQUIRED_SETTINGS; each must be present and not null in the merged settings. */
|
|
12
|
+
requiredSettings: readonly string[];
|
|
13
|
+
}
|
|
14
|
+
export type AppSettings = Record<string, unknown> & {
|
|
15
|
+
APP_NAME: string;
|
|
16
|
+
APP_ID: string;
|
|
17
|
+
ENVIRONMENT: Environment;
|
|
18
|
+
BASE_URL: string;
|
|
19
|
+
VERSION_DISPLAY: string;
|
|
20
|
+
VERSION_INTERNAL: string | number;
|
|
21
|
+
};
|
|
22
|
+
/** The keys every app's merged appsettings must carry before a build. */
|
|
23
|
+
export declare const REQUIRED_SETTINGS: readonly ["APP_NAME", "APP_ID", "ENVIRONMENT", "BASE_URL", "VERSION_DISPLAY", "VERSION_INTERNAL"];
|
|
24
|
+
export declare const parseEnvironment: (value: string) => Environment;
|
|
25
|
+
export declare const envSuffix: (env: Environment) => string;
|
|
26
|
+
/** Android flavor names are the environment in lower case: development, staging, production. */
|
|
27
|
+
export declare const flavorOf: (env: Environment) => string;
|
|
28
|
+
/** The id the app installs under: the base id plus the environment's suffix. */
|
|
29
|
+
export declare const applicationId: (baseId: string, env: Environment) => string;
|
|
30
|
+
export type BuildType = "debug" | "release";
|
|
31
|
+
export type AndroidArtifact = "apk" | "aab";
|
|
32
|
+
/** The Gradle variant: flavor then build type (stagingRelease), or the build type alone without flavors. */
|
|
33
|
+
export declare const variantName: (env: Environment, flavors: boolean, buildType: BuildType) => string;
|
|
34
|
+
/** The task that builds one artifact of one variant: assembleStagingRelease, bundleProductionRelease, assembleDebug. */
|
|
35
|
+
export declare const gradleTask: (env: Environment, flavors: boolean, artifact: AndroidArtifact, buildType: BuildType) => string;
|
|
36
|
+
/** Where that task writes: outputs/apk/<flavor>/<buildType> (apk/<buildType> without flavors), or outputs/bundle/<variant>. */
|
|
37
|
+
export declare const gradleOutputDir: (appRoot: string, env: Environment, flavors: boolean, artifact: AndroidArtifact, buildType: BuildType) => string;
|
|
38
|
+
/** The R8 mapping of the release variant. */
|
|
39
|
+
export declare const mappingFile: (appRoot: string, env: Environment, flavors: boolean) => string;
|
|
40
|
+
export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
|
|
41
|
+
/** Validates mobile-tools.config.json; every unknown key or wrong type fails, naming the key. */
|
|
42
|
+
export declare const parseToolsConfig: (raw: unknown, source?: string) => ToolsConfig;
|
|
43
|
+
export declare const loadToolsConfig: (appRoot: string) => ToolsConfig;
|
|
44
|
+
/** The configured iOS project name, or the one `*.xcodeproj` under ios/; undefined when the app has no ios/. */
|
|
45
|
+
export declare const resolveIosProjectName: (appRoot: string, config: ToolsConfig) => string | undefined;
|
|
46
|
+
/** Base settings overlaid by one environment's file, then validated. Pure apart from the inputs. */
|
|
47
|
+
export declare const mergeAppSettings: (base: unknown, overlay: unknown, env: Environment, requiredSettings: readonly string[]) => AppSettings;
|
|
48
|
+
export declare const loadAppSettings: (appRoot: string, env: Environment, requiredSettings: readonly string[]) => AppSettings;
|
|
49
|
+
/** The production APP_ID from appsettings.json; the build cache files builds under it. */
|
|
50
|
+
export declare const baseAppId: (appRoot: string) => string;
|
|
51
|
+
/** The ENVIRONMENT of the last compile, for --same-env. */
|
|
52
|
+
export declare const lastCompiledEnvironment: (appRoot: string) => Environment;
|
|
53
|
+
/**
|
|
54
|
+
* The local API port `run` reverses for Development: the configured port, else the port of a
|
|
55
|
+
* localhost BASE_URL, else none (the API is remote and needs no tunnel).
|
|
56
|
+
*/
|
|
57
|
+
export declare const localApiPort: (devBaseUrl: string, config: ToolsConfig) => number | undefined;
|
package/lib/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import path from"node:path";import{fail}from"./output.js";export const ENVIRONMENTS=["Development","Staging","Production"];const SUFFIX={Development:".development",Staging:".staging",Production:""};export const CONFIG_FILE="mobile-tools.config.json";export const COMPILED_FILE="appsettings.Compiled.json";export const REQUIRED_SETTINGS=["APP_NAME","APP_ID","ENVIRONMENT","BASE_URL","VERSION_DISPLAY","VERSION_INTERNAL"];export const parseEnvironment=t=>ENVIRONMENTS.find(e=>e.toLowerCase()===t.toLowerCase())??fail("badInput",`unknown environment "${t}": use ${ENVIRONMENTS.join(", ")}`);export const envSuffix=t=>SUFFIX[t];export const flavorOf=t=>t.toLowerCase();export const applicationId=(t,e)=>`${t}${envSuffix(e)}`;const capitalize=t=>{const e=t.charAt(0);if(""===e)throw new Error("capitalize needs a non-empty word");return`${e.toUpperCase()}${t.slice(1)}`};export const variantName=(t,e,n)=>e?`${flavorOf(t)}${capitalize(n)}`:n;export const gradleTask=(t,e,n,o)=>`${"apk"===n?"assemble":"bundle"}${capitalize(variantName(t,e,o))}`;export const gradleOutputDir=(t,e,n,o,i)=>{const s=path.join(t,"android","app","build","outputs");return"aab"===o?path.join(s,"bundle",variantName(e,n,i)):n?path.join(s,"apk",flavorOf(e),i):path.join(s,"apk",i)};export const mappingFile=(t,e,n)=>path.join(t,"android","app","build","outputs","mapping",variantName(e,n,"release"),"mapping.txt");const readJson=t=>{try{return JSON.parse(readFileSync(t,"utf8"))}catch(e){return fail("appConfigInvalid",`cannot read ${t}: ${e instanceof Error?e.message:String(e)}`)}}
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import path from"node:path";import{fail}from"./output.js";export const ENVIRONMENTS=["Development","Staging","Production"];const SUFFIX={Development:".development",Staging:".staging",Production:""};export const CONFIG_FILE="mobile-tools.config.json";export const COMPILED_FILE="appsettings.Compiled.json";export const REQUIRED_SETTINGS=["APP_NAME","APP_ID","ENVIRONMENT","BASE_URL","VERSION_DISPLAY","VERSION_INTERNAL"];export const parseEnvironment=t=>ENVIRONMENTS.find(e=>e.toLowerCase()===t.toLowerCase())??fail("badInput",`unknown environment "${t}": use ${ENVIRONMENTS.join(", ")}`);export const envSuffix=t=>SUFFIX[t];export const flavorOf=t=>t.toLowerCase();export const applicationId=(t,e)=>`${t}${envSuffix(e)}`;const capitalize=t=>{const e=t.charAt(0);if(""===e)throw new Error("capitalize needs a non-empty word");return`${e.toUpperCase()}${t.slice(1)}`};export const variantName=(t,e,n)=>e?`${flavorOf(t)}${capitalize(n)}`:n;export const gradleTask=(t,e,n,o)=>`${"apk"===n?"assemble":"bundle"}${capitalize(variantName(t,e,o))}`;export const gradleOutputDir=(t,e,n,o,i)=>{const s=path.join(t,"android","app","build","outputs");return"aab"===o?path.join(s,"bundle",variantName(e,n,i)):n?path.join(s,"apk",flavorOf(e),i):path.join(s,"apk",i)};export const mappingFile=(t,e,n)=>path.join(t,"android","app","build","outputs","mapping",variantName(e,n,"release"),"mapping.txt");const readJson=t=>{try{return JSON.parse(readFileSync(t,"utf8"))}catch(e){return fail("appConfigInvalid",`cannot read ${t}: ${e instanceof Error?e.message:String(e)}`)}};export const isRecord=t=>"object"==typeof t&&null!==t&&!Array.isArray(t);const isStringList=t=>Array.isArray(t)&&t.every(t=>"string"==typeof t),isWholeNumber=t=>("string"==typeof t||"number"==typeof t)&&/^[1-9][0-9]*$/.test(String(t)),CONFIG_KEYS={iosProjectName:"string",flavors:"boolean",localApiPort:"port",iconSource:"string",firebasePlistDir:"string",requiredSettings:"settingNames"},SETTING_NAME_PATTERN=/^[A-Z][A-Z0-9_]*$/,checkSettingNames=(t,e)=>{if(!isStringList(t))return fail("appConfigInvalid",`${e}: "requiredSettings" must be an array of setting names such as ["LOG_LEVEL"]`);const n=new Set;for(const o of t)SETTING_NAME_PATTERN.test(o)||fail("appConfigInvalid",`${e}: "requiredSettings" holds ${JSON.stringify(o)}; a setting name is upper case letters, digits and _`),n.has(o)&&fail("appConfigInvalid",`${e}: "requiredSettings" lists ${o} twice`),REQUIRED_SETTINGS.some(t=>t===o)&&fail("appConfigInvalid",`${e}: "requiredSettings" lists ${o}, which prebuild always requires; remove it`),n.add(o);return t};export const parseToolsConfig=(t,e=CONFIG_FILE)=>{if(!isRecord(t))return fail("appConfigInvalid",`${e} must hold a JSON object`);for(const[n,o]of Object.entries(t)){const t=Object.hasOwn(CONFIG_KEYS,n)?CONFIG_KEYS[n]:void 0;if(!t)return fail("appConfigInvalid",`${e}: unknown key "${n}" (known: ${Object.keys(CONFIG_KEYS).join(", ")})`);if("settingNames"===t){checkSettingNames(o,e);continue}if(!("port"===t?"number"==typeof o&&Number.isInteger(o)&&o>0&&o<65536:"string"===t?"string"==typeof o&&""!==o.trim():typeof o===t)){fail("appConfigInvalid",`${e}: "${n}" must be ${{port:"a port number",string:"a non-empty string",boolean:"true or false"}[t]}`)}}return{iosProjectName:"string"==typeof t.iosProjectName?t.iosProjectName:void 0,flavors:"boolean"!=typeof t.flavors||t.flavors,localApiPort:"number"==typeof t.localApiPort?t.localApiPort:void 0,iconSource:"string"==typeof t.iconSource?t.iconSource:void 0,firebasePlistDir:"string"==typeof t.firebasePlistDir?t.firebasePlistDir:path.join("ios","firebase"),requiredSettings:Array.isArray(t.requiredSettings)?t.requiredSettings:[]}};export const loadToolsConfig=t=>{const e=path.join(t,CONFIG_FILE);return parseToolsConfig(existsSync(e)?readJson(e):{})};export const resolveIosProjectName=(t,e)=>{if(e.iosProjectName)return e.iosProjectName;const n=path.join(t,"ios");if(!existsSync(n))return;const o=readdirSync(n).filter(t=>t.endsWith(".xcodeproj")),[i]=o;return 1!==o.length||void 0===i?fail("appConfigInvalid",`found ${o.length} .xcodeproj folders in ios/: set "iosProjectName" in ${CONFIG_FILE}`):i.slice(0,-10)};const APP_ID_PATTERN=/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/;export const mergeAppSettings=(t,e,n,o)=>{if(!isRecord(t))return fail("appConfigInvalid","appsettings.json must hold a JSON object");if(!isRecord(e))return fail("appConfigInvalid",`appsettings.${n}.json must hold a JSON object`);const i={...t,...e},s=REQUIRED_SETTINGS.filter(t=>void 0===i[t]||null===i[t]||""===i[t]);s.length>0&&fail("appConfigInvalid",`appsettings (${n}) is missing required key(s): ${s.join(", ")}`);const r=o.filter(t=>void 0===i[t]||null===i[t]);r.length>0&&fail("appConfigInvalid",`appsettings (${n}) is missing setting(s) mobile-tools.config.json requires: ${r.join(", ")}`),i.ENVIRONMENT!==n&&fail("appConfigInvalid",`appsettings.${n}.json sets ENVIRONMENT to ${JSON.stringify(i.ENVIRONMENT)}; it must be "${n}"`),void 0!==i.APP_ID_SUFFIX&&i.APP_ID_SUFFIX!==envSuffix(n)&&fail("appConfigInvalid",`appsettings (${n}) sets APP_ID_SUFFIX to ${JSON.stringify(i.APP_ID_SUFFIX)}; ${n} builds always use ${JSON.stringify(envSuffix(n))}. Remove the key or correct it.`);const text=t=>{const e=i[t];return"string"==typeof e?e:fail("appConfigInvalid",`appsettings (${n}): ${t} must be text, not ${JSON.stringify(e)}`)},a=i.VERSION_INTERNAL;if(!isWholeNumber(a))return fail("appConfigInvalid",`VERSION_INTERNAL must be a positive whole number, not ${JSON.stringify(a)}`);const p=text("APP_ID");return APP_ID_PATTERN.test(p)||fail("appConfigInvalid",`APP_ID ${JSON.stringify(p)} is not a reverse-domain id such as com.example.app`),{...i,APP_NAME:text("APP_NAME"),APP_ID:p,ENVIRONMENT:n,BASE_URL:text("BASE_URL"),VERSION_DISPLAY:text("VERSION_DISPLAY"),VERSION_INTERNAL:a}};export const loadAppSettings=(t,e,n)=>{const o=path.join(t,"appsettings.json"),i=path.join(t,`appsettings.${e}.json`);return existsSync(o)||fail("appConfigInvalid",`no appsettings.json in ${t}: run mobile-tools from the app's root folder`),existsSync(i)||fail("appConfigInvalid",`appsettings.${e}.json not found: every buildable environment declares its own file`),mergeAppSettings(readJson(o),readJson(i),e,n)};export const baseAppId=t=>{const e=path.join(t,"appsettings.json");if(!existsSync(e))return fail("appConfigInvalid",`no appsettings.json in ${t}: run mobile-tools from the app's root folder`);const n=readJson(e),o=isRecord(n)?n.APP_ID:void 0;return"string"==typeof o&&APP_ID_PATTERN.test(o)?o:fail("appConfigInvalid",`APP_ID ${JSON.stringify(o)} in appsettings.json is not a reverse-domain id such as com.example.app`)};export const lastCompiledEnvironment=t=>{const e=path.join(t,COMPILED_FILE);if(!existsSync(e))return fail("appConfigInvalid",`--same-env: no ${COMPILED_FILE} yet; pass --env <Environment> once`);const n=readJson(e);return isRecord(n)&&"string"==typeof n.ENVIRONMENT?parseEnvironment(n.ENVIRONMENT):fail("appConfigInvalid",`--same-env: ${COMPILED_FILE} has no ENVIRONMENT`)};export const localApiPort=(t,e)=>{if(void 0!==e.localApiPort)return e.localApiPort;let n;try{n=new URL(t)}catch{return}return"localhost"===n.hostname||"127.0.0.1"===n.hostname?""!==n.port?Number(n.port):"https:"===n.protocol?443:80:void 0};
|
package/lib/devices.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type AppleDevice } from "./ios.js";
|
|
2
|
+
import type { MobilePlatform } from "./prebuild.js";
|
|
3
|
+
export interface AdbEntry {
|
|
4
|
+
serial: string;
|
|
5
|
+
state: string;
|
|
6
|
+
}
|
|
7
|
+
/** What one adb serial reports about the device behind it. */
|
|
8
|
+
export interface DeviceProbe {
|
|
9
|
+
serial: string;
|
|
10
|
+
serialNo: string;
|
|
11
|
+
androidId: string;
|
|
12
|
+
model: string;
|
|
13
|
+
abi: string;
|
|
14
|
+
}
|
|
15
|
+
/** One physical (or emulated) device, however many adb serials reach it. */
|
|
16
|
+
export interface Device {
|
|
17
|
+
serial: string;
|
|
18
|
+
serials: string[];
|
|
19
|
+
model: string;
|
|
20
|
+
abi: string;
|
|
21
|
+
}
|
|
22
|
+
/** Parses `adb devices`. */
|
|
23
|
+
export declare const parseAdbDevices: (text: string) => AdbEntry[];
|
|
24
|
+
export declare const dedupeDevices: (probes: DeviceProbe[]) => Device[];
|
|
25
|
+
export declare const probeDevice: (adb: string, serial: string, cwd: string) => DeviceProbe;
|
|
26
|
+
export declare const listAndroidDevices: (adb: string, cwd: string) => Device[];
|
|
27
|
+
export declare const describeDevice: (device: Device) => string;
|
|
28
|
+
/** Matches --device against any serial of a device or its model name (case-insensitive). */
|
|
29
|
+
export declare const findDevice: <T extends {
|
|
30
|
+
serials: string[];
|
|
31
|
+
model: string;
|
|
32
|
+
}>(devices: T[], requested: string) => T | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* The device to use: the --device match, the only device, or the user's pick on a terminal.
|
|
35
|
+
* Without a terminal several devices are an error listing them, never a guess.
|
|
36
|
+
*/
|
|
37
|
+
export declare const pickDevice: <T extends {
|
|
38
|
+
serials: string[];
|
|
39
|
+
model: string;
|
|
40
|
+
}>(devices: T[], requested: string | undefined, describe: (device: T) => string, interactive: boolean) => Promise<T>;
|
|
41
|
+
/** adb ports of local emulators adb cannot find alone: MuMu Player 12 instances (16384 + 32 n) and the legacy MuMu port. */
|
|
42
|
+
export declare const LOCAL_EMULATOR_PORTS: readonly number[];
|
|
43
|
+
/** One listed device, as the devices command prints it in JSON. */
|
|
44
|
+
export type ListedDevice = ({
|
|
45
|
+
platform: "android";
|
|
46
|
+
} & Device) | ({
|
|
47
|
+
platform: "ios";
|
|
48
|
+
} & AppleDevice);
|
|
49
|
+
/** Runs adb connect for every open local emulator port adb does not list yet; resolves to the serials it connected. Never fails on a refusal. */
|
|
50
|
+
export declare const connectLocalEmulators: (adb: string, cwd: string) => Promise<string[]>;
|
|
51
|
+
export interface DevicesOptions {
|
|
52
|
+
appRoot: string;
|
|
53
|
+
platform: MobilePlatform;
|
|
54
|
+
}
|
|
55
|
+
/** The devices command: connects local emulators, then lists every ready device once (human lines or JSON). */
|
|
56
|
+
export declare const devices: (options: DevicesOptions) => Promise<void>;
|
package/lib/doctor.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type HostPlatform } from "./platform.js";
|
|
2
|
+
import { type MobilePlatform } from "./prebuild.js";
|
|
3
|
+
export type DoctorCheckCode = "nodeVersion" | "androidHome" | "adb" | "adbServer" | "jdk" | "ndk" | "buildTools" | "androidPlatform" | "ninja" | "install" | "autolinkingCache" | "ndkHook" | "firebaseConfig" | "xcode" | "cocoapods" | "xos" | "appPath";
|
|
4
|
+
export type DoctorStatus = "ok" | "problem" | "warning" | "skipped" | "fixed";
|
|
5
|
+
export interface DoctorCheck {
|
|
6
|
+
code: DoctorCheckCode;
|
|
7
|
+
status: DoctorStatus;
|
|
8
|
+
message: string;
|
|
9
|
+
fix?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface DoctorReport {
|
|
12
|
+
checks: DoctorCheck[];
|
|
13
|
+
problems: number;
|
|
14
|
+
}
|
|
15
|
+
export interface DoctorOptions {
|
|
16
|
+
appRoot: string;
|
|
17
|
+
platform?: MobilePlatform;
|
|
18
|
+
fix: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** The Java major React Native and Gradle are validated on. */
|
|
21
|
+
export declare const JDK_MAJOR = 17;
|
|
22
|
+
/** The Java major in `java -version` output: 17 for version "17.0.12", 8 for version "1.8.0_402"; undefined when none is found. */
|
|
23
|
+
export declare const javaMajor: (versionOutput: string) => number | undefined;
|
|
24
|
+
/** ndkVersion, buildToolsVersion and compileSdkVersion as android/build.gradle declares them. */
|
|
25
|
+
export declare const gradleSdkVersions: (buildGradle: string) => {
|
|
26
|
+
ndk?: string;
|
|
27
|
+
buildTools?: string;
|
|
28
|
+
compileSdk?: string;
|
|
29
|
+
};
|
|
30
|
+
/** Why autolinking.json no longer matches this tree (moved root, missing package folder, unreadable JSON), or undefined when it matches. */
|
|
31
|
+
export declare const autolinkingProblem: (text: string, appRoot: string, exists: (dir: string) => boolean) => string | undefined;
|
|
32
|
+
/** Xcode on a Mac, where the Simulator lives; xOS Tools elsewhere, where the iOS build runs on the xOS build host. */
|
|
33
|
+
export declare const iosChecks: (appRoot: string, platform: HostPlatform) => DoctorCheck[];
|
|
34
|
+
/** Checks the machine and the app tree, prints every check (or the JSON report), and sets exit code 1 while a problem remains. */
|
|
35
|
+
export declare const doctor: (options: DoctorOptions) => Promise<void>;
|
package/lib/exec.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Invocation } from "./platform.js";
|
|
2
|
+
export interface Captured {
|
|
3
|
+
status: number;
|
|
4
|
+
stdout: string;
|
|
5
|
+
stderr: string;
|
|
6
|
+
}
|
|
7
|
+
/** Run to completion and capture the output. A program that cannot start reports status -1. */
|
|
8
|
+
export declare const capture: (inv: Invocation, cwd: string) => Captured;
|
|
9
|
+
/** Run with the terminal attached (installs, pod install, codegen) and fail on a non-zero exit. */
|
|
10
|
+
export declare const runInherit: (inv: Invocation, cwd: string, what: string) => void;
|
|
11
|
+
/** Run with stdout and stderr written to a log file; resolves to the exit status. */
|
|
12
|
+
export declare const runToLog: (inv: Invocation, cwd: string, logFile: string) => Promise<number>;
|
|
13
|
+
/**
|
|
14
|
+
* Start a long-lived process that outlives this one, its output in a log file; returns its pid.
|
|
15
|
+
* Detached gives it its own process group on macOS and Linux. On Windows detached means no console at all, so every
|
|
16
|
+
* helper Metro starts opens a visible terminal window; there it keeps a hidden console its helpers share instead.
|
|
17
|
+
*/
|
|
18
|
+
export declare const startDetached: (inv: Invocation, cwd: string, logFile: string) => number;
|
package/lib/hooks.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const HOOK_NAMES: readonly ["post-merge", "post-checkout"];
|
|
2
|
+
/** The block one app adds: a stale-tree check that prints its one line and never fails the git command. */
|
|
3
|
+
export declare const hookBlock: (appDir: string) => string;
|
|
4
|
+
export declare const chainedName: (hook: string) => string;
|
|
5
|
+
export declare const isOwnHook: (content: string) => boolean;
|
|
6
|
+
/**
|
|
7
|
+
* The hook file after adding or refreshing one app's block. A hook this tool did not write is
|
|
8
|
+
* never edited: the caller moves it aside and the new hook runs it first, passing its exit status
|
|
9
|
+
* through.
|
|
10
|
+
*/
|
|
11
|
+
export declare const composeHook: (hook: string, existing: string | undefined, appDir: string) => string;
|
|
12
|
+
/** The hooks folder git runs: core.hooksPath when set (relative to the work tree top), else the repo's own. */
|
|
13
|
+
export declare const hooksDir: (appRoot: string) => {
|
|
14
|
+
dir: string;
|
|
15
|
+
topLevel: string;
|
|
16
|
+
};
|
|
17
|
+
export declare const installHooks: (appRoot: string) => void;
|
package/lib/iconArt.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Environment } from "./config.js";
|
|
2
|
+
export interface Ribbon {
|
|
3
|
+
label: string;
|
|
4
|
+
color: string;
|
|
5
|
+
}
|
|
6
|
+
/** Production is clean; the other two carry a corner ribbon so testers can tell builds apart. */
|
|
7
|
+
export declare const RIBBONS: Record<Environment, Ribbon | undefined>;
|
|
8
|
+
/** The square a ribbon sits in: the whole icon, or the visible part of an adaptive foreground. */
|
|
9
|
+
export interface Box {
|
|
10
|
+
x: number;
|
|
11
|
+
y: number;
|
|
12
|
+
size: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A band across the bottom-right corner of the box, with the label along it. The band's middle
|
|
16
|
+
* sits far enough in from the corner that a circular or rounded launcher mask still shows the
|
|
17
|
+
* whole label. Text is SVG text in a generic sans-serif: no font file ships with the package.
|
|
18
|
+
*/
|
|
19
|
+
export declare const ribbonSvg: (canvas: number, box: Box, ribbon: Ribbon) => string;
|
|
20
|
+
export declare const circleMaskSvg: (size: number) => string;
|
|
21
|
+
/** Density buckets and their scale from mdpi. */
|
|
22
|
+
export declare const DENSITIES: [string, number][];
|
|
23
|
+
/** Legacy launcher icons are 48dp; adaptive layers are 108dp, of which the middle 72dp shows. */
|
|
24
|
+
export declare const LEGACY_DP = 48;
|
|
25
|
+
export declare const ADAPTIVE_DP = 108;
|
|
26
|
+
export declare const ADAPTIVE_VISIBLE_DP = 72;
|
|
27
|
+
export declare const ADAPTIVE_ICON_XML: string;
|
|
28
|
+
export declare const backgroundColorXml: (color: string) => string;
|
|
29
|
+
/** A single 1024 px universal icon; Xcode derives every other size from it. */
|
|
30
|
+
export declare const IOS_ICON_FILE = "AppIcon-1024.png";
|
|
31
|
+
export declare const iosContentsJson: () => string;
|
|
32
|
+
export declare const toHex: (red: number, green: number, blue: number) => string;
|
package/lib/icons.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface IconsOptions {
|
|
2
|
+
appRoot: string;
|
|
3
|
+
source?: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Renders launcher icons from one source for each environment the app has: Android per flavor
|
|
7
|
+
* (legacy, round and adaptive) and an iOS AppIcon-<Env> set, which prebuild then selects.
|
|
8
|
+
*/
|
|
9
|
+
export declare const icons: (options: IconsOptions) => Promise<void>;
|
package/lib/ios.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface AppleDevice {
|
|
2
|
+
udid: string;
|
|
3
|
+
name: string;
|
|
4
|
+
kind: "simulator";
|
|
5
|
+
serials: string[];
|
|
6
|
+
model: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const PLUTIL = "/usr/bin/plutil";
|
|
9
|
+
/** Booted simulators from `xcrun simctl list -j devices booted`. */
|
|
10
|
+
export declare const parseSimctlBooted: (json: string) => AppleDevice[];
|
|
11
|
+
export declare const listAppleDevices: (cwd: string) => AppleDevice[];
|
|
12
|
+
export declare const describeAppleDevice: (device: AppleDevice) => string;
|
|
13
|
+
/** The bundle identifier a built .app declares in its Info.plist. */
|
|
14
|
+
export declare const appBundleId: (appPath: string, cwd: string) => string;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The SHA-256 fingerprint of a `keytool -list -v` listing, lower-case hex without colons. */
|
|
2
|
+
export declare const sha256Fingerprint: (keytoolListOutput: string) => string | undefined;
|
|
3
|
+
export declare const initKeystore: (opts: {
|
|
4
|
+
out: string;
|
|
5
|
+
alias: string;
|
|
6
|
+
dname: string;
|
|
7
|
+
validityDays: number;
|
|
8
|
+
}) => Promise<void>;
|
package/lib/metro.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const DEFAULT_METRO_PORT = 8081;
|
|
2
|
+
export declare const HUNG_PROBE_MS = 5000;
|
|
3
|
+
export type MetroState = "ours" | "other" | "free" | "hung";
|
|
4
|
+
/**
|
|
5
|
+
* Whether the Metro answering on a port serves this app. The CLI's dev server names its project
|
|
6
|
+
* root in the X-React-Native-Project-Root header; a server that does not say is treated as
|
|
7
|
+
* another project's.
|
|
8
|
+
*/
|
|
9
|
+
export declare const classifyStatus: (body: string, projectRootHeader: string | null, appRoot: string) => MetroState;
|
|
10
|
+
export declare const probeMetro: (port: number, appRoot: string) => Promise<MetroState>;
|
|
11
|
+
/** The JavaScript a Metro serves: production with the profiling renderer, or development. */
|
|
12
|
+
export type MetroMode = "profiling" | "development";
|
|
13
|
+
/** What ensureMetro records about the Metro it starts, in logDir(appRoot)/metro.json. A record with no mode is development. */
|
|
14
|
+
export interface MetroRecord {
|
|
15
|
+
port: number;
|
|
16
|
+
pid: number;
|
|
17
|
+
appRoot: string;
|
|
18
|
+
startedAtUtc: string;
|
|
19
|
+
mode?: MetroMode;
|
|
20
|
+
}
|
|
21
|
+
export declare const METRO_RECORD_FILE = "metro.json";
|
|
22
|
+
/** The record of the Metro mobile-tools last started for this app, or undefined. */
|
|
23
|
+
export declare const readMetroRecord: (appRoot: string) => MetroRecord | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* A Metro serving this app: reuses one already running for it, otherwise starts one detached on
|
|
26
|
+
* 8081 or, when another project holds 8081, the next free port. Never prompts. Returns the port.
|
|
27
|
+
* A running Metro of the other mode is refused, never reused.
|
|
28
|
+
*/
|
|
29
|
+
export declare const ensureMetro: (appRoot: string, logFile: string, { fixedPort, profiling }: {
|
|
30
|
+
fixedPort: boolean;
|
|
31
|
+
profiling: boolean;
|
|
32
|
+
}) => Promise<number>;
|
|
33
|
+
/** Stops the Metro mobile-tools started for this app (its whole process tree) and starts it again on the same port; resolves to the port. */
|
|
34
|
+
export declare const restartMetro: (appRoot: string) => Promise<number>;
|
package/lib/metro.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{createRequire}from"node:module";import{createServer}from"node:net";import path from"node:path";import{logDir}from"./buildLog.js";import{capture,startDetached}from"./exec.js";import{fail,say}from"./output.js";export const DEFAULT_METRO_PORT=8081;export const HUNG_PROBE_MS=5e3;const PORT_FREE_WAIT_MS=1e4,TERM_WAIT_MS=5e3,samePath=(t
|
|
1
|
+
import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{createRequire}from"node:module";import{createServer}from"node:net";import path from"node:path";import{logDir}from"./buildLog.js";import{isRecord}from"./config.js";import{capture,startDetached}from"./exec.js";import{fail,say}from"./output.js";export const DEFAULT_METRO_PORT=8081;export const HUNG_PROBE_MS=5e3;const PORT_FREE_WAIT_MS=1e4,TERM_WAIT_MS=5e3,samePath=(e,t)=>{const norm=e=>{const t=path.resolve(e).replace(/[\\/]+$/,"");return"win32"===process.platform?t.toLowerCase():t};return norm(e)===norm(t)};export const classifyStatus=(e,t,r)=>{if(!e.includes("packager-status:running"))return"other";const o=t??/project-root:(.+)/.exec(e)?.[1]?.trim();return o&&samePath(decodeHeaderPath(o),r)?"ours":"other"};const decodeHeaderPath=e=>{try{return decodeURIComponent(e)}catch{return e}},portIsFree=e=>new Promise(t=>{const r=createServer();r.once("error",()=>t(!1)),r.once("listening",()=>r.close(()=>t(!0))),r.listen(e)});export const probeMetro=async(e,t)=>{try{const r=await fetch(`http://localhost:${e}/status`,{signal:AbortSignal.timeout(1e3)});return classifyStatus(await r.text(),r.headers.get("X-React-Native-Project-Root"),t)}catch{return await portIsFree(e)?"free":"other"}};const sleep=e=>new Promise(t=>setTimeout(t,e)),waitForMetro=async(e,t,r)=>{const o=Date.now()+12e4;for(;Date.now()<o;){if("ours"===await probeMetro(e,t))return;await new Promise(e=>setTimeout(e,500))}fail("metroUnavailable",`Metro did not answer on port ${e} within 2 minutes; see ${r}`)};export const METRO_RECORD_FILE="metro.json";const isMetroRecord=e=>isRecord(e)&&"number"==typeof e.port&&"number"==typeof e.pid&&"string"==typeof e.appRoot&&"string"==typeof e.startedAtUtc&&(void 0===e.mode||"profiling"===e.mode||"development"===e.mode);export const readMetroRecord=e=>{const t=path.join(logDir(e),"metro.json");if(existsSync(t))try{const e=JSON.parse(readFileSync(t,"utf8"));return isMetroRecord(e)?e:void 0}catch{return}};const writeMetroRecord=(e,t,r,o)=>{mkdirSync(logDir(e),{recursive:!0});const s={port:t,pid:r,appRoot:e,startedAtUtc:(new Date).toISOString(),mode:o};writeFileSync(path.join(logDir(e),"metro.json"),JSON.stringify(s,null,2))},servedMode=(e,t)=>{const r=readMetroRecord(e);return(r?.port===t?r.mode:void 0)??"development"},withProfilingEnv=(e,t)=>{const r=process.env.WEBORITY_PROFILING;e?process.env.WEBORITY_PROFILING="1":delete process.env.WEBORITY_PROFILING;try{return t()}finally{void 0===r?delete process.env.WEBORITY_PROFILING:process.env.WEBORITY_PROFILING=r}},startMetro=async(e,t,r,o)=>{const s=createRequire(path.join(e,"package.json")),resolveCli=e=>{try{return s.resolve(e)}catch{return}},i=resolveCli("expo/bin/cli"),n=i?void 0:resolveCli("react-native/cli.js");let a;if(i)a=[i,"start","--port",String(t),...o?["--no-dev","--minify"]:[]];else{if(!n)return fail("toolMissing","neither expo nor react-native is installed in this app; run pnpm install in the app");if(o)return fail("toolMissing","profiling Metro needs the Expo CLI; add expo to the app or run without profiling");a=[n,"start","--port",String(t)]}const p=withProfilingEnv(o,()=>startDetached({file:process.execPath,args:a},e,r));writeMetroRecord(e,t,p,o?"profiling":"development"),say(`metro: started on port ${t}, log ${r}`),await waitForMetro(t,e,r)},answers=async(e,t)=>{try{return await fetch(`http://localhost:${e}/status`,{signal:AbortSignal.timeout(t)}),!0}catch{return!1}},systemTool=e=>path.join(process.env.SystemRoot??"C:/Windows","System32",e),isNodeProcess=e=>{try{process.kill(e,0)}catch{return!1}if("win32"===process.platform){return capture({file:systemTool("tasklist.exe"),args:["/FI",`PID eq ${e}`,"/FO","CSV","/NH"]},process.cwd()).stdout.toLowerCase().includes("node.exe")}return capture({file:"/bin/ps",args:["-p",String(e),"-o","comm="]},process.cwd()).stdout.trim().endsWith("node")},signalGroup=(e,t)=>{try{process.kill(-e,t)}catch(e){if("ESRCH"!==(e instanceof Error&&"code"in e?e.code:void 0))throw e}},stopTree=async e=>{if("win32"===process.platform){const t=capture({file:systemTool("taskkill.exe"),args:["/PID",String(e),"/T","/F"]},process.cwd());if(0!==t.status&&isNodeProcess(e)){const r=`${t.stdout}${t.stderr}`.trim();fail("toolFailed",`taskkill could not stop pid ${e}: ${r}`)}return}signalGroup(e,"SIGTERM");const t=Date.now()+5e3;for(;isNodeProcess(e)&&Date.now()<t;)await sleep(250);isNodeProcess(e)&&signalGroup(e,"SIGKILL")},waitPortFree=async(e,t)=>{const r=Date.now()+1e4;for(;!await portIsFree(e);)Date.now()>=r&&fail("metroUnavailable",`port ${e} is still held 10 s after stopping pid ${t}; stop the holder and rerun`),await sleep(250)};export const ensureMetro=async(e,t,{fixedPort:r,profiling:o})=>{const s=o?"profiling":"development",i=r?8081:8100;for(let r=8081;r<=i;r++){const i=await probeMetro(r,e);if("ours"===i){const t=servedMode(e,r);return t!==s?fail("metroUnavailable",`Metro on port ${r}: stop the running Metro first; it serves ${t} JavaScript`):(say(`metro: reusing the server on port ${r}`),r)}if("other"===i){const s=readMetroRecord(e);if(s?.port===r&&isNodeProcess(s.pid)&&!await answers(r,5e3))return say(`metro: the server on port ${r} (pid ${s.pid}) does not answer; restarting it, log ${t}`),await stopTree(s.pid),await waitPortFree(r,s.pid),await startMetro(e,r,t,o),r}if("free"===i)return await startMetro(e,r,t,o),r}return fail("metroUnavailable",r?"port 8081 is held by another server (the iOS app always looks there); stop it and rerun":"ports 8081-8100 are all held by other servers; stop one and rerun")};export const restartMetro=async e=>{const t=path.join(logDir(e),"metro.log"),r=readMetroRecord(e);if(r&&isNodeProcess(r.pid))return await stopTree(r.pid),say(`metro: stopped pid ${r.pid} on port ${r.port}`),await waitPortFree(r.port,r.pid),await startMetro(e,r.port,t,"profiling"===r.mode),say(`metro: ready on port ${r.port}`),r.port;const o=r?.port??8081,s=await probeMetro(o,e);return"ours"===s?fail("metroUnavailable",`the Metro on port ${o} was not started by mobile-tools; stop it in its own terminal (Ctrl+C), then run mobile-tools metro restart`):"other"===s?fail("metroUnavailable",`port ${o} is held by another server; stop it and rerun`):(await startMetro(e,o,t,!1),say(`metro: ready on port ${o}`),o)};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
interface ResolutionResult {
|
|
2
|
+
type: string;
|
|
3
|
+
filePath?: string;
|
|
4
|
+
}
|
|
5
|
+
interface ResolveContext {
|
|
6
|
+
resolveRequest: ResolveRequest;
|
|
7
|
+
[key: string]: unknown;
|
|
8
|
+
}
|
|
9
|
+
type ResolveRequest = (context: ResolveContext, moduleName: string, platform: string | null) => ResolutionResult;
|
|
10
|
+
/** The Metro config an app's metro.config.js exports; only the keys this module sets are typed. */
|
|
11
|
+
export interface MetroConfig {
|
|
12
|
+
transformer: {
|
|
13
|
+
minifierConfig?: {
|
|
14
|
+
compress?: Record<string, unknown>;
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
};
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
};
|
|
19
|
+
resolver: {
|
|
20
|
+
resolveRequest?: ResolveRequest;
|
|
21
|
+
[key: string]: unknown;
|
|
22
|
+
};
|
|
23
|
+
serializer: {
|
|
24
|
+
getModulesRunBeforeMainModule: (entryFile: string) => string[];
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
};
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Expo's default Metro config for the app at appRoot (expo/metro-config, resolved from the app),
|
|
31
|
+
* with console calls dropped from minified bundles. An app's metro.config.js:
|
|
32
|
+
* module.exports = require("@webority/mobile-tools/metro-config").createMetroConfig(__dirname);
|
|
33
|
+
* With WEBORITY_PROFILING=1 (mobile-tools run --profiling) the bundle is production JavaScript
|
|
34
|
+
* with the profiling renderer; WEBORITY_PROFILING set during a release bundle is refused.
|
|
35
|
+
*/
|
|
36
|
+
export declare const createMetroConfig: (appRoot: string) => MetroConfig;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Environment } from "./config.js";
|
|
2
|
+
export type OtaPlatform = "android" | "ios";
|
|
3
|
+
/** The compiled settings key holding each platform's OTA component id on the update server. */
|
|
4
|
+
export declare const COMPONENT_KEY: Record<OtaPlatform, string>;
|
|
5
|
+
/** A platform's component id from the settings; a missing or non-numeric id fails, naming the key. */
|
|
6
|
+
export declare const componentIdFor: (settings: Record<string, unknown>, platform: OtaPlatform) => string;
|
|
7
|
+
/**
|
|
8
|
+
* The code-signing key id an app's certificate carries: its common name, which the update server
|
|
9
|
+
* holds the matching private key under. A name that is not a key id (the retired shared
|
|
10
|
+
* certificate included) fails, because the binary would ask for a key the server cannot pick.
|
|
11
|
+
*/
|
|
12
|
+
export declare const codeSigningKeyIdOf: (certificatePem: string, certSetting: string) => string;
|
|
13
|
+
export interface OtaNativeSettings {
|
|
14
|
+
updateUrl: string;
|
|
15
|
+
runtimeVersion: string;
|
|
16
|
+
certificate: string;
|
|
17
|
+
keyId: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The expo-updates settings for one platform, or undefined when the app has no OTA there: no
|
|
21
|
+
* `OTA_UPDATE_BASE_URL`, or no component id for this platform. Once the base URL is set, a missing
|
|
22
|
+
* project id or signing certificate fails, because a binary that cannot verify updates never
|
|
23
|
+
* applies one.
|
|
24
|
+
*/
|
|
25
|
+
export declare const otaNativeSettings: (appRoot: string, settings: Record<string, unknown>, env: Environment, platform: OtaPlatform, otaTest: boolean) => OtaNativeSettings | undefined;
|
|
26
|
+
/** The Android meta-data expo-updates reads, in the order a new entry is written. */
|
|
27
|
+
export declare const androidOtaMetaData: (ota: OtaNativeSettings) => [string, string][];
|
|
28
|
+
/**
|
|
29
|
+
* The whole generated flavor manifest. With OTA off it holds only ENABLED false, which switches
|
|
30
|
+
* expo-updates off for the flavor. A newline in a value is written as ` `, the one form an XML
|
|
31
|
+
* parser keeps inside an attribute.
|
|
32
|
+
*/
|
|
33
|
+
export declare const androidOtaManifest: (ota: OtaNativeSettings | undefined) => string;
|
|
34
|
+
type PlistValue = string | number | boolean | Record<string, string>;
|
|
35
|
+
/** The Expo.plist keys expo-updates reads on iOS, in the order a new key is written. */
|
|
36
|
+
export declare const iosOtaPlistKeys: (ota: OtaNativeSettings) => [string, PlistValue][];
|
|
37
|
+
/**
|
|
38
|
+
* The whole generated Expo.plist. With OTA off it holds only EXUpdatesEnabled false. Tabs indent it
|
|
39
|
+
* the way Xcode writes its plists.
|
|
40
|
+
*/
|
|
41
|
+
export declare const expoPlist: (ota: OtaNativeSettings | undefined) => string;
|
|
42
|
+
export {};
|
package/lib/output.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Why a command stopped. badInput exits 2; every other code exits 1. */
|
|
2
|
+
export type ErrorCode = "badInput" | "appConfigInvalid" | "toolMissing" | "toolFailed" | "buildFailed" | "artifactMissing" | "deviceNotFound" | "deviceAmbiguous" | "platformUnavailable" | "installStale" | "metroUnavailable";
|
|
3
|
+
/** A failure the CLI reports as one {code, message} and a non-zero exit, without a stack trace. */
|
|
4
|
+
export declare class CliError extends Error {
|
|
5
|
+
readonly code: ErrorCode;
|
|
6
|
+
readonly exitCode: 1 | 2;
|
|
7
|
+
constructor(code: ErrorCode, message: string);
|
|
8
|
+
}
|
|
9
|
+
export declare const fail: (code: ErrorCode, message: string) => never;
|
|
10
|
+
/** Set once by cli.ts, before the command runs, for a command given --json. */
|
|
11
|
+
export declare const setJsonOutput: (on: boolean) => void;
|
|
12
|
+
export declare const isJsonOutput: () => boolean;
|
|
13
|
+
/** A progress line: stdout, or stderr while stdout carries the command's JSON document. */
|
|
14
|
+
export declare const say: (message: string) => void;
|
|
15
|
+
export declare const warn: (message: string) => void;
|
|
16
|
+
/** The command's one JSON document on stdout. */
|
|
17
|
+
export declare const sayJson: (value: unknown) => void;
|
|
18
|
+
/** The one way a failure is printed: the {code, message} JSON document, or one stderr line. */
|
|
19
|
+
export declare const reportFailure: (error: CliError) => void;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
export type HostPlatform = NodeJS.Platform;
|
|
3
|
+
/** The Android ABIs Gradle builds, as the tokens -PreactNativeArchitectures takes. */
|
|
4
|
+
export declare const ANDROID_ABIS: readonly ["arm64-v8a", "armeabi-v7a", "x86_64", "x86"];
|
|
5
|
+
/** The ABI token Gradle receives; anything else from a device is refused rather than passed on. */
|
|
6
|
+
export declare const ABI_PATTERN: RegExp;
|
|
7
|
+
/** The ABIs a comma list of --arch names for apk or aab, de-duplicated in the order given. `arm64` means arm64-v8a. */
|
|
8
|
+
export declare const parseAndroidAbis: (value: string) => string[];
|
|
9
|
+
export type Env = Record<string, string | undefined>;
|
|
10
|
+
/** A program and its arguments, ready for spawn without a shell. */
|
|
11
|
+
export interface Invocation {
|
|
12
|
+
file: string;
|
|
13
|
+
args: string[];
|
|
14
|
+
/** Set only for the cmd.exe hop that runs a .bat file, see gradleInvocation. */
|
|
15
|
+
windowsVerbatimArguments?: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** The path flavour of the host, so a Windows path is built with Windows rules on any machine. */
|
|
18
|
+
export declare const pathFor: (platform: HostPlatform) => typeof path.posix;
|
|
19
|
+
/**
|
|
20
|
+
* The environment every child gets. `NoDefaultCurrentDirectoryInExePath` is set by some agent
|
|
21
|
+
* shells and stops cmd.exe finding `gradlew.bat` in the current folder, so it never reaches a
|
|
22
|
+
* child, under any casing.
|
|
23
|
+
*/
|
|
24
|
+
export declare const childEnv: (env: Env) => Env;
|
|
25
|
+
/** The absolute path of a program on PATH. On Windows only `.exe` counts: nothing here spawns a script shim. */
|
|
26
|
+
export declare const findOnPath: (name: string, env: Env, platform: HostPlatform, exists?: (file: string) => boolean) => string | undefined;
|
|
27
|
+
/** adb from the SDK named by ANDROID_HOME, else the first adb on PATH. */
|
|
28
|
+
export declare const adbPath: (env: Env, platform: HostPlatform, exists?: (file: string) => boolean) => string;
|
|
29
|
+
/**
|
|
30
|
+
* How to run the Gradle wrapper. POSIX runs `android/gradlew` directly. Windows runs
|
|
31
|
+
* `android/gradlew.bat`, which Node can only start through cmd.exe (it refuses to spawn a .bat
|
|
32
|
+
* without a shell), so cmd.exe is named by absolute path and every argument is checked to be a
|
|
33
|
+
* plain token first.
|
|
34
|
+
*/
|
|
35
|
+
export declare const gradleInvocation: (androidDir: string, args: string[], platform: HostPlatform, env: Env) => Invocation;
|
|
36
|
+
/** iOS commands exist only on macOS; elsewhere they stop with one line. */
|
|
37
|
+
export declare const requireDarwin: (platform: HostPlatform, what: string) => void;
|
|
38
|
+
/** The warning text when the app folder is too deep for the Windows Android native build, else undefined. */
|
|
39
|
+
export declare const longWindowsPathWarning: (appRoot: string, platform: HostPlatform) => string | undefined;
|
|
40
|
+
export declare const warnLongWindowsPath: (appRoot: string) => void;
|
|
41
|
+
export declare const XCRUN = "/usr/bin/xcrun";
|
|
42
|
+
/**
|
|
43
|
+
* npm as `node <npm-cli.js>`: on Windows `npm` is a .cmd shim Node will not spawn without a
|
|
44
|
+
* shell. npm_execpath is set when this CLI itself runs under npm or npx.
|
|
45
|
+
*/
|
|
46
|
+
export declare const npmInvocation: (args: string[], env: Env, platform: HostPlatform, execPath: string, exists?: (file: string) => boolean) => Invocation;
|
|
47
|
+
/** pnpm as its own executable, or as `node <pnpm.cjs>` when this CLI runs under pnpm. */
|
|
48
|
+
export declare const pnpmInvocation: (args: string[], env: Env, platform: HostPlatform, execPath: string, exists?: (file: string) => boolean) => Invocation;
|
|
49
|
+
/**
|
|
50
|
+
* The Firebase CLI. On Windows `firebase` is a .cmd shim Node will not spawn without a shell, so the
|
|
51
|
+
* script it wraps runs under node instead.
|
|
52
|
+
*/
|
|
53
|
+
export declare const firebaseInvocation: (args: string[], env: Env, platform: HostPlatform, execPath: string, exists?: (file: string) => boolean) => Invocation | undefined;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { type AppSettings, type Environment, type ToolsConfig } from "./config.js";
|
|
2
|
+
export type MobilePlatform = "android" | "ios";
|
|
3
|
+
export declare const IOS_COMPILED_XCCONFIG = "ios/appsettings.Compiled.xcconfig";
|
|
4
|
+
/** The generated expo-updates manifest of the environment's flavor. */
|
|
5
|
+
export declare const androidFlavorManifest: (env: Environment) => string;
|
|
6
|
+
export declare const expoPlistPath: (iosProjectName: string) => string;
|
|
7
|
+
/** An app on expo-updates: package.json dependencies name it. */
|
|
8
|
+
export declare const usesExpoUpdates: (appRoot: string) => boolean;
|
|
9
|
+
/** Every file prebuild writes for this environment and platform, relative to the app root; each must be git-ignored. */
|
|
10
|
+
export declare const generatedNativeFiles: (appRoot: string, iosProjectName: string | undefined, env: Environment, platform: MobilePlatform) => string[];
|
|
11
|
+
/** The native inputs prebuild generated for the platform (file bytes plus APP_ID, APP_NAME, VERSION_DISPLAY, VERSION_INTERNAL), as one stable text for the build cache key. */
|
|
12
|
+
export declare const nativeBuildInputs: (appRoot: string, platform: MobilePlatform) => string;
|
|
13
|
+
/**
|
|
14
|
+
* The INFOPLIST_FILE of every app and extension target in a project.pbxproj, as written there
|
|
15
|
+
* (relative to the ios folder, or under $(SRCROOT)), each named with its target.
|
|
16
|
+
*/
|
|
17
|
+
export declare const shippedInfoPlists: (text: string) => {
|
|
18
|
+
target: string;
|
|
19
|
+
file: string;
|
|
20
|
+
}[];
|
|
21
|
+
/**
|
|
22
|
+
* The bundle id and version keys in an Info.plist text that hold a fixed value instead of the
|
|
23
|
+
* build setting prebuild writes. A key the plist leaves out is fine: Xcode fills it from the setting.
|
|
24
|
+
*/
|
|
25
|
+
export declare const fixedInfoPlistValues: (text: string) => {
|
|
26
|
+
key: string;
|
|
27
|
+
value: string;
|
|
28
|
+
setting: string;
|
|
29
|
+
}[];
|
|
30
|
+
/**
|
|
31
|
+
* prebuild writes the bundle id and versions into the xcconfig only, so a shipped Info.plist
|
|
32
|
+
* holding its own fixed value would build under that id or version whatever the environment. The
|
|
33
|
+
* app's own plist shows the name the xcconfig sets.
|
|
34
|
+
*/
|
|
35
|
+
export declare const checkInfoPlistReferences: (appRoot: string, projectName: string) => void;
|
|
36
|
+
/**
|
|
37
|
+
* The project-level configurations must take their base configuration from the xcconfig, and no
|
|
38
|
+
* configuration may set a value the xcconfig owns: a setting in either place would win over the other.
|
|
39
|
+
*/
|
|
40
|
+
export declare const checkPbxprojSettings: (text: string, hasIconSet: boolean) => void;
|
|
41
|
+
/**
|
|
42
|
+
* The short HEAD sha, with -dirty when the app folder has uncommitted changes. prebuild writes only
|
|
43
|
+
* git-ignored files, so none of them can read dirty. "nogit" when the folder is not a git checkout.
|
|
44
|
+
*/
|
|
45
|
+
export declare const buildCommit: (appRoot: string) => string;
|
|
46
|
+
/**
|
|
47
|
+
* Refuses a generated file git would track: the app's .gitignore must list every file prebuild
|
|
48
|
+
* writes, so no environment's values can reach a commit. A file that is tracked reads as not ignored.
|
|
49
|
+
*/
|
|
50
|
+
export declare const requireIgnored: (appRoot: string, files: string[]) => void;
|
|
51
|
+
/**
|
|
52
|
+
* An app on React Native Firebase cannot build without its Firebase config: the Android Gradle
|
|
53
|
+
* plugin fails, and on iOS the Crashlytics build phase fails, or a release ships reporting no crashes.
|
|
54
|
+
*/
|
|
55
|
+
export declare const usesFirebase: (appRoot: string) => boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Libraries that compile native code without reading ext.ndkVersion (expo-updates, expo-sqlite)
|
|
58
|
+
* take the Android Gradle plugin's default NDK, which the read-only CI SDK does not have, so the
|
|
59
|
+
* root build.gradle must hand them the app's version. A project without the file is left to Gradle.
|
|
60
|
+
*/
|
|
61
|
+
export declare const checkNdkHook: (appRoot: string) => void;
|
|
62
|
+
export declare const stampAndroid: (appRoot: string, settings: AppSettings, env: Environment, config: ToolsConfig, otaTest: boolean) => void;
|
|
63
|
+
export declare const stampIos: (appRoot: string, settings: AppSettings, env: Environment, config: ToolsConfig, projectName: string, otaTest: boolean) => void;
|
|
64
|
+
export interface PrebuildOptions {
|
|
65
|
+
appRoot: string;
|
|
66
|
+
env?: Environment;
|
|
67
|
+
sameEnv?: boolean;
|
|
68
|
+
platform?: MobilePlatform;
|
|
69
|
+
/** Only `build --ota-test` sets it: the OTA runtime version gets the `-otatest` suffix. */
|
|
70
|
+
otaTest?: boolean;
|
|
71
|
+
}
|
|
72
|
+
/** Compiles appsettings and stamps the native layers. Returns the settings it compiled. */
|
|
73
|
+
export declare const prebuild: (options: PrebuildOptions) => AppSettings;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type Renderer = unknown;
|
|
2
|
+
interface DevToolsHook {
|
|
3
|
+
supportsFiber: true;
|
|
4
|
+
renderers: Map<number, Renderer>;
|
|
5
|
+
inject(renderer: Renderer): number;
|
|
6
|
+
onCommitFiberRoot(rendererId: number, root: unknown): void;
|
|
7
|
+
onCommitFiberUnmount(rendererId: number, fiber: unknown): void;
|
|
8
|
+
onPostCommitFiberRoot(rendererId: number, root: unknown): void;
|
|
9
|
+
getFiberRoots(rendererId: number): Set<unknown>;
|
|
10
|
+
checkDCE(fn: unknown): void;
|
|
11
|
+
}
|
|
12
|
+
declare global {
|
|
13
|
+
var __REACT_DEVTOOLS_GLOBAL_HOOK__: DevToolsHook | undefined;
|
|
14
|
+
var __WEBORITY_PROFILING__: boolean | undefined;
|
|
15
|
+
}
|
|
16
|
+
export {};
|
package/lib/profilingHook.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
if(void 0===globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__){const e=new Map,o=new Map;let t=1;globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__={supportsFiber:!0,renderers:e,inject(_){const i=t++;return e.set(i,_),o.set(i,new Set),i},onCommitFiberRoot(e,t){o.get(e)?.add(t)},onCommitFiberUnmount(){},onPostCommitFiberRoot(){},getFiberRoots:e=>o.get(e)??new Set,checkDCE(){}}}globalThis.__WEBORITY_PROFILING__=!0;export{};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one part of a build log worth printing. Metro's "Unable to resolve module" comes first
|
|
3
|
+
* when present: Gradle reports that failure only as a generic non-zero exit of the bundling
|
|
4
|
+
* command, at the very end of the build. Then Gradle's first "What went wrong" block, then
|
|
5
|
+
* compiler-style "error:" lines (xcodebuild), then the log's tail.
|
|
6
|
+
*/
|
|
7
|
+
export declare const extractRootError: (log: string) => string;
|
package/lib/run.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type Environment } from "./config.js";
|
|
2
|
+
import { type MobilePlatform } from "./prebuild.js";
|
|
3
|
+
export interface RunOptions {
|
|
4
|
+
appRoot: string;
|
|
5
|
+
env: Environment;
|
|
6
|
+
platform: MobilePlatform;
|
|
7
|
+
device?: string;
|
|
8
|
+
rebuild: boolean;
|
|
9
|
+
/** Serve production JavaScript with the profiling renderer; the native build is the same debug build. */
|
|
10
|
+
profiling: boolean;
|
|
11
|
+
/** iOS only and required there: the simulator .app built by `build --artifact ios-sim`; run never builds for iOS. */
|
|
12
|
+
app?: string;
|
|
13
|
+
}
|
|
14
|
+
/** The Android namespace from build.gradle (`namespace "x"` or `namespace = 'x'`); MainActivity lives in it. */
|
|
15
|
+
export declare const readNamespace: (buildGradle: string) => string | undefined;
|
|
16
|
+
/** The APK a debug build produced, preferring one built for the device's ABI. */
|
|
17
|
+
export declare const chooseApk: (files: string[], abi: string) => string | undefined;
|
|
18
|
+
/** adb install can exit 0 while printing `Failure [INSTALL_FAILED_...]`, so its output decides. */
|
|
19
|
+
export declare const installFailure: (output: string) => string | undefined;
|
|
20
|
+
/** Why an install failed, read from adb's stderr and stdout together; never empty. */
|
|
21
|
+
export declare const installFailureReason: (stderr: string, stdout: string, serial: string, appId: string) => string;
|
|
22
|
+
/**
|
|
23
|
+
* The app's default-preferences XML with React Native's bundler host set to `host`, or with it removed
|
|
24
|
+
* when `host` is undefined. Every other preference is kept.
|
|
25
|
+
*/
|
|
26
|
+
export declare const withDevHost: (xml: string, host: string | undefined) => string;
|
|
27
|
+
/** Guard, pick a device, prebuild, build for that device only, install, Metro, launch. */
|
|
28
|
+
export declare const run: (options: RunOptions) => Promise<void>;
|
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{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
|
|
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)??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/symbols.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Environment } from "./config.js";
|
|
2
|
+
/** The Firebase app id a GoogleService-Info.plist names; Crashlytics files an app's symbols under it. */
|
|
3
|
+
export declare const googleAppId: (plistXml: string) => string | undefined;
|
|
4
|
+
export declare const uploadSymbols: (opts: {
|
|
5
|
+
appRoot: string;
|
|
6
|
+
env: Environment;
|
|
7
|
+
dsym: string;
|
|
8
|
+
}) => Promise<void>;
|
package/lib/sync.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type HostPlatform, type Invocation } from "./platform.js";
|
|
2
|
+
export declare const STAMP_FILE: string;
|
|
3
|
+
/** The native packages the last pod install ran against; a change to them means the pods are stale. */
|
|
4
|
+
export declare const PODS_RECORD: string;
|
|
5
|
+
export type PackageManager = "npm" | "pnpm";
|
|
6
|
+
export interface InstallStamp {
|
|
7
|
+
hash: string;
|
|
8
|
+
manager: PackageManager;
|
|
9
|
+
nativePackages?: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
export declare const lockfileOf: (appRoot: string) => {
|
|
12
|
+
manager: PackageManager;
|
|
13
|
+
file: string;
|
|
14
|
+
};
|
|
15
|
+
/** One hash over the lockfile, the install-relevant package.json fields and patches/. */
|
|
16
|
+
export declare const installHash: (appRoot: string) => string;
|
|
17
|
+
export declare const readStamp: (appRoot: string) => InstallStamp | undefined;
|
|
18
|
+
export declare const podsStale: (appRoot: string) => boolean;
|
|
19
|
+
/**
|
|
20
|
+
* What is stale, as messages that each end with the command that fixes it. Empty when the tree
|
|
21
|
+
* matches its lockfiles. Reads files only, so it answers well inside a second. An Android build
|
|
22
|
+
* passes `withPods` false: it never reads ios/Pods.
|
|
23
|
+
*/
|
|
24
|
+
export declare const checkSync: (appRoot: string, platform: HostPlatform, withPods?: boolean) => string[];
|
|
25
|
+
/** Stops a build or run before it starts when node_modules (or, with `pods`, ios/Pods) no longer matches the lockfiles. */
|
|
26
|
+
export declare const requireSynced: (appRoot: string, { pods }: {
|
|
27
|
+
pods: boolean;
|
|
28
|
+
}) => void;
|
|
29
|
+
/** Top-level packages that ship an android/ folder, name to version. Autolinking reads only these. */
|
|
30
|
+
export declare const nativePackages: (appRoot: string) => Record<string, string>;
|
|
31
|
+
/** Native packages added, removed or moved between two snapshots, sorted. */
|
|
32
|
+
export declare const changedNativePackages: (before: Record<string, string>, after: Record<string, string>) => string[];
|
|
33
|
+
/** What the pod install record holds: the native packages and pod inputs the last pod install ran against. */
|
|
34
|
+
export declare const podsRecord: (appRoot: string) => string;
|
|
35
|
+
/**
|
|
36
|
+
* Records that node_modules matches the lockfile now. `sync` calls it after its install; an app
|
|
37
|
+
* also calls it from `postinstall` (`mobile-tools sync --stamp`), so a plain `npm ci` or
|
|
38
|
+
* `pnpm install` leaves an accurate stamp and `sync --check` never asks for a needless reinstall.
|
|
39
|
+
*/
|
|
40
|
+
export declare const writeStamp: (appRoot: string) => Required<InstallStamp>;
|
|
41
|
+
export declare const installInvocation: (manager: PackageManager, platform: HostPlatform) => Invocation;
|
|
42
|
+
/** The names of the pods whose EXTERNAL SOURCES entry is a local `:path:` (a node_modules folder), in lock order. */
|
|
43
|
+
export declare const localPathPods: (podfileLock: string) => string[];
|
|
44
|
+
/**
|
|
45
|
+
* Reinstalls ios/Pods when it is missing or out of step with ios/Podfile.lock, the installed
|
|
46
|
+
* native packages or the pod inputs (ios/Podfile, ios/Podfile.properties.json), then records what that install ran against.
|
|
47
|
+
* Does nothing without an ios/Podfile.
|
|
48
|
+
* When a package upgrade moved local pods, one `pod update` refreshes all of them together, since
|
|
49
|
+
* CocoaPods stops at each moved pod it is asked to update alone.
|
|
50
|
+
*/
|
|
51
|
+
export declare const ensurePods: (appRoot: string, platform: HostPlatform) => void;
|
|
52
|
+
/**
|
|
53
|
+
* Installs from the lockfile, stamps node_modules, and when a native package moved, regenerates
|
|
54
|
+
* library codegen and drops the CMake caches that still point at the old output. On a Mac or the
|
|
55
|
+
* xOS build host it also brings ios/Pods in line with Podfile.lock.
|
|
56
|
+
*/
|
|
57
|
+
export declare const sync: (appRoot: string, platform: HostPlatform) => void;
|
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{capture,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 s=path.join(e,"pnpm-lock.yaml"),
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import path from"node:path";import{isRecord}from"./config.js";import{capture,runInherit}from"./exec.js";import{CliError,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 s=path.join(e,"pnpm-lock.yaml"),o=path.join(e,"package-lock.json");return existsSync(s)&&existsSync(o)?fail("appConfigInvalid","both pnpm-lock.yaml and package-lock.json exist: delete the one not in use"):existsSync(s)?{manager:"pnpm",file:s}:existsSync(o)?{manager:"npm",file:o}:fail("appConfigInvalid",`no package-lock.json or pnpm-lock.yaml in ${e}`)};const filesUnder=(e,s="")=>readdirSync(e,{withFileTypes:!0}).flatMap(o=>{const n=""===s?o.name:`${s}/${o.name}`;return o.isDirectory()?filesUnder(path.join(e,o.name),n):[n]}).sort();export const installHash=e=>{const{file:s}=lockfileOf(e),o=JSON.parse(readFileSync(path.join(e,"package.json"),"utf8"));if(!isRecord(o))return fail("appConfigInvalid",`${path.join(e,"package.json")} must hold a JSON object`);const n=createHash("sha256");n.update(`lockfile:${path.basename(s)}\0`),n.update(readFileSync(s)),n.update("\0package.json\0"),n.update(JSON.stringify(INSTALL_FIELDS.map(e=>[e,o[e]??null])));const t=path.join(e,"patches");if(existsSync(t))for(const e of filesUnder(t))n.update(`\0patches/${e}\0`),n.update(readFileSync(path.join(t,...e.split("/"))));return n.digest("hex")};const isInstallStamp=e=>isRecord(e)&&"string"==typeof e.hash&&("npm"===e.manager||"pnpm"===e.manager)&&(void 0===e.nativePackages||isRecord(e.nativePackages)&&Object.values(e.nativePackages).every(e=>"string"==typeof e));export const readStamp=e=>{const s=path.join(e,STAMP_FILE);if(existsSync(s))try{const e=JSON.parse(readFileSync(s,"utf8"));return isInstallStamp(e)?e:void 0}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 s=path.join(e,"ios","Podfile.lock"),o=path.join(e,"ios","Pods","Manifest.lock");return!(!existsSync(s)||!existsSync(o))&&!readFileSync(s).equals(readFileSync(o))};const nodeModulesNewerThanPods=e=>{const s=[path.join(e,"node_modules",".modules.yaml"),path.join(e,"node_modules",".pnpm","lock.yaml")].find(e=>existsSync(e)),o=path.join(e,"ios","Pods","Manifest.lock");return!(!s||!existsSync(o))&&statSync(s).mtimeMs>statSync(o).mtimeMs};export const checkSync=(e,s,o=!0)=>{const n=[],t=readStamp(e),{file:a}=lockfileOf(e);if(t?t.hash!==installHash(e)&&n.push(`node_modules is stale: ${path.basename(a)}, package.json or patches/ changed since the last install. Fix: npx mobile-tools sync`):n.push("node_modules has no install stamp (never installed through mobile-tools). Fix: npx mobile-tools sync"),t){const s=changedNativePackages(t.nativePackages??{},nativePackages(e));s.length>0&&n.push(`node_modules native packages changed since the last install: ${s.join(", ")}. Fix: npx mobile-tools sync`)}const i=o&&installsPods(s);return i&&podsStale(e)&&n.push(`ios/Pods is stale: ios/Podfile.lock differs from ios/Pods/Manifest.lock. Fix: ${POD_FIX}`),i&&existsSync(path.join(e,"ios","Podfile.lock"))&&nodeModulesNewerThanPods(e)&&n.push("node_modules changed after the last pod install; run pod install in ios/ (or mobile-tools sync)"),n};export const requireSynced=(e,{pods:s})=>{const o=checkSync(e,process.platform,s);o.length>0&&fail("installStale",o.join("\n"))};export const nativePackages=e=>{const s=path.join(e,"node_modules");if(!existsSync(s))return{};const o=[];for(const e of readdirSync(s,{withFileTypes:!0}))if(!e.name.startsWith(".")&&e.isDirectory())if(e.name.startsWith("@"))for(const n of readdirSync(path.join(s,e.name),{withFileTypes:!0}))n.isDirectory()&&o.push(path.join(s,e.name,n.name));else o.push(path.join(s,e.name));const n={};for(const e of o){const s=path.join(e,"android"),o=path.join(e,"package.json");if(existsSync(s)&&statSync(s).isDirectory()&&existsSync(o))try{const e=JSON.parse(readFileSync(o,"utf8"));isRecord(e)&&"string"==typeof e.name&&"string"==typeof e.version&&""!==e.name&&""!==e.version&&(n[e.name]=e.version)}catch(e){fail("toolFailed",`${o} is not valid package.json, so its native package cannot be read: ${e instanceof Error?e.message:String(e)}`)}}return n};export const changedNativePackages=(e,s)=>[...new Set([...Object.keys(e),...Object.keys(s)])].filter(o=>e[o]!==s[o]).sort();const POD_INPUT_FILES=["ios/Podfile","ios/Podfile.properties.json"],podInputsHash=e=>{const s=createHash("sha256");for(const o of POD_INPUT_FILES){const n=path.join(e,...o.split("/"));s.update(`${o}\0`),existsSync(n)&&s.update(readFileSync(n))}return s.digest("hex")};export const podsRecord=e=>JSON.stringify({nativePackages:nativePackages(e),podInputs:podInputsHash(e)});export const writeStamp=e=>{const{manager:s}=lockfileOf(e),o={hash:installHash(e),manager:s,nativePackages:nativePackages(e)};return writeFileSync(path.join(e,STAMP_FILE),`${JSON.stringify(o,null,2)}\n`,"utf8"),o};export const installInvocation=(e,s)=>"pnpm"===e?pnpmInvocation(["install","--frozen-lockfile"],process.env,s,process.execPath):npmInvocation(["ci"],process.env,s,process.execPath);export const localPathPods=e=>{const s=[];let o,n=!1;for(const t of e.split(/\r?\n/)){if(/^\S/.test(t)){n="EXTERNAL SOURCES:"===t,o=void 0;continue}if(!n)continue;const e=/^ {2}"?([^"\s:]+)"?:$/.exec(t);e?o=e[1]:void 0!==o&&/^ {4}:path:/.test(t)&&(s.push(o),o=void 0)}return s};const recordChange=(e,s)=>{let o;try{o=JSON.parse(e)}catch{return"the pod install record is from an older mobile-tools"}return isRecord(o)&&"string"==typeof o.podInputs&&isRecord(o.nativePackages)?o.podInputs!==podInputsHash(s)?"ios/Podfile or ios/Podfile.properties.json changed since the last pod install":JSON.stringify(o.nativePackages)!==JSON.stringify(nativePackages(s))?"native packages changed since the last pod install":void 0:"the pod install record is from an older mobile-tools"},POD_VERSION_MOVED=/changed the version of the dependency|pod update/,runPod=(e,s,o)=>{const n=capture({file:e,args:s},o);return-1===n.status&&fail("toolFailed",`pod ${s[0]} could not start: ${n.stderr}`),process.stdout.write(n.stdout),process.stderr.write(n.stderr),n};export const ensurePods=(e,s)=>{if(!existsSync(path.join(e,"ios","Podfile")))return;const o=path.join(e,"ios","Pods"),n=path.join(e,PODS_RECORD);let t;if(t=existsSync(o)?existsSync(path.join(e,"ios","Podfile.lock"))?existsSync(path.join(o,"Manifest.lock"))?podsStale(e)?"ios/Podfile.lock differs from ios/Pods/Manifest.lock":nodeModulesNewerThanPods(e)?"node_modules changed after the last pod install":existsSync(n)?recordChange(readFileSync(n,"utf8"),e):"no pod install record":"ios/Pods/Manifest.lock is missing":"ios/Podfile.lock is missing":"ios/Pods is missing",void 0===t)return void say("pods: up to date with ios/Podfile.lock and the Podfile settings");say(`pods: ${t}; running pod install`);const a=findOnPath("pod",process.env,s);if(!a){const e=hasXos(s)?"check xos doctor --json names its shims folder":"install CocoaPods (brew install cocoapods)";throw new CliError("toolMissing",`pod not found on PATH; ${e}, then ${POD_FIX}`)}const i=path.join(e,"ios");let c=runPod(a,["install"],i);if(0!==c.status&&POD_VERSION_MOVED.test(`${c.stdout}${c.stderr}`)){const e=path.join(i,"Podfile.lock"),s=existsSync(e)?localPathPods(readFileSync(e,"utf8")):[];s.length>0&&(say(`pods: updating ${s.length} local pods moved by a package upgrade`),c=runPod(a,["update",...s,"--no-repo-update"],i),0!==c.status&&fail("toolFailed",`pod update failed (exit ${c.status})`))}0!==c.status&&fail("toolFailed",`pod install failed (exit ${c.status})`);const r=path.join(e,"ios","build","ModuleCache.noindex");existsSync(r)&&(rmSync(r,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,r)}`)),writeFileSync(n,podsRecord(e),"utf8")};export const sync=(e,s)=>{const{manager:o}=lockfileOf(e),n=readStamp(e)?.nativePackages??nativePackages(e);say("sync: "+("pnpm"===o?"pnpm install --frozen-lockfile":"npm ci")),runInherit(installInvocation(o,s),e,`${o} install`);const t=writeStamp(e).nativePackages,a=changedNativePackages(n,t),i=path.join(e,"android"),c=existsSync(path.join(i,"app",".cxx"))||existsSync(path.join(i,"app","build"));if(a.length>0&&c){say(`sync: native packages changed (${a.join(", ")}): regenerating codegen`),runInherit(gradleInvocation(i,["generateCodegenArtifactsFromSchema"],s,process.env),i,"gradlew generateCodegenArtifactsFromSchema");for(const s of[path.join(i,"app",".cxx"),path.join(i,"app","build","generated","autolinking")])rmSync(s,{recursive:!0,force:!0}),say(`sync: removed ${path.relative(e,s)}`)}installsPods(s)&&existsSync(path.join(e,"ios","Podfile"))&&(hasXos(s)&&prependXosShims(xosPath(process.env,s),e),ensurePods(e,s)),say("sync: done")};
|
package/lib/xos.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Env, type HostPlatform } from "./platform.js";
|
|
2
|
+
/** The simulator architectures xOS Tools builds: x86_64 for an Intel Mac, arm64 for Apple silicon. */
|
|
3
|
+
export type SimulatorArch = "x86_64" | "arm64";
|
|
4
|
+
export declare const SIMULATOR_ARCHS: readonly SimulatorArch[];
|
|
5
|
+
export type IosConfiguration = "Debug" | "Release";
|
|
6
|
+
export interface XosSimulatorBuild {
|
|
7
|
+
appRoot: string;
|
|
8
|
+
projectName: string;
|
|
9
|
+
configuration: IosConfiguration;
|
|
10
|
+
arch: SimulatorArch;
|
|
11
|
+
}
|
|
12
|
+
export declare 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>.";
|
|
13
|
+
/** xos on PATH, else toolMissing with the recipe for building on a host that has xos. */
|
|
14
|
+
export declare const xosPath: (env: Env, platform: HostPlatform) => string;
|
|
15
|
+
/** Puts the shim folder `xos doctor --json` names (field `shims`) first on this process's PATH, as ios-release.sh does before pod install. */
|
|
16
|
+
export declare const prependXosShims: (xos: string, cwd: string) => void;
|
|
17
|
+
/** Where an ios-sim build writes its pods, intermediates and app. */
|
|
18
|
+
export declare const simulatorBuildDir: (appRoot: string, configuration: IosConfiguration) => string;
|
|
19
|
+
/** `xos build --pods` then `xos app` for the simulator, both into `log`; returns the absolute path of <projectName>.app. */
|
|
20
|
+
export declare const xosSimulatorBuild: (xos: string, build: XosSimulatorBuild, log: string) => Promise<string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.150.0",
|
|
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",
|
|
@@ -24,8 +24,14 @@
|
|
|
24
24
|
},
|
|
25
25
|
"exports": {
|
|
26
26
|
"./package.json": "./package.json",
|
|
27
|
-
"./metro-config":
|
|
28
|
-
|
|
27
|
+
"./metro-config": {
|
|
28
|
+
"types": "./lib/metroConfig.d.ts",
|
|
29
|
+
"default": "./lib/metroConfig.js"
|
|
30
|
+
},
|
|
31
|
+
"./profiling-hook": {
|
|
32
|
+
"types": "./lib/profilingHook.d.ts",
|
|
33
|
+
"default": "./lib/profilingHook.js"
|
|
34
|
+
}
|
|
29
35
|
},
|
|
30
36
|
"files": [
|
|
31
37
|
"lib",
|
|
@@ -50,7 +56,7 @@
|
|
|
50
56
|
"@types/node": "25.6.0",
|
|
51
57
|
"@webority/mobile-dev": "0.0.0",
|
|
52
58
|
"jest": "29.7.0",
|
|
53
|
-
"typescript": "
|
|
59
|
+
"typescript": "7.0.2"
|
|
54
60
|
},
|
|
55
61
|
"scripts": {
|
|
56
62
|
"build": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node ../mobile-dev/scripts/minify-lib.mjs",
|