@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
@@ -1,58 +1,24 @@
1
- import { type BundlePointer } from '../fs/bundlePointer';
1
+ import type { BundleInfo } from '../bundleInfo';
2
+ import { type StartupRecoveryState, type StartupCandidateActivation, type StartupRollbackResult } from '../native/bundleDropNative';
2
3
  export type RollbackPolicy = {
3
4
  maxCrashCount?: number;
4
5
  healthCheckMode?: 'auto' | 'manual';
5
6
  healthyAfterSec?: number;
6
7
  };
7
- export type FailedBundleReason = 'crash_loop';
8
- export type FailedBundleRecord = {
9
- reason: FailedBundleReason;
10
- failedAt: number;
11
- crashCount?: number;
12
- channelName?: string;
13
- runtimeVersion?: string;
14
- previousHash?: string;
15
- };
16
- export type RollbackState = {
17
- activeHash?: string;
18
- lastGoodHash?: string;
19
- candidateHash?: string;
20
- candidateActivatedAt?: number;
21
- candidateCommitted?: boolean;
22
- crashCount?: number;
23
- lastLaunchAt?: number;
24
- failedBundles?: Record<string, FailedBundleRecord>;
25
- };
26
- type RollbackDecision = {
27
- shouldRollback: false;
28
- } | {
29
- shouldRollback: true;
30
- reason: FailedBundleReason;
31
- };
32
- declare function readState(): Promise<RollbackState | null>;
33
- export { readState as readRollbackState };
34
- export declare function markCandidateActivated(hash: string): Promise<void>;
35
- export declare function reportActiveBundleHealthy(cached?: {
36
- currentPointer?: BundlePointer | null;
37
- }, expectedHash?: string): Promise<boolean>;
38
- export declare function commitActiveBundle(cached?: {
39
- currentPointer?: BundlePointer | null;
40
- }): Promise<void>;
41
- export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
42
- export declare function getFailedBundleHashes(): Promise<string[]>;
43
- export declare function evaluateRollbackOnLaunch(policy: Required<RollbackPolicy>, cached?: {
44
- currentPointer?: BundlePointer | null;
45
- rollbackState?: RollbackState | null;
46
- }): Promise<RollbackDecision>;
47
- export declare function rollbackToPreviousIfNeeded(policy: Required<RollbackPolicy>, cached?: {
48
- currentPointer?: BundlePointer | null;
49
- rollbackState?: RollbackState | null;
50
- }): Promise<{
51
- rolledBack: boolean;
52
- reason?: FailedBundleReason;
53
- }>;
8
+ export type { FailedBundleRecord } from './reporting';
9
+ export type { StartupRecoveryState } from '../native/bundleDropNative';
10
+ export declare const STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH: string;
54
11
  export declare function getRollbackPolicy(): Required<RollbackPolicy>;
55
- export declare function rollbackToPreviousOrNative(): Promise<{
56
- rolledBack: boolean;
57
- toNative?: boolean;
58
- }>;
12
+ export declare function activateStartupCandidate(hash: string): Promise<StartupCandidateActivation | null>;
13
+ export declare function reportActiveBundleHealthy(): Promise<boolean>;
14
+ export declare function readStartupRecoveryState(): Promise<StartupRecoveryState | null>;
15
+ export declare function getFailedBundleHashes(cachedState?: StartupRecoveryState | null): Promise<string[]>;
16
+ export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
17
+ export declare function syncVerifiedRevokedHashes(hashes: string[]): Promise<boolean>;
18
+ export declare function rollbackStartupBundle(forceEmbedded: boolean): Promise<StartupRollbackResult | null>;
19
+ /**
20
+ * Flush native recovery events without making JS part of the recovery decision.
21
+ * Native keeps each event durable until its backend report succeeds and JS
22
+ * acknowledges that exact event id.
23
+ */
24
+ export declare function reconcileStartupRecovery(cachedState?: StartupRecoveryState | null, failedBundleInfo?: BundleInfo | null): Promise<StartupRecoveryState | null>;
@@ -3,246 +3,145 @@ 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.readRollbackState = readState;
7
- exports.markCandidateActivated = markCandidateActivated;
6
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = void 0;
7
+ exports.getRollbackPolicy = getRollbackPolicy;
8
+ exports.activateStartupCandidate = activateStartupCandidate;
8
9
  exports.reportActiveBundleHealthy = reportActiveBundleHealthy;
