@aramiworks/app-updates 0.0.0-stage → 0.0.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.
@@ -0,0 +1,7 @@
1
+ export type Distribution = 'app-store' | 'play' | 'firebase';
2
+ export interface StoreUpdate {
3
+ installed: string;
4
+ available: string;
5
+ source: Distribution;
6
+ url: string | null;
7
+ }
package/build/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,3 @@
1
+ import type { AppUpdateState, UseAppUpdateOptions } from './useAppUpdateCore';
2
+ export type { AppUpdateState, UseAppUpdateOptions } from './useAppUpdateCore';
3
+ export declare function useAppUpdate(options?: UseAppUpdateOptions): AppUpdateState;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAppUpdate = useAppUpdate;
4
+ const useAppUpdateCore_1 = require("./useAppUpdateCore");
5
+ function useAppUpdate(options = {}) {
6
+ return (0, useAppUpdateCore_1.useAppUpdateWithDeps)(options, {});
7
+ }
@@ -0,0 +1,43 @@
1
+ import { readVerified, writeVerified, type KeyValueStore } from './cache';
2
+ import { checkWarmOta, runColdStartOta } from './ota';
3
+ import { checkStoreUpdate, type StoreCheckEnv } from './storeCheck';
4
+ import { type TesterState } from './tester';
5
+ import type { StoreUpdate } from './types';
6
+ export interface UseAppUpdateOptions {
7
+ /** false → inert state with no side effects (e.g. dev clients). Default true. */
8
+ enabled?: boolean;
9
+ }
10
+ export interface AppUpdateState {
11
+ /** true while the cold-start OTA runs; render NoticeTemplate "Updating…". */
12
+ coldStartUpdating: boolean;
13
+ /** Non-null → render the blocking NoticeTemplate; wins over everything else. */
14
+ storeUpdate: StoreUpdate | null;
15
+ openStore: () => Promise<void>;
16
+ /** A warm OTA is downloaded; render the persistent Snackbar. */
17
+ otaReady: boolean;
18
+ restart: () => Promise<void>;
19
+ dismissOta: () => void;
20
+ /** Firebase builds only: inert (signedIn null, no prompt) elsewhere. */
21
+ tester: TesterState;
22
+ }
23
+ /**
24
+ * Every collaborator the hook uses. Tests pass a partial mock as the hook's second
25
+ * parameter, so they need no global module mocks. Apps never pass it.
26
+ */
27
+ export interface AppUpdateDeps {
28
+ getEnv: () => StoreCheckEnv;
29
+ checkStoreUpdate: typeof checkStoreUpdate;
30
+ runColdStartOta: typeof runColdStartOta;
31
+ checkWarmOta: typeof checkWarmOta;
32
+ readVerified: typeof readVerified;
33
+ writeVerified: typeof writeVerified;
34
+ isFirebaseAvailable: () => boolean;
35
+ isTesterSignedIn: () => Promise<boolean>;
36
+ signInTester: () => Promise<void>;
37
+ openStore: (update: StoreUpdate) => Promise<void>;
38
+ reload: () => Promise<void>;
39
+ now: () => number;
40
+ store: KeyValueStore;
41
+ }
42
+ /** Hook body with injectable collaborators. Internal: tests import it; the public hook wraps it. */
43
+ export declare function useAppUpdateWithDeps(options: UseAppUpdateOptions, deps: Partial<AppUpdateDeps>): AppUpdateState;
@@ -0,0 +1,209 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.useAppUpdateWithDeps = useAppUpdateWithDeps;
37
+ const Updates = __importStar(require("expo-updates"));
38
+ const react_1 = require("react");
39
+ const react_native_1 = require("react-native");
40
+ const cache_1 = require("./cache");
41
+ const env_1 = require("./env");
42
+ const native_1 = require("./native");
43
+ const openStore_1 = require("./openStore");
44
+ const ota_1 = require("./ota");
45
+ const storeCheck_1 = require("./storeCheck");
46
+ const tester_1 = require("./tester");
47
+ const throttle_1 = require("./throttle");
48
+ const DEFAULT_DEPS = {
49
+ getEnv: env_1.getEnv,
50
+ checkStoreUpdate: storeCheck_1.checkStoreUpdate,
51
+ runColdStartOta: ota_1.runColdStartOta,
52
+ checkWarmOta: ota_1.checkWarmOta,
53
+ readVerified: cache_1.readVerified,
54
+ writeVerified: cache_1.writeVerified,
55
+ isFirebaseAvailable: native_1.isFirebaseAvailable,
56
+ isTesterSignedIn: native_1.isTesterSignedIn,
57
+ signInTester: native_1.signInTester,
58
+ openStore: (update) => (0, openStore_1.openStore)(update),
59
+ reload: () => Updates.reloadAsync(),
60
+ now: Date.now,
61
+ store: cache_1.secureStore,
62
+ };
63
+ const INERT = {
64
+ coldStartUpdating: false,
65
+ storeUpdate: null,
66
+ openStore: async () => { },
67
+ otaReady: false,
68
+ restart: async () => { },
69
+ dismissOta: () => { },
70
+ tester: tester_1.INERT_TESTER,
71
+ };
72
+ const NULL_OTA_ID = '\0no-update-id';
73
+ /** Hook body with injectable collaborators. Internal: tests import it; the public hook wraps it. */
74
+ function useAppUpdateWithDeps(options, deps) {
75
+ const d = { ...DEFAULT_DEPS };
76
+ for (const key of Object.keys(deps)) {
77
+ if (deps[key] !== undefined)
78
+ d[key] = deps[key];
79
+ }
80
+ const depsRef = (0, react_1.useRef)(d);
81
+ (0, react_1.useEffect)(() => {
82
+ depsRef.current = d;
83
+ });
84
+ // The environment is read once per mount. `enabled` is honoured at mount; flipping it
85
+ // from false to true later does not start checks until the component remounts.
86
+ const [env] = (0, react_1.useState)(() => options.enabled !== false ? d.getEnv() : null);
87
+ const active = env !== null && env.platform !== 'web';
88
+ const mounted = (0, react_1.useRef)(true);
89
+ const started = (0, react_1.useRef)(false);
90
+ const lastCheckAt = (0, react_1.useRef)(null);
91
+ const dismissedOta = (0, react_1.useRef)(new Set());
92
+ const [coldStartUpdating, setColdStartUpdating] = (0, react_1.useState)(active);
93
+ const [storeUpdate, setStoreUpdate] = (0, react_1.useState)(null);
94
+ const [otaKey, setOtaKey] = (0, react_1.useState)(null);
95
+ const isMounted = (0, react_1.useCallback)(() => mounted.current, []);
96
+ (0, react_1.useEffect)(() => {
97
+ mounted.current = true;
98
+ return () => {
99
+ mounted.current = false;
100
+ };
101
+ }, []);
102
+ const runStoreCheck = (0, react_1.useCallback)(async () => {
103
+ if (!env)
104
+ return;
105
+ const { checkStoreUpdate: check, writeVerified: write, store, now } = depsRef.current;
106
+ try {
107
+ const result = await check(env);
108
+ if (result.kind === 'update') {
109
+ await write(store, result.update, now());
110
+ if (mounted.current)
111
+ setStoreUpdate(result.update);
112
+ }
113
+ else if (result.kind === 'none') {
114
+ // The source said definitively nothing newer exists: lift the gate.
115
+ await (0, cache_1.clearVerified)(store);
116
+ if (mounted.current)
117
+ setStoreUpdate(null);
118
+ }
119
+ // 'error': keep the current state and cache (fail open without unblocking).
120
+ }
121
+ catch {
122
+ // checkStoreUpdate never throws; stay fail-open if a fake does
123
+ }
124
+ }, [env]);
125
+ const runWarmCheck = (0, react_1.useCallback)(async () => {
126
+ try {
127
+ const r = await depsRef.current.checkWarmOta();
128
+ if (!r.ready || !mounted.current)
129
+ return;
130
+ const key = r.updateId ?? NULL_OTA_ID;
131
+ if (!dismissedOta.current.has(key))
132
+ setOtaKey(key);
133
+ }
134
+ catch {
135
+ // checkWarmOta never throws
136
+ }
137
+ }, []);
138
+ const recheckStore = (0, react_1.useCallback)(() => {
139
+ lastCheckAt.current = depsRef.current.now();
140
+ runStoreCheck();
141
+ }, [runStoreCheck]);
142
+ (0, react_1.useEffect)(() => {
143
+ if (!active || !env)
144
+ return;
145
+ const { readVerified: readCache, runColdStartOta: coldStart, store, now } = depsRef.current;
146
+ // One-shot mount work runs once per hook instance, even if StrictMode re-runs the effect.
147
+ if (!started.current) {
148
+ started.current = true;
149
+ lastCheckAt.current = now();
150
+ if (env.installed) {
151
+ readCache(store, env.installed, now()).then((cached) => {
152
+ if (cached && mounted.current)
153
+ setStoreUpdate((prev) => prev ?? cached);
154
+ });
155
+ }
156
+ runStoreCheck();
157
+ coldStart()
158
+ .then((result) => {
159
+ if (result !== 'reloading' && mounted.current)
160
+ setColdStartUpdating(false);
161
+ })
162
+ .catch(() => {
163
+ if (mounted.current)
164
+ setColdStartUpdating(false);
165
+ });
166
+ }
167
+ const sub = react_native_1.AppState.addEventListener('change', (state) => {
168
+ if (state !== 'active')
169
+ return;
170
+ const at = depsRef.current.now();
171
+ if (!(0, throttle_1.shouldCheck)(lastCheckAt.current, at))
172
+ return;
173
+ lastCheckAt.current = at;
174
+ runStoreCheck();
175
+ runWarmCheck();
176
+ });
177
+ return () => sub.remove();
178
+ }, [active, env, runStoreCheck, runWarmCheck]);
179
+ const blocked = storeUpdate !== null;
180
+ const isAndroid = env?.platform === 'android';
181
+ (0, react_1.useEffect)(() => {
182
+ if (!blocked || !isAndroid)
183
+ return;
184
+ const sub = react_native_1.BackHandler.addEventListener('hardwareBackPress', () => true);
185
+ return () => sub.remove();
186
+ }, [blocked, isAndroid]);
187
+ const tester = (0, tester_1.useTester)(active && env !== null && (0, tester_1.isFirebaseBuild)(env) && d.isFirebaseAvailable(), d, recheckStore, isMounted);
188
+ const openStore = (0, react_1.useCallback)(async () => {
189
+ if (storeUpdate)
190
+ await depsRef.current.openStore(storeUpdate);
191
+ }, [storeUpdate]);
192
+ const restart = (0, react_1.useCallback)(() => depsRef.current.reload(), []);
193
+ const dismissOta = (0, react_1.useCallback)(() => {
194
+ if (otaKey !== null)
195
+ dismissedOta.current.add(otaKey);
196
+ setOtaKey(null);
197
+ }, [otaKey]);
198
+ if (!active)
199
+ return INERT;
200
+ return {
201
+ coldStartUpdating,
202
+ storeUpdate,
203
+ openStore,
204
+ otaReady: otaKey !== null && storeUpdate === null,
205
+ restart,
206
+ dismissOta,
207
+ tester,
208
+ };
209
+ }
@@ -0,0 +1,13 @@
1
+ export type MajorMinor = {
2
+ major: number;
3
+ minor: number;
4
+ };
5
+ /** Reads the leading `v?<int>.<int>` of a version string; anything else yields null. */
6
+ export declare function parseMajorMinor(v: string | null | undefined): MajorMinor | null;
7
+ /** True when the candidate's major.minor is strictly greater than the installed one. */
8
+ export declare function isNewerMajorMinor(installed: MajorMinor, candidate: MajorMinor): boolean;
9
+ /** Android versionCode is `major * 1_000_000 + minor * 1_000 + build`. */
10
+ export declare function decodeVersionCode(code: number): MajorMinor & {
11
+ build: number;
12
+ };
13
+ export declare function formatMajorMinor(v: MajorMinor): string;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseMajorMinor = parseMajorMinor;
4
+ exports.isNewerMajorMinor = isNewerMajorMinor;
5
+ exports.decodeVersionCode = decodeVersionCode;
6
+ exports.formatMajorMinor = formatMajorMinor;
7
+ const LEADING_MAJOR_MINOR = /^v?(\d+)\.(\d+)/;
8
+ /** Reads the leading `v?<int>.<int>` of a version string; anything else yields null. */
9
+ function parseMajorMinor(v) {
10
+ if (!v)
11
+ return null;
12
+ const match = LEADING_MAJOR_MINOR.exec(v);
13
+ if (!match)
14
+ return null;
15
+ return { major: Number(match[1]), minor: Number(match[2]) };
16
+ }
17
+ /** True when the candidate's major.minor is strictly greater than the installed one. */
18
+ function isNewerMajorMinor(installed, candidate) {
19
+ if (candidate.major !== installed.major)
20
+ return candidate.major > installed.major;
21
+ return candidate.minor > installed.minor;
22
+ }
23
+ /** Android versionCode is `major * 1_000_000 + minor * 1_000 + build`. */
24
+ function decodeVersionCode(code) {
25
+ const major = Math.floor(code / 1_000_000);
26
+ const minor = Math.floor((code % 1_000_000) / 1_000);
27
+ const build = code % 1_000;
28
+ return { major, minor, build };
29
+ }
30
+ function formatMajorMinor(v) {
31
+ return `${v.major}.${v.minor}`;
32
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "platforms": ["android"],
3
+ "android": {
4
+ "modules": ["so.arami.appupdates.AppUpdatesModule"]
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@aramiworks/app-updates",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Native app update checks and OTA flow for Expo apps",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "files": [
8
+ "build",
9
+ "plugin/build",
10
+ "app.plugin.js",
11
+ "android",
12
+ "!android/build",
13
+ "expo-module.config.json"
14
+ ],
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.build.json && tsc -p plugin/tsconfig.build.json",
17
+ "clean": "node -e \"for (const d of ['build','plugin/build']) require('fs').rmSync(d,{recursive:true,force:true})\"",
18
+ "lint": "eslint src/ plugin/src/",
19
+ "test": "jest --passWithNoTests",
20
+ "typecheck": "tsc --noEmit && tsc --noEmit -p plugin/tsconfig.json"
21
+ },
22
+ "keywords": [
23
+ "react-native",
24
+ "expo",
25
+ "app-updates"
26
+ ],
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/arami-works/foundation.git",
30
+ "directory": "packages/app-updates"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/arami-works/foundation/issues"
34
+ },
35
+ "author": "Arami <jaemin@arami.so> (https://github.com/arami-works)",
36
+ "license": "MIT",
37
+ "homepage": "https://github.com/arami-works/foundation/tree/main/packages/app-updates#readme",
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "jest": {
42
+ "preset": "jest-expo",
43
+ "roots": [
44
+ "<rootDir>/src",
45
+ "<rootDir>/plugin/src"
46
+ ]
47
+ },
48
+ "peerDependencies": {
49
+ "@react-native-firebase/app-distribution": ">=27",
50
+ "expo": ">=57",
51
+ "expo-application": ">=57",
52
+ "expo-localization": ">=57",
53
+ "expo-secure-store": ">=57",
54
+ "expo-updates": ">=57",
55
+ "react": ">=19",
56
+ "react-native": ">=0.86"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "@react-native-firebase/app-distribution": {
60
+ "optional": true
61
+ }
62
+ }
63
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Pure string transforms over the app-level `android/app/build.gradle` (Groovy).
3
+ * Kept free of Expo imports so they are trivially testable.
4
+ */
5
+ export declare const MARKER = "// @aramiworks/app-updates";
6
+ export declare const DISTRIBUTION_DIMENSION = "distribution";
7
+ export declare const DISTRIBUTION_RESOURCE = "app_updates_distribution";
8
+ export declare function addDistributionFlavors(appBuildGradle: string): string;
9
+ export declare function addFirebaseDependency(appBuildGradle: string, version: string): string;
10
+ export declare const DEBUGGABLE_VARIANTS: readonly ["playDebug", "firebaseDebug"];
11
+ /**
12
+ * With flavors the RN Gradle plugin's debug variants are `playDebug` / `firebaseDebug`;
13
+ * its default `debuggableVariants = ["debug"]` matches none of them (exact variant name,
14
+ * case-insensitive), so debug builds would bundle JS instead of loading from Metro.
15
+ */
16
+ export declare function setDebuggableVariants(appBuildGradle: string): string;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * Pure string transforms over the app-level `android/app/build.gradle` (Groovy).
4
+ * Kept free of Expo imports so they are trivially testable.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.DEBUGGABLE_VARIANTS = exports.DISTRIBUTION_RESOURCE = exports.DISTRIBUTION_DIMENSION = exports.MARKER = void 0;
8
+ exports.addDistributionFlavors = addDistributionFlavors;
9
+ exports.addFirebaseDependency = addFirebaseDependency;
10
+ exports.setDebuggableVariants = setDebuggableVariants;
11
+ exports.MARKER = '// @aramiworks/app-updates';
12
+ exports.DISTRIBUTION_DIMENSION = 'distribution';
13
+ exports.DISTRIBUTION_RESOURCE = 'app_updates_distribution';
14
+ const FLAVORS = ['play', 'firebase'];
15
+ /**
16
+ * Finds direct-child `name { ... }` blocks of the range (depth 0 relative to `from`).
17
+ * Skips line/block comments and quoted strings so braces inside them do not count.
18
+ */
19
+ function findChildBlock(src, name, from, to) {
20
+ const head = new RegExp(`^${name}\\s*\\{`);
21
+ let depth = 0;
22
+ let i = from;
23
+ let open = -1;
24
+ while (i < to) {
25
+ const ch = src[i];
26
+ const next = src[i + 1];
27
+ if (ch === '/' && next === '/') {
28
+ const nl = src.indexOf('\n', i);
29
+ i = nl === -1 ? to : nl;
30
+ continue;
31
+ }
32
+ if (ch === '/' && next === '*') {
33
+ const end = src.indexOf('*/', i + 2);
34
+ i = end === -1 ? to : end + 2;
35
+ continue;
36
+ }
37
+ if (ch === '"' || ch === "'") {
38
+ i++;
39
+ while (i < to && src[i] !== ch) {
40
+ if (src[i] === '\\')
41
+ i++;
42
+ i++;
43
+ }
44
+ i++;
45
+ continue;
46
+ }
47
+ if (ch === '{') {
48
+ if (depth === 0) {
49
+ // `name {` start: look back for the identifier on this line.
50
+ const lineStart = src.lastIndexOf('\n', i) + 1;
51
+ const before = src.slice(Math.max(lineStart, from), i + 1).trim();
52
+ open = head.test(before) ? i : -1;
53
+ }
54
+ depth++;
55
+ }
56
+ else if (ch === '}') {
57
+ depth--;
58
+ if (depth === 0 && open !== -1)
59
+ return { open, close: i };
60
+ if (depth < 0)
61
+ return null;
62
+ }
63
+ i++;
64
+ }
65
+ return null;
66
+ }
67
+ /** Inserts `text` (newline-terminated lines) on its own lines just before the `}` at `close`. */
68
+ function insertBeforeClose(src, close, text) {
69
+ const lineStart = src.lastIndexOf('\n', close) + 1;
70
+ if (src.slice(lineStart, close).trim() === '') {
71
+ return src.slice(0, lineStart) + text + src.slice(lineStart);
72
+ }
73
+ return src.slice(0, close) + '\n' + text + src.slice(close);
74
+ }
75
+ function indentOf(src, pos) {
76
+ const lineStart = src.lastIndexOf('\n', pos) + 1;
77
+ return /^[ \t]*/.exec(src.slice(lineStart))[0];
78
+ }
79
+ function flavorBlock(name, indent) {
80
+ return (`${indent}${name} {\n` +
81
+ `${indent} dimension "${exports.DISTRIBUTION_DIMENSION}"\n` +
82
+ `${indent} resValue "string", "${exports.DISTRIBUTION_RESOURCE}", "${name}"\n` +
83
+ `${indent}}\n`);
84
+ }
85
+ function addDistributionFlavors(appBuildGradle) {
86
+ let src = appBuildGradle;
87
+ const android = findChildBlock(src, 'android', 0, src.length);
88
+ if (!android) {
89
+ throw new Error('@aramiworks/app-updates: no `android { }` block found in app/build.gradle');
90
+ }
91
+ // 1. flavorDimensions
92
+ const body = src.slice(android.open, android.close);
93
+ const dimsPresent = /^\s*flavorDimensions\b/m.test(body);
94
+ const hasDistribution = /flavorDimensions[^\n]*["']distribution["']/.test(body);
95
+ const baseIndent = indentOf(src, android.open) + ' ';
96
+ if (!hasDistribution) {
97
+ const stmt = dimsPresent
98
+ ? `flavorDimensions += "${exports.DISTRIBUTION_DIMENSION}"`
99
+ : `flavorDimensions "${exports.DISTRIBUTION_DIMENSION}"`;
100
+ src = insertBeforeClose(src, android.close, `${baseIndent}${exports.MARKER}\n${baseIndent}${stmt}\n`);
101
+ }
102
+ // 2. productFlavors
103
+ let range = findChildBlock(src, 'android', 0, src.length);
104
+ let pf = findChildBlock(src, 'productFlavors', range.open + 1, range.close);
105
+ if (!pf) {
106
+ src = insertBeforeClose(src, range.close, `${baseIndent}${exports.MARKER}\n${baseIndent}productFlavors {\n${baseIndent}}\n`);
107
+ range = findChildBlock(src, 'android', 0, src.length);
108
+ pf = findChildBlock(src, 'productFlavors', range.open + 1, range.close);
109
+ }
110
+ const flavorIndent = indentOf(src, pf.open) + ' ';
111
+ for (const name of FLAVORS) {
112
+ const android2 = findChildBlock(src, 'android', 0, src.length);
113
+ const pf2 = findChildBlock(src, 'productFlavors', android2.open + 1, android2.close);
114
+ const flavor = findChildBlock(src, name, pf2.open + 1, pf2.close);
115
+ if (!flavor) {
116
+ src = insertBeforeClose(src, pf2.close, flavorBlock(name, flavorIndent));
117
+ }
118
+ else if (!new RegExp(`resValue\\s+["']string["']\\s*,\\s*["']${exports.DISTRIBUTION_RESOURCE}["']`).test(src.slice(flavor.open, flavor.close))) {
119
+ const ind = flavorIndent + ' ';
120
+ src = insertBeforeClose(src, flavor.close, `${ind}resValue "string", "${exports.DISTRIBUTION_RESOURCE}", "${name}"\n`);
121
+ }
122
+ }
123
+ return src;
124
+ }
125
+ function addFirebaseDependency(appBuildGradle, version) {
126
+ const line = `firebaseImplementation "com.google.firebase:firebase-appdistribution:${version}"`;
127
+ const existing = /firebaseImplementation[ \t(]*["']com\.google\.firebase:firebase-appdistribution:[^"']*["']\)?/;
128
+ if (existing.test(appBuildGradle)) {
129
+ return appBuildGradle.replace(existing, line);
130
+ }
131
+ const deps = findChildBlock(appBuildGradle, 'dependencies', 0, appBuildGradle.length);
132
+ if (!deps) {
133
+ throw new Error('@aramiworks/app-updates: no `dependencies { }` block found in app/build.gradle');
134
+ }
135
+ const ind = indentOf(appBuildGradle, deps.open) + ' ';
136
+ return insertBeforeClose(appBuildGradle, deps.close, `\n${ind}${exports.MARKER}\n${ind}${line}\n`);
137
+ }
138
+ exports.DEBUGGABLE_VARIANTS = ['playDebug', 'firebaseDebug'];
139
+ /**
140
+ * With flavors the RN Gradle plugin's debug variants are `playDebug` / `firebaseDebug`;
141
+ * its default `debuggableVariants = ["debug"]` matches none of them (exact variant name,
142
+ * case-insensitive), so debug builds would bundle JS instead of loading from Metro.
143
+ */
144
+ function setDebuggableVariants(appBuildGradle) {
145
+ const quoted = exports.DEBUGGABLE_VARIANTS.map((v) => `"${v}"`).join(', ');
146
+ const react = findChildBlock(appBuildGradle, 'react', 0, appBuildGradle.length);
147
+ if (!react) {
148
+ const sep = appBuildGradle.endsWith('\n') ? '' : '\n';
149
+ return `${appBuildGradle}${sep}\n${exports.MARKER}\nreact {\n debuggableVariants = [${quoted}]\n}\n`;
150
+ }
151
+ const body = appBuildGradle.slice(react.open + 1, react.close);
152
+ const active = /^([ \t]*debuggableVariants\s*=\s*\[)([^\]]*)(\])/m.exec(body);
153
+ if (active) {
154
+ const items = active[2]
155
+ .split(',')
156
+ .map((s) => s.trim())
157
+ .filter(Boolean);
158
+ const have = new Set(items.map((s) => s.replace(/^["']|["']$/g, '')));
159
+ const missing = exports.DEBUGGABLE_VARIANTS.filter((v) => !have.has(v));
160
+ if (missing.length === 0)
161
+ return appBuildGradle;
162
+ const merged = [...items, ...missing.map((v) => `"${v}"`)].join(', ');
163
+ const start = react.open + 1 + active.index;
164
+ return (appBuildGradle.slice(0, start) +
165
+ active[1] +
166
+ merged +
167
+ active[3] +
168
+ appBuildGradle.slice(start + active[0].length));
169
+ }
170
+ const ind = indentOf(appBuildGradle, react.open) + ' ';
171
+ return insertBeforeClose(appBuildGradle, react.close, `\n${ind}${exports.MARKER}\n${ind}debuggableVariants = [${quoted}]\n`);
172
+ }
@@ -0,0 +1,16 @@
1
+ import type { ConfigPlugin } from 'expo/config-plugins';
2
+ /** Same version line as the `firebase-appdistribution-api` artifact in android/build.gradle. */
3
+ export declare const DEFAULT_FIREBASE_APPDISTRIBUTION_VERSION = "16.0.0-beta21";
4
+ export type AppUpdatesPluginProps = {
5
+ /** Version of `com.google.firebase:firebase-appdistribution` added to the firebase flavor. */
6
+ firebaseVersion?: string;
7
+ };
8
+ /**
9
+ * Android: adds `play` / `firebase` product flavors (each writing the
10
+ * `app_updates_distribution` string resource) and the full Firebase App Distribution
11
+ * SDK for the firebase flavor only, and sets `react { debuggableVariants }` for the flavored
12
+ * debug variants. Build tasks are renamed, so set `android.gradleCommand` per EAS profile:
13
+ * `:app:bundlePlayRelease` (store .aab), `:app:assembleFirebaseRelease` (Firebase tester APK). iOS: nothing (D36, no iOS native setup).
14
+ */
15
+ export declare const withAppUpdates: ConfigPlugin<AppUpdatesPluginProps | void>;
16
+ export default withAppUpdates;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withAppUpdates = exports.DEFAULT_FIREBASE_APPDISTRIBUTION_VERSION = void 0;
4
+ const config_plugins_1 = require("expo/config-plugins");
5
+ const gradle_1 = require("./gradle");
6
+ /** Same version line as the `firebase-appdistribution-api` artifact in android/build.gradle. */
7
+ exports.DEFAULT_FIREBASE_APPDISTRIBUTION_VERSION = '16.0.0-beta21';
8
+ /**
9
+ * Android: adds `play` / `firebase` product flavors (each writing the
10
+ * `app_updates_distribution` string resource) and the full Firebase App Distribution
11
+ * SDK for the firebase flavor only, and sets `react { debuggableVariants }` for the flavored
12
+ * debug variants. Build tasks are renamed, so set `android.gradleCommand` per EAS profile:
13
+ * `:app:bundlePlayRelease` (store .aab), `:app:assembleFirebaseRelease` (Firebase tester APK). iOS: nothing (D36, no iOS native setup).
14
+ */
15
+ const withAppUpdates = (config, props) => {
16
+ const firebaseVersion = props?.firebaseVersion ?? exports.DEFAULT_FIREBASE_APPDISTRIBUTION_VERSION;
17
+ return (0, config_plugins_1.withAppBuildGradle)(config, (cfg) => {
18
+ if (cfg.modResults.language !== 'groovy') {
19
+ throw new Error('@aramiworks/app-updates: only Groovy app/build.gradle is supported (found ' +
20
+ cfg.modResults.language +
21
+ ').');
22
+ }
23
+ cfg.modResults.contents = (0, gradle_1.addFirebaseDependency)((0, gradle_1.setDebuggableVariants)((0, gradle_1.addDistributionFlavors)(cfg.modResults.contents)), firebaseVersion);
24
+ return cfg;
25
+ });
26
+ };
27
+ exports.withAppUpdates = withAppUpdates;
28
+ exports.default = exports.withAppUpdates;