import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') function updateFile(path, update) { if (!existsSync(path)) return false const current = readFileSync(path, 'utf8') const next = update(current) if (next !== current) writeFileSync(path, next, 'utf8') return true } function configureAndroid() { const variablesPath = resolve(webRoot, 'android', 'variables.gradle') const manifestPath = resolve( webRoot, 'android', 'app', 'src', 'main', 'AndroidManifest.xml', ) if (!existsSync(variablesPath) || !existsSync(manifestPath)) return false updateFile(variablesPath, content => { if (!/minSdkVersion\s*=\s*\d+/.test(content)) { throw new Error('未在 android/variables.gradle 中找到 minSdkVersion。') } return content.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 26') }) updateFile(manifestPath, content => { const declarations = [ '', '', '', '', '', ] const missing = declarations.filter(declaration => !content.includes(declaration)) if (!missing.length) return content return content.replace( '', ` ${missing.join('\n ')}\n`, ) }) return true } function configureIos() { const infoPlistPath = resolve(webRoot, 'ios', 'App', 'App', 'Info.plist') if (!existsSync(infoPlistPath)) return false updateFile(infoPlistPath, content => { const descriptions = [ ['NSCameraUsageDescription', '用于扫描教师展示的课堂签到二维码。'], ['NSLocationWhenInUseUsageDescription', '用于在课堂签到时校验当前位置。'], ['NSLocationAlwaysAndWhenInUseUsageDescription', '用于在课堂签到时校验当前位置。'], ] const missing = descriptions.filter(([key]) => !content.includes(`${key}`)) if (!missing.length) return content const entries = missing .map(([key, value]) => `\t${key}\n\t${value}`) .join('\n') return content.replace('', `${entries}\n`) }) return true } const configuredPlatforms = [ configureAndroid() ? 'Android' : null, configureIos() ? 'iOS' : null, ].filter(Boolean) if (!configuredPlatforms.length) { throw new Error('尚未生成 Capacitor 原生工程,请先运行 npx cap add android 或 ios。') } console.log(`已配置 ${configuredPlatforms.join('、')} 的扫码和定位权限。`)