9
- exports.commitActiveBundle = commitActiveBundle;
10
- exports.isBundleHashFailed = isBundleHashFailed;
10
+ exports.readStartupRecoveryState = readStartupRecoveryState;
11
11
  exports.getFailedBundleHashes = getFailedBundleHashes;
12
- exports.evaluateRollbackOnLaunch = evaluateRollbackOnLaunch;
13
- exports.rollbackToPreviousIfNeeded = rollbackToPreviousIfNeeded;
14
- exports.getRollbackPolicy = getRollbackPolicy;
15
- exports.rollbackToPreviousOrNative = rollbackToPreviousOrNative;
16
- const fs_1 = __importDefault(require("../native/fs"));
12
+ exports.isBundleHashFailed = isBundleHashFailed;
13
+ exports.syncVerifiedRevokedHashes = syncVerifiedRevokedHashes;
14
+ exports.rollbackStartupBundle = rollbackStartupBundle;
15
+ exports.reconcileStartupRecovery = reconcileStartupRecovery;
17
16
  const context_1 = require("../context");
18
17
  const fsUtils_1 = require("../fs/fsUtils");
19
- const bundlePointer_1 = require("../fs/bundlePointer");
20
- const bundleInfo_1 = require("../bundleInfo");
18
+ const fs_1 = __importDefault(require("../native/fs"));
19
+ const bundleDropNative_1 = require("../native/bundleDropNative");
21
20
  const reporting_1 = require("./reporting");
