@gfean/react-native-bundle-drop 0.4.6 → 0.6.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.
Files changed (102) hide show
  1. package/README.md +168 -4
  2. package/android/build.gradle +1 -0
  3. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +69 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  6. package/ios/BundleDropBridge.m +18 -0
  7. package/ios/BundleDropLocator.swift +48 -2
  8. package/ios/BundleDropModule.swift +75 -0
  9. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  10. package/lib/CLI/cli.d.ts +1 -0
  11. package/lib/CLI/cli.js +166 -79
  12. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  13. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  14. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  15. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  16. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  17. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  18. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  19. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  20. package/lib/CLI/scripts/aipowered/init-project-config.js +228 -43
  21. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  22. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  23. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  24. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  25. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  26. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  27. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  28. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  29. package/lib/CLI/scripts/doctor.js +143 -22
  30. package/lib/CLI/scripts/expo/configure-expo.js +51 -60
  31. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  32. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  33. package/lib/CLI/scripts/init-config.d.ts +7 -7
  34. package/lib/CLI/scripts/init-config.js +246 -32
  35. package/lib/CLI/scripts/login-cli.js +35 -10
  36. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  37. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  38. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  39. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  40. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  41. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  42. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  43. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  44. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  45. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  46. package/lib/CLI/scripts/sight-artifacts.d.ts +17 -0
  47. package/lib/CLI/scripts/sight-artifacts.js +204 -0
  48. package/lib/CLI/scripts/sight-cli.d.ts +10 -0
  49. package/lib/CLI/scripts/sight-cli.js +127 -0
  50. package/lib/CLI/scripts/sight-session.d.ts +14 -0
  51. package/lib/CLI/scripts/sight-session.js +192 -0
  52. package/lib/api/clientApi.d.ts +3 -1
  53. package/lib/api/clientApi.js +14 -0
  54. package/lib/api/types.d.ts +39 -0
  55. package/lib/context.d.ts +1 -1
  56. package/lib/index.d.ts +2 -0
  57. package/lib/index.js +3 -1
  58. package/lib/install/installFromZip.d.ts +3 -0
  59. package/lib/install/installFromZip.js +10 -1
  60. package/lib/loadConfig.d.ts +17 -1
  61. package/lib/loadConfig.js +16 -0
  62. package/lib/manager/downloadAndInstall.d.ts +3 -2
  63. package/lib/manager/downloadAndInstall.js +111 -46
  64. package/lib/manager/rollbackState.d.ts +3 -1
  65. package/lib/manager/rollbackState.js +2 -2
  66. package/lib/manager/updateCheck.d.ts +1 -0
  67. package/lib/manager/updateCheck.js +218 -78
  68. package/lib/metro.d.ts +8 -1
  69. package/lib/metro.js +68 -19
  70. package/lib/native/bundleDropNative.js +2 -1
  71. package/lib/native/fs.d.ts +6 -0
  72. package/lib/native/fs.js +24 -0
  73. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  74. package/lib/patch-engine/installFromPatchSet.js +14 -3
  75. package/lib/patch-engine/patchTransport.d.ts +2 -0
  76. package/lib/patch-engine/patchTransport.js +9 -0
  77. package/lib/runtime/initState.d.ts +5 -0
  78. package/lib/runtime/initState.js +4 -0
  79. package/lib/runtime/service.js +60 -3
  80. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  81. package/lib/runtime-delivery/artifactCapability.js +32 -0
  82. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  83. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  84. package/lib/runtime-delivery/bootstrapConfig.d.ts +50 -0
  85. package/lib/runtime-delivery/bootstrapConfig.js +217 -0
  86. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  87. package/lib/runtime-delivery/diagnostics.js +58 -0
  88. package/lib/runtime-delivery/encoding.d.ts +5 -0
  89. package/lib/runtime-delivery/encoding.js +132 -0
  90. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  91. package/lib/runtime-delivery/heartbeat.js +88 -0
  92. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  93. package/lib/runtime-delivery/localResolver.js +81 -0
  94. package/lib/runtime-delivery/manifestState.d.ts +9 -0
  95. package/lib/runtime-delivery/manifestState.js +102 -0
  96. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  97. package/lib/runtime-delivery/manifestVerifier.js +329 -0
  98. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  99. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  100. package/lib/runtime-delivery/types.d.ts +87 -0
  101. package/lib/runtime-delivery/types.js +6 -0
  102. package/package.json +2 -2
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.assertCommonJsMetroConfig = exports.newCommonJsMetroConfigFile = exports.findSingleMetroConfig = exports.hasAuthoritativeMetroWrapper = exports.hasExecutableMetroModuleReference = exports.hasExecutableMetroWrapperReference = exports.METRO_CONFIG_FILES = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const native_setup_contract_1 = require("./native-setup-contract");
9
+ const safe_file_transaction_1 = require("./safe-file-transaction");
10
+ exports.METRO_CONFIG_FILES = [
11
+ 'metro.config.js',
12
+ 'metro.config.cjs',
13
+ 'metro.config.mjs',
14
+ 'metro.config.ts',
15
+ ];
16
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
17
+ const stripJavaScriptComments = (source) => {
18
+ let output = '';
19
+ let quote = '';
20
+ let escaped = false;
21
+ for (let index = 0; index < source.length; index += 1) {
22
+ const character = source[index];
23
+ const next = source[index + 1];
24
+ if (quote) {
25
+ output += character;
26
+ if (escaped)
27
+ escaped = false;
28
+ else if (character === '\\')
29
+ escaped = true;
30
+ else if (character === quote)
31
+ quote = '';
32
+ continue;
33
+ }
34
+ if (character === '"' || character === "'" || character === '`') {
35
+ quote = character;
36
+ output += character;
37
+ continue;
38
+ }
39
+ if (character === '/' && next === '/') {
40
+ while (index < source.length && source[index] !== '\n')
41
+ index += 1;
42
+ output += '\n';
43
+ continue;
44
+ }
45
+ if (character === '/' && next === '*') {
46
+ index += 2;
47
+ while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) {
48
+ if (source[index] === '\n')
49
+ output += '\n';
50
+ index += 1;
51
+ }
52
+ index += 1;
53
+ continue;
54
+ }
55
+ output += character;
56
+ }
57
+ return output;
58
+ };
59
+ const javascriptStringRanges = (source) => {
60
+ const ranges = [];
61
+ let quote = '';
62
+ let start = -1;
63
+ let escaped = false;
64
+ for (let index = 0; index < source.length; index += 1) {
65
+ const character = source[index];
66
+ if (!quote && (character === '"' || character === "'" || character === '`')) {
67
+ quote = character;
68
+ start = index;
69
+ continue;
70
+ }
71
+ if (!quote)
72
+ continue;
73
+ if (escaped)
74
+ escaped = false;
75
+ else if (character === '\\')
76
+ escaped = true;
77
+ else if (character === quote) {
78
+ ranges.push({ start, end: index + 1 });
79
+ quote = '';
80
+ start = -1;
81
+ }
82
+ }
83
+ if (quote)
84
+ ranges.push({ start, end: source.length });
85
+ return ranges;
86
+ };
87
+ const executableMatches = (source, pattern) => {
88
+ const ranges = javascriptStringRanges(source);
89
+ return [...source.matchAll(pattern)].filter(match => {
90
+ const position = match.index || 0;
91
+ return ranges.every(range => position < range.start || position >= range.end);
92
+ });
93
+ };
94
+ const structuralSource = (source) => {
95
+ const characters = [...source];
96
+ for (const range of javascriptStringRanges(source)) {
97
+ for (let index = range.start; index < range.end; index += 1) {
98
+ if (characters[index] !== '\n')
99
+ characters[index] = ' ';
100
+ }
101
+ }
102
+ return characters.join('');
103
+ };
104
+ const isUnconditionalTopLevel = (source, position) => {
105
+ const structure = structuralSource(source);
106
+ const prefix = structure.slice(0, position);
107
+ const depth = [...prefix].reduce((value, character) => {
108
+ if ('{[('.includes(character))
109
+ return value + 1;
110
+ if ('}])'.includes(character))
111
+ return value - 1;
112
+ return value;
113
+ }, 0);
114
+ if (depth !== 0)
115
+ return false;
116
+ const statementPrefix = prefix.slice(Math.max(prefix.lastIndexOf('\n'), prefix.lastIndexOf(';'), prefix.lastIndexOf('}')) + 1);
117
+ return !/\b(?:if|for|while|switch|catch)\s*\(|=>/.test(statementPrefix);
118
+ };
119
+ const hasExactBindingEntry = (bindingBody, name) => bindingBody.split(',').map(entry => entry.trim()).includes(name);
120
+ const topLevelNamedBindingCount = (source, name, moduleNames) => {
121
+ const withoutComments = stripJavaScriptComments(source);
122
+ let count = 0;
123
+ for (const moduleName of moduleNames) {
124
+ const escapedModule = escapeRegExp(moduleName);
125
+ const commonJs = new RegExp(`\\b(?:const|let|var)\\s*\\{([^}]*)\\}\\s*=\\s*` +
126
+ `require\\(\\s*(['"])${escapedModule}\\2\\s*\\)`, 'g');
127
+ const moduleImport = new RegExp(`\\bimport\\s*\\{([^}]*)\\}\\s*from\\s*(['"])${escapedModule}\\2`, 'g');
128
+ for (const match of [
129
+ ...executableMatches(withoutComments, commonJs),
130
+ ...executableMatches(withoutComments, moduleImport),
131
+ ]) {
132
+ if (isUnconditionalTopLevel(withoutComments, match.index || 0) &&
133
+ hasExactBindingEntry(match[1], name)) {
134
+ count += 1;
135
+ }
136
+ }
137
+ }
138
+ return count;
139
+ };
140
+ const hasPackageWrapperBinding = (source, wrapper) => topLevelNamedBindingCount(source, wrapper, ['@gfean/react-native-bundle-drop/metro']) === 1;
141
+ const hasExecutableMetroWrapperReference = (source, wrapper) => new RegExp(`\\b${escapeRegExp(wrapper)}\\b`).test((0, native_setup_contract_1.stripCommentsAndStrings)(source));
142
+ exports.hasExecutableMetroWrapperReference = hasExecutableMetroWrapperReference;
143
+ const hasExecutableMetroModuleReference = (source, moduleName) => {
144
+ const withoutComments = stripJavaScriptComments(source);
145
+ const escapedModule = escapeRegExp(moduleName);
146
+ return executableMatches(withoutComments, new RegExp(`\\brequire\\(\\s*(['"])${escapedModule}\\1\\s*\\)|` +
147
+ `\\bfrom\\s*(['"])${escapedModule}\\2`, 'g')).some(match => isUnconditionalTopLevel(withoutComments, match.index || 0));
148
+ };
149
+ exports.hasExecutableMetroModuleReference = hasExecutableMetroModuleReference;
150
+ const findBalancedParenthesis = (source, opening) => {
151
+ let depth = 0;
152
+ for (let index = opening; index < source.length; index += 1) {
153
+ if (source[index] === '(')
154
+ depth += 1;
155
+ if (source[index] === ')')
156
+ depth -= 1;
157
+ if (depth === 0)
158
+ return index;
159
+ }
160
+ return -1;
161
+ };
162
+ const splitTopLevelArguments = (source) => {
163
+ const argumentsList = [];
164
+ let depth = 0;
165
+ let start = 0;
166
+ for (let index = 0; index < source.length; index += 1) {
167
+ if ('{[('.includes(source[index]))
168
+ depth += 1;
169
+ else if ('}])'.includes(source[index]))
170
+ depth -= 1;
171
+ else if (source[index] === ',' && depth === 0) {
172
+ argumentsList.push(source.slice(start, index).trim());
173
+ start = index + 1;
174
+ }
175
+ }
176
+ argumentsList.push(source.slice(start).trim());
177
+ return argumentsList;
178
+ };
179
+ const expressionEnd = (source, start) => {
180
+ let depth = 0;
181
+ for (let index = start; index < source.length; index += 1) {
182
+ const character = source[index];
183
+ if ('{[('.includes(character))
184
+ depth += 1;
185
+ else if ('}])'.includes(character))
186
+ depth -= 1;
187
+ else if ((character === ';' || character === '\n') && depth === 0)
188
+ return index;
189
+ }
190
+ return source.length;
191
+ };
192
+ const topLevelVariableInitializer = (source, name, before) => {
193
+ const structure = structuralSource(source);
194
+ const pattern = new RegExp(`\\b(?:const|let|var)\\s+${escapeRegExp(name)}\\s*=`, 'g');
195
+ const declarations = [...structure.matchAll(pattern)].filter(match => (match.index || 0) < before && isUnconditionalTopLevel(structure, match.index || 0));
196
+ if (declarations.length !== 1)
197
+ return null;
198
+ const initializerStart = (declarations[0].index || 0) + declarations[0][0].length;
199
+ return structure.slice(initializerStart, expressionEnd(structure, initializerStart)).trim();
200
+ };
201
+ const hasSupportedMetroExpression = (source, expression, before, visited = new Set()) => {
202
+ const value = expression.trim();
203
+ if (!value || /^(?:null|undefined|false|true)$/.test(value))
204
+ return false;
205
+ if (/^\{[\s\S]*\}$/.test(value))
206
+ return true;
207
+ if (/^getDefaultConfig\s*\([^)]*\)$/.test(value)) {
208
+ return topLevelNamedBindingCount(source, 'getDefaultConfig', ['@react-native/metro-config', 'expo/metro-config']) === 1;
209
+ }
210
+ if (/^mergeConfig\s*\([\s\S]*\)$/.test(value)) {
211
+ if (topLevelNamedBindingCount(source, 'mergeConfig', ['@react-native/metro-config']) !== 1)
212
+ return false;
213
+ const opening = value.indexOf('(');
214
+ const closing = findBalancedParenthesis(value, opening);
215
+ if (opening < 0 || closing !== value.length - 1)
216
+ return false;
217
+ const argumentsList = splitTopLevelArguments(value.slice(opening + 1, closing));
218
+ return Boolean(argumentsList[0]) && hasSupportedMetroExpression(source, argumentsList[0], before, visited);
219
+ }
220
+ if (/^[A-Za-z_$][\w$]*$/.test(value)) {
221
+ if (visited.has(value))
222
+ return false;
223
+ const initializer = topLevelVariableInitializer(source, value, before);
224
+ return initializer !== null && hasSupportedMetroExpression(source, initializer, before, new Set([...visited, value]));
225
+ }
226
+ return false;
227
+ };
228
+ const hasSupportedEarlierExport = (source, before) => {
229
+ const structure = structuralSource(source);
230
+ const exports = [...structure.matchAll(/\bmodule\s*\.\s*exports\s*=\s*/g)].filter(match => (match.index || 0) < before && isUnconditionalTopLevel(structure, match.index || 0));
231
+ if (exports.length !== 1)
232
+ return false;
233
+ const expressionStart = (exports[0].index || 0) + exports[0][0].length;
234
+ const expression = structure.slice(expressionStart, expressionEnd(structure, expressionStart));
235
+ return hasSupportedMetroExpression(source, expression, exports[0].index || 0);
236
+ };
237
+ const hasSupportedMetroBase = (source, base, exportPosition) => {
238
+ if (/^module\s*\.\s*exports\s*\|\|\s*\{\s*\}$/.test(base))
239
+ return true;
240
+ if (/^module\s*\.\s*exports$/.test(base)) {
241
+ return hasSupportedEarlierExport(source, exportPosition);
242
+ }
243
+ return hasSupportedMetroExpression(source, base, exportPosition);
244
+ };
245
+ const hasAuthoritativeMetroWrapper = (source, wrapper) => {
246
+ if (!hasPackageWrapperBinding(source, wrapper))
247
+ return false;
248
+ const executable = stripJavaScriptComments(source);
249
+ const structure = structuralSource(executable);
250
+ const exports = [
251
+ ...structure.matchAll(/\bmodule\s*\.\s*exports\s*=\s*/g),
252
+ ...structure.matchAll(/\bexport\s+default\s+/g),
253
+ ].filter(match => isUnconditionalTopLevel(structure, match.index || 0))
254
+ .sort((left, right) => (left.index || 0) - (right.index || 0));
255
+ const wrapperExports = exports.filter(match => {
256
+ const expressionStart = (match.index || 0) + match[0].length;
257
+ return new RegExp(`^\\s*${escapeRegExp(wrapper)}\\s*\\(`).test(structure.slice(expressionStart));
258
+ });
259
+ if (wrapperExports.length !== 1 || wrapperExports[0] !== exports[exports.length - 1]) {
260
+ return false;
261
+ }
262
+ const wrapperExport = wrapperExports[0];
263
+ const expressionStart = (wrapperExport.index || 0) + wrapperExport[0].length;
264
+ const opening = structure.indexOf('(', expressionStart + wrapper.length);
265
+ const closing = opening < 0 ? -1 : findBalancedParenthesis(structure, opening);
266
+ if (closing < 0)
267
+ return false;
268
+ if (!/^\s*;?\s*$/.test(structure.slice(closing + 1)))
269
+ return false;
270
+ const argumentsList = splitTopLevelArguments(structure.slice(opening + 1, closing));
271
+ if (!argumentsList[0])
272
+ return false;
273
+ return hasSupportedMetroBase(executable, argumentsList[0], wrapperExport.index || 0);
274
+ };
275
+ exports.hasAuthoritativeMetroWrapper = hasAuthoritativeMetroWrapper;
276
+ const findSingleMetroConfig = (projectRoot) => {
277
+ const existing = exports.METRO_CONFIG_FILES.filter(file => (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, file).exists);
278
+ if (existing.length > 1) {
279
+ throw new Error(`Multiple Metro config files were found (${existing.join(', ')}). ` +
280
+ 'Keep one authoritative Metro config before running Bundle Drop setup.');
281
+ }
282
+ return existing[0];
283
+ };
284
+ exports.findSingleMetroConfig = findSingleMetroConfig;
285
+ const packageUsesEsm = (projectRoot) => {
286
+ const packageFile = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, 'package.json');
287
+ if (!packageFile.exists)
288
+ return false;
289
+ const manifest = JSON.parse(packageFile.content);
290
+ return manifest.type === 'module';
291
+ };
292
+ const newCommonJsMetroConfigFile = (projectRoot) => packageUsesEsm(projectRoot) ? 'metro.config.cjs' : 'metro.config.js';
293
+ exports.newCommonJsMetroConfigFile = newCommonJsMetroConfigFile;
294
+ const assertCommonJsMetroConfig = (projectRoot, relativePath) => {
295
+ const extension = path_1.default.extname(relativePath);
296
+ if (extension === '.mjs' ||
297
+ extension === '.ts' ||
298
+ (extension === '.js' && packageUsesEsm(projectRoot))) {
299
+ throw new Error(`${relativePath} uses ESM or TypeScript syntax. Bundle Drop will not append CommonJS ` +
300
+ 'to it automatically; wrap its exported config manually, then rerun setup.');
301
+ }
302
+ };
303
+ exports.assertCommonJsMetroConfig = assertCommonJsMetroConfig;
@@ -0,0 +1,2 @@
1
+ export type NativeEntrypointPlatform = 'android' | 'ios';
2
+ export declare const findNativeEntrypointAuthorityIssue: (projectRoot: string, platform: NativeEntrypointPlatform, entrypoints: string[]) => string | null;
@@ -0,0 +1,378 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.findNativeEntrypointAuthorityIssue = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const safe_file_transaction_1 = require("./safe-file-transaction");
10
+ const native_setup_contract_1 = require("./native-setup-contract");
11
+ const toPosix = (filePath) => filePath.split(path_1.default.sep).join('/');
12
+ const maskXmlComments = (source) => {
13
+ let masked = '';
14
+ let cursor = 0;
15
+ while (cursor < source.length) {
16
+ const commentStart = source.indexOf('<!--', cursor);
17
+ if (commentStart < 0)
18
+ return masked + source.slice(cursor);
19
+ masked += source.slice(cursor, commentStart);
20
+ const commentEnd = source.indexOf('-->', commentStart + 4);
21
+ const maskedEnd = commentEnd < 0 ? source.length : commentEnd + 3;
22
+ masked += ' '.repeat(maskedEnd - commentStart);
23
+ cursor = maskedEnd;
24
+ }
25
+ return masked;
26
+ };
27
+ const androidPackageFromPath = (relativePath) => {
28
+ const match = relativePath.match(/^android\/app\/src\/main\/(?:java|kotlin)\/(.+)\/MainApplication\.(?:java|kt)$/);
29
+ return match ? match[1].split('/').join('.') : '';
30
+ };
31
+ const androidEntrypointClass = (relativePath, content) => {
32
+ const declaredPackage = content.match(/(?:^|\n)\s*package\s+([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*;?/)?.[1];
33
+ const packageName = declaredPackage || androidPackageFromPath(relativePath);
34
+ return packageName ? `${packageName}.MainApplication` : 'MainApplication';
35
+ };
36
+ const androidManifestFiles = (projectRoot) => {
37
+ const sourceRoot = path_1.default.join(projectRoot, 'android/app/src');
38
+ let sourceSets;
39
+ try {
40
+ const stat = fs_1.default.lstatSync(sourceRoot);
41
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
42
+ throw new Error('Android source-set root is not a regular project directory.');
43
+ }
44
+ sourceSets = fs_1.default.readdirSync(sourceRoot);
45
+ }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT')
48
+ return [];
49
+ throw error;
50
+ }
51
+ return sourceSets.flatMap(sourceSet => {
52
+ if (/^(?:androidTest|benchmark|test|testFixtures|unitTest)$/i.test(sourceSet))
53
+ return [];
54
+ const relativeDirectory = `android/app/src/${sourceSet}`;
55
+ const directoryStat = fs_1.default.lstatSync(path_1.default.join(projectRoot, relativeDirectory));
56
+ if (directoryStat.isSymbolicLink()) {
57
+ throw new Error(`Android source-set path is a symbolic link: ${relativeDirectory}`);
58
+ }
59
+ if (!directoryStat.isDirectory())
60
+ return [];
61
+ const relativeManifest = `${relativeDirectory}/AndroidManifest.xml`;
62
+ return (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, relativeManifest).exists ? [relativeManifest] : [];
63
+ }).sort();
64
+ };
65
+ const androidGradleNamespace = (projectRoot) => {
66
+ for (const file of ['android/app/build.gradle', 'android/app/build.gradle.kts']) {
67
+ const buildFile = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, file);
68
+ if (!buildFile.exists)
69
+ continue;
70
+ const namespace = buildFile.content.match(/(?:^|\n)\s*namespace\s*(?:=\s*)?["']([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)["']/)?.[1];
71
+ if (namespace)
72
+ return namespace;
73
+ }
74
+ return '';
75
+ };
76
+ const androidAuthorityIssue = (projectRoot, entrypoint) => {
77
+ const entrypointFile = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, entrypoint);
78
+ if (!entrypointFile.exists)
79
+ return `Android application entrypoint is missing: ${entrypoint}`;
80
+ const entrypointClass = androidEntrypointClass(entrypoint, entrypointFile.content);
81
+ const manifests = androidManifestFiles(projectRoot);
82
+ const mainManifest = 'android/app/src/main/AndroidManifest.xml';
83
+ if (!manifests.includes(mainManifest)) {
84
+ return 'The main AndroidManifest.xml is missing; application startup authority is unknown.';
85
+ }
86
+ const gradleNamespace = androidGradleNamespace(projectRoot);
87
+ for (const manifestPath of manifests) {
88
+ const manifest = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, manifestPath);
89
+ const manifestSource = maskXmlComments(manifest.content);
90
+ const applicationTags = [...manifestSource.matchAll(/<application\b[^>]*>/gi)];
91
+ if (applicationTags.length > 1) {
92
+ return `${manifestPath} has multiple application declarations.`;
93
+ }
94
+ const applicationTag = applicationTags[0]?.[0];
95
+ if (!applicationTag) {
96
+ if (manifestPath === mainManifest) {
97
+ return `${manifestPath} has no application declaration to bind the native entrypoint.`;
98
+ }
99
+ continue;
100
+ }
101
+ const applicationNames = [...applicationTag.matchAll(/(?:^|\s)android:name\s*=\s*["']([^"']+)["']/gi)].map(match => match[1].trim());
102
+ if (applicationNames.length > 1) {
103
+ return `${manifestPath} has multiple android:name application authorities.`;
104
+ }
105
+ if (!applicationNames.length) {
106
+ if (manifestPath === mainManifest) {
107
+ return `${manifestPath} does not explicitly name the application class.`;
108
+ }
109
+ continue;
110
+ }
111
+ const applicationName = applicationNames[0];
112
+ if (/\$\{|[^A-Za-z0-9_.$]/.test(applicationName)) {
113
+ return `${manifestPath} application class is not statically resolvable: ${applicationName}`;
114
+ }
115
+ const manifestPackage = manifestSource.match(/<manifest\b[^>]*\s+package\s*=\s*["']([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)["']/i)?.[1] || '';
116
+ const namespace = manifestPackage || gradleNamespace;
117
+ if ((!applicationName.includes('.') || applicationName.startsWith('.')) && !namespace) {
118
+ return `${manifestPath} uses a relative application class without a manifest package or Gradle namespace.`;
119
+ }
120
+ const expectedClass = applicationName.startsWith('.')
121
+ ? `${namespace}${applicationName}`
122
+ : applicationName.includes('.')
123
+ ? applicationName
124
+ : `${namespace}.${applicationName}`;
125
+ if (expectedClass !== entrypointClass) {
126
+ return `${manifestPath} starts ${expectedClass}, not ${entrypointClass}.`;
127
+ }
128
+ }
129
+ return null;
130
+ };
131
+ const findIosAuthoritySources = (projectRoot) => {
132
+ const iosRoot = path_1.default.join(projectRoot, 'ios');
133
+ try {
134
+ const rootStat = fs_1.default.lstatSync(iosRoot);
135
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
136
+ throw new Error('iOS source root is not a regular project directory.');
137
+ }
138
+ }
139
+ catch (error) {
140
+ if (error.code === 'ENOENT') {
141
+ return { mainFiles: [], swiftFiles: [] };
142
+ }
143
+ throw error;
144
+ }
145
+ const pending = ['ios'];
146
+ const mainFiles = [];
147
+ const swiftFiles = [];
148
+ let visited = 0;
149
+ while (pending.length) {
150
+ const relativeDirectory = pending.pop();
151
+ for (const entry of fs_1.default.readdirSync(path_1.default.join(projectRoot, relativeDirectory), { withFileTypes: true })) {
152
+ visited += 1;
153
+ if (visited > 5000)
154
+ throw new Error('iOS principal source scan exceeded 5000 entries.');
155
+ if (entry.name === 'Pods' || entry.name === 'build' || entry.name === 'DerivedData')
156
+ continue;
157
+ const relativePath = toPosix(path_1.default.join(relativeDirectory, entry.name));
158
+ const stat = fs_1.default.lstatSync(path_1.default.join(projectRoot, relativePath));
159
+ if (stat.isSymbolicLink()) {
160
+ throw new Error(`iOS principal source path is a symbolic link: ${relativePath}`);
161
+ }
162
+ if (stat.isDirectory())
163
+ pending.push(relativePath);
164
+ else if (stat.isFile()) {
165
+ if (/\.swift$/i.test(entry.name))
166
+ swiftFiles.push(relativePath);
167
+ if (/^main\.(?:m|mm|swift)$/i.test(entry.name))
168
+ mainFiles.push(relativePath);
169
+ }
170
+ }
171
+ }
172
+ return { mainFiles: mainFiles.sort(), swiftFiles: swiftFiles.sort() };
173
+ };
174
+ const findBalancedCall = (source, name) => {
175
+ const calls = [];
176
+ let searchFrom = 0;
177
+ while (searchFrom < source.length) {
178
+ const nameIndex = source.indexOf(name, searchFrom);
179
+ if (nameIndex < 0)
180
+ break;
181
+ const previousCharacter = source[nameIndex - 1] || '';
182
+ const nextCharacter = source[nameIndex + name.length] || '';
183
+ if (/\w/.test(previousCharacter) || /\w/.test(nextCharacter)) {
184
+ searchFrom = nameIndex + name.length;
185
+ continue;
186
+ }
187
+ const opening = source.indexOf('(', nameIndex + name.length);
188
+ if (opening < 0)
189
+ break;
190
+ let depth = 0;
191
+ let quote = '';
192
+ let escaped = false;
193
+ for (let index = opening; index < source.length; index += 1) {
194
+ const character = source[index];
195
+ if (quote) {
196
+ if (escaped)
197
+ escaped = false;
198
+ else if (character === '\\')
199
+ escaped = true;
200
+ else if (character === quote)
201
+ quote = '';
202
+ continue;
203
+ }
204
+ if (character === '"' || character === "'") {
205
+ quote = character;
206
+ continue;
207
+ }
208
+ if (character === '(')
209
+ depth += 1;
210
+ if (character === ')')
211
+ depth -= 1;
212
+ if (depth === 0) {
213
+ calls.push(source.slice(opening + 1, index));
214
+ searchFrom = index + 1;
215
+ break;
216
+ }
217
+ }
218
+ if (depth !== 0)
219
+ break;
220
+ }
221
+ return calls;
222
+ };
223
+ const stripCComments = (source) => {
224
+ let output = '';
225
+ let quote = '';
226
+ let escaped = false;
227
+ let blockCommentDepth = 0;
228
+ for (let index = 0; index < source.length; index += 1) {
229
+ const character = source[index];
230
+ const next = source[index + 1];
231
+ if (quote) {
232
+ output += character;
233
+ if (escaped)
234
+ escaped = false;
235
+ else if (character === '\\')
236
+ escaped = true;
237
+ else if (character === quote)
238
+ quote = '';
239
+ continue;
240
+ }
241
+ if (character === '"' || character === "'") {
242
+ quote = character;
243
+ output += character;
244
+ continue;
245
+ }
246
+ if (character === '/' && next === '/') {
247
+ while (index < source.length && source[index] !== '\n')
248
+ index += 1;
249
+ output += '\n';
250
+ continue;
251
+ }
252
+ if (character === '/' && next === '*') {
253
+ blockCommentDepth = 1;
254
+ index += 2;
255
+ while (index < source.length && blockCommentDepth > 0) {
256
+ if (source[index] === '/' && source[index + 1] === '*') {
257
+ blockCommentDepth += 1;
258
+ index += 2;
259
+ continue;
260
+ }
261
+ if (source[index] === '*' && source[index + 1] === '/') {
262
+ blockCommentDepth -= 1;
263
+ index += 2;
264
+ continue;
265
+ }
266
+ if (source[index] === '\n')
267
+ output += '\n';
268
+ index += 1;
269
+ }
270
+ index -= 1;
271
+ continue;
272
+ }
273
+ output += character;
274
+ }
275
+ return output;
276
+ };
277
+ const topLevelCallArguments = (body) => {
278
+ const argumentsList = [];
279
+ const stack = [];
280
+ let quote = '';
281
+ let escaped = false;
282
+ let start = 0;
283
+ for (let index = 0; index < body.length; index += 1) {
284
+ const character = body[index];
285
+ if (quote) {
286
+ if (escaped)
287
+ escaped = false;
288
+ else if (character === '\\')
289
+ escaped = true;
290
+ else if (character === quote)
291
+ quote = '';
292
+ continue;
293
+ }
294
+ if (character === '"' || character === "'")
295
+ quote = character;
296
+ else if ('([{'.includes(character))
297
+ stack.push(character);
298
+ else if (')]}'.includes(character))
299
+ stack.pop();
300
+ else if (character === ',' && !stack.length) {
301
+ argumentsList.push(body.slice(start, index).trim());
302
+ start = index + 1;
303
+ }
304
+ }
305
+ argumentsList.push(body.slice(start).trim());
306
+ return argumentsList;
307
+ };
308
+ const exactPrincipalFromCall = (call, swift) => {
309
+ const argumentsList = topLevelCallArguments(call);
310
+ if (argumentsList.length !== 4)
311
+ return null;
312
+ const principal = argumentsList[3];
313
+ if (swift) {
314
+ if (/^NSStringFromClass\s*\(\s*AppDelegate\.self\s*\)$/.test(principal)) {
315
+ return 'AppDelegate';
316
+ }
317
+ return /^"AppDelegate"$/.test(principal) ? 'AppDelegate' : null;
318
+ }
319
+ if (/^NSStringFromClass\s*\(\s*\[\s*AppDelegate\s+class\s*\]\s*\)$/.test(principal)) {
320
+ return 'AppDelegate';
321
+ }
322
+ return /^@"AppDelegate"$/.test(principal) ? 'AppDelegate' : null;
323
+ };
324
+ const objcAuthorityIssue = (projectRoot, mainFiles) => {
325
+ if (mainFiles.length !== 1 || !/\.m{1,2}$/i.test(mainFiles[0])) {
326
+ return mainFiles.length
327
+ ? 'Multiple or conflicting iOS application principal sources were found.'
328
+ : 'Objective-C main/UIApplicationMain principal source is missing.';
329
+ }
330
+ const mainFile = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, mainFiles[0]);
331
+ const calls = findBalancedCall(stripCComments(mainFile.content), 'UIApplicationMain');
332
+ if (calls.length !== 1)
333
+ return 'Exactly one UIApplicationMain call is required.';
334
+ return exactPrincipalFromCall(calls[0], false)
335
+ ? null
336
+ : `UIApplicationMain argument 4 does not select AppDelegate.`;
337
+ };
338
+ const swiftAuthorityIssue = (projectRoot, entrypoint, mainFiles, swiftFiles) => {
339
+ const principals = swiftFiles.flatMap(file => {
340
+ const source = (0, native_setup_contract_1.stripCommentsAndStrings)((0, safe_file_transaction_1.inspectProjectFile)(projectRoot, file).content);
341
+ return [...source.matchAll(/@(?:main|UIApplicationMain)\b[\s\n]*(?:(?:final|public|private|internal|open)\s+)*(?:class|struct)\s+([A-Za-z_$][\w$]*)/g)].map(match => ({ file, name: match[1] }));
342
+ });
343
+ if (principals.length === 1 &&
344
+ principals[0].name === 'AppDelegate' &&
345
+ principals[0].file === entrypoint) {
346
+ return mainFiles.length
347
+ ? 'An annotated Swift AppDelegate conflicts with an external main source.'
348
+ : null;
349
+ }
350
+ if (principals.length)
351
+ return 'Swift principal annotation does not uniquely select AppDelegate.';
352
+ if (mainFiles.length !== 1 || !mainFiles[0].endsWith('/main.swift')) {
353
+ return mainFiles.length
354
+ ? 'Multiple or conflicting iOS application principal sources were found.'
355
+ : 'Swift @main/UIApplicationMain principal is missing.';
356
+ }
357
+ const mainFile = (0, safe_file_transaction_1.inspectProjectFile)(projectRoot, mainFiles[0]);
358
+ const calls = findBalancedCall(stripCComments(mainFile.content), 'UIApplicationMain');
359
+ if (calls.length !== 1 || !exactPrincipalFromCall(calls[0], true)) {
360
+ return 'Swift main UIApplicationMain argument 4 does not select AppDelegate.';
361
+ }
362
+ return null;
363
+ };
364
+ const findNativeEntrypointAuthorityIssue = (projectRoot, platform, entrypoints) => {
365
+ if (!entrypoints.length)
366
+ return null;
367
+ if (entrypoints.length > 1) {
368
+ return `Multiple ${platform} application entrypoints were found; startup authority is ambiguous.`;
369
+ }
370
+ if (platform === 'android')
371
+ return androidAuthorityIssue(projectRoot, entrypoints[0]);
372
+ const { mainFiles, swiftFiles } = findIosAuthoritySources(projectRoot);
373
+ if (entrypoints[0].endsWith('.swift')) {
374
+ return swiftAuthorityIssue(projectRoot, entrypoints[0], mainFiles, swiftFiles);
375
+ }
376
+ return objcAuthorityIssue(projectRoot, mainFiles);
377
+ };
378
+ exports.findNativeEntrypointAuthorityIssue = findNativeEntrypointAuthorityIssue;