@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
@@ -3,24 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readCurrentBundlePointer = readCurrentBundlePointer;
7
- exports.readPreviousBundlePointer = readPreviousBundlePointer;
8
- exports.writeCurrentBundlePointer = writeCurrentBundlePointer;
9
- exports.writePreviousBundlePointer = writePreviousBundlePointer;
10
- exports.restorePreviousBundlePointer = restorePreviousBundlePointer;
11
- exports.setCurrentBundlePointer = setCurrentBundlePointer;
12
- exports.rollbackToPreviousPointer = rollbackToPreviousPointer;
13
- exports.deleteCurrentBundlePointer = deleteCurrentBundlePointer;
14
- exports.deletePreviousBundlePointer = deletePreviousBundlePointer;
15
- exports.clearCurrentBundlePointer = clearCurrentBundlePointer;
6
+ exports.readCurrentBundleHash = readCurrentBundleHash;
16
7
  const fs_1 = __importDefault(require("../native/fs"));
17
8
  const context_1 = require("../context");
18
- const fsUtils_1 = require("./fsUtils");
19
9
  const CURRENT_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/current.json`;
20
- const PREVIOUS_POINTER_PATH = `${context_1.BUNDLE_DROP_ROOT}/previous.json`;
21
10
  const BUNDLE_HASH_PATTERN = /^[a-f0-9]{64}$/;
22
- const bundlePathForHash = (hash) => `${context_1.BUNDLE_DROP_ROOT}/bundles/${hash}/main.jsbundle`;
23
- async function readPointer(path) {
11
+ async function readPointerHash(path) {
24
12
  try {
25
13
  if (!(await fs_1.default.exists(path)))
26
14
  return null;
@@ -28,88 +16,12 @@ async function readPointer(path) {
28
16
  const parsed = JSON.parse(raw);
29
17
  if (!BUNDLE_HASH_PATTERN.test(parsed?.hash ?? ''))
30
18
  return null;
31
- return {
32
- hash: parsed.hash,
33
- bundlePath: bundlePathForHash(parsed.hash),
34
- updatedAt: typeof parsed.updatedAt === 'string' ? parsed.updatedAt : '',
35
- };
19
+ return parsed.hash;
36
20
  }
37
21
  catch {
38
22
  return null;
39
23
  }
40
24
  }
41
- async function readCurrentBundlePointer() {
42
- return readPointer(CURRENT_POINTER_PATH);
43
- }
44
- async function readPreviousBundlePointer() {
45
- return readPointer(PREVIOUS_POINTER_PATH);
46
- }
47
- async function writeCurrentBundlePointer(pointer) {
48
- assertCanonicalPointerHash(pointer.hash);
49
- const root = context_1.BUNDLE_DROP_ROOT;
50
- await (0, fsUtils_1.ensureDir)(root);
51
- await (0, fsUtils_1.atomicWriteJson)(CURRENT_POINTER_PATH, pointerJson(pointer));
52
- }
53
- async function writePreviousBundlePointer(pointer) {
54
- assertCanonicalPointerHash(pointer.hash);
55
- const root = context_1.BUNDLE_DROP_ROOT;
56
- await (0, fsUtils_1.ensureDir)(root);
57
- await (0, fsUtils_1.atomicWriteJson)(PREVIOUS_POINTER_PATH, pointerJson(pointer));
58
- }
59
- async function restorePreviousBundlePointer(pointer) {
60
- if (pointer) {
61
- await writePreviousBundlePointer({ ...pointer, updatedAt: new Date().toISOString() });
62
- return;
63
- }
64
- await deletePreviousBundlePointer();
65
- }
66
- async function setCurrentBundlePointer(_bundlePath, hash, options) {
67
- assertCanonicalPointerHash(hash);
68
- const root = context_1.BUNDLE_DROP_ROOT;
69
- await (0, fsUtils_1.ensureDir)(root);
70
- const current = await readCurrentBundlePointer();
71
- if (options?.setPrevious !== false && current?.hash && current?.bundlePath) {
72
- await writePreviousBundlePointer({ ...current, updatedAt: new Date().toISOString() });
73
- }
74
- await writeCurrentBundlePointer({
75
- hash,
76
- bundlePath: bundlePathForHash(hash),
77
- updatedAt: new Date().toISOString(),
78
- });
79
- }
80
- function pointerJson(pointer) {
81
- return {
82
- hash: pointer.hash,
83
- updatedAt: pointer.updatedAt,
84
- };
85
- }
86
- function assertCanonicalPointerHash(hash) {
87
- if (!BUNDLE_HASH_PATTERN.test(hash)) {
88
- throw new Error('Bundle pointer hash must be a canonical 64-character lowercase SHA-256 hash');
89
- }
90
- }
91
- async function rollbackToPreviousPointer() {
92
- const previous = await readPreviousBundlePointer();
93
- if (!previous)
94
- return null;
95
- await writeCurrentBundlePointer({ ...previous, updatedAt: new Date().toISOString() });
96
- return previous;
97
- }
98
- async function deleteCurrentBundlePointer() {
99
- if (await fs_1.default.exists(CURRENT_POINTER_PATH)) {
100
- await fs_1.default.unlink(CURRENT_POINTER_PATH);
101
- }
102
- }
103
- async function deletePreviousBundlePointer() {
104
- if (await fs_1.default.exists(PREVIOUS_POINTER_PATH)) {
105
- await fs_1.default.unlink(PREVIOUS_POINTER_PATH);
106
- }
107
- }
108
- async function clearCurrentBundlePointer() {
109
- try {
110
- await deleteCurrentBundlePointer();
111
- }
112
- catch {
113
- // Best-effort cleanup for callers that do not need strict rollback semantics.
114
- }
25
+ async function readCurrentBundleHash() {
26
+ return readPointerHash(CURRENT_POINTER_PATH);
115
27
  }
package/lib/index.d.ts CHANGED
@@ -13,6 +13,8 @@ export type { BundleListItem } from './api/types';
13
13
  export type { BundleDropProjectConfig } from './loadConfig';
14
14
  export type { BundleDropConfig } from './context';
15
15
  export type { BundleDropInitOptions, BundleDropRuntimeConfig } from './runtime/initState';
16
+ export { getRuntimeDeliveryDiagnosticCounters } from './runtime-delivery/diagnostics';
17
+ export type { RuntimeDeliveryDiagnosticCounters, RuntimeDeliveryDiagnosticDetails, RuntimeDeliveryDiagnosticEvent, RuntimeDeliveryDiagnosticName, } from './runtime-delivery/diagnostics';
16
18
  export { useBundleDrop } from './useBundleDrop';
17
19
  export type { UseBundleDropReturn } from './useBundleDrop';
18
20
  export { bundleDropConfig } from './context';
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BundleDrop = exports.bundleDropConfig = exports.useBundleDrop = exports.resetUserProperties = exports.removeUserProperty = exports.setUserProperty = exports.getUserProperties = exports.getCurrentUserProperties = exports.isBundleDropError = exports.BundleDropError = exports.reportHealthy = exports.getChannelName = exports.setChannel = exports.applyUpdate = exports.getUpdateState = exports.installBundle = exports.downloadUpdate = exports.getAvailableBundles = exports.getObservabilityContext = exports.getInstalledBundleInfo = exports.checkForUpdate = exports.getAvailableChannels = void 0;
3
+ exports.BundleDrop = exports.bundleDropConfig = exports.useBundleDrop = exports.getRuntimeDeliveryDiagnosticCounters = exports.resetUserProperties = exports.removeUserProperty = exports.setUserProperty = exports.getUserProperties = exports.getCurrentUserProperties = exports.isBundleDropError = exports.BundleDropError = exports.reportHealthy = exports.getChannelName = exports.setChannel = exports.applyUpdate = exports.getUpdateState = exports.installBundle = exports.downloadUpdate = exports.getAvailableBundles = exports.getObservabilityContext = exports.getInstalledBundleInfo = exports.checkForUpdate = exports.getAvailableChannels = void 0;
4
4
  require("./bootstrap");
5
5
  const service_1 = require("./runtime/service");
6
6
  var service_2 = require("./runtime/service");
@@ -26,6 +26,8 @@ Object.defineProperty(exports, "getUserProperties", { enumerable: true, get: fun
26
26
  Object.defineProperty(exports, "setUserProperty", { enumerable: true, get: function () { return userProperties_1.setUserProperty; } });
27
27
  Object.defineProperty(exports, "removeUserProperty", { enumerable: true, get: function () { return userProperties_1.removeUserProperty; } });
28
28
  Object.defineProperty(exports, "resetUserProperties", { enumerable: true, get: function () { return userProperties_1.resetUserProperties; } });
29
+ var diagnostics_1 = require("./runtime-delivery/diagnostics");
30
+ Object.defineProperty(exports, "getRuntimeDeliveryDiagnosticCounters", { enumerable: true, get: function () { return diagnostics_1.getRuntimeDeliveryDiagnosticCounters; } });
29
31
  var useBundleDrop_1 = require("./useBundleDrop");
30
32
  Object.defineProperty(exports, "useBundleDrop", { enumerable: true, get: function () { return useBundleDrop_1.useBundleDrop; } });
31
33
  var context_1 = require("./context");
@@ -68,8 +68,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
68
68
  existingManifest = await (0, bundleVerification_1.verifyBundleDir)(bundleDir, hash, platform);
69
69
  }
70
70
  catch (e) {
71
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
72
- if (currentPointer?.hash === hash) {
71
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
72
+ if (currentHash === hash) {
73
73
  throw new Error('Active bundle folder failed verification');
74
74
  }
75
75
  }
@@ -82,8 +82,8 @@ const finalizeInstall = async (verifiedTempDir, fileNames, hash, platform, statu
82
82
  catch { /* best-effort cleanup */ }
83
83
  return { bundlePath, metadataFromZip };
84
84
  }
85
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
86
- if (currentPointer?.hash === hash) {
85
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
86
+ if (currentHash === hash) {
87
87
  throw new Error('Active bundle folder failed verification');
88
88
  }
89
89
  await fs_1.default.unlink(bundleDir);
@@ -4,6 +4,9 @@ type InstallFromZipParams = {
4
4
  hash?: string;
5
5
  platform?: 'ios' | 'android';
6
6
  statusCb?: (status: string) => void;
7
+ expectedArchiveHash?: string;
8
+ expectedManifestHash?: string;
9
+ expectedJsBundleHash?: string;
7
10
  };
8
11
  export declare function installFromZip(params: InstallFromZipParams): Promise<InstallResult>;
9
12
  export {};
@@ -12,7 +12,7 @@ const bundleManifest_1 = require("../manifest/bundleManifest");
12
12
  const bundleVerification_1 = require("./bundleVerification");
13
13
  const bundleInstallShared_1 = require("./bundleInstallShared");
14
14
  async function installFromZip(params) {
15
- const { downloadUrl, hash, statusCb, platform = context_1.platform } = params;
15
+ const { downloadUrl, hash, statusCb, platform = context_1.platform, expectedArchiveHash, expectedManifestHash, expectedJsBundleHash, } = params;
16
16
  if (!hash) {
17
17
  throw new Error('Missing bundle hash');
18
18
  }
@@ -33,6 +33,9 @@ async function installFromZip(params) {
33
33
  catch (e) {
34
34
  throw new errors_1.InstallPhaseError('download', e);
35
35
  }
36
+ if (expectedArchiveHash && (await fs_1.default.sha256File(tempZipPath)) !== expectedArchiveHash) {
37
+ throw new errors_1.InstallPhaseError('install', new Error('Full bundle archive hash mismatch'));
38
+ }
36
39
  try {
37
40
  fileNames = await fs_1.default.unzip(tempZipPath, tempDir);
38
41
  }
@@ -47,6 +50,12 @@ async function installFromZip(params) {
47
50
  if (!manifest) {
48
51
  throw new Error('Bundle manifest is missing');
49
52
  }
53
+ if (expectedManifestHash && manifest.manifestHash !== expectedManifestHash) {
54
+ throw new Error('Signed manifest hash does not match downloaded bundle manifest');
55
+ }
56
+ if (expectedJsBundleHash && manifest.jsBundleHash !== expectedJsBundleHash) {
57
+ throw new Error('Signed JavaScript bundle hash does not match downloaded bundle manifest');
58
+ }
50
59
  verifiedHash = manifest.bundleHash;
51
60
  }
52
61
  catch (e) {
@@ -1,6 +1,18 @@
1
1
  /**
2
2
  * Shape of `bundle.drop.config.js` after it is loaded through Metro.
3
3
  */
4
+ export type RuntimeDeliveryConfig = {
5
+ manifestBaseUrl: string;
6
+ manifestAccessId: string;
7
+ publicKeys: Record<string, {
8
+ kty: 'EC';
9
+ crv: 'P-256';
10
+ x: string;
11
+ y: string;
12
+ }>;
13
+ };
14
+ /** Returns true only for a complete package-managed trust configuration. */
15
+ export declare function isRuntimeDeliveryConfigured(value: unknown): value is RuntimeDeliveryConfig;
4
16
  export type BundleDropProjectConfig = {
5
17
  /** Persisted project shape used to keep Expo and bare runtime behavior distinct. */
6
18
  projectType?: 'expo' | 'bare';
@@ -51,4 +63,8 @@ export type BundleDropProjectConfig = {
51
63
  healthyAfterSec?: number;
52
64
  };
53
65
  };
54
- export declare function loadConfig(): BundleDropProjectConfig;
66
+ /** Internal Metro-resolved config. Generated trust data is deliberately absent from the public type. */
67
+ export type ResolvedBundleDropProjectConfig = BundleDropProjectConfig & {
68
+ runtimeDelivery?: RuntimeDeliveryConfig;
69
+ };
70
+ export declare function loadConfig(): ResolvedBundleDropProjectConfig;
package/lib/loadConfig.js CHANGED
@@ -1,6 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRuntimeDeliveryConfigured = isRuntimeDeliveryConfigured;
3
4
  exports.loadConfig = loadConfig;
5
+ /** Returns true only for a complete package-managed trust configuration. */
6
+ function isRuntimeDeliveryConfigured(value) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value))
8
+ return false;
9
+ const candidate = value;
10
+ if (candidate.mode === 'v1' || candidate.mode === 'shadow')
11
+ return false;
12
+ return (typeof candidate.manifestBaseUrl === 'string' &&
13
+ Boolean(candidate.manifestBaseUrl) &&
14
+ typeof candidate.manifestAccessId === 'string' &&
15
+ Boolean(candidate.manifestAccessId) &&
16
+ Boolean(candidate.publicKeys) &&
17
+ typeof candidate.publicKeys === 'object' &&
18
+ !Array.isArray(candidate.publicKeys));
19
+ }
4
20
  function loadConfig() {
5
21
  try {
6
22
  // ✅ Resolved via Metro alias in the host app (extraNodeModules)
@@ -1,4 +1,4 @@
1
- import type { OtaPatchSet } from '../api/types';
1
+ import type { OtaPatchSet, UpdateCheckResponse } from '../api/types';
2
2
  export type DownloadUpdateResult = {
3
3
  status: 'staged';
4
4
  bundlePath: string;
@@ -20,7 +20,7 @@ type DownloadOptions = {
20
20
  channelName?: string;
21
21
  resolvedTarget?: {
22
22
  hash: string;
23
- downloadUrl: string;
23
+ downloadUrl?: string;
24
24
  bundleVersion?: number;
25
25
  version?: string;
26
26
  runtimeVersion?: string;
@@ -32,6 +32,7 @@ type DownloadOptions = {
32
32
  mode: 'full';
33
33
  downloadUrl: string;
34
34
  };
35
+ runtimeDelivery?: UpdateCheckResponse['runtimeDelivery'];
35
36
  };
36
37
  };
37
38
  export declare const downloadUpdate: (options?: DownloadOptions, onStatusUpdate?: (status: string) => void) => Promise<DownloadUpdateResult>;
@@ -3,19 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.installBundle = exports.downloadUpdate = void 0;
4
4
  const context_1 = require("../context");
5
5
  const bundleInfo_1 = require("../bundleInfo");
6
- const bundlePointer_1 = require("../fs/bundlePointer");
7
6
  const installFromZip_1 = require("../install/installFromZip");
8
7
  const patchTransport_1 = require("../patch-engine/patchTransport");
9
- const bundleDropNative_1 = require("../native/bundleDropNative");
10
8
  const updateCheck_1 = require("./updateCheck");
11
9
  const errors_1 = require("../errors");
12
10
  const rollbackState_1 = require("./rollbackState");
13
- async function restoreCurrentPointer(pointer) {
14
- if (pointer) {
15
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...pointer, updatedAt: new Date().toISOString() });
16
- return;
11
+ const artifactCapability_1 = require("../runtime-delivery/artifactCapability");
12
+ function isSameRuntimeDeliverySelection(selected, refreshed) {
13
+ if (!refreshed ||
14
+ refreshed.action !== 'INSTALL' ||
15
+ refreshed.hash !== selected.hash ||
16
+ refreshed.runtimeVersion !== selected.runtimeVersion ||
17
+ !selected.runtimeDelivery ||
18
+ !refreshed.runtimeDelivery) {
19
+ return false;
17
20
  }
18
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
21
+ const before = selected.runtimeDelivery;
22
+ const after = refreshed.runtimeDelivery;
23
+ return before.generation === after.generation &&
24
+ before.targetReleaseRef === after.targetReleaseRef &&
25
+ before.selectedMode === after.selectedMode &&
26
+ (before.baseHash ?? null) === (after.baseHash ?? null) &&
27
+ (before.patchAlgorithm ?? null) === (after.patchAlgorithm ?? null) &&
28
+ (before.patchSetHash ?? null) === (after.patchSetHash ?? null) &&
29
+ (before.patchArtifactRef ?? null) === (after.patchArtifactRef ?? null) &&
30
+ (before.missingAssetsHash ?? null) === (after.missingAssetsHash ?? null) &&
31
+ (before.manifestHash ?? null) === (after.manifestHash ?? null) &&
32
+ (before.jsBundleHash ?? null) === (after.jsBundleHash ?? null) &&
33
+ (before.fullBundleHash ?? null) === (after.fullBundleHash ?? null);
19
34
  }
20
35
  async function downloadAndStageUpdate(options, onStatusUpdate) {
21
36
  const { project } = context_1.config;
@@ -24,9 +39,10 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
24
39
  const statusCb = onStatusUpdate;
25
40
  const resolvedTarget = options?.resolvedTarget;
26
41
  // Resolve target via /ota/resolve unless the caller already provided it.
27
- const checkResult = resolvedTarget
42
+ const unresolvedCheckResult = resolvedTarget
28
43
  ? {
29
44
  action: 'INSTALL',
45
+ channelName,
30
46
  hash: resolvedTarget.hash,
31
47
  bundleHash: resolvedTarget.hash,
32
48
  downloadUrl: resolvedTarget.downloadUrl,
@@ -38,8 +54,12 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
38
54
  baseHash: resolvedTarget.baseHash,
39
55
  patchSet: resolvedTarget.patchSet,
40
56
  fallback: resolvedTarget.fallback,
57
+ runtimeDelivery: resolvedTarget.runtimeDelivery,
41
58
  }
42
59
  : await (0, updateCheck_1.checkForUpdate)(channelName, statusCb);
60
+ let checkResult = unresolvedCheckResult
61
+ ? await (0, updateCheck_1.authorizeRuntimeDeliveryUpdate)(unresolvedCheckResult)
62
+ : null;
43
63
  if (!checkResult) {
44
64
  throw new errors_1.BundleDropError({
45
65
  message: 'Failed to resolve update decision',
@@ -73,9 +93,6 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
73
93
  const serverBundleVersion = checkResult.bundleVersion;
74
94
  const serverVersion = checkResult.version;
75
95
  const serverRuntimeVersion = checkResult.runtimeVersion;
76
- const fullBundleZipUrl = checkResult.mode === 'patch'
77
- ? checkResult.fallback?.downloadUrl || null
78
- : checkResult.downloadUrl || null;
79
96
  try {
80
97
  if (!serverHash) {
81
98
  throw new errors_1.BundleDropError({
@@ -85,18 +102,6 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
85
102
  context: { channelName, platform, projectSlug: project.slug },
86
103
  });
87
104
  }
88
- if (!fullBundleZipUrl) {
89
- throw new errors_1.BundleDropError({
90
- message: 'Missing downloadUrl from ota resolve response',
91
- code: 'DOWNLOAD_URL_MISSING',
92
- step: 'resolve',
93
- context: {
94
- channelName,
95
- platform,
96
- projectSlug: project.slug,
97
- },
98
- });
99
- }
100
105
  const hash = serverHash;
101
106
  if (await (0, rollbackState_1.isBundleHashFailed)(hash)) {
102
107
  statusCb?.('✅ Current bundle retained; selected update previously failed on this device');
@@ -107,50 +112,97 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
107
112
  skippedHash: hash,
108
113
  };
109
114
  }
110
- let installResult = await (0, patchTransport_1.tryInstallPatchTransport)({
111
- target: {
112
- mode: checkResult.mode,
113
- hash,
114
- manifestUrl: checkResult.manifestUrl,
115
- baseHash: checkResult.baseHash,
116
- patchSet: checkResult.patchSet,
117
- },
118
- projectSlug: project.slug,
119
- platform,
120
- runtimeVersionValue: serverRuntimeVersion,
121
- statusCb,
122
- });
123
- try {
124
- if (!installResult) {
125
- statusCb?.('⬇️ Downloading full bundle ZIP!...');
126
- installResult = await (0, installFromZip_1.installFromZip)({
127
- downloadUrl: fullBundleZipUrl,
128
- hash,
115
+ let installResult;
116
+ let capabilityRefreshAttempted = false;
117
+ let patchFallbackSelected = false;
118
+ while (true) {
119
+ const fullBundleZipUrl = checkResult.mode === 'patch'
120
+ ? checkResult.fallback?.downloadUrl || null
121
+ : checkResult.downloadUrl || null;
122
+ if (!fullBundleZipUrl) {
123
+ throw new errors_1.BundleDropError({
124
+ message: 'Missing downloadUrl from ota resolve response',
125
+ code: 'DOWNLOAD_URL_MISSING',
126
+ step: 'resolve',
127
+ context: { channelName, platform, projectSlug: project.slug },
128
+ });
129
+ }
130
+ try {
131
+ installResult = patchFallbackSelected ? null : await (0, patchTransport_1.tryInstallPatchTransport)({
132
+ target: {
133
+ mode: checkResult.mode,
134
+ hash,
135
+ manifestUrl: checkResult.manifestUrl,
136
+ baseHash: checkResult.baseHash,
137
+ patchSet: checkResult.patchSet,
138
+ ...(checkResult.runtimeDelivery?.manifestHash
139
+ ? { expectedManifestHash: checkResult.runtimeDelivery.manifestHash }
140
+ : {}),
141
+ ...(checkResult.runtimeDelivery?.jsBundleHash
142
+ ? { expectedJsBundleHash: checkResult.runtimeDelivery.jsBundleHash }
143
+ : {}),
144
+ },
145
+ projectSlug: project.slug,
129
146
  platform,
147
+ runtimeVersionValue: serverRuntimeVersion,
130
148
  statusCb,
131
149
  });
150
+ if (!installResult) {
151
+ patchFallbackSelected = checkResult.mode === 'patch';
152
+ statusCb?.('⬇️ Downloading full bundle ZIP!...');
153
+ installResult = await (0, installFromZip_1.installFromZip)({
154
+ downloadUrl: fullBundleZipUrl,
155
+ hash,
156
+ platform,
157
+ statusCb,
158
+ ...(checkResult.runtimeDelivery?.fullBundleHash
159
+ ? { expectedArchiveHash: checkResult.runtimeDelivery.fullBundleHash }
160
+ : {}),
161
+ ...(checkResult.runtimeDelivery?.manifestHash
162
+ ? { expectedManifestHash: checkResult.runtimeDelivery.manifestHash }
163
+ : {}),
164
+ ...(checkResult.runtimeDelivery?.jsBundleHash
165
+ ? { expectedJsBundleHash: checkResult.runtimeDelivery.jsBundleHash }
166
+ : {}),
167
+ });
168
+ }
169
+ break;
170
+ }
171
+ catch (e) {
172
+ if (!capabilityRefreshAttempted &&
173
+ unresolvedCheckResult.runtimeDelivery &&
174
+ (0, artifactCapability_1.isArtifactCapabilityRejected)(e)) {
175
+ capabilityRefreshAttempted = true;
176
+ statusCb?.('🔐 Download authorization expired; refreshing once...');
177
+ const refreshed = await (0, updateCheck_1.authorizeRuntimeDeliveryUpdate)(unresolvedCheckResult);
178
+ if (!isSameRuntimeDeliverySelection(unresolvedCheckResult, refreshed)) {
179
+ throw new errors_1.BundleDropError({
180
+ message: 'Refreshed download authorization changed update identity',
181
+ code: 'DOWNLOAD_FAILED',
182
+ step: 'download',
183
+ context: { channelName, platform, hash },
184
+ cause: e,
185
+ });
186
+ }
187
+ checkResult = refreshed;
188
+ continue;
189
+ }
190
+ const phaseErr = (0, errors_1.isInstallPhaseError)(e);
191
+ const isDownload = phaseErr && e.phase === 'download';
192
+ throw new errors_1.BundleDropError({
193
+ message: isDownload ? 'Failed to download update ZIP' : 'Failed to install update ZIP',
194
+ code: isDownload ? 'DOWNLOAD_FAILED' : 'INSTALL_FAILED',
195
+ step: isDownload ? 'download' : 'install',
196
+ context: { channelName, platform, hash },
197
+ cause: phaseErr ? e.originalCause : e,
198
+ });
132
199
  }
133
- }
134
- catch (e) {
135
- const phaseErr = (0, errors_1.isInstallPhaseError)(e);
136
- const isDownload = phaseErr && e.phase === 'download';
137
- throw new errors_1.BundleDropError({
138
- message: isDownload ? 'Failed to download update ZIP' : 'Failed to install update ZIP',
139
- code: isDownload ? 'DOWNLOAD_FAILED' : 'INSTALL_FAILED',
140
- step: isDownload ? 'download' : 'install',
141
- context: { channelName, platform, hash },
142
- cause: phaseErr ? e.originalCause : e,
143
- });
144
200
  }
145
201
  const { bundlePath, metadataFromZip } = installResult;
146
202
  const installedHash = hash;
147
203
  statusCb?.('✅ Update downloaded. Will apply on next launch or when you call applyUpdate().');
148
204
  // Persist installed metadata for future skip logic.
149
- const [previousInfo, previousCurrentPointer, previousRollbackPointer] = await Promise.all([
150
- (0, bundleInfo_1.readBundleInfo)(),
151
- (0, bundlePointer_1.readCurrentBundlePointer)(),
152
- (0, bundlePointer_1.readPreviousBundlePointer)(),
153
- ]);
205
+ const previousInfo = await (0, bundleInfo_1.readBundleInfo)();
154
206
  const installedInfo = {
155
207
  bundleVersion: serverBundleVersion ?? metadataFromZip.bundleVersion,
156
208
  version: serverVersion ?? metadataFromZip.version,
@@ -163,21 +215,39 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
163
215
  lastInstalledReportedHash: previousInfo?.lastInstalledReportedHash,
164
216
  installedReportedHashes: previousInfo?.installedReportedHashes,
165
217
  };
166
- await (0, bundlePointer_1.setCurrentBundlePointer)(bundlePath, installedHash);
218
+ let candidateActivated = false;
167
219
  try {
168
- const resolvedBundlePath = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
169
- if (resolvedBundlePath !== bundlePath) {
220
+ const activation = await (0, rollbackState_1.activateStartupCandidate)(installedHash);
221
+ candidateActivated = activation !== null;
222
+ if (!activation) {
223
+ throw new errors_1.BundleDropError({
224
+ message: 'Installed bundle requires native startup recovery support',
225
+ code: 'INSTALL_FAILED',
226
+ step: 'install',
227
+ context: { channelName, platform, hash },
228
+ });
229
+ }
230
+ if (activation.hash !== installedHash || activation.bundlePath !== bundlePath) {
170
231
  throw new errors_1.BundleDropError({
171
232
  message: 'Installed bundle was not accepted by the native resolver',
172
233
  code: 'INSTALL_FAILED',
173
234
  step: 'install',
174
- context: { channelName, platform, hash, expectedBundlePath: bundlePath, resolvedBundlePath },
235
+ context: {
236
+ channelName,
237
+ platform,
238
+ hash,
239
+ expectedBundlePath: bundlePath,
240
+ resolvedBundlePath: activation.bundlePath,
241
+ resolvedHash: activation.hash,
242
+ },
175
243
  });
176
244
  }
245
+ await (0, bundleInfo_1.writeBundleInfoDurably)(installedInfo);
177
246
  }
178
247
  catch (nativeError) {
179
- await restoreCurrentPointer(previousCurrentPointer);
180
- await (0, bundlePointer_1.restorePreviousBundlePointer)(previousRollbackPointer);
248
+ if (candidateActivated) {
249
+ await (0, rollbackState_1.rollbackStartupBundle)(false).catch(() => false);
250
+ }
181
251
  if (nativeError instanceof errors_1.BundleDropError) {
182
252
  throw nativeError;
183
253
  }
@@ -189,8 +259,6 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
189
259
  cause: nativeError,
190
260
  });
191
261
  }
192
- await (0, bundleInfo_1.writeBundleInfo)(installedInfo);
193
- await (0, rollbackState_1.markCandidateActivated)(installedHash);
194
262
  return { status: 'staged', bundlePath, hash: installedHash };
195
263
  }
196
264
  catch (err) {
@@ -1,5 +1,12 @@
1
1
  import { BundleInfo } from '../bundleInfo';
2
- import type { FailedBundleRecord } from './rollbackState';
2
+ export type FailedBundleRecord = {
3
+ reason: 'crash_loop';
4
+ failedAt: number;
5
+ crashCount?: number;
6
+ channelName?: string;
7
+ runtimeVersion?: string;
8
+ previousHash?: string;
9
+ };
3
10
  export declare function reportInstalledIfReady(state?: {
4
11
  hasBundle?: boolean;
5
12
  info?: BundleInfo | null;
@@ -74,26 +74,21 @@ async function reportInstalledIfReady(state) {
74
74
  }
75
75
  }
76
76
  async function reportLocalRollback(hash, record) {
77
- try {
78
- const [installId, userProperties] = await Promise.all([
79
- (0, installId_1.getOrCreateInstallId)(),
80
- (0, userProperties_1.getCurrentUserProperties)(),
81
- ]);
82
- const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
83
- await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
84
- reason: record.reason,
85
- previousHash: record.previousHash ?? null,
86
- channelName: record.channelName ?? null,
87
- platform: context_1.platform,
88
- installId,
89
- runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
90
- environment: appEnvironment,
91
- userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
92
- crashCount: record.crashCount ?? null,
93
- failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
94
- });
95
- }
96
- catch (e) {
97
- console.warn('⚠️ Failed to report local rollback:', e?.toString?.() || e);
98
- }
77
+ const [installId, userProperties] = await Promise.all([
78
+ (0, installId_1.getOrCreateInstallId)(),
79
+ (0, userProperties_1.getCurrentUserProperties)(),
80
+ ]);
81
+ const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
82
+ await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
83
+ reason: record.reason,
84
+ previousHash: record.previousHash ?? null,
85
+ channelName: record.channelName ?? null,
86
+ platform: context_1.platform,
87
+ installId,
88
+ runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
89
+ environment: appEnvironment,
90
+ userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
91
+ crashCount: record.crashCount ?? null,
92
+ failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
93
+ });
99
94
  }