@gfean/react-native-bundle-drop 0.5.1 → 0.7.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 (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -0,0 +1,375 @@
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.runtimeDeliveryManifestUrl = runtimeDeliveryManifestUrl;
7
+ exports.runtimeDeliveryAuthorityLeaseUrl = runtimeDeliveryAuthorityLeaseUrl;
8
+ exports.fetchRuntimeDeliveryManifest = fetchRuntimeDeliveryManifest;
9
+ exports.resolveFromRuntimeDeliveryManifest = resolveFromRuntimeDeliveryManifest;
10
+ exports.reportActiveInstall = reportActiveInstall;
11
+ exports.shouldRollbackFromLastKnownRevocations = shouldRollbackFromLastKnownRevocations;
12
+ const context_1 = require("../context");
13
+ const loadConfig_1 = require("../loadConfig");
14
+ const fs_1 = __importDefault(require("../native/fs"));
15
+ const encoding_1 = require("./encoding");
16
+ const authorityLeaseVerifier_1 = require("./authorityLeaseVerifier");
17
+ const diagnostics_1 = require("./diagnostics");
18
+ const heartbeat_1 = require("./heartbeat");
19
+ const localResolver_1 = require("./localResolver");
20
+ const manifestState_1 = require("./manifestState");
21
+ const manifestVerifier_1 = require("./manifestVerifier");
22
+ const diagnosticNameByFailureCode = {
23
+ body_too_large: 'manifest_too_large',
24
+ http_error: 'manifest_http_error',
25
+ network_error: 'manifest_network_error',
26
+ timeout: 'manifest_timeout',
27
+ stream_unavailable: 'manifest_stream_unavailable',
28
+ invalid_manifest: 'manifest_invalid',
29
+ invalid_signature: 'invalid_signature',
30
+ unknown_key: 'unknown_key',
31
+ lane_mismatch: 'lane_mismatch',
32
+ generation_regression: 'generation_regression',
33
+ generation_equivocation: 'generation_equivocation',
34
+ authority_body_too_large: 'authority_lease_too_large',
35
+ authority_http_error: 'authority_lease_http_error',
36
+ authority_network_error: 'authority_lease_network_error',
37
+ authority_timeout: 'authority_lease_timeout',
38
+ authority_stream_unavailable: 'authority_lease_invalid',
39
+ authority_invalid: 'authority_lease_invalid',
40
+ authority_invalid_signature: 'authority_lease_invalid_signature',
41
+ authority_unknown_key: 'authority_lease_unknown_key',
42
+ authority_expired: 'authority_lease_expired',
43
+ authority_origin_mismatch: 'authority_lease_origin_mismatch',
44
+ authority_disabled: 'authority_lease_disabled',
45
+ };
46
+ const RUNTIME_MANIFEST_TIMEOUT_MS = 5000;
47
+ const RUNTIME_MANIFEST_TOO_LARGE_MESSAGE = 'Runtime manifest exceeds the 1 MB safety limit';
48
+ function normalizeManifestError(error, fallbackCode, fallbackMessage) {
49
+ return error instanceof manifestVerifier_1.RuntimeDeliveryManifestError
50
+ ? error
51
+ : new manifestVerifier_1.RuntimeDeliveryManifestError(fallbackCode, fallbackMessage, { cause: error });
52
+ }
53
+ async function readBoundedManifestBody(response, abortTransfer) {
54
+ const reader = response.body?.getReader?.();
55
+ const rawContentLength = response.headers?.get?.('content-length');
56
+ if (rawContentLength && /^\d+$/.test(rawContentLength)) {
57
+ const contentLength = Number(rawContentLength);
58
+ if (contentLength > manifestVerifier_1.MAX_RUNTIME_MANIFEST_BYTES) {
59
+ abortTransfer?.();
60
+ try {
61
+ await reader?.cancel(RUNTIME_MANIFEST_TOO_LARGE_MESSAGE).catch(() => undefined);
62
+ }
63
+ finally {
64
+ reader?.releaseLock?.();
65
+ }
66
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('body_too_large', RUNTIME_MANIFEST_TOO_LARGE_MESSAGE);
67
+ }
68
+ }
69
+ if (!reader) {
70
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('stream_unavailable', 'Runtime manifest response does not expose a readable byte stream');
71
+ }
72
+ const chunks = [];
73
+ let totalBytes = 0;
74
+ try {
75
+ while (true) {
76
+ const { done, value } = await reader.read();
77
+ if (done)
78
+ break;
79
+ if (!(value instanceof Uint8Array)) {
80
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('invalid_manifest', 'Runtime manifest stream returned a non-byte chunk');
81
+ }
82
+ totalBytes += value.byteLength;
83
+ if (totalBytes > manifestVerifier_1.MAX_RUNTIME_MANIFEST_BYTES) {
84
+ await reader.cancel(RUNTIME_MANIFEST_TOO_LARGE_MESSAGE).catch(() => undefined);
85
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('body_too_large', RUNTIME_MANIFEST_TOO_LARGE_MESSAGE);
86
+ }
87
+ chunks.push(value);
88
+ }
89
+ }
90
+ finally {
91
+ reader.releaseLock?.();
92
+ }
93
+ const bytes = new Uint8Array(totalBytes);
94
+ let offset = 0;
95
+ for (const chunk of chunks) {
96
+ bytes.set(chunk, offset);
97
+ offset += chunk.byteLength;
98
+ }
99
+ try {
100
+ return (0, encoding_1.decodeUtf8Bytes)(bytes);
101
+ }
102
+ catch (error) {
103
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('invalid_manifest', 'Runtime manifest body is not valid UTF-8', { cause: error });
104
+ }
105
+ }
106
+ function isReactNativeRuntime() {
107
+ return typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
108
+ }
109
+ function nativeDownloadFailure(error) {
110
+ const nativeError = error;
111
+ const code = typeof nativeError?.code === 'string' ? nativeError.code : '';
112
+ const message = typeof nativeError?.message === 'string' ? nativeError.message : '';
113
+ if (code === 'ERR_DOWNLOAD_TOO_LARGE') {
114
+ return new manifestVerifier_1.RuntimeDeliveryManifestError('body_too_large', RUNTIME_MANIFEST_TOO_LARGE_MESSAGE, { cause: error });
115
+ }
116
+ if (code === 'ERR_DOWNLOAD_TIMEOUT') {
117
+ return new manifestVerifier_1.RuntimeDeliveryManifestError('timeout', 'Runtime manifest request timed out', { cause: error });
118
+ }
119
+ if (code === 'ERR_DOWNLOAD_HTTP') {
120
+ const status = /^HTTP (\d{3})(?:\b|:)/.exec(message)?.[1];
121
+ const numericStatus = status ? Number(status) : undefined;
122
+ return new manifestVerifier_1.RuntimeDeliveryManifestError('http_error', numericStatus === undefined
123
+ ? 'Manifest request failed with an HTTP error'
124
+ : `Manifest request failed with HTTP ${numericStatus}`, { cause: error, status: numericStatus });
125
+ }
126
+ return new manifestVerifier_1.RuntimeDeliveryManifestError('network_error', 'Runtime manifest request failed', { cause: error });
127
+ }
128
+ async function readBoundedManifestWithNativeDownload(url, artifactName) {
129
+ const tempPath = [
130
+ fs_1.default.LibraryDirectoryPath,
131
+ 'bundle-drop',
132
+ 'runtime-delivery',
133
+ `${artifactName}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}.jws`,
134
+ ].join('/');
135
+ try {
136
+ try {
137
+ await fs_1.default.downloadFileBounded(url, tempPath, manifestVerifier_1.MAX_RUNTIME_MANIFEST_BYTES, RUNTIME_MANIFEST_TIMEOUT_MS);
138
+ }
139
+ catch (error) {
140
+ throw nativeDownloadFailure(error);
141
+ }
142
+ let encodedBody;
143
+ try {
144
+ encodedBody = await fs_1.default.readFile(tempPath, 'base64');
145
+ }
146
+ catch (error) {
147
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('network_error', 'Runtime manifest body read failed', { cause: error });
148
+ }
149
+ const bytes = (0, encoding_1.decodeBase64UrlBytes)(encodedBody.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''));
150
+ if (bytes.length > manifestVerifier_1.MAX_RUNTIME_MANIFEST_BYTES) {
151
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('body_too_large', RUNTIME_MANIFEST_TOO_LARGE_MESSAGE);
152
+ }
153
+ try {
154
+ return (0, encoding_1.decodeUtf8Bytes)(bytes);
155
+ }
156
+ catch (error) {
157
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('invalid_manifest', 'Runtime manifest body is not valid UTF-8', { cause: error });
158
+ }
159
+ }
160
+ finally {
161
+ await fs_1.default.unlink(tempPath).catch(() => undefined);
162
+ }
163
+ }
164
+ function mapAuthorityTransportError(error) {
165
+ const normalized = normalizeManifestError(error, 'network_error', 'Runtime delivery authority lease request failed');
166
+ const code = {
167
+ body_too_large: 'authority_body_too_large',
168
+ http_error: 'authority_http_error',
169
+ network_error: 'authority_network_error',
170
+ timeout: 'authority_timeout',
171
+ stream_unavailable: 'authority_stream_unavailable',
172
+ }[normalized.code];
173
+ return code
174
+ ? new manifestVerifier_1.RuntimeDeliveryManifestError(code, normalized.message, {
175
+ cause: normalized,
176
+ status: normalized.status,
177
+ })
178
+ : normalized;
179
+ }
180
+ function recordManifestFailure(channelName, error) {
181
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)(diagnosticNameByFailureCode[error.code], {
182
+ channelName,
183
+ reason: error.code,
184
+ ...(error.status === undefined ? {} : { status: error.status }),
185
+ });
186
+ }
187
+ function laneIdentity(channelName) {
188
+ if (!context_1.runtimeVersion)
189
+ throw new Error('Runtime version is required for runtime delivery');
190
+ return {
191
+ projectSlug: context_1.config.project.slug,
192
+ channelName,
193
+ platform: context_1.platform,
194
+ runtimeVersion: context_1.runtimeVersion,
195
+ };
196
+ }
197
+ function runtimeDeliveryManifestUrl(identity) {
198
+ const delivery = context_1.config.runtimeDelivery;
199
+ if (!delivery)
200
+ throw new Error('Runtime delivery is not configured');
201
+ const base = delivery.manifestBaseUrl.replace(/\/+$/, '');
202
+ return [
203
+ base,
204
+ 'v2',
205
+ encodeURIComponent(delivery.manifestAccessId),
206
+ 'lanes',
207
+ (0, encoding_1.encodeBase64UrlUtf8)(identity.channelName),
208
+ encodeURIComponent(identity.platform),
209
+ (0, encoding_1.encodeBase64UrlUtf8)(identity.runtimeVersion),
210
+ 'current.json',
211
+ ].join('/');
212
+ }
213
+ function runtimeDeliveryAuthorityLeaseUrl() {
214
+ const delivery = context_1.config.runtimeDelivery;
215
+ if (!delivery)
216
+ throw new Error('Runtime delivery is not configured');
217
+ return `${delivery.manifestBaseUrl.replace(/\/+$/, '')}/v2/_authority/publisher-lease.json`;
218
+ }
219
+ async function fetchBoundedJws(url, artifactName, controller) {
220
+ if (isReactNativeRuntime()) {
221
+ return readBoundedManifestWithNativeDownload(url, artifactName);
222
+ }
223
+ let response;
224
+ try {
225
+ response = await fetch(url, {
226
+ method: 'GET',
227
+ headers: { Accept: 'application/jose+json, application/json' },
228
+ signal: controller?.signal,
229
+ });
230
+ }
231
+ catch (error) {
232
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError(controller?.signal.aborted ? 'timeout' : 'network_error', controller?.signal.aborted
233
+ ? 'Runtime manifest request timed out'
234
+ : 'Runtime manifest request failed', { cause: error });
235
+ }
236
+ if (!response.ok) {
237
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('http_error', `Manifest request failed with HTTP ${response.status}`, { status: response.status });
238
+ }
239
+ try {
240
+ return await readBoundedManifestBody(response, () => controller?.abort());
241
+ }
242
+ catch (error) {
243
+ if (!(error instanceof manifestVerifier_1.RuntimeDeliveryManifestError) && controller?.signal.aborted) {
244
+ throw new manifestVerifier_1.RuntimeDeliveryManifestError('timeout', 'Runtime manifest request timed out', { cause: error });
245
+ }
246
+ throw normalizeManifestError(error, 'network_error', 'Runtime manifest body read failed');
247
+ }
248
+ }
249
+ async function fetchRuntimeDeliveryManifest(channelName) {
250
+ const delivery = context_1.config.runtimeDelivery;
251
+ if (!(0, loadConfig_1.isRuntimeDeliveryConfigured)(delivery))
252
+ throw new Error('Runtime delivery is not enabled');
253
+ const identity = laneIdentity(channelName);
254
+ const manifestUrl = runtimeDeliveryManifestUrl(identity);
255
+ const authorityLeaseUrl = runtimeDeliveryAuthorityLeaseUrl();
256
+ const useNativeDownload = isReactNativeRuntime();
257
+ const controller = !useNativeDownload && typeof AbortController !== 'undefined'
258
+ ? new AbortController()
259
+ : null;
260
+ const timeoutId = controller
261
+ ? setTimeout(() => controller.abort(), RUNTIME_MANIFEST_TIMEOUT_MS)
262
+ : null;
263
+ try {
264
+ try {
265
+ const [leaseResult, manifestResult] = await Promise.allSettled([
266
+ fetchBoundedJws(authorityLeaseUrl, 'authority-lease', controller),
267
+ fetchBoundedJws(manifestUrl, 'manifest', controller),
268
+ ]);
269
+ if (leaseResult.status === 'rejected') {
270
+ throw mapAuthorityTransportError(leaseResult.reason);
271
+ }
272
+ if (manifestResult.status === 'rejected') {
273
+ throw manifestResult.reason;
274
+ }
275
+ await (0, authorityLeaseVerifier_1.verifyRuntimeDeliveryAuthorityLease)(leaseResult.value, delivery.manifestBaseUrl, delivery.publicKeys);
276
+ let manifest;
277
+ try {
278
+ manifest = await (0, manifestVerifier_1.verifyRuntimeDeliveryManifest)(manifestResult.value, identity, delivery.publicKeys);
279
+ }
280
+ catch (error) {
281
+ throw normalizeManifestError(error, 'invalid_manifest', 'Runtime manifest validation failed');
282
+ }
283
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)('manifest_hit', { channelName });
284
+ if (manifest.resolutionMode === 'dynamic') {
285
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)('dynamic_manifest', {
286
+ channelName,
287
+ reason: manifest.dynamicReason,
288
+ });
289
+ }
290
+ return manifest;
291
+ }
292
+ catch (error) {
293
+ const manifestError = normalizeManifestError(error, 'invalid_manifest', 'Runtime manifest processing failed');
294
+ recordManifestFailure(channelName, manifestError);
295
+ throw manifestError;
296
+ }
297
+ }
298
+ finally {
299
+ if (timeoutId)
300
+ clearTimeout(timeoutId);
301
+ }
302
+ }
303
+ async function resolveFromRuntimeDeliveryManifest(manifest, context) {
304
+ const decision = await (0, localResolver_1.resolveRuntimeDeliveryLane)(manifest, {
305
+ currentHash: context.currentHash,
306
+ rejectedHashes: context.rejectedHashes,
307
+ installId: context.installId,
308
+ patchAlgorithms: context.patchAlgorithms,
309
+ supportsContentAddressedAssets: context.supportsContentAddressedAssets,
310
+ });
311
+ if (decision.action === 'NOOP') {
312
+ const incompatible = decision.reason === 'NO_COMPATIBLE_BUNDLE';
313
+ return {
314
+ action: 'NOOP',
315
+ upToDate: decision.reason === 'UP_TO_DATE',
316
+ channelName: context.channelName,
317
+ reason: decision.reason,
318
+ incompatible: incompatible || undefined,
319
+ requestedRuntimeVersion: incompatible ? manifest.runtimeVersion : undefined,
320
+ runtimeVersion: manifest.runtimeVersion,
321
+ };
322
+ }
323
+ if (decision.action === 'ROLLBACK') {
324
+ return {
325
+ action: 'ROLLBACK',
326
+ channelName: context.channelName,
327
+ reason: decision.reason,
328
+ runtimeVersion: manifest.runtimeVersion,
329
+ };
330
+ }
331
+ return {
332
+ action: 'INSTALL',
333
+ upToDate: false,
334
+ channelName: context.channelName,
335
+ hash: decision.target.bundleHash,
336
+ bundleHash: decision.target.bundleHash,
337
+ bundleVersion: decision.target.bundleVersion,
338
+ version: decision.target.version,
339
+ runtimeVersion: decision.target.runtimeVersion,
340
+ mode: decision.mode,
341
+ baseHash: decision.patchEdge?.baseHash,
342
+ runtimeDelivery: {
343
+ generation: manifest.generation,
344
+ targetReleaseRef: decision.target.releaseRef,
345
+ selectedMode: decision.mode,
346
+ baseHash: decision.patchEdge?.baseHash,
347
+ patchAlgorithm: decision.patchEdge?.algorithm,
348
+ patchSetHash: decision.patchEdge?.patchSetHash,
349
+ patchArtifactRef: decision.patchEdge?.patchArtifactRef,
350
+ missingAssetsHash: decision.patchEdge?.missingAssetsHash,
351
+ manifestHash: decision.target.manifestHash,
352
+ jsBundleHash: decision.target.jsBundleHash,
353
+ fullBundleHash: decision.target.fullBundleHash,
354
+ },
355
+ };
356
+ }
357
+ function reportActiveInstall(context) {
358
+ if (!context_1.runtimeVersion)
359
+ return;
360
+ (0, heartbeat_1.reportActiveInstallWhenDue)(context_1.config.project.slug, {
361
+ channelName: context.channelName,
362
+ platform: context_1.platform,
363
+ runtimeVersion: context_1.runtimeVersion,
364
+ installId: context.installId,
365
+ currentHash: context.currentHash,
366
+ environment: context.environment || undefined,
367
+ userProperties: Object.keys(context.userProperties).length ? context.userProperties : undefined,
368
+ });
369
+ }
370
+ async function shouldRollbackFromLastKnownRevocations(channelName, currentHash) {
371
+ if (!currentHash || !context_1.runtimeVersion)
372
+ return false;
373
+ const state = await (0, manifestState_1.readVerifiedLaneState)(laneIdentity(channelName));
374
+ return !!state?.revokedHashes.includes(currentHash);
375
+ }
@@ -0,0 +1,87 @@
1
+ export declare const RUNTIME_DELIVERY_ROLLOUT_ALGORITHM: "sha256-install-id-uint32be-mod100-v1";
2
+ export declare const RUNTIME_DELIVERY_MANIFEST_JWS_TYPE: "bundledrop-manifest+jws";
3
+ export declare const RUNTIME_DELIVERY_AUTHORITY_LEASE_JWS_TYPE: "bundledrop-authority-lease+jws";
4
+ export type RuntimeDeliveryPublicKey = {
5
+ kty: 'EC';
6
+ crv: 'P-256';
7
+ x: string;
8
+ y: string;
9
+ };
10
+ export type RuntimeDeliveryRelease = {
11
+ releaseRef: string;
12
+ bundleHash: string;
13
+ bundleVersion: number;
14
+ version?: string;
15
+ runtimeVersion: string;
16
+ manifestHash: string;
17
+ jsBundleHash: string;
18
+ fullBundleHash: string;
19
+ fullBundleSizeBytes: number;
20
+ available: boolean;
21
+ expiresAt?: string | null;
22
+ };
23
+ export type RuntimeDeliveryPublishedRollout = {
24
+ releaseRef: string;
25
+ rolloutPercentage: number;
26
+ status: 'active' | 'completed';
27
+ };
28
+ export type RuntimeDeliveryPatchEdge = {
29
+ baseHash: string;
30
+ targetHash: string;
31
+ algorithm: string;
32
+ patchSetHash: string;
33
+ patchArtifactRef: string;
34
+ patchSizeBytes: number;
35
+ fullBundleSizeBytes: number;
36
+ missingAssetsHash?: string | null;
37
+ expiresAt?: string | null;
38
+ };
39
+ export type RuntimeDeliveryLaneManifest = {
40
+ schemaVersion: 3;
41
+ type: 'lane';
42
+ projectSlug: string;
43
+ channelName: string;
44
+ platform: string;
45
+ runtimeVersion: string;
46
+ generation: number;
47
+ generatedAt: string;
48
+ resolutionMode: 'local' | 'dynamic';
49
+ dynamicReason?: string;
50
+ publishingMode: 'automatic' | 'managed';
51
+ rolloutAlgorithm: typeof RUNTIME_DELIVERY_ROLLOUT_ALGORITHM;
52
+ revokedHashes: string[];
53
+ releases: RuntimeDeliveryRelease[];
54
+ publishedRollouts: RuntimeDeliveryPublishedRollout[];
55
+ patchPolicy: {
56
+ enabled: boolean;
57
+ maxPatchToFullRatio: number;
58
+ };
59
+ patchEdges: RuntimeDeliveryPatchEdge[];
60
+ candidateSetComplete: boolean;
61
+ };
62
+ export type RuntimeDeliveryJws = {
63
+ protected: string;
64
+ payload: string;
65
+ signature: string;
66
+ };
67
+ export type RuntimeDeliveryAuthorityLeaseV1 = {
68
+ schemaVersion: 1;
69
+ type: 'publisher-lease';
70
+ manifestOrigin: string;
71
+ generatedAt: string;
72
+ expiresAt: string;
73
+ };
74
+ export type RuntimeDeliveryAuthorityLease = {
75
+ schemaVersion: 2;
76
+ type: 'publisher-lease';
77
+ manifestOrigin: string;
78
+ generatedAt: string;
79
+ expiresAt: string;
80
+ clientAuthority: 'enabled' | 'disabled';
81
+ };
82
+ export type RuntimeDeliveryLaneIdentity = {
83
+ projectSlug: string;
84
+ channelName: string;
85
+ platform: string;
86
+ runtimeVersion: string;
87
+ };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RUNTIME_DELIVERY_AUTHORITY_LEASE_JWS_TYPE = exports.RUNTIME_DELIVERY_MANIFEST_JWS_TYPE = exports.RUNTIME_DELIVERY_ROLLOUT_ALGORITHM = void 0;
4
+ exports.RUNTIME_DELIVERY_ROLLOUT_ALGORITHM = 'sha256-install-id-uint32be-mod100-v1';
5
+ exports.RUNTIME_DELIVERY_MANIFEST_JWS_TYPE = 'bundledrop-manifest+jws';
6
+ exports.RUNTIME_DELIVERY_AUTHORITY_LEASE_JWS_TYPE = 'bundledrop-authority-lease+jws';
@@ -1,11 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { spawnSync } from 'child_process';
2
3
  import { findProjectRoot } from './projectRoot';