22
- const bundleManifest_1 = require("../manifest/bundleManifest");
23
- const STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/state.json`;
24
- const MAX_FAILED_BUNDLES = 20;
25
- function nowSec() {
26
- return Math.floor(Date.now() / 1000);
27
- }
28
- async function readState() {
21
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = `${context_1.BUNDLE_DROP_ROOT}/recovery-telemetry-context.json`;
22
+ let telemetryContextMutation = Promise.resolve();
23
+ async function readRecoveryTelemetryContexts() {
29
24
  try {
30
- if (!(await fs_1.default.exists(STATE_PATH)))
31
- return null;
32
- const raw = await fs_1.default.readFile(STATE_PATH, 'utf8');
33
- return JSON.parse(raw);
25
+ if (!await fs_1.default.exists(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH)) {
26
+ return { schemaVersion: 1, events: {} };
27
+ }
28
+ const parsed = JSON.parse(await fs_1.default.readFile(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, 'utf8'));
29
+ if (parsed?.schemaVersion !== 1 || !parsed.events || typeof parsed.events !== 'object') {
30
+ throw new Error('unsupported recovery telemetry context');
31
+ }
32
+ return parsed;
34
33
  }
35
- catch {
36
- return null;
34
+ catch (error) {
35
+ console.warn('⚠️ Ignoring malformed BundleDrop recovery telemetry context:', error);
36
+ return { schemaVersion: 1, events: {} };
37
37
  }
38
38
  }
39
- async function writeState(state) {
40
- await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
41
- await (0, fsUtils_1.atomicWriteJson)(STATE_PATH, state);
39
+ async function mutateRecoveryTelemetryContexts(mutate) {
40
+ let result = { schemaVersion: 1, events: {} };
41
+ const mutation = telemetryContextMutation.then(async () => {
42
+ result = await readRecoveryTelemetryContexts();
43
+ if (!mutate(result))
44
+ return;
45
+ await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
46
+ await (0, fsUtils_1.atomicWriteJson)(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, result);
47
+ });
48
+ telemetryContextMutation = mutation.then(() => undefined, () => undefined);
49
+ await mutation;
50
+ return result;
51
+ }
52
+ async function prepareRecoveryTelemetryContexts(events, failedBundleInfo) {
53
+ const pendingEventIds = new Set(events.map(event => event.id));
54
+ return mutateRecoveryTelemetryContexts(state => {
55
+ let changed = false;
56
+ for (const eventId of Object.keys(state.events)) {
57
+ if (!pendingEventIds.has(eventId)) {
58
+ delete state.events[eventId];
59
+ changed = true;
60
+ }
61
+ }
62
+ for (const event of events) {
63
+ if (!state.events[event.id] &&
64
+ failedBundleInfo?.hash === event.failedHash) {
65
+ state.events[event.id] = {
66
+ failedHash: event.failedHash,
67
+ channelName: failedBundleInfo.channelName,
68
+ runtimeVersion: failedBundleInfo.runtimeVersion,
69
+ };
70
+ changed = true;
71
+ }
72
+ }
73
+ return changed;
74
+ });
42
75
  }
43
- async function updateState(partial) {
44
- const existing = (await readState()) || {};
45
- const next = { ...existing, ...partial };
46
- await writeState(next);
47
- return next;
76
+ async function removeRecoveryTelemetryContext(eventId) {
77
+ await mutateRecoveryTelemetryContexts(state => {
78
+ if (!state.events[eventId])
79
+ return false;
80
+ delete state.events[eventId];
81
+ return true;
82
+ });
48
83
  }
49
- function pruneFailedBundles(failedBundles) {
50
- return Object.fromEntries(Object.entries(failedBundles)
51
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
52
- .slice(0, MAX_FAILED_BUNDLES));
84
+ function getRollbackPolicy() {
85
+ return context_1.bundleDropConfig.rollback;
53
86
  }
54
- async function markCandidateActivated(hash) {
55
- const previous = await (0, bundlePointer_1.readPreviousBundlePointer)();
56
- const previousHash = previous?.hash;
57
- const now = nowSec();
58
- await updateState({
59
- activeHash: hash,
60
- candidateHash: hash,
61
- candidateActivatedAt: now,
62
- candidateCommitted: false,
63
- crashCount: 0,
64
- lastLaunchAt: now,
65
- lastGoodHash: previousHash ?? undefined,
66
- });
87
+ async function activateStartupCandidate(hash) {
88
+ return (0, bundleDropNative_1.activateStartupCandidateNative)(hash, getRollbackPolicy());
67
89
  }
68
- async function reportActiveBundleHealthy(cached, expectedHash) {
69
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
70
- const hash = current?.hash;
71
- if (!hash)
72
- return false;
73
- if (expectedHash && hash !== expectedHash)
74
- return false;
75
- const state = (await readState()) || {};
76
- const isCandidate = state.candidateHash === hash && state.candidateCommitted !== true;
77
- if (!isCandidate)
90
+ async function reportActiveBundleHealthy() {
91
+ const attempt = (0, bundleDropNative_1.getStartupRecoveryAttemptNative)();
92
+ if (!attempt)
78
93
  return false;
79
- await updateState({
80
- activeHash: hash,
81
- candidateHash: hash,
82
- candidateCommitted: true,
83
- crashCount: 0,
84
- lastGoodHash: hash,
85
- });
86
- return true;
94
+ return (0, bundleDropNative_1.markStartupHealthyNative)(attempt);
95
+ }
96
+ async function readStartupRecoveryState() {
97
+ return (0, bundleDropNative_1.getStartupRecoveryStateNative)();
87
98
  }
88
- async function commitActiveBundle(cached) {
89
- await reportActiveBundleHealthy(cached);
99
+ async function getFailedBundleHashes(cachedState) {
100
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
101
+ return [...(state?.quarantinedHashes || [])];
90
102
  }
91
103
  async function isBundleHashFailed(hash) {
92
104
  if (!hash)
93
105
  return false;
94
- const state = await readState();
95
- return !!state?.failedBundles?.[hash];
106
+ return (await getFailedBundleHashes()).includes(hash);
96
107
  }
97
- async function getFailedBundleHashes() {
98
- const state = await readState();
99
- return Object.entries(state?.failedBundles || {})
100
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
101
- .slice(0, MAX_FAILED_BUNDLES)
102
- .map(([hash]) => hash);
108
+ async function syncVerifiedRevokedHashes(hashes) {
109
+ return (0, bundleDropNative_1.setStartupRecoveryRevokedHashesNative)(hashes);
103
110
  }
104
- async function buildFailedBundleRecord(hash, reason, state) {
105
- const [bundleInfo, previous] = await Promise.all([
106
- (0, bundleInfo_1.readBundleInfo)(),
107
- (0, bundlePointer_1.readPreviousBundlePointer)(),
108
- ]);
109
- const record = {
110
- reason,
111
- failedAt: nowSec(),
112
- crashCount: state.crashCount,
113
- channelName: bundleInfo?.channelName,
114
- runtimeVersion: bundleInfo?.runtimeVersion,
115
- previousHash: previous?.hash,
116
- };
117
- return record;
111
+ async function rollbackStartupBundle(forceEmbedded) {
112
+ return (0, bundleDropNative_1.rollbackStartupBundleNative)(forceEmbedded);
118
113
  }
119
- async function recordFailedBundle(hash, record) {
120
- const state = (await readState()) || {};
121
- const failedBundles = pruneFailedBundles({
122
- ...(state.failedBundles || {}),
123
- [hash]: record,
124
- });
125
- await updateState({ failedBundles });
126
- }
127
- async function evaluateRollbackOnLaunch(policy, cached) {
128
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
129
- const activeHash = current?.hash;
130
- if (!activeHash)
131
- return { shouldRollback: false };
132
- const now = nowSec();
133
- const persistedState = (await readState()) || {};
134
- const state = cached?.rollbackState !== undefined
135
- ? {
136
- ...persistedState,
137
- ...cached.rollbackState,
138
- failedBundles: persistedState.failedBundles ?? cached.rollbackState?.failedBundles,
139
- }
140
- : persistedState;
141
- const next = {
142
- ...state,
143
- activeHash,
144
- lastLaunchAt: now,
114
+ function recoveryRecord(event, context) {
115
+ return {
116
+ reason: event.reason,
117
+ failedAt: event.failedAt,
118
+ crashCount: event.crashCount,
119
+ channelName: context?.channelName,
120
+ runtimeVersion: context?.runtimeVersion,
121
+ previousHash: event.recoveredHash,
145
122
  };
146
- const isCandidate = state.candidateHash === activeHash && state.candidateCommitted !== true;
147
- if (isCandidate) {
148
- const crashCount = (state.crashCount ?? 0) + 1;
149
- next.crashCount = crashCount;
150
- if (policy.maxCrashCount > 0 &&
151
- crashCount >= policy.maxCrashCount) {
152
- await writeState(next);
153
- return { shouldRollback: true, reason: 'crash_loop' };
154
- }
155
- }
156
- await writeState(next);
157
- return { shouldRollback: false };
158
123
  }
159
- async function rollbackToPreviousIfNeeded(policy, cached) {
160
- const decision = await evaluateRollbackOnLaunch(policy, cached);
161
- if (!decision.shouldRollback)
162
- return { rolledBack: false };
163
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
164
- const failedHash = current?.hash;
165
- const state = (await readState()) || {};
166
- if (!failedHash)
167
- return { rolledBack: false };
168
- const failedRecord = await buildFailedBundleRecord(failedHash, decision.reason, state);
169
- await rollbackToPreviousOrNative();
170
- await recordFailedBundle(failedHash, failedRecord);
171
- await (0, reporting_1.reportLocalRollback)(failedHash, failedRecord).catch(() => undefined);
172
- return { rolledBack: true, reason: decision.reason };
173
- }
174
- function getRollbackPolicy() {
175
- return context_1.bundleDropConfig.rollback;
176
- }
177
- async function rollbackToPreviousOrNative() {
178
- const [current, previous, state] = await Promise.all([
179
- (0, bundlePointer_1.readCurrentBundlePointer)(),
180
- (0, bundlePointer_1.readPreviousBundlePointer)(),
181
- readState(),
182
- ]);
183
- const previousIsFailed = previous ? !!state?.failedBundles?.[previous.hash] : false;
184
- if (previous && previous.hash !== current?.hash && !previousIsFailed) {
185
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...previous, updatedAt: new Date().toISOString() });
186
- const metadata = await readBundleMetadata(previous.bundlePath);
187
- await (0, bundleInfo_1.updateBundleInfo)({
188
- hash: previous.hash,
189
- bundleVersion: metadata?.bundleVersion,
190
- version: metadata?.version,
191
- runtimeVersion: metadata?.runtimeVersion,
192
- pendingApply: false,
193
- installedAt: new Date().toISOString(),
194
- lastInstalledReportedHash: previous.hash,
195
- });
196
- await updateState({
197
- activeHash: previous.hash,
198
- candidateHash: previous.hash,
199
- candidateCommitted: true,
200
- crashCount: 0,
201
- lastGoodHash: previous.hash,
202
- });
203
- return { rolledBack: true };
204
- }
205
- // No previous OTA bundle exists; fall back to native bundle by clearing the active pointer.
206
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
207
- await (0, bundlePointer_1.deletePreviousBundlePointer)();
208
- await (0, bundleInfo_1.updateBundleInfo)({
209
- hash: undefined,
210
- bundleVersion: undefined,
211
- version: undefined,
212
- runtimeVersion: undefined,
213
- pendingApply: false,
214
- installedAt: new Date().toISOString(),
215
- });
216
- await updateState({
217
- activeHash: undefined,
218
- candidateHash: undefined,
219
- candidateCommitted: true,
220
- crashCount: 0,
221
- });
222
- return { rolledBack: true, toNative: true };
223
- }
224
- async function readJsonIfExists(path) {
225
- try {
226
- if (!(await fs_1.default.exists(path)))
227
- return null;
228
- const raw = await fs_1.default.readFile(path, 'utf8');
229
- return JSON.parse(raw);
230
- }
231
- catch {
232
- return null;
233
- }
234
- }
235
- async function readBundleMetadata(bundlePath) {
236
- const dir = bundlePath.substring(0, bundlePath.lastIndexOf('/'));
237
- const manifest = await readJsonIfExists(`${dir}/${bundleManifest_1.BUNDLE_MANIFEST}`);
238
- const metadataFile = context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json';
239
- const parsed = await readJsonIfExists(`${dir}/${metadataFile}`);
240
- if (!manifest && !parsed) {
124
+ /**
125
+ * Flush native recovery events without making JS part of the recovery decision.
126
+ * Native keeps each event durable until its backend report succeeds and JS
127
+ * acknowledges that exact event id.
128
+ */
129
+ async function reconcileStartupRecovery(cachedState, failedBundleInfo) {
130
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
131
+ if (!state)
241
132
  return null;
133
+ const telemetryContexts = await prepareRecoveryTelemetryContexts(state.pendingRecoveryEvents, failedBundleInfo);
134
+ for (const event of state.pendingRecoveryEvents) {
135
+ try {
136
+ const telemetryContext = telemetryContexts.events[event.id];
137
+ await (0, reporting_1.reportLocalRollback)(event.failedHash, recoveryRecord(event, telemetryContext?.failedHash === event.failedHash ? telemetryContext : undefined));
138
+ if (await (0, bundleDropNative_1.acknowledgeStartupRecoveryNative)(event.id)) {
139
+ await removeRecoveryTelemetryContext(event.id);
140
+ }
141
+ }
142
+ catch (error) {
143
+ console.warn(`⚠️ Failed to report BundleDrop startup recovery event ${event.id}:`, error?.toString?.() || error);
144
+ }
242
145
  }
243
- return {
244
- bundleVersion: parsed?.bundleVersion,
245
- version: manifest?.version ?? parsed?.version,
246
- runtimeVersion: manifest?.runtimeVersion ?? parsed?.runtimeVersion,
247
- };
146
+ return state;
248
147
  }
@@ -2,6 +2,7 @@ import { BundleInfo } from '../bundleInfo';
2
2
  import type { UpdateCheckResponse, BundleListItem } from '../api/types';
3
3
  export declare function getAvailableChannels(): Promise<string[]>;
4
4
  export declare function checkForUpdate(channelName?: string, onStatusUpdate?: (status: string) => void): Promise<UpdateCheckResponse | null>;
5
+ export declare function authorizeRuntimeDeliveryUpdate(decision: UpdateCheckResponse): Promise<UpdateCheckResponse | null>;
5
6
  export declare function getInstalledBundleInfo(): Promise<BundleInfo | null>;
6
7
  /**
7
8
  * Query options for browsing downloadable bundles from a public channel.