@webority/mobile-tools 0.146.2 → 0.147.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/config.js +1 -1
- package/lib/devices.js +1 -1
- package/lib/doctor.js +1 -1
- package/lib/icons.js +1 -1
- package/lib/keystore.js +1 -1
- package/lib/otaNative.js +1 -1
- package/lib/prebuild.js +1 -1
- package/lib/rootError.js +1 -1
- package/package.json +1 -1
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
|
|
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)}`)}},isRecord=t=>"object"==typeof t&&null!==t&&!Array.isArray(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)=>{Array.isArray(t)&&!t.some(t=>"string"!=typeof t)||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.includes(o)&&fail("appConfigInvalid",`${e}: "requiredSettings" lists ${o}, which prebuild always requires; remove it`),n.add(o)};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.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:t.iosProjectName,flavors:t.flavors??!0,localApiPort:t.localApiPort,iconSource:t.iconSource,firebasePlistDir:t.firebasePlistDir??path.join("ios","firebase"),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 a=o.filter(t=>void 0===i[t]||null===i[t]);return a.length>0&&fail("appConfigInvalid",`appsettings (${n}) is missing setting(s) mobile-tools.config.json requires: ${a.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.`),/^[1-9][0-9]*$/.test(String(i.VERSION_INTERNAL))||fail("appConfigInvalid",`VERSION_INTERNAL must be a positive whole number, not ${JSON.stringify(i.VERSION_INTERNAL)}`),APP_ID_PATTERN.test(String(i.APP_ID))||fail("appConfigInvalid",`APP_ID ${JSON.stringify(i.APP_ID)} is not a reverse-domain id such as com.example.app`),i};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.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Socket}from"node:net";import{createInterface}from"node:readline/promises";import{capture}from"./exec.js";import{listAppleDevices}from"./ios.js";import{fail,isJsonOutput,say,sayJson,warn}from"./output.js";import{adbPath,requireDarwin}from"./platform.js";export const parseAdbDevices=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>""!==e&&!e.startsWith("List of devices")&&!e.startsWith("*")).map(e=>{const[t,o=""]=e.split(/\s+/);return{serial:t,state:o}});const serialRank=e=>e.startsWith("emulator-")?1:e.includes(":")?2:0,deviceKey=e=>""!==e.serialNo?`${e.serialNo}|${e.androidId}`:/^[0-9a-f]{16}$/i.test(e.androidId)?`android:${e.androidId}`:`serial:${e.serial}`;export const dedupeDevices=e=>{const t=new Map;for(const o of e){const e=deviceKey(o);t.set(e,[...t.get(e)??[],o])}return[...t.values()].map(e=>{const t=e.
|
|
1
|
+
import{Socket}from"node:net";import{createInterface}from"node:readline/promises";import{capture}from"./exec.js";import{listAppleDevices}from"./ios.js";import{fail,isJsonOutput,say,sayJson,warn}from"./output.js";import{adbPath,requireDarwin}from"./platform.js";export const parseAdbDevices=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>""!==e&&!e.startsWith("List of devices")&&!e.startsWith("*")).map(e=>{const[t,o=""]=e.split(/\s+/);if(void 0===t)throw new Error("a non-empty adb line starts with its serial");return{serial:t,state:o}});const serialRank=e=>e.startsWith("emulator-")?1:e.includes(":")?2:0,deviceKey=e=>""!==e.serialNo?`${e.serialNo}|${e.androidId}`:/^[0-9a-f]{16}$/i.test(e.androidId)?`android:${e.androidId}`:`serial:${e.serial}`;export const dedupeDevices=e=>{const t=new Map;for(const o of e){const e=deviceKey(o);t.set(e,[...t.get(e)??[],o])}return[...t.values()].map(e=>{const t=[...e].sort((e,t)=>serialRank(e.serial)-serialRank(t.serial)||e.serial.localeCompare(t.serial)),[o]=t;if(void 0===o)throw new Error("a device group holds at least one probe");return{serial:o.serial,serials:t.map(e=>e.serial),model:o.model,abi:o.abi}}).sort((e,t)=>e.serial.localeCompare(t.serial))};const PROBE_SCRIPT="getprop ro.serialno; getprop ro.product.model; getprop ro.product.cpu.abi; settings get secure android_id";export const probeDevice=(e,t,o)=>{const s=capture({file:e,args:["-s",t,"shell",PROBE_SCRIPT]},o);if(0!==s.status)return fail("toolFailed",`adb could not read ${t}: ${s.stderr.trim()||s.stdout.trim()}`);const[r="",i="",a="",n=""]=s.stdout.split(/\r?\n/).map(e=>e.trim());return{serial:t,serialNo:r,model:i,abi:a,androidId:n}};export const listAndroidDevices=(e,t)=>{const o=capture({file:e,args:["devices"]},t);if(0!==o.status)return fail("toolFailed",`adb devices failed: ${o.stderr.trim()}`);const s=parseAdbDevices(o.stdout),r=s.filter(e=>"device"!==e.state),i=s.filter(e=>"device"===e.state);if(0===i.length){const e=r.map(e=>`${e.serial} is ${e.state}`).join("; ");return fail("deviceNotFound",`no Android device ready${e?` (${e})`:""}. Connect a phone with USB debugging, start an emulator, or adb connect host:port.`)}return dedupeDevices(i.map(o=>probeDevice(e,o.serial,t)))};export const describeDevice=e=>`${e.model||"unknown model"} (${e.serial}, ${e.abi})`;export const findDevice=(e,t)=>e.find(e=>e.serials.includes(t))??e.find(e=>e.model.toLowerCase()===t.toLowerCase());export const pickDevice=async(e,t,o,s)=>{const r=e.map((e,t)=>` ${t+1}. ${o(e)}`).join("\n");if(t)return findDevice(e,t)??fail("deviceNotFound",`no device matches --device ${t}. Connected:\n${r}`);const[i]=e;if(1===e.length&&void 0!==i)return i;if(!s)return fail("deviceAmbiguous",`several devices are connected; pass --device <serial|name>:\n${r}`);const a=createInterface({input:process.stdin,output:process.stdout});try{const t=await a.question(`Several devices are connected:\n${r}\nRun on which? [1-${e.length}] `);return e[Number(t.trim())-1]??fail("badInput",`no device numbered ${t.trim()}`)}finally{a.close()}};export const LOCAL_EMULATOR_PORTS=[...Array.from({length:16},(e,t)=>16384+32*t),7555];const isPortOpen=e=>new Promise(t=>{const o=new Socket;o.setTimeout(300),o.once("connect",()=>{o.destroy(),t(!0)}),o.once("timeout",()=>{o.destroy(),t(!1)}),o.once("error",()=>{o.destroy(),t(!1)}),o.connect(e,"127.0.0.1")});export const connectLocalEmulators=async(e,t)=>{const o=(await Promise.all(LOCAL_EMULATOR_PORTS.map(async e=>({port:e,open:await isPortOpen(e)})))).filter(e=>e.open).map(e=>e.port),s=capture({file:e,args:["devices"]},t),r=0===s.status?parseAdbDevices(s.stdout).map(e=>e.serial):[],i=[];for(const s of o){const o=`127.0.0.1:${s}`;if(r.includes(o))continue;const a=capture({file:e,args:["connect",o]},t),n=`${a.stdout}${a.stderr}`.trim();n.includes("connected to")?(say(`devices: connected ${o}`),i.push(o)):warn(`devices: ${o} is open but adb connect said: ${n}`)}return i};export const devices=async e=>{const{appRoot:t,platform:o}=e;let s;if("android"===o){const e=adbPath(process.env,process.platform);await connectLocalEmulators(e,t),s=listAndroidDevices(e,t).map(e=>({platform:"android",...e}))}else requireDarwin(process.platform,"devices --platform ios"),s=listAppleDevices(t).map(e=>({platform:"ios",...e}));if(isJsonOutput())sayJson({devices:s});else for(const e of s)if("android"===e.platform){const t=e.serials.length>1?` (also ${e.serials.slice(1).join(", ")})`:"";say(`${e.serial} ${e.model} ${e.abi}${t}`)}else say(`${e.udid} ${e.name} ${e.kind}`)};
|
package/lib/doctor.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync,rmSync}from"node:fs";import path from"node:path";import{capture}from"./exec.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{adbPath,findOnPath,longWindowsPathWarning}from"./platform.js";import{checkNdkHook,usesFirebase}from"./prebuild.js";import{checkSync}from"./sync.js";import{xosPath}from"./xos.js";export const JDK_MAJOR=17;const JDK_FIX="install JDK 17 and set JAVA_HOME",ADB_FIX="set ANDROID_HOME to the Android SDK (adb lives in its platform-tools folder) or put adb on PATH",NINJA_FIX="install ninja 1.11 or newer (scoop install ninja) and put it first on PATH",XCODE_FIX="install Xcode, then xcode-select -s /Applications/Xcode.app",XOS_FIX="install xOS Tools (xos) and put it on PATH",APP_PATH_FIX="move the app to a short folder such as C:\\w\\<app>, or map one with subst W: <path>",AUTOLINKING_FILE=path.join("android","build","generated","autolinking","autolinking.json"),AUTOLINKING_DIRS=[path.join("android","build","generated","autolinking"),path.join("android","app","build","generated","autolinking")];export const javaMajor=o=>{const e=/version\b[^"]*"([^"]+)"/.exec(o);if(
|
|
1
|
+
import{existsSync,readFileSync,rmSync}from"node:fs";import path from"node:path";import{capture}from"./exec.js";import{fail,isJsonOutput,say,sayJson}from"./output.js";import{adbPath,findOnPath,longWindowsPathWarning}from"./platform.js";import{checkNdkHook,usesFirebase}from"./prebuild.js";import{checkSync}from"./sync.js";import{xosPath}from"./xos.js";export const JDK_MAJOR=17;const JDK_FIX="install JDK 17 and set JAVA_HOME",ADB_FIX="set ANDROID_HOME to the Android SDK (adb lives in its platform-tools folder) or put adb on PATH",NINJA_FIX="install ninja 1.11 or newer (scoop install ninja) and put it first on PATH",XCODE_FIX="install Xcode, then xcode-select -s /Applications/Xcode.app",XOS_FIX="install xOS Tools (xos) and put it on PATH",APP_PATH_FIX="move the app to a short folder such as C:\\w\\<app>, or map one with subst W: <path>",AUTOLINKING_FILE=path.join("android","build","generated","autolinking","autolinking.json"),AUTOLINKING_DIRS=[path.join("android","build","generated","autolinking"),path.join("android","app","build","generated","autolinking")];export const javaMajor=o=>{const e=/version\b[^"]*"([^"]+)"/.exec(o)?.[1];if(void 0===e)return;const s=e.split(/[._+-]/),t=Number(s[0]),n=1===t?Number(s[1]):t;return Number.isInteger(n)?n:void 0};export const gradleSdkVersions=o=>{const e={},s=/ndkVersion\s*=\s*["']([^"']+)["']/.exec(o),t=/buildToolsVersion\s*=\s*["']([^"']+)["']/.exec(o),n=/compileSdkVersion\s*=\s*(\d+)/.exec(o);return s&&(e.ndk=s[1]),t&&(e.buildTools=t[1]),n&&(e.compileSdk=n[1]),e};const samePath=(o,e)=>{const norm=o=>{const e=path.resolve(o).replace(/[\\/]+$/,"");return"win32"===process.platform?e.toLowerCase():e};return norm(o)===norm(e)};export const autolinkingProblem=(o,e,s)=>{let t;try{t=JSON.parse(o)}catch{return"android/build/generated/autolinking/autolinking.json does not parse"}if("string"==typeof t?.root&&!samePath(t.root,e))return`the autolinking cache was made for ${t.root}, not ${e}`;for(const[o,e]of Object.entries(t?.dependencies??{}))if("string"==typeof e?.root&&!s(e.root))return`the autolinking cache names ${o} at ${e.root}, which no longer exists`};const ok=(o,e)=>({code:o,status:"ok",message:e}),skipped=(o,e)=>({code:o,status:"skipped",message:e}),problem=(o,e,s)=>({code:o,status:"problem",message:e,fix:s}),probe=(o,e,s)=>{try{return s()}catch(s){return problem(o,s instanceof Error?s.message:String(s),e)}},outputOf=o=>[o.stdout,o.stderr].join("\n").trim()||`exited with status ${o.status}`,SDK_SPECS=[{code:"ndk",key:"ndkVersion",field:"ndk",folder:(o,e)=>path.join(o,"ndk",e),install:o=>`sdkmanager "ndk;${o}"`},{code:"buildTools",key:"buildToolsVersion",field:"buildTools",folder:(o,e)=>path.join(o,"build-tools",e),install:o=>`sdkmanager "build-tools;${o}"`},{code:"androidPlatform",key:"compileSdkVersion",field:"compileSdk",folder:(o,e)=>path.join(o,"platforms",`android-${e}`),install:o=>`sdkmanager "platforms;android-${o}"`}],sdkCheck=(o,e)=>probe(e.code,"fix the Android SDK under ANDROID_HOME",()=>{const s=path.join(o,"android","build.gradle");if(!existsSync(s))return skipped(e.code,"no android/build.gradle");const t=process.env.ANDROID_HOME;if(!t)return skipped(e.code,"ANDROID_HOME is not set");const n=gradleSdkVersions(readFileSync(s,"utf8"))[e.field];if(void 0===n)return skipped(e.code,`${e.key} is not declared in android/build.gradle`);const r=e.folder(t,n);return existsSync(r)?ok(e.code,r):problem(e.code,`${r} is missing`,e.install(n))}),androidChecks=o=>{const{appRoot:e}=o,s=[];s.push(probe("nodeVersion","install Node 24",()=>{const o=process.versions.node;return 24===Number(o.split(".")[0])?ok("nodeVersion",`Node ${o}`):problem("nodeVersion",`Node ${o} is not Node 24`,"install Node 24")})),s.push(probe("androidHome","set ANDROID_HOME to the Android SDK folder",()=>{const o=process.env.ANDROID_HOME;return o?existsSync(o)?ok("androidHome",o):problem("androidHome",`ANDROID_HOME ${o} does not exist`,"set ANDROID_HOME to the Android SDK folder"):problem("androidHome","ANDROID_HOME is not set","set ANDROID_HOME to the Android SDK folder")}));const t={};s.push(probe("adb",ADB_FIX,()=>{const o=adbPath(process.env,process.platform),s=capture({file:o,args:["version"]},e);if(0!==s.status)return problem("adb",outputOf(s),ADB_FIX);t.path=o;const n=s.stdout.split(/\r?\n/).find(o=>o.startsWith("Version"));return ok("adb",n?`${o}, ${n.trim()}`:o)}));const n=t.path;s.push(void 0===n?skipped("adbServer","adb is not available"):probe("adbServer","use one adb, the SDK platform-tools one: MuMu ships its own adb",()=>{const o=capture({file:n,args:["devices"]},e),s=`${o.stdout}\n${o.stderr}`.split(/\r?\n/).find(o=>o.includes("doesn't match this client"));return void 0===s?ok("adbServer","one adb server version"):problem("adbServer",`another adb restarted the adb server at a different version: ${s.trim()}`,"use one adb, the SDK platform-tools one: MuMu ships its own adb")})),s.push(probe("jdk",JDK_FIX,()=>{const o=process.env.JAVA_HOME,s="win32"===process.platform?"java.exe":"java",t=o?path.join(o,"bin",s):void 0,n=void 0!==t&&existsSync(t)?t:findOnPath("java",process.env,process.platform);if(void 0===n)return problem("jdk","java not found",JDK_FIX);const r=capture({file:n,args:["-version"]},e),i=javaMajor(`${r.stderr}${r.stdout}`);return 17===i?ok("jdk",`Java ${i} at ${n}`):problem("jdk",`Java ${i??"unknown"} at ${n}; React Native builds need Java 17`,JDK_FIX)}));for(const o of SDK_SPECS)s.push(sdkCheck(e,o));s.push("win32"!==process.platform?skipped("ninja","only Windows builds need ninja on PATH"):probe("ninja",NINJA_FIX,()=>{const o=findOnPath("ninja",process.env,process.platform);if(void 0===o)return problem("ninja","ninja not found on PATH",NINJA_FIX);const s=capture({file:o,args:["--version"]},e).stdout.trim(),t=/^(\d+)\.(\d+)/.exec(s);if(!t)return problem("ninja",`ninja --version printed no version at ${o}`,NINJA_FIX);return Number(t[1])>1||1===Number(t[1])&&Number(t[2])>=11?ok("ninja",`ninja ${s} at ${o}`):problem("ninja",`ninja ${s} at ${o} is older than 1.11`,NINJA_FIX)})),s.push(probe("install","npx mobile-tools sync",()=>{const o=checkSync(e,process.platform);return 0===o.length?ok("install","node_modules matches the lockfile"):problem("install",o.join("; "),"npx mobile-tools sync")})),s.push("win32"!==process.platform?skipped("appPath","only Windows has the long-path limit"):probe("appPath",APP_PATH_FIX,()=>{const o=longWindowsPathWarning(e,process.platform);return void 0===o?ok("appPath","the app folder path is short enough for the Android native build"):{code:"appPath",status:"warning",message:o}}));const r="npx mobile-tools doctor --fix";return s.push(probe("autolinkingCache",r,()=>{const s=path.join(e,AUTOLINKING_FILE);if(!existsSync(s))return ok("autolinkingCache","no autolinking cache yet");const t=autolinkingProblem(readFileSync(s,"utf8"),e,existsSync);if(void 0===t)return ok("autolinkingCache","matches this tree");if(!o.fix)return problem("autolinkingCache",t,r);for(const o of AUTOLINKING_DIRS)rmSync(path.join(e,o),{recursive:!0,force:!0});return{code:"autolinkingCache",status:"fixed",message:"removed both autolinking caches; the next build regenerates them"}})),s.push(probe("ndkHook","add the subprojects block the message names to android/build.gradle",()=>(checkNdkHook(e),ok("ndkHook","library modules get the app NDK")))),s.push(probe("firebaseConfig","add the Firebase Android config for this app",()=>{if(!usesFirebase(e))return skipped("firebaseConfig","the app does not use @react-native-firebase");const o=path.join(e,"android","app","google-services.json");return existsSync(o)?ok("firebaseConfig","android/app/google-services.json"):problem("firebaseConfig","android/app/google-services.json is missing","add the Firebase Android config for this app")})),s},xcodeCheck=o=>probe("xcode",XCODE_FIX,()=>{const e=capture({file:"/usr/bin/xcode-select",args:["-p"]},o);return 0===e.status?ok("xcode",e.stdout.trim()):problem("xcode","no Xcode developer directory is selected",XCODE_FIX)}),xosCheck=o=>probe("xos",XOS_FIX,()=>{const e=xosPath(process.env,process.platform),s=capture({file:e,args:["doctor","--json"]},o);return 0===s.status?ok("xos",e):problem("xos",s.stderr.trim().split(/\r?\n/)[0]||`xos doctor exited with status ${s.status}`,"run xos doctor and install what it names")});export const iosChecks=(o,e)=>["darwin"===e?xcodeCheck(o):xosCheck(o),probe("cocoapods","install CocoaPods",()=>{const o=findOnPath("pod",process.env,e);return void 0===o?problem("cocoapods","pod not found on PATH","install CocoaPods"):ok("cocoapods",o)})];export const doctor=async o=>{const e=path.join(o.appRoot,"android"),s=path.join(o.appRoot,"ios");"android"!==o.platform||existsSync(e)||fail("appConfigInvalid",`no android/ folder in ${o.appRoot}`);const t=[];("android"===o.platform||void 0===o.platform&&existsSync(e))&&t.push(...androidChecks(o));const n="darwin"===process.platform||void 0!==findOnPath("xos",process.env,process.platform);("ios"===o.platform||void 0===o.platform&&n&&existsSync(s))&&t.push(...iosChecks(o.appRoot,process.platform));const r=t.filter(o=>"problem"===o.status).length;if(isJsonOutput())sayJson({checks:t,problems:r});else{for(const o of t){const e="problem"===o.status&&o.fix?` Fix: ${o.fix}`:"";say(`doctor: ${o.status} ${o.code}: ${o.message}${e}`)}say(0===r?"doctor: ready":`doctor: ${r} problem(s)`)}r>0&&(process.exitCode=1)};
|
package/lib/icons.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{ENVIRONMENTS,flavorOf,loadToolsConfig,resolveIosProjectName}from"./config.js";import{ADAPTIVE_DP,ADAPTIVE_ICON_XML,ADAPTIVE_VISIBLE_DP,backgroundColorXml,circleMaskSvg,DENSITIES,IOS_ICON_FILE,iosContentsJson,LEGACY_DP,RIBBONS,ribbonSvg,toHex}from"./iconArt.js";import{fail,say}from"./output.js";const MASTER=1024,PNG={compressionLevel:9,adaptiveFiltering:!1,palette:!1,force:!0},ICON_NAMES=["ic_launcher","ic_launcher_round","ic_launcher_foreground"],removeOtherFormats=o=>{if(existsSync(o))for(const n of readdirSync(o)){const{name:e,ext:r}=path.parse(n);ICON_NAMES.includes(e)&&".png"!==r&&rmSync(path.join(o,n))}},write=(o,n)=>{mkdirSync(path.dirname(o),{recursive:!0}),writeFileSync(o,n)},assertNoColorClash=(o,n)=>{if(existsSync(o))for(const e of readdirSync(o))e!==n&&e.endsWith(".xml")&&readFileSync(path.join(o,e),"utf8").includes('name="ic_launcher_background"')&&fail("appConfigInvalid",`${path.join(o,e)} already defines ic_launcher_background; remove it there`)},loadMaster=async(o,n)=>{const e=await o(n).metadata();if("png"!==e.format&&"svg"!==e.format)return fail("appConfigInvalid",`icon source must be a PNG or an SVG, not ${e.format??"unknown"}: ${n}`);const r=e.width??0,t=e.height??0;if(r!==t)return fail("appConfigInvalid",`icon source must be square, ${n} is ${r}x${t}`);if("png"===e.format&&r<1024)return fail("appConfigInvalid",`a PNG icon source must be at least 1024x1024, ${n} is ${r}x${t}`);return o(n,"svg"===e.format?{density:73728/r}:{}).resize(1024,1024,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).ensureAlpha().png(PNG).toBuffer()},cornerColor=async(o,n)=>{const{data:e}=await o(n).raw().toBuffer({resolveWithObject:!0});return 0===e
|
|
1
|
+
import{existsSync,mkdirSync,readdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{ENVIRONMENTS,flavorOf,loadToolsConfig,resolveIosProjectName}from"./config.js";import{ADAPTIVE_DP,ADAPTIVE_ICON_XML,ADAPTIVE_VISIBLE_DP,backgroundColorXml,circleMaskSvg,DENSITIES,IOS_ICON_FILE,iosContentsJson,LEGACY_DP,RIBBONS,ribbonSvg,toHex}from"./iconArt.js";import{fail,say}from"./output.js";const MASTER=1024,PNG={compressionLevel:9,adaptiveFiltering:!1,palette:!1,force:!0},ICON_NAMES=["ic_launcher","ic_launcher_round","ic_launcher_foreground"],removeOtherFormats=o=>{if(existsSync(o))for(const n of readdirSync(o)){const{name:e,ext:r}=path.parse(n);ICON_NAMES.includes(e)&&".png"!==r&&rmSync(path.join(o,n))}},write=(o,n)=>{mkdirSync(path.dirname(o),{recursive:!0}),writeFileSync(o,n)},assertNoColorClash=(o,n)=>{if(existsSync(o))for(const e of readdirSync(o))e!==n&&e.endsWith(".xml")&&readFileSync(path.join(o,e),"utf8").includes('name="ic_launcher_background"')&&fail("appConfigInvalid",`${path.join(o,e)} already defines ic_launcher_background; remove it there`)},loadMaster=async(o,n)=>{const e=await o(n).metadata();if("png"!==e.format&&"svg"!==e.format)return fail("appConfigInvalid",`icon source must be a PNG or an SVG, not ${e.format??"unknown"}: ${n}`);const r=e.width??0,t=e.height??0;if(r!==t)return fail("appConfigInvalid",`icon source must be square, ${n} is ${r}x${t}`);if("png"===e.format&&r<1024)return fail("appConfigInvalid",`a PNG icon source must be at least 1024x1024, ${n} is ${r}x${t}`);return o(n,"svg"===e.format?{density:73728/r}:{}).resize(1024,1024,{fit:"contain",background:{r:0,g:0,b:0,alpha:0}}).ensureAlpha().png(PNG).toBuffer()},cornerColor=async(o,n)=>{const{data:e}=await o(n).raw().toBuffer({resolveWithObject:!0});return 0===e.readUInt8(3)?"#FFFFFF":toHex(e.readUInt8(0),e.readUInt8(1),e.readUInt8(2))},withRibbon=async(o,n,e,r)=>{const t=RIBBONS[e];return t?o(n).composite([{input:Buffer.from(ribbonSvg(1024,r,t))}]).png(PNG).toBuffer():n},renderAndroid=async(o,n,e,r,t)=>{const a=path.join(n,"android","app","src",flavorOf(e),"res"),i=await withRibbon(o,r,e,{x:0,y:0,size:1024}),s=Math.round(1024*ADAPTIVE_VISIBLE_DP/ADAPTIVE_DP),c=Math.round((1024-s)/2),p=await o(r).resize(s,s).png(PNG).toBuffer(),f=await o({create:{width:1024,height:1024,channels:4,background:{r:0,g:0,b:0,alpha:0}}}).composite([{input:p,left:c,top:c}]).png(PNG).toBuffer(),l=await withRibbon(o,f,e,{x:c,y:c,size:s});for(const[n,e]of DENSITIES){const r=path.join(a,`mipmap-${n}`);removeOtherFormats(r);const t=Math.round(LEGACY_DP*e),s=Math.round(ADAPTIVE_DP*e);write(path.join(r,"ic_launcher.png"),await o(i).resize(t,t).png(PNG).toBuffer()),write(path.join(r,"ic_launcher_round.png"),await o(await o(i).resize(t,t).png(PNG).toBuffer()).composite([{input:Buffer.from(circleMaskSvg(t)),blend:"dest-in"}]).png(PNG).toBuffer()),write(path.join(r,"ic_launcher_foreground.png"),await o(l).resize(s,s).png(PNG).toBuffer())}const u=path.join(a,"mipmap-anydpi-v26");removeOtherFormats(u),write(path.join(u,"ic_launcher.xml"),ADAPTIVE_ICON_XML),write(path.join(u,"ic_launcher_round.xml"),ADAPTIVE_ICON_XML);const d=path.join(a,"values");assertNoColorClash(d,"ic_launcher_background.xml"),write(path.join(d,"ic_launcher_background.xml"),backgroundColorXml(t)),say(`icons: ${path.relative(n,a)}`)},renderIos=async(o,n,e,r,t,a)=>{const i=path.join(n,"ios",e,"Images.xcassets");existsSync(i)||fail("appConfigInvalid",`${path.relative(n,i)} not found: check "iosProjectName"`);const s=path.join(i,`AppIcon-${r}.appiconset`);rmSync(s,{recursive:!0,force:!0});const c=await withRibbon(o,t,r,{x:0,y:0,size:1024});write(path.join(s,IOS_ICON_FILE),await o(c).flatten({background:a}).png(PNG).toBuffer()),write(path.join(s,"Contents.json"),iosContentsJson()),say(`icons: ${path.relative(n,s)}`)},appEnvironments=o=>{const n=ENVIRONMENTS.filter(n=>existsSync(path.join(o,`appsettings.${n}.json`)));return 0===n.length&&fail("appConfigInvalid",`no appsettings.<Env>.json in ${o} (${ENVIRONMENTS.join(", ")}): run mobile-tools from the app's root folder`),n};export const icons=async o=>{const{appRoot:n}=o,e=appEnvironments(n),r=loadToolsConfig(n),t=o.source??r.iconSource??fail("badInput",'no icon source: pass --source <png|svg> or set "iconSource" in mobile-tools.config.json'),a=path.resolve(n,t);existsSync(a)||fail("appConfigInvalid",`icon source not found: ${a}`);const{default:i}=await(import("sharp")),s=await loadMaster(i,a),c=await cornerColor(i,s),p=resolveIosProjectName(n,r),f=existsSync(path.join(n,"android"));f&&!r.flavors&&say('icons: Android skipped, "flavors" is false: per-environment icons live in flavor source sets');for(const o of e)f&&r.flavors&&await renderAndroid(i,n,o,s,c),p&&await renderIos(i,n,p,o,s,c)};
|
package/lib/keystore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{capture}from"./exec.js";import{fail,say}from"./output.js";const PASSWORD_ENV="MOBILE_TOOLS_KEYSTORE_PASSWORD",MIN_PASSWORD_LENGTH=8,SHA256_LINE=/^[ \t]*SHA256:[ \t]*((?:[0-9A-F]{2}:){31}[0-9A-F]{2})\s*$/im;export const sha256Fingerprint=t=>SHA256_LINE.exec(t)?.[1]
|
|
1
|
+
import{existsSync}from"node:fs";import{capture}from"./exec.js";import{fail,say}from"./output.js";const PASSWORD_ENV="MOBILE_TOOLS_KEYSTORE_PASSWORD",MIN_PASSWORD_LENGTH=8,SHA256_LINE=/^[ \t]*SHA256:[ \t]*((?:[0-9A-F]{2}:){31}[0-9A-F]{2})\s*$/im;export const sha256Fingerprint=t=>SHA256_LINE.exec(t)?.[1]?.replace(/:/g,"").toLowerCase();export const initKeystore=async t=>{if(existsSync(t.out))return fail("badInput",`${t.out} exists; a keystore is never overwritten`);const e=process.env[PASSWORD_ENV];if(void 0===e||e.length<8)return fail("badInput",`${PASSWORD_ENV} must hold a keystore password of at least 8 characters`);const o=capture({file:"keytool",args:["-genkeypair","-noprompt","-keystore",t.out,"-storetype","PKCS12","-alias",t.alias,"-keyalg","RSA","-keysize","2048","-validity",String(t.validityDays),"-dname",t.dname,"-storepass:env",PASSWORD_ENV,"-keypass:env",PASSWORD_ENV]},process.cwd());if(-1===o.status)return fail("toolMissing","keytool not found on PATH; install a JDK, whose bin folder holds keytool");if(0!==o.status)return fail("toolFailed",`keytool could not create ${t.out} (exit ${o.status}): ${o.stderr.trim()}`);const s=capture({file:"keytool",args:["-list","-v","-keystore",t.out,"-alias",t.alias,"-storepass:env",PASSWORD_ENV]},process.cwd());if(0!==s.status)return fail("toolFailed",`keytool could not read ${t.out} back (exit ${s.status}): ${s.stderr.trim()}`);const a=sha256Fingerprint(s.stdout);if(void 0===a)return fail("toolFailed",`keytool printed no SHA-256 fingerprint for alias ${t.alias} in ${t.out}`);say(`keystore ${t.out} created; upload key SHA-256 ${a}`),say(`set apps.<app>.mobile.android.uploadKeySha256 in .webority/infra/store.json to ${a}`)};
|
package/lib/otaNative.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{X509Certificate}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import path from"node:path";import{fail}from"./output.js";export const COMPONENT_KEY={android:"OTA_ANDROID_COMPONENT_ID",ios:"OTA_IOS_COMPONENT_ID"};const CODE_SIGNING_ALG="rsa-v1_5-sha256",KEY_ID=/^[a-z][a-z0-9]*$/,WHOLE_NUMBER=/^[1-9][0-9]*$/,isSet=e=>null!=e&&""!==e;export const componentIdFor=(e,t)=>{const i=COMPONENT_KEY[t],n=e[i];return isSet(n)?WHOLE_NUMBER.test(String(n))?String(n):fail("appConfigInvalid",`${i} must be a positive whole number, not ${JSON.stringify(n)}`):fail("appConfigInvalid",`appsettings has no ${i}: the ${t} app has no OTA component to publish to`)};export const codeSigningKeyIdOf=(e,t)=>{let i;try{i=new X509Certificate(e).subject}catch{return fail("appConfigInvalid",`${t} is not a readable X.509 certificate`)}const n=i.split("\n").filter(e=>e.startsWith("CN=")),a=1===n.length?
|
|
1
|
+
import{X509Certificate}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import path from"node:path";import{fail}from"./output.js";export const COMPONENT_KEY={android:"OTA_ANDROID_COMPONENT_ID",ios:"OTA_IOS_COMPONENT_ID"};const CODE_SIGNING_ALG="rsa-v1_5-sha256",KEY_ID=/^[a-z][a-z0-9]*$/,WHOLE_NUMBER=/^[1-9][0-9]*$/,isSet=e=>null!=e&&""!==e;export const componentIdFor=(e,t)=>{const i=COMPONENT_KEY[t],n=e[i];return isSet(n)?WHOLE_NUMBER.test(String(n))?String(n):fail("appConfigInvalid",`${i} must be a positive whole number, not ${JSON.stringify(n)}`):fail("appConfigInvalid",`appsettings has no ${i}: the ${t} app has no OTA component to publish to`)};export const codeSigningKeyIdOf=(e,t)=>{let i;try{i=new X509Certificate(e).subject}catch{return fail("appConfigInvalid",`${t} is not a readable X.509 certificate`)}const n=i.split("\n").filter(e=>e.startsWith("CN=")),[a]=n,o=1===n.length&&void 0!==a?a.slice(3):"";return o.endsWith(" OTA Updates")?fail("appConfigInvalid",`${t} is the shared OTA certificate (CN=${o}), which is retired for this app: get the product's own certificate with \`bash scripts/ota-signing-key.sh cert <keyid> --out certs/ota-code-signing-cert.pem\` in the repository that owns the OTA signing keys`):KEY_ID.test(o)?o:fail("appConfigInvalid",`${t} has common name ${JSON.stringify(o)}, which is not a signing key id (a lowercase name, for example acme)`)};export const otaNativeSettings=(e,t,i,n,a)=>{const o=t.OTA_UPDATE_BASE_URL;if(!isSet(o)||!isSet(t[COMPONENT_KEY[n]]))return;const s=componentIdFor(t,n),r=t.OTA_PROJECT_ID;if(!isSet(r)||!WHOLE_NUMBER.test(String(r)))return fail("appConfigInvalid",`OTA_PROJECT_ID must be the update server's project id (a positive whole number), not ${JSON.stringify(r)}`);const p=t.OTA_CODE_SIGNING_CERT;if("string"!=typeof p||""===p.trim())return fail("appConfigInvalid","OTA_CODE_SIGNING_CERT must name the PEM certificate file, relative to the app folder");const d=path.join(e,p);if(!existsSync(d))return fail("appConfigInvalid",`OTA_CODE_SIGNING_CERT ${p} not found in ${e}`);const c=readFileSync(d,"utf8").replace(/\r\n/g,"\n").trim();return c.startsWith("-----BEGIN CERTIFICATE-----")?{updateUrl:`${String(o).replace(/\/+$/,"")}/ota/manifest/${r}/${s}/${i}`,runtimeVersion:a?`${String(t.VERSION_INTERNAL)}-otatest`:String(t.VERSION_INTERNAL),certificate:c,keyId:codeSigningKeyIdOf(c,p)}:fail("appConfigInvalid",`${p} is not a PEM certificate`)};const escapeXml=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");export const androidOtaMetaData=e=>[["expo.modules.updates.ENABLED","true"],["expo.modules.updates.EXPO_UPDATE_URL",e.updateUrl],["expo.modules.updates.EXPO_RUNTIME_VERSION",e.runtimeVersion],["expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH","ALWAYS"],["expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS","0"],["expo.modules.updates.CODE_SIGNING_CERTIFICATE",e.certificate],["expo.modules.updates.CODE_SIGNING_METADATA",JSON.stringify({keyid:e.keyId,alg:CODE_SIGNING_ALG})]];export const androidOtaManifest=e=>'<?xml version="1.0" encoding="utf-8"?>\n\x3c!-- Written by mobile-tools prebuild for this flavor\'s environment. Not tracked: run prebuild to change it. --\x3e\n<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n <application>\n'+(e?androidOtaMetaData(e):[["expo.modules.updates.ENABLED","false"]]).map(([e,t])=>` <meta-data android:name="${e}" android:value="${escapeXml(t).replace(/\n/g," ")}" />\n`).join("")+" </application>\n</manifest>\n";export const iosOtaPlistKeys=e=>[["EXUpdatesEnabled",!0],["EXUpdatesURL",e.updateUrl],["EXUpdatesRuntimeVersion",e.runtimeVersion],["EXUpdatesCheckOnLaunch","ALWAYS"],["EXUpdatesLaunchWaitMs",0],["EXUpdatesCodeSigningCertificate",e.certificate],["EXUpdatesCodeSigningMetadata",{keyid:e.keyId,alg:CODE_SIGNING_ALG}]];const plistValue=(e,t,i)=>{if("boolean"==typeof e)return e?"<true/>":"<false/>";if("number"==typeof e)return`<integer>${e}</integer>`;if("string"==typeof e)return`<string>${escapeXml(e).replace(/\n/g,i)}</string>`;const n=`${t}${t.includes("\t")?"\t":" "}`,a=Object.entries(e).map(([e,t])=>`${n}<key>${escapeXml(e)}</key>${i}${n}<string>${escapeXml(t)}</string>`).join(i);return`<dict>${i}${a}${i}${t}</dict>`};export const expoPlist=e=>'<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n'+(e?iosOtaPlistKeys(e):[["EXUpdatesEnabled",!1]]).map(([e,t])=>`\t<key>${escapeXml(e)}</key>\n\t${plistValue(t,"\t","\n")}\n`).join("")+"</dict>\n</plist>\n";
|
package/lib/prebuild.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{copyFileSync,existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{checkAppSettings}from"./appSettingsRules.js";import{applicationId,COMPILED_FILE,ENVIRONMENTS,flavorOf,lastCompiledEnvironment,loadAppSettings,loadToolsConfig,resolveIosProjectName}from"./config.js";import{capture}from"./exec.js";import{androidOtaManifest,expoPlist,otaNativeSettings}from"./otaNative.js";import{fail,say}from"./output.js";import{findOnPath}from"./platform.js";export const IOS_COMPILED_XCCONFIG="ios/appsettings.Compiled.xcconfig";export const androidFlavorManifest=e=>`android/app/src/${flavorOf(e)}/AndroidManifest.xml`;export const expoPlistPath=e=>`ios/${e}/Supporting/Expo.plist`;export const usesExpoUpdates=e=>dependsOn(e,"expo-updates");export const generatedNativeFiles=(e,t,i,o)=>{if("android"===o)return usesExpoUpdates(e)?[androidFlavorManifest(i)]:[];const n=[IOS_COMPILED_XCCONFIG];if(void 0!==t){const o=path.join(e,loadToolsConfig(e).firebasePlistDir,`GoogleService-Info.${i}.plist`);existsSync(o)&&n.push(`ios/${t}/GoogleService-Info.plist`),usesExpoUpdates(e)&&n.push(expoPlistPath(t))}return n};export const nativeBuildInputs=(e,t)=>{const i=path.join(e,COMPILED_FILE);if(!existsSync(i))return fail("appConfigInvalid",`${COMPILED_FILE} is missing: run npx mobile-tools prebuild --env <Development|Staging|Production> first`);const o=JSON.parse(readFileSync(i,"utf8")),n=resolveIosProjectName(e,loadToolsConfig(e)),s=generatedNativeFiles(e,n,o.ENVIRONMENT,t).filter(t=>existsSync(path.join(e,t)));return[...["APP_ID","APP_NAME","VERSION_DISPLAY","VERSION_INTERNAL"].map(e=>`${e}=${JSON.stringify(o[e])}`),...s.map(t=>`${t}=${JSON.stringify(readFileSync(path.join(e,t),"utf8"))}`)].join("\n")};const objectsOf=(e,t)=>[...e.matchAll(new RegExp(`\\n\\s*(\\w+)(?: /\\*([^\\n]*?)\\*/)? = \\{\\s*isa = ${t};`,"g"))].map(([,e,t=""])=>({id:e,name:t.trim()})),pbxObject=(e,t)=>{const i=new RegExp(`\\n\\s*${t}(?: /\\*[^\\n]*?\\*/)? = \\{`).exec(e);if(!i)return;let o=0;for(let t=i.index+i[0].length-1;t<e.length;t++)if(e.startsWith("/*",t)){if(t=e.indexOf("*/",t+2)+1,0===t)return}else if('"'===e[t])for(t++;t<e.length&&'"'!==e[t];t++)"\\"===e[t]&&t++;else if("{"===e[t])o++;else if("}"===e[t]&&0===--o)return e.slice(i.index,t+1)},configurationsOf=(e,t)=>[...(/buildConfigurations = \(([^)]*)\)/.exec(pbxObject(e,t)??"")?.[1]??"").matchAll(/(\w+)(?: \/\* ([^*]*?) \*\/)?,/g)].map(([,e,t=""])=>({id:e,name:t})),unquote=e=>e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e,shipsInfoPlist=e=>/^com\.apple\.product-type\.(application|.*extension)/.test(e);export const shippedInfoPlists=e=>{const t=new Map,i=/\n\s*(\w+)(?: \/\*[^\n]*?\*\/)? = \{\s*isa = PBXNativeTarget;/g;for(const[,o]of e.matchAll(i)){const i=pbxObject(e,o)??"",n=unquote(/\sproductType = ([^;\n]*);/.exec(i)?.[1]??"");if(!shipsInfoPlist(n))continue;const s=unquote(/\sname = ([^;\n]*);/.exec(i)?.[1]??o),a=/\sbuildConfigurationList = (\w+)/.exec(i)?.[1],r=a&&pbxObject(e,a)||"",p=/buildConfigurations = \(([^)]*)\)/.exec(r)?.[1]??"";for(const[i]of p.matchAll(/\w+(?= \/\*|,)/g)){const o=/\sINFOPLIST_FILE = ([^;\n]*);/.exec(pbxObject(e,i)??"")?.[1];o&&!t.has(unquote(o))&&t.set(unquote(o),s)}}return[...t].map(([e,t])=>({target:t,file:e}))};const BUILD_SETTING_KEYS=[["CFBundleIdentifier","PRODUCT_BUNDLE_IDENTIFIER"],["CFBundleShortVersionString","MARKETING_VERSION"],["CFBundleVersion","CURRENT_PROJECT_VERSION"]];export const fixedInfoPlistValues=e=>BUILD_SETTING_KEYS.flatMap(([t,i])=>{const o=new RegExp(`<key>${t}</key>\\s*(<[^>]*>)?([^<]*)`).exec(e);if(!o)return[];const n="<string>"===o[1]?o[2].trim():o[1]??o[2].trim();return n===`$(${i})`||n===`\${${i}}`?[]:[{key:t,value:n,setting:i}]});export const checkInfoPlistReferences=(e,t)=>{const i=path.join(e,"ios"),o=readFileSync(path.join(i,`${t}.xcodeproj`,"project.pbxproj"),"utf8"),n=[{target:t,file:`${t}/Info.plist`},...shippedInfoPlists(o)],s=path.resolve(i,`${t}/Info.plist`),a=[],r=new Set;for(const{target:t,file:o}of n){const n=o.replace(/^(\$\(SRCROOT\)|\$\{SRCROOT\}|\$\(PROJECT_DIR\))\//,"");if(/\$[({]/.test(n)){a.push(`target ${t}: INFOPLIST_FILE ${o} uses a build setting prebuild cannot resolve`);continue}const p=path.resolve(i,n);if(r.has(p))continue;r.add(p);const c=path.relative(e,p).replace(/\\/g,"/");if(!existsSync(p)){a.push(`${c} not found (INFOPLIST_FILE of target ${t})`);continue}const d=readFileSync(p,"utf8");for(const{key:e,value:t,setting:i}of fixedInfoPlistValues(d))a.push(`${c}: ${e} is "${t}", must be $(${i})`);p!==s||/<key>CFBundleDisplayName<\/key>\s*<string>\$\(APP_NAME\)<\/string>/.test(d)||a.push(`${c}: CFBundleDisplayName must be $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}a.length>0&&fail("appConfigInvalid",`Info.plist values that ignore what prebuild writes into appsettings.Compiled.xcconfig:\n ${a.join("\n ")}`)};const XCCONFIG_BASE=/baseConfigurationReference = \w+ \/\* appsettings\.Compiled\.xcconfig \*\//,MANAGED_BUILD_SETTINGS=["PRODUCT_BUNDLE_IDENTIFIER","MARKETING_VERSION","CURRENT_PROJECT_VERSION"];export const checkPbxprojSettings=(e,t)=>{const i=[],o=objectsOf(e,"PBXProject")[0];void 0===o&&i.push("project.pbxproj has no PBXProject object to carry the base configuration");const n=o?/\sbuildConfigurationList = (\w+)/.exec(pbxObject(e,o.id)??"")?.[1]:void 0;for(const{id:t,name:o}of n?configurationsOf(e,n):[])XCCONFIG_BASE.test(pbxObject(e,t)??"")||i.push(`project configuration ${t} /* ${o} */ does not use appsettings.Compiled.xcconfig as its base configuration: set the project-level configurations' base configuration to appsettings.Compiled.xcconfig`);const s=t?[...MANAGED_BUILD_SETTINGS,"ASSETCATALOG_COMPILER_APPICON_NAME"]:MANAGED_BUILD_SETTINGS;for(const{id:t,name:o}of objectsOf(e,"XCBuildConfiguration")){const n=pbxObject(e,t)??"";for(const e of s)new RegExp(`\\s${e} = `).test(n)&&i.push(`configuration ${t} /* ${o} */ sets ${e}: remove it; ios/appsettings.Compiled.xcconfig sets it`);/\sINFOPLIST_KEY_CFBundleDisplayName = /.test(n)&&i.push(`configuration ${t} /* ${o} */ sets INFOPLIST_KEY_CFBundleDisplayName: remove it; Info.plist reads $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}i.length>0&&fail("appConfigInvalid",`project.pbxproj sets values that ios/appsettings.Compiled.xcconfig owns:\n ${i.join("\n ")}`)};const XCCONFIG_UNSAFE=/\/\/|[$";]/,xcconfigText=(e,t,i)=>{const o=[["APP_NAME",String(e.APP_NAME)],["PRODUCT_BUNDLE_IDENTIFIER",applicationId(String(e.APP_ID),t)],["MARKETING_VERSION",String(e.VERSION_DISPLAY)],["CURRENT_PROJECT_VERSION",String(e.VERSION_INTERNAL)],...i?[["ASSETCATALOG_COMPILER_APPICON_NAME",`AppIcon-${t}`]]:[]];for(const[e,t]of o)XCCONFIG_UNSAFE.test(t)&&fail("appConfigInvalid",`${e} must not contain // $ " or ;: it is written unquoted into ios/appsettings.Compiled.xcconfig`);return["// Written by mobile-tools prebuild from appsettings.Compiled.json for one environment. Not tracked: run prebuild to change it.",...o.map(([e,t])=>`${e} = ${t}`)].map(e=>`${e}\n`).join("")};export const buildCommit=e=>{const t=findOnPath("git",process.env,process.platform);if(!t)return"nogit";const i=capture({file:t,args:["rev-parse","--short","HEAD"]},e);if(0!==i.status)return"nogit";const o=capture({file:t,args:["status","--porcelain","--","."]},e);return 0!==o.status?fail("toolFailed",`git status failed in ${e}: ${o.stderr.trim()}`):""===o.stdout.trim()?i.stdout.trim():`${i.stdout.trim()}-dirty`};export const requireIgnored=(e,t)=>{const i=findOnPath("git",process.env,process.platform);if(!i||0!==capture({file:i,args:["rev-parse","--is-inside-work-tree"]},e).status)return;const o=t.filter(t=>{const o=capture({file:i,args:["check-ignore","-q","--",t]},e);return 0!==o.status&&1!==o.status&&fail("toolFailed",`git check-ignore failed for ${t}: ${o.stderr.trim()}`),1===o.status});o.length>0&&fail("appConfigInvalid",`add these lines to ${path.basename(e)}/.gitignore; prebuild writes them per environment:\n${o.join("\n")}`)};const writeIfChanged=(e,t)=>(!existsSync(e)||readFileSync(e,"utf8")!==t)&&(writeFileSync(e,t,"utf8"),!0),report=(e,t,i)=>{say(`prebuild: ${i?"wrote":"unchanged"} ${path.relative(e,t)}`)},dependsOn=(e,t)=>{const i=path.join(e,"package.json");if(!existsSync(i))return!1;const o=JSON.parse(readFileSync(i,"utf8"));return Boolean(o.dependencies?.[t])};export const usesFirebase=e=>dependsOn(e,"@react-native-firebase/app");export const checkNdkHook=e=>{const t=path.join(e,"android","build.gradle");if(!existsSync(t))return;const i=readFileSync(t,"utf8");/withId\(\s*["']com\.android\.library["']\s*\)/.test(i)&&/\.ndkVersion\s*=\s*rootProject\.ext\.ndkVersion/.test(i)||fail("appConfigInvalid",'android/build.gradle does not hand the app NDK to library modules; add after apply plugin "com.facebook.react.rootproject": subprojects { project -> project.plugins.withId("com.android.library") { project.android.ndkVersion = rootProject.ext.ndkVersion } }')};const MANAGED_GRADLE_KEYS=/^\s*(APP_NAME|APP_ID|VERSION_DISPLAY|VERSION_INTERNAL)\s*[=:]/gm;export const stampAndroid=(e,t,i,o,n)=>{const s=path.join(e,"android","gradle.properties");existsSync(s)||fail("appConfigInvalid",`android/gradle.properties not found in ${e}`),usesFirebase(e)&&!existsSync(path.join(e,"android","app","google-services.json"))&&fail("appConfigInvalid","android/app/google-services.json is missing; the app uses @react-native-firebase, whose Gradle plugin needs it"),checkNdkHook(e);const a=[...new Set([...readFileSync(s,"utf8").matchAll(MANAGED_GRADLE_KEYS)].map(([,e])=>e))];a.length>0&&fail("appConfigInvalid",`android/gradle.properties sets ${a.join(", ")}: remove them; android/app/build.gradle reads them from appsettings.Compiled.json`);const r=path.join(e,"android","app","build.gradle");if(existsSync(r)&&readFileSync(r,"utf8").includes("appsettings.Compiled.json")||fail("appConfigInvalid","android/app/build.gradle does not read appsettings.Compiled.json; add the compiledSettings loader (mobile-tools README, prebuild)"),usesExpoUpdates(e)){o.flavors||fail("appConfigInvalid",'expo-updates settings go into the flavor\'s manifest; set "flavors": true');const s=path.join(e,"android","app","src","main","AndroidManifest.xml");existsSync(s)||fail("appConfigInvalid","android/app/src/main/AndroidManifest.xml not found");const a=[...readFileSync(s,"utf8").matchAll(/android:name="(expo\.modules\.updates\.[^"]*)"/g)].map(([,e])=>e);a.length>0&&fail("appConfigInvalid",`android/app/src/main/AndroidManifest.xml sets ${a.join(", ")}: remove them from android/app/src/main/AndroidManifest.xml; prebuild writes them into ${androidFlavorManifest(i)}`);const r=otaNativeSettings(e,t,i,"android",n),p=path.join(e,androidFlavorManifest(i));mkdirSync(path.dirname(p),{recursive:!0}),report(e,p,writeIfChanged(p,androidOtaManifest(r)))}};export const stampIos=(e,t,i,o,n,s)=>{const a=path.join(e,"ios",n),r=path.join(a,"Info.plist"),p=path.join(e,"ios",`${n}.xcodeproj`,"project.pbxproj");for(const t of[r,p])existsSync(t)||fail("appConfigInvalid",`${path.relative(e,t)} not found: check "iosProjectName"`);checkInfoPlistReferences(e,n);const c=`AppIcon-${i}`,d=path.join(a,"Images.xcassets"),l=existsSync(path.join(d,`${c}.appiconset`)),f=ENVIRONMENTS.filter(e=>e!==i&&existsSync(path.join(d,`AppIcon-${e}.appiconset`)));!l&&f.length>0&&fail("appConfigInvalid",`ios/${n}/Images.xcassets has AppIcon-${f[0]} but no ${c}: run mobile-tools icons`),checkPbxprojSettings(readFileSync(p,"utf8"),l);const u=path.join(e,IOS_COMPILED_XCCONFIG);report(e,u,writeIfChanged(u,xcconfigText(t,i,l))),l||say(`prebuild: no AppIcon-${i} set, so ios/appsettings.Compiled.xcconfig sets no app icon name`);const g=path.join(a,"GoogleService-Info.plist"),I=path.join(e,o.firebasePlistDir,`GoogleService-Info.${i}.plist`);if(!existsSync(I)&&usesFirebase(e)&&fail("appConfigInvalid",`${path.relative(e,I)} is missing; the app uses @react-native-firebase, and an iOS build without it reports no crashes`),existsSync(I)){const t=!existsSync(g)||!readFileSync(I).equals(readFileSync(g));t&©FileSync(I,g),report(e,g,t)}else existsSync(g)&&(rmSync(g),say(`prebuild: removed ${path.relative(e,g)}, no ${path.relative(e,I)}`));if(usesExpoUpdates(e)){readFileSync(p,"utf8").includes("Expo.plist in Resources")||fail("appConfigInvalid","add Supporting/Expo.plist to the Xcode project's Copy Bundle Resources; prebuild writes its contents");const o=otaNativeSettings(e,t,i,"ios",s),a=path.join(e,expoPlistPath(n));mkdirSync(path.dirname(a),{recursive:!0}),report(e,a,writeIfChanged(a,expoPlist(o)))}};export const prebuild=e=>{const{appRoot:t,sameEnv:i,platform:o}=e,n=!0===e.otaTest;i&&e.env&&fail("badInput","pass --env or --same-env, not both");const s=i?lastCompiledEnvironment(t):e.env;if(!s)return fail("badInput","prebuild needs --env <Development|Staging|Production> or --same-env");const a=loadToolsConfig(t),r=resolveIosProjectName(t,a),p=loadAppSettings(t,s,a.requiredSettings);checkAppSettings(t,p,s);const c="android"===o||!o&&existsSync(path.join(t,"android")),d="android"===o?void 0:r;if("ios"===o&&void 0===d)return fail("appConfigInvalid",`no ios/ folder in ${t}`);const l=[...c?generatedNativeFiles(t,d,s,"android"):[],...void 0!==d?generatedNativeFiles(t,d,s,"ios"):[]];requireIgnored(t,[COMPILED_FILE,...l]);const f={...p,COMMIT:buildCommit(t),BUILD_TIME:(new Date).toISOString()};return writeFileSync(path.join(t,COMPILED_FILE),`${JSON.stringify(f,null,2)}\n`,"utf8"),say(`prebuild: wrote ${COMPILED_FILE} (${s}, ${f.COMMIT})`),c&&stampAndroid(t,f,s,a,n),void 0!==d&&stampIos(t,f,s,a,d,n),f};
|
|
1
|
+
import{copyFileSync,existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"node:fs";import path from"node:path";import{checkAppSettings}from"./appSettingsRules.js";import{applicationId,COMPILED_FILE,ENVIRONMENTS,flavorOf,lastCompiledEnvironment,loadAppSettings,loadToolsConfig,resolveIosProjectName}from"./config.js";import{capture}from"./exec.js";import{androidOtaManifest,expoPlist,otaNativeSettings}from"./otaNative.js";import{fail,say}from"./output.js";import{findOnPath}from"./platform.js";export const IOS_COMPILED_XCCONFIG="ios/appsettings.Compiled.xcconfig";export const androidFlavorManifest=e=>`android/app/src/${flavorOf(e)}/AndroidManifest.xml`;export const expoPlistPath=e=>`ios/${e}/Supporting/Expo.plist`;export const usesExpoUpdates=e=>dependsOn(e,"expo-updates");export const generatedNativeFiles=(e,t,i,o)=>{if("android"===o)return usesExpoUpdates(e)?[androidFlavorManifest(i)]:[];const n=[IOS_COMPILED_XCCONFIG];if(void 0!==t){const o=path.join(e,loadToolsConfig(e).firebasePlistDir,`GoogleService-Info.${i}.plist`);existsSync(o)&&n.push(`ios/${t}/GoogleService-Info.plist`),usesExpoUpdates(e)&&n.push(expoPlistPath(t))}return n};export const nativeBuildInputs=(e,t)=>{const i=path.join(e,COMPILED_FILE);if(!existsSync(i))return fail("appConfigInvalid",`${COMPILED_FILE} is missing: run npx mobile-tools prebuild --env <Development|Staging|Production> first`);const o=JSON.parse(readFileSync(i,"utf8")),n=resolveIosProjectName(e,loadToolsConfig(e)),s=generatedNativeFiles(e,n,o.ENVIRONMENT,t).filter(t=>existsSync(path.join(e,t)));return[...["APP_ID","APP_NAME","VERSION_DISPLAY","VERSION_INTERNAL"].map(e=>`${e}=${JSON.stringify(o[e])}`),...s.map(t=>`${t}=${JSON.stringify(readFileSync(path.join(e,t),"utf8"))}`)].join("\n")};const requiredGroup=(e,t)=>{const i=e[t];if(void 0===i)throw new Error(`the pattern did not capture group ${t}`);return i},objectsOf=(e,t)=>[...e.matchAll(new RegExp(`\\n\\s*(\\w+)(?: /\\*([^\\n]*?)\\*/)? = \\{\\s*isa = ${t};`,"g"))].map(e=>({id:requiredGroup(e,1),name:(e[2]??"").trim()})),pbxObject=(e,t)=>{const i=new RegExp(`\\n\\s*${t}(?: /\\*[^\\n]*?\\*/)? = \\{`).exec(e);if(!i)return;let o=0;for(let t=i.index+i[0].length-1;t<e.length;t++)if(e.startsWith("/*",t)){if(t=e.indexOf("*/",t+2)+1,0===t)return}else if('"'===e[t])for(t++;t<e.length&&'"'!==e[t];t++)"\\"===e[t]&&t++;else if("{"===e[t])o++;else if("}"===e[t]&&0===--o)return e.slice(i.index,t+1)},configurationsOf=(e,t)=>[...(/buildConfigurations = \(([^)]*)\)/.exec(pbxObject(e,t)??"")?.[1]??"").matchAll(/(\w+)(?: \/\* ([^*]*?) \*\/)?,/g)].map(e=>({id:requiredGroup(e,1),name:e[2]??""})),unquote=e=>e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e,shipsInfoPlist=e=>/^com\.apple\.product-type\.(application|.*extension)/.test(e);export const shippedInfoPlists=e=>{const t=new Map,i=/\n\s*(\w+)(?: \/\*[^\n]*?\*\/)? = \{\s*isa = PBXNativeTarget;/g;for(const o of e.matchAll(i)){const i=requiredGroup(o,1),n=pbxObject(e,i)??"",s=unquote(/\sproductType = ([^;\n]*);/.exec(n)?.[1]??"");if(!shipsInfoPlist(s))continue;const r=unquote(/\sname = ([^;\n]*);/.exec(n)?.[1]??i),a=/\sbuildConfigurationList = (\w+)/.exec(n)?.[1],p=a&&pbxObject(e,a)||"",c=/buildConfigurations = \(([^)]*)\)/.exec(p)?.[1]??"";for(const i of c.matchAll(/\w+(?= \/\*|,)/g)){const o=requiredGroup(i,0),n=/\sINFOPLIST_FILE = ([^;\n]*);/.exec(pbxObject(e,o)??"")?.[1];n&&!t.has(unquote(n))&&t.set(unquote(n),r)}}return[...t].map(([e,t])=>({target:t,file:e}))};const BUILD_SETTING_KEYS=[["CFBundleIdentifier","PRODUCT_BUNDLE_IDENTIFIER"],["CFBundleShortVersionString","MARKETING_VERSION"],["CFBundleVersion","CURRENT_PROJECT_VERSION"]];export const fixedInfoPlistValues=e=>BUILD_SETTING_KEYS.flatMap(([t,i])=>{const o=new RegExp(`<key>${t}</key>\\s*(<[^>]*>)?([^<]*)`).exec(e);if(!o)return[];const n=requiredGroup(o,2),s=o[1],r="<string>"===s?n.trim():s??n.trim();return r===`$(${i})`||r===`\${${i}}`?[]:[{key:t,value:r,setting:i}]});export const checkInfoPlistReferences=(e,t)=>{const i=path.join(e,"ios"),o=readFileSync(path.join(i,`${t}.xcodeproj`,"project.pbxproj"),"utf8"),n=[{target:t,file:`${t}/Info.plist`},...shippedInfoPlists(o)],s=path.resolve(i,`${t}/Info.plist`),r=[],a=new Set;for(const{target:t,file:o}of n){const n=o.replace(/^(\$\(SRCROOT\)|\$\{SRCROOT\}|\$\(PROJECT_DIR\))\//,"");if(/\$[({]/.test(n)){r.push(`target ${t}: INFOPLIST_FILE ${o} uses a build setting prebuild cannot resolve`);continue}const p=path.resolve(i,n);if(a.has(p))continue;a.add(p);const c=path.relative(e,p).replace(/\\/g,"/");if(!existsSync(p)){r.push(`${c} not found (INFOPLIST_FILE of target ${t})`);continue}const d=readFileSync(p,"utf8");for(const{key:e,value:t,setting:i}of fixedInfoPlistValues(d))r.push(`${c}: ${e} is "${t}", must be $(${i})`);p!==s||/<key>CFBundleDisplayName<\/key>\s*<string>\$\(APP_NAME\)<\/string>/.test(d)||r.push(`${c}: CFBundleDisplayName must be $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}r.length>0&&fail("appConfigInvalid",`Info.plist values that ignore what prebuild writes into appsettings.Compiled.xcconfig:\n ${r.join("\n ")}`)};const XCCONFIG_BASE=/baseConfigurationReference = \w+ \/\* appsettings\.Compiled\.xcconfig \*\//,MANAGED_BUILD_SETTINGS=["PRODUCT_BUNDLE_IDENTIFIER","MARKETING_VERSION","CURRENT_PROJECT_VERSION"];export const checkPbxprojSettings=(e,t)=>{const i=[],o=objectsOf(e,"PBXProject")[0];void 0===o&&i.push("project.pbxproj has no PBXProject object to carry the base configuration");const n=o?/\sbuildConfigurationList = (\w+)/.exec(pbxObject(e,o.id)??"")?.[1]:void 0;for(const{id:t,name:o}of n?configurationsOf(e,n):[])XCCONFIG_BASE.test(pbxObject(e,t)??"")||i.push(`project configuration ${t} /* ${o} */ does not use appsettings.Compiled.xcconfig as its base configuration: set the project-level configurations' base configuration to appsettings.Compiled.xcconfig`);const s=t?[...MANAGED_BUILD_SETTINGS,"ASSETCATALOG_COMPILER_APPICON_NAME"]:MANAGED_BUILD_SETTINGS;for(const{id:t,name:o}of objectsOf(e,"XCBuildConfiguration")){const n=pbxObject(e,t)??"";for(const e of s)new RegExp(`\\s${e} = `).test(n)&&i.push(`configuration ${t} /* ${o} */ sets ${e}: remove it; ios/appsettings.Compiled.xcconfig sets it`);/\sINFOPLIST_KEY_CFBundleDisplayName = /.test(n)&&i.push(`configuration ${t} /* ${o} */ sets INFOPLIST_KEY_CFBundleDisplayName: remove it; Info.plist reads $(APP_NAME), which ios/appsettings.Compiled.xcconfig sets`)}i.length>0&&fail("appConfigInvalid",`project.pbxproj sets values that ios/appsettings.Compiled.xcconfig owns:\n ${i.join("\n ")}`)};const XCCONFIG_UNSAFE=/\/\/|[$";]/,xcconfigText=(e,t,i)=>{const o=[["APP_NAME",String(e.APP_NAME)],["PRODUCT_BUNDLE_IDENTIFIER",applicationId(String(e.APP_ID),t)],["MARKETING_VERSION",String(e.VERSION_DISPLAY)],["CURRENT_PROJECT_VERSION",String(e.VERSION_INTERNAL)],...i?[["ASSETCATALOG_COMPILER_APPICON_NAME",`AppIcon-${t}`]]:[]];for(const[e,t]of o)XCCONFIG_UNSAFE.test(t)&&fail("appConfigInvalid",`${e} must not contain // $ " or ;: it is written unquoted into ios/appsettings.Compiled.xcconfig`);return["// Written by mobile-tools prebuild from appsettings.Compiled.json for one environment. Not tracked: run prebuild to change it.",...o.map(([e,t])=>`${e} = ${t}`)].map(e=>`${e}\n`).join("")};export const buildCommit=e=>{const t=findOnPath("git",process.env,process.platform);if(!t)return"nogit";const i=capture({file:t,args:["rev-parse","--short","HEAD"]},e);if(0!==i.status)return"nogit";const o=capture({file:t,args:["status","--porcelain","--","."]},e);return 0!==o.status?fail("toolFailed",`git status failed in ${e}: ${o.stderr.trim()}`):""===o.stdout.trim()?i.stdout.trim():`${i.stdout.trim()}-dirty`};export const requireIgnored=(e,t)=>{const i=findOnPath("git",process.env,process.platform);if(!i||0!==capture({file:i,args:["rev-parse","--is-inside-work-tree"]},e).status)return;const o=t.filter(t=>{const o=capture({file:i,args:["check-ignore","-q","--",t]},e);return 0!==o.status&&1!==o.status&&fail("toolFailed",`git check-ignore failed for ${t}: ${o.stderr.trim()}`),1===o.status});o.length>0&&fail("appConfigInvalid",`add these lines to ${path.basename(e)}/.gitignore; prebuild writes them per environment:\n${o.join("\n")}`)};const writeIfChanged=(e,t)=>(!existsSync(e)||readFileSync(e,"utf8")!==t)&&(writeFileSync(e,t,"utf8"),!0),report=(e,t,i)=>{say(`prebuild: ${i?"wrote":"unchanged"} ${path.relative(e,t)}`)},dependsOn=(e,t)=>{const i=path.join(e,"package.json");if(!existsSync(i))return!1;const o=JSON.parse(readFileSync(i,"utf8"));return Boolean(o.dependencies?.[t])};export const usesFirebase=e=>dependsOn(e,"@react-native-firebase/app");export const checkNdkHook=e=>{const t=path.join(e,"android","build.gradle");if(!existsSync(t))return;const i=readFileSync(t,"utf8");/withId\(\s*["']com\.android\.library["']\s*\)/.test(i)&&/\.ndkVersion\s*=\s*rootProject\.ext\.ndkVersion/.test(i)||fail("appConfigInvalid",'android/build.gradle does not hand the app NDK to library modules; add after apply plugin "com.facebook.react.rootproject": subprojects { project -> project.plugins.withId("com.android.library") { project.android.ndkVersion = rootProject.ext.ndkVersion } }')};const MANAGED_GRADLE_KEYS=/^\s*(APP_NAME|APP_ID|VERSION_DISPLAY|VERSION_INTERNAL)\s*[=:]/gm;export const stampAndroid=(e,t,i,o,n)=>{const s=path.join(e,"android","gradle.properties");existsSync(s)||fail("appConfigInvalid",`android/gradle.properties not found in ${e}`),usesFirebase(e)&&!existsSync(path.join(e,"android","app","google-services.json"))&&fail("appConfigInvalid","android/app/google-services.json is missing; the app uses @react-native-firebase, whose Gradle plugin needs it"),checkNdkHook(e);const r=[...new Set([...readFileSync(s,"utf8").matchAll(MANAGED_GRADLE_KEYS)].map(([,e])=>e))];r.length>0&&fail("appConfigInvalid",`android/gradle.properties sets ${r.join(", ")}: remove them; android/app/build.gradle reads them from appsettings.Compiled.json`);const a=path.join(e,"android","app","build.gradle");if(existsSync(a)&&readFileSync(a,"utf8").includes("appsettings.Compiled.json")||fail("appConfigInvalid","android/app/build.gradle does not read appsettings.Compiled.json; add the compiledSettings loader (mobile-tools README, prebuild)"),usesExpoUpdates(e)){o.flavors||fail("appConfigInvalid",'expo-updates settings go into the flavor\'s manifest; set "flavors": true');const s=path.join(e,"android","app","src","main","AndroidManifest.xml");existsSync(s)||fail("appConfigInvalid","android/app/src/main/AndroidManifest.xml not found");const r=[...readFileSync(s,"utf8").matchAll(/android:name="(expo\.modules\.updates\.[^"]*)"/g)].map(([,e])=>e);r.length>0&&fail("appConfigInvalid",`android/app/src/main/AndroidManifest.xml sets ${r.join(", ")}: remove them from android/app/src/main/AndroidManifest.xml; prebuild writes them into ${androidFlavorManifest(i)}`);const a=otaNativeSettings(e,t,i,"android",n),p=path.join(e,androidFlavorManifest(i));mkdirSync(path.dirname(p),{recursive:!0}),report(e,p,writeIfChanged(p,androidOtaManifest(a)))}};export const stampIos=(e,t,i,o,n,s)=>{const r=path.join(e,"ios",n),a=path.join(r,"Info.plist"),p=path.join(e,"ios",`${n}.xcodeproj`,"project.pbxproj");for(const t of[a,p])existsSync(t)||fail("appConfigInvalid",`${path.relative(e,t)} not found: check "iosProjectName"`);checkInfoPlistReferences(e,n);const c=`AppIcon-${i}`,d=path.join(r,"Images.xcassets"),l=existsSync(path.join(d,`${c}.appiconset`)),f=ENVIRONMENTS.filter(e=>e!==i&&existsSync(path.join(d,`AppIcon-${e}.appiconset`)));!l&&f.length>0&&fail("appConfigInvalid",`ios/${n}/Images.xcassets has AppIcon-${f[0]} but no ${c}: run mobile-tools icons`),checkPbxprojSettings(readFileSync(p,"utf8"),l);const u=path.join(e,IOS_COMPILED_XCCONFIG);report(e,u,writeIfChanged(u,xcconfigText(t,i,l))),l||say(`prebuild: no AppIcon-${i} set, so ios/appsettings.Compiled.xcconfig sets no app icon name`);const g=path.join(r,"GoogleService-Info.plist"),I=path.join(e,o.firebasePlistDir,`GoogleService-Info.${i}.plist`);if(!existsSync(I)&&usesFirebase(e)&&fail("appConfigInvalid",`${path.relative(e,I)} is missing; the app uses @react-native-firebase, and an iOS build without it reports no crashes`),existsSync(I)){const t=!existsSync(g)||!readFileSync(I).equals(readFileSync(g));t&©FileSync(I,g),report(e,g,t)}else existsSync(g)&&(rmSync(g),say(`prebuild: removed ${path.relative(e,g)}, no ${path.relative(e,I)}`));if(usesExpoUpdates(e)){readFileSync(p,"utf8").includes("Expo.plist in Resources")||fail("appConfigInvalid","add Supporting/Expo.plist to the Xcode project's Copy Bundle Resources; prebuild writes its contents");const o=otaNativeSettings(e,t,i,"ios",s),r=path.join(e,expoPlistPath(n));mkdirSync(path.dirname(r),{recursive:!0}),report(e,r,writeIfChanged(r,expoPlist(o)))}};export const prebuild=e=>{const{appRoot:t,sameEnv:i,platform:o}=e,n=!0===e.otaTest;i&&e.env&&fail("badInput","pass --env or --same-env, not both");const s=i?lastCompiledEnvironment(t):e.env;if(!s)return fail("badInput","prebuild needs --env <Development|Staging|Production> or --same-env");const r=loadToolsConfig(t),a=resolveIosProjectName(t,r),p=loadAppSettings(t,s,r.requiredSettings);checkAppSettings(t,p,s);const c="android"===o||!o&&existsSync(path.join(t,"android")),d="android"===o?void 0:a;if("ios"===o&&void 0===d)return fail("appConfigInvalid",`no ios/ folder in ${t}`);const l=[...c?generatedNativeFiles(t,d,s,"android"):[],...void 0!==d?generatedNativeFiles(t,d,s,"ios"):[]];requireIgnored(t,[COMPILED_FILE,...l]);const f={...p,COMMIT:buildCommit(t),BUILD_TIME:(new Date).toISOString()};return writeFileSync(path.join(t,COMPILED_FILE),`${JSON.stringify(f,null,2)}\n`,"utf8"),say(`prebuild: wrote ${COMPILED_FILE} (${s}, ${f.COMMIT})`),c&&stampAndroid(t,f,s,r,n),void 0!==d&&stampIos(t,f,s,r,d,n),f};
|
package/lib/rootError.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const MAX_LINES=40,blockFrom=(t,n,r)=>{const
|
|
1
|
+
const MAX_LINES=40,blockFrom=(t,n,r)=>{const o=[];for(const e of t.slice(n,n+40)){if(o.length>0&&r(e))break;o.push(e)}for(;o.length>0&&""===o.at(-1)?.trim();)o.pop();return o};export const extractRootError=t=>{const n=t.split(/\r?\n/),r=n.findIndex(t=>t.includes("Unable to resolve module"));if(r>=0)return blockFrom(n,r,t=>""===t.trim()).join("\n");const o=n.findIndex(t=>"* What went wrong:"===t.trim());if(o>=0)return blockFrom(n,o+1,t=>/^\* [A-Z]/.test(t)).join("\n");const e=[...new Set(n.filter(t=>/(^|\s)error:/.test(t)).map(t=>t.trim()))];return e.length>0?e.slice(0,10).join("\n"):n.filter(t=>""!==t.trim()).slice(-20).join("\n")};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/mobile-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.147.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",
|