4
+ import { type ModuleResolver } from './resolveModule';
3
5
  export { findProjectRoot };
4
- export declare function runBundleScript(options?: {
6
+ type SpawnProcess = typeof spawnSync;
7
+ type BundleScriptOptions = {
5
8
  platform?: string;
6
9
  cwd?: string;
7
10
  sourcemap?: boolean;
8
- }): {
11
+ packageRoot?: string;
12
+ spawnProcess?: SpawnProcess;
13
+ resolveModule?: ModuleResolver;
14
+ };
15
+ export declare function runBundleScript(options?: BundleScriptOptions): {
9
16
  outputDir: string;
10
17
  bundlePath: string;
11
18
  sourceMapPath?: string;
@@ -43,9 +43,31 @@ const bundleManifest_1 = require("../manifest/bundleManifest");
43
43
  const canonicalArtifact_1 = require("./canonicalArtifact");
44
44
  const projectRoot_1 = require("./projectRoot");
45
45
  Object.defineProperty(exports, "findProjectRoot", { enumerable: true, get: function () { return projectRoot_1.findProjectRoot; } });
46
+ const resolveModule_1 = require("./resolveModule");
46
47
  const SENTRY_HERMES_OTA_DOCS_URL = 'https://bundledrop.app/docs/observability#sentry-and-hermes-ota-builds';
47
48
  const SENTRY_DEBUG_ID_MARKERS = ['//# debugId=', 'sentry-dbid-'];
48
- const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
49
+ const runProcess = (spawnProcess, executable, args, options) => {
50
+ const result = spawnProcess(executable, args, {
51
+ ...options,
52
+ shell: false,
53
+ });
54
+ if (result.error)
55
+ throw result.error;
56
+ if (result.status !== 0) {
57
+ const detail = typeof result.stderr === 'string' ? result.stderr.trim() : '';
58
+ throw new Error(detail || `${path.basename(executable)} exited with status ${result.status}`);
59
+ }
60
+ return result;
61
+ };
62
+ const assertGeneratedPath = (targetPath, outputDir) => {
63
+ const relative = path.relative(path.resolve(outputDir), path.resolve(targetPath));
64
+ const escapesOutput = relative === '..' ||
65
+ relative.startsWith(`..${path.sep}`) ||
66
+ path.isAbsolute(relative);
67
+ if (escapesOutput) {
68
+ throw new Error(`Generated artifact path escaped the package output directory: ${targetPath}`);
69
+ }
70
+ };
49
71
  const readTextIfExists = (filePath) => {
50
72
  if (!fs.existsSync(filePath))
51
73
  return null;
@@ -84,17 +106,21 @@ const readIosProjectSettings = (projectRoot) => {
84
106
  .filter((content) => Boolean(content));
85
107
  return contents.length ? contents.join('\n') : null;
86
108
  };
87
- const readHermesHelp = (hermescPath) => {
109
+ const readHermesHelp = (hermescPath, spawnProcess) => {
88
110
  try {
89
- return String((0, child_process_1.execSync)(`"${hermescPath}" -help`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }));
111
+ const result = runProcess(spawnProcess, hermescPath, ['-help'], {
112
+ encoding: 'utf8',
113
+ stdio: ['ignore', 'pipe', 'pipe'],
114
+ });
115
+ return String(result.stdout || '');
90
116
  }
91
117
  catch {
92
118
  return '';
93
119
  }
94
120
  };
95
121
  const hermesHelpIncludesFlag = (help, flag) => new RegExp(`(?:^|\\n)\\s*${flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?:\\s|=)`).test(help);
96
- const buildHermesFlags = (hermescPath, generateSourceMap) => {
97
- const help = readHermesHelp(hermescPath);
122
+ const buildHermesFlags = (hermescPath, generateSourceMap, spawnProcess) => {
123
+ const help = readHermesHelp(hermescPath, spawnProcess);
98
124
  const flags = ['-emit-binary'];
99
125
  if (hermesHelpIncludesFlag(help, '-O')) {
100
126
  flags.push('-O');
@@ -167,8 +193,10 @@ const shouldCompileHermesBytecode = (cfg, platform, projectRoot) => {
167
193
  }
168
194
  return false;
169
195
  };
170
- function runBundleScript(options) {
171
- const packageRoot = getPackageRoot();
196
+ function runBundleScript(options = {}) {
197
+ const packageRoot = options.packageRoot || path.resolve(__dirname, '..', '..');
198
+ const spawnProcess = options.spawnProcess || child_process_1.spawnSync;
199
+ const resolveModule = options.resolveModule || resolveModule_1.resolveModuleFrom;
172
200
  const platform = options?.platform || process.argv[2] || 'ios';
173
201
  if (!['ios', 'android'].includes(platform)) {
174
202
  console.error('❌ Please provide platform: ios or android');
@@ -205,22 +233,44 @@ function runBundleScript(options) {
205
233
  }
206
234
  const hermesEnabled = shouldCompileHermesBytecode(cfg, platform, projectRoot);
207
235
  [bundlePath, zipPath, metadataPath, manifestPath, sourceMapPath].forEach(file => {
236
+ assertGeneratedPath(file, outputDir);
208
237
  if (fs.existsSync(file))
209
238
  fs.unlinkSync(file);
210
239
  });
240
+ assertGeneratedPath(assetsDir, outputDir);
211
241
  if (fs.existsSync(assetsDir))
212
242
  fs.rmSync(assetsDir, { recursive: true, force: true });
213
243
  fs.mkdirSync(outputDir, { recursive: true });
214
244
  fs.mkdirSync(assetsDir, { recursive: true });
215
245
  console.log(`📦 Bundling React Native code for platform: ${platform}...`);
216
- const sourcemapFlag = generateSourceMap ? ` \\\n --sourcemap-output "${sourceMapPath}"` : '';
217
- (0, child_process_1.execSync)(`npx react-native bundle \
218
- --platform ${platform} \
219
- --dev false \
220
- --entry-file index.js \
221
- --bundle-output "${bundlePath}" \
222
- --assets-dest "${assetsDir}" \
223
- --reset-cache${sourcemapFlag}`, {
246
+ const reactNativePackageJson = resolveModule('react-native/package.json', [
247
+ projectRoot,
248
+ packageRoot,
249
+ __dirname,
250
+ ]);
251
+ const reactNativeCli = path.join(path.dirname(reactNativePackageJson), 'cli.js');
252
+ if (!fs.existsSync(reactNativeCli)) {
253
+ throw new Error(`React Native CLI entrypoint is missing: ${reactNativeCli}`);
254
+ }
255
+ const reactNativeArgs = [
256
+ reactNativeCli,
257
+ 'bundle',
258
+ '--platform',
259
+ platform,
260
+ '--dev',
261
+ 'false',
262
+ '--entry-file',
263
+ 'index.js',
264
+ '--bundle-output',
265
+ bundlePath,
266
+ '--assets-dest',
267
+ assetsDir,
268
+ '--reset-cache',
269
+ ];
270
+ if (generateSourceMap) {
271
+ reactNativeArgs.push('--sourcemap-output', sourceMapPath);
272
+ }
273
+ runProcess(spawnProcess, process.execPath, reactNativeArgs, {
224
274
  stdio: 'inherit',
225
275
  env: {
226
276
  ...process.env,
@@ -244,8 +294,8 @@ function runBundleScript(options) {
244
294
  const hbcPath = bundlePath + '.hbc';
245
295
  try {
246
296
  console.log(`🔥 Compiling to Hermes bytecode (${platform})...`);
247
- const hermesFlags = buildHermesFlags(hermescPath, generateSourceMap).join(' ');
248
- (0, child_process_1.execSync)(`"${hermescPath}" ${hermesFlags} -out "${hbcPath}" "${bundlePath}"`, { stdio: ['ignore', 'ignore', 'ignore'] });
297
+ const hermesFlags = buildHermesFlags(hermescPath, generateSourceMap, spawnProcess);
298
+ runProcess(spawnProcess, hermescPath, [...hermesFlags, '-out', hbcPath, bundlePath], { stdio: ['ignore', 'ignore', 'ignore'] });
249
299
  promoteHermesBytecode(hbcPath, bundlePath);
250
300
  console.log('✅ Hermes bytecode compiled');
251
301
  }
@@ -259,7 +309,7 @@ function runBundleScript(options) {
259
309
  if (fs.existsSync(composeScript)) {
260
310
  try {
261
311
  const composedPath = sourceMapPath + '.composed';
262
- (0, child_process_1.execSync)(`node "${composeScript}" "${sourceMapPath}" "${hermesMapPath}" -o "${composedPath}"`, { stdio: ['ignore', 'ignore', 'ignore'] });
312
+ runProcess(spawnProcess, process.execPath, [composeScript, sourceMapPath, hermesMapPath, '-o', composedPath], { stdio: ['ignore', 'ignore', 'ignore'] });
263
313
  fs.renameSync(composedPath, sourceMapPath);
264
314
  console.log('✅ Source maps composed');
265
315
  }
@@ -2,4 +2,5 @@
2
2
  export declare function runDownloadBundle(options?: {
3
3
  argv?: string[];
4
4
  cwd?: string;
5
+ packageRoot?: string;
5
6
  }): Promise<string>;
@@ -41,9 +41,9 @@ exports.runDownloadBundle = runDownloadBundle;
41
41
  const axios_1 = __importDefault(require("axios"));
42
42
  const fs = __importStar(require("fs"));
43
43
  const path = __importStar(require("path"));
44
- const getPackageRoot = () => process.env.BUNDLE_DROP_PACKAGE_ROOT_OVERRIDE || path.resolve(__dirname, '..', '..');
45
44
  async function runDownloadBundle(options) {
46
- const outputDir = path.join(getPackageRoot(), 'dist');
45
+ const packageRoot = options?.packageRoot || path.resolve(__dirname, '..', '..');
46
+ const outputDir = path.join(packageRoot, 'dist');
47
47
  const argv = options?.argv || process.argv;
48
48
  const platform = argv[2];
49
49
  if (!platform || !['ios', 'android'].includes(platform)) {
@@ -0,0 +1,2 @@
1
+ export type ModuleResolver = (moduleId: string, searchPaths: string[]) => string;
2
+ export declare const resolveModuleFrom: ModuleResolver;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveModuleFrom = void 0;
4
+ const resolveModuleFrom = (moduleId, searchPaths) => require.resolve(moduleId, { paths: searchPaths });
5
+ exports.resolveModuleFrom = resolveModuleFrom;