@devicecloud.dev/dcd 5.11.0-beta.4 → 5.11.0-beta.6

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.
@@ -197,7 +197,7 @@ export declare const cloudCommand: import("citty").CommandDef<{
197
197
  };
198
198
  readonly 'android-device-matrix': {
199
199
  readonly type: "string";
200
- readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-7:34 or pixel-7:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
200
+ readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-8:34 or pixel-8:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
201
201
  };
202
202
  readonly orientation: {
203
203
  readonly type: "string";
@@ -133,7 +133,7 @@ const startSub = defineCommand({
133
133
  },
134
134
  'android-device': {
135
135
  type: 'string',
136
- description: '[Android] Device profile to match a cloud run (options: pixel-6, pixel-6-pro, pixel-7, pixel-7-pro, pixel-8, pixel-10, pixel-10-pro, pixel-10-pro-xl, pixel-11)',
136
+ description: '[Android] Device profile to match a cloud run (options: pixel-6, pixel-8, pixel-10, pixel-10-pro, pixel-10-pro-xl, pixel-11)',
137
137
  },
138
138
  'android-api-level': {
139
139
  type: 'string',
@@ -37,7 +37,7 @@ export declare const deviceFlags: {
37
37
  };
38
38
  readonly 'android-device-matrix': {
39
39
  readonly type: "string";
40
- readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-7:34 or pixel-7:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
40
+ readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-8:34 or pixel-8:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
41
41
  };
42
42
  readonly orientation: {
43
43
  readonly type: "string";
@@ -42,7 +42,7 @@ export const deviceFlags = {
42
42
  },
43
43
  'android-device-matrix': {
44
44
  type: 'string',
45
- description: `[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-7:34 or pixel-7:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.`,
45
+ description: `[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-8:34 or pixel-8:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.`,
46
46
  },
47
47
  orientation: {
48
48
  type: 'string',
@@ -183,7 +183,7 @@ export declare const flags: {
183
183
  };
184
184
  readonly 'android-device-matrix': {
185
185
  readonly type: "string";
186
- readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-7:34 or pixel-7:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
186
+ readonly description: "[Android only] Device-matrix cell as <device>:<apiLevel> (append :play for Google Play), e.g. pixel-8:34 or pixel-8:34:play. Repeatable — every flow runs once per cell (no cross-product). Cannot be combined with --ios-device-matrix.";
187
187
  };
188
188
  readonly orientation: {
189
189
  readonly type: "string";
@@ -55,7 +55,7 @@ export function registerRunCloudTest(server) {
55
55
  iosVersion: z.string().optional().describe('iOS version, e.g. "17"'),
56
56
  iosDevice: z.string().optional().describe('iOS device, e.g. "iphone-14"'),
57
57
  androidApiLevel: z.string().optional().describe('Android API level, e.g. "34"'),
58
- androidDevice: z.string().optional().describe('Android device, e.g. "pixel-7"'),
58
+ androidDevice: z.string().optional().describe('Android device, e.g. "pixel-10"'),
59
59
  googlePlay: z.boolean().optional().describe('Use a Google Play-enabled Android image'),
60
60
  name: z.string().optional().describe('A name for this run'),
61
61
  env: z
package/dist/methods.d.ts CHANGED
@@ -16,6 +16,21 @@ interface UploadBinaryConfig {
16
16
  log?: boolean;
17
17
  }
18
18
  export declare const uploadBinary: (config: UploadBinaryConfig) => Promise<string>;
19
+ type UploadResult = {
20
+ error: Error | null;
21
+ success: boolean;
22
+ };
23
+ /**
24
+ * Validates upload results and throws if all uploads failed. The message names
25
+ * both failures: the Supabase error alone hid every Backblaze failure behind
26
+ * it, which is what made a dropped B2 request look like a Supabase outage.
27
+ * @param supabase - Result of the Supabase upload
28
+ * @param backblaze - Result of the Backblaze upload
29
+ * @param b2 - Backblaze configuration
30
+ * @param debug - Enable debug logging
31
+ * @returns void - throws error if all uploads failed
32
+ */
33
+ export declare function validateUploadResults(supabase: UploadResult, backblaze: UploadResult, b2: unknown, debug: boolean): void;
19
34
  /**
20
35
  * Storage reference for an already-uploaded flow zip, threaded into the
21
36
  * `submitFlowTest` JSON body so the API can locate the staged file.
@@ -47,6 +62,15 @@ export declare const uploadFlowZip: (config: {
47
62
  buffer: Buffer;
48
63
  debug?: boolean;
49
64
  }) => Promise<FlowZipUploadResult>;
65
+ /**
66
+ * Picks the upload URL for one attempt at one part. The API mints one URL per
67
+ * part, but each is bound to the large file rather than to a part number (the
68
+ * part number travels in `X-Bz-Part-Number`), so any of them can carry any
69
+ * part. A retry moves on to the next one, which is what B2 asks for after a
70
+ * 503 or a dropped connection. Parts upload one at a time, so no URL is ever
71
+ * in use twice at once.
72
+ */
73
+ export declare function partUploadUrlFor<T>(urls: T[], partNumber: number, attempt: number): T;
50
74
  /**
51
75
  * Writes JSON data to a file with error handling
52
76
  * @param filePath - Path to the output JSON file
package/dist/methods.js CHANGED
@@ -11,6 +11,7 @@ import { inferEnvFromApiUrl } from './config/environments.js';
11
11
  import { ApiError, ApiGateway } from './gateways/api-gateway.js';
12
12
  import { SupabaseGateway } from './gateways/supabase-gateway.js';
13
13
  import { detectFlutterEngine, MetadataExtractorService, } from './services/metadata-extractor.service.js';
14
+ import { assertB2Ok, B2HttpError, withB2Retry } from './utils/b2-retry.js';
14
15
  import { encryptFileToPath, generateDek, resolveKekPublicKey, wrapDek, } from './utils/envelope.js';
15
16
  import { colors, formatId } from './utils/styling.js';
16
17
  const mimeTypeLookupByExtension = {
@@ -472,7 +473,10 @@ async function handleBackblazeUpload(config) {
472
473
  ? `[DEBUG] Backblaze upload completed successfully in ${durationSeconds.toFixed(2)}s (${duration}ms)`
473
474
  : `[DEBUG] Backblaze upload failed after ${durationSeconds.toFixed(2)}s (${duration}ms)`);
474
475
  }
475
- return { error: null, success: backblazeSuccess };
476
+ return {
477
+ error: backblazeSuccess ? null : new Error(`Backblaze upload strategy '${b2.strategy}' is not usable`),
478
+ success: backblazeSuccess,
479
+ };
476
480
  }
477
481
  catch (error) {
478
482
  const b2Error = error instanceof Error ? error : new Error(String(error));
@@ -557,22 +561,24 @@ async function extractBinaryMetadata(filePath, debug) {
557
561
  return metadata;
558
562
  }
559
563
  /**
560
- * Validates upload results and throws if all uploads failed
561
- * @param supabaseSuccess - Whether Supabase upload succeeded
562
- * @param backblazeSuccess - Whether Backblaze upload succeeded
563
- * @param lastError - Last error encountered during uploads
564
+ * Validates upload results and throws if all uploads failed. The message names
565
+ * both failures: the Supabase error alone hid every Backblaze failure behind
566
+ * it, which is what made a dropped B2 request look like a Supabase outage.
567
+ * @param supabase - Result of the Supabase upload
568
+ * @param backblaze - Result of the Backblaze upload
564
569
  * @param b2 - Backblaze configuration
565
570
  * @param debug - Enable debug logging
566
571
  * @returns void - throws error if all uploads failed
567
572
  */
568
- function validateUploadResults(supabaseSuccess, backblazeSuccess, lastError, b2, debug) {
569
- if (supabaseSuccess || backblazeSuccess) {
573
+ export function validateUploadResults(supabase, backblaze, b2, debug) {
574
+ if (supabase.success || backblaze.success) {
570
575
  return;
571
576
  }
577
+ const lastError = supabase.error ?? backblaze.error;
572
578
  if (debug) {
573
579
  console.error(`[DEBUG] === ALL UPLOADS FAILED ===`);
574
- console.error(`[DEBUG] Supabase upload: FAILED`);
575
- console.error(`[DEBUG] Backblaze upload: ${b2 ? 'FAILED' : 'NOT CONFIGURED'}`);
580
+ console.error(`[DEBUG] Supabase upload: FAILED${supabase.error ? ` (${supabase.error.message})` : ''}`);
581
+ console.error(`[DEBUG] Backblaze upload: ${b2 ? `FAILED${backblaze.error ? ` (${backblaze.error.message})` : ''}` : 'NOT CONFIGURED'}`);
576
582
  if (lastError) {
577
583
  console.error(`[DEBUG] Final error details:`);
578
584
  console.error(`[DEBUG] - Message: ${lastError.message}`);
@@ -580,7 +586,8 @@ function validateUploadResults(supabaseSuccess, backblazeSuccess, lastError, b2,
580
586
  console.error(`[DEBUG] - Stack: ${lastError.stack}`);
581
587
  }
582
588
  }
583
- throw new Error(`All uploads failed. ${lastError ? `Last error: ${JSON.stringify({ message: lastError.message, name: lastError.name, stack: lastError.stack })}` : 'No upload targets available.'}`);
589
+ const backblazePart = b2 && backblaze.error ? `Backblaze error: ${backblaze.error.message}. ` : '';
590
+ throw new Error(`All uploads failed. ${backblazePart}${lastError ? `Last error: ${JSON.stringify({ message: lastError.message, name: lastError.name, stack: lastError.stack })}` : 'No upload targets available.'}`);
584
591
  }
585
592
  /**
586
593
  * Performs the actual file upload
@@ -618,17 +625,13 @@ async function performUpload(config) {
618
625
  finalPath,
619
626
  source,
620
627
  });
621
- let lastError = backblazeResult.error;
622
628
  // Always upload to Supabase (re-enabled as always-on alongside Backblaze)
623
629
  if (debug) {
624
630
  console.log('[DEBUG] Uploading to Supabase...');
625
631
  }
626
632
  const supabaseResult = await uploadToSupabase(env, tempPath, source, debug);
627
- if (!supabaseResult.success && supabaseResult.error) {
628
- lastError = supabaseResult.error;
629
- }
630
633
  // Validate results
631
- validateUploadResults(supabaseResult.success, backblazeResult.success, lastError, b2, debug);
634
+ validateUploadResults(supabaseResult, backblazeResult, b2, debug);
632
635
  // Log upload summary
633
636
  if (debug) {
634
637
  console.log(`[DEBUG] Upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`);
@@ -703,13 +706,9 @@ export const uploadFlowZip = async (config) => {
703
706
  finalPath,
704
707
  source,
705
708
  });
706
- let lastError = backblazeResult.error;
707
709
  // Always upload to Supabase (always-on alongside Backblaze)
708
710
  const supabaseResult = await uploadToSupabase(env, tempPath, source, debug);
709
- if (!supabaseResult.success && supabaseResult.error) {
710
- lastError = supabaseResult.error;
711
- }
712
- validateUploadResults(supabaseResult.success, backblazeResult.success, lastError, b2, debug);
711
+ validateUploadResults(supabaseResult, backblazeResult, b2, debug);
713
712
  if (debug) {
714
713
  console.log(`[DEBUG] Flow zip upload summary - Backblaze: ${backblazeResult.success ? '✓' : '✗'}, Supabase: ${supabaseResult.success ? '✓' : '✗'}`);
715
714
  }
@@ -733,79 +732,67 @@ export const uploadFlowZip = async (config) => {
733
732
  * @param fileName - Name/path of the file
734
733
  * @param source - Upload source descriptor (streamed from disk)
735
734
  * @param debug - Whether debug logging is enabled
736
- * @returns Promise that resolves when upload completes or fails gracefully
735
+ * @returns Promise resolving to true once the upload succeeds; throws the last
736
+ * error once transient failures have used up their retries
737
737
  */
738
738
  async function uploadToBackblaze(uploadUrl, authorizationToken, fileName, source, debug) {
739
- try {
740
- // The API only picks the simple strategy for small binaries (large files
741
- // get the multi-part path), so one transient buffer here is bounded.
742
- // S3 pre-signed PUTs reject chunked transfer encoding, which rules out a
743
- // plain stream body.
744
- const body = await readFile(source.diskPath);
745
- // Calculate SHA1 hash for Backblaze (B2 requires SHA1, not SHA256)
746
- const sha1 = createHash('sha1');
747
- sha1.update(body);
748
- const sha1Hex = sha1.digest('hex');
749
- // Detect if this is an S3 pre-signed URL (authorization token is empty)
750
- const isS3PreSignedUrl = !authorizationToken || authorizationToken === '';
751
- if (debug) {
752
- console.log(`[DEBUG] Uploading to Backblaze URL: ${uploadUrl}`);
753
- console.log(`[DEBUG] Upload method: ${isS3PreSignedUrl ? 'S3 pre-signed URL (PUT)' : 'B2 native API (POST)'}`);
754
- console.log(`[DEBUG] File name: ${fileName}`);
755
- console.log(`[DEBUG] File SHA1: ${sha1Hex}`);
756
- }
757
- // Build headers based on upload method
758
- const headers = {
759
- 'Content-Length': body.length.toString(),
760
- 'Content-Type': source.contentType || 'application/octet-stream',
761
- 'X-Bz-Content-Sha1': sha1Hex,
762
- };
763
- // S3 pre-signed URLs have auth embedded in URL, native B2 uses Authorization header
764
- if (!isS3PreSignedUrl) {
765
- headers.Authorization = authorizationToken;
766
- headers['X-Bz-File-Name'] = encodeURIComponent(fileName);
767
- }
768
- const response = await fetch(uploadUrl, {
769
- // Zero-copy view over the buffer (new Uint8Array(buffer) would clone it).
770
- body: new Uint8Array(body.buffer, body.byteOffset, body.byteLength),
771
- headers,
772
- method: isS3PreSignedUrl ? 'PUT' : 'POST',
773
- });
774
- if (!response.ok) {
775
- const errorText = await response.text();
776
- if (debug) {
777
- console.error(`[DEBUG] Backblaze upload failed with status ${response.status}: ${errorText}`);
778
- }
779
- // Don't throw and don't warn — Backblaze is the primary attempt and the
780
- // Supabase fallback usually recovers. A user-facing error is raised only
781
- // if every strategy fails (see validateUploadResults).
782
- return false;
783
- }
784
- if (debug) {
785
- console.log('[DEBUG] Backblaze upload successful');
786
- }
787
- return true;
788
- }
789
- catch (error) {
790
- if (debug) {
791
- console.error('[DEBUG] === BACKBLAZE UPLOAD EXCEPTION ===');
792
- console.error('[DEBUG] Backblaze upload exception:', error);
793
- console.error(`[DEBUG] Error type: ${error instanceof Error ? error.name : typeof error}`);
794
- console.error(`[DEBUG] Error message: ${error instanceof Error ? error.message : String(error)}`);
795
- if (error instanceof Error && error.stack) {
796
- console.error(`[DEBUG] Stack trace:\n${error.stack}`);
797
- }
798
- }
799
- // Provide more specific error messages for common network errors
800
- if (error instanceof TypeError && error.message === 'fetch failed') {
739
+ // The API only picks the simple strategy for small binaries (large files
740
+ // get the multi-part path), so one transient buffer here is bounded.
741
+ // S3 pre-signed PUTs reject chunked transfer encoding, which rules out a
742
+ // plain stream body.
743
+ const body = await readFile(source.diskPath);
744
+ // Calculate SHA1 hash for Backblaze (B2 requires SHA1, not SHA256)
745
+ const sha1 = createHash('sha1');
746
+ sha1.update(body);
747
+ const sha1Hex = sha1.digest('hex');
748
+ // Detect if this is an S3 pre-signed URL (authorization token is empty)
749
+ const isS3PreSignedUrl = !authorizationToken || authorizationToken === '';
750
+ if (debug) {
751
+ console.log(`[DEBUG] Uploading to Backblaze URL: ${uploadUrl}`);
752
+ console.log(`[DEBUG] Upload method: ${isS3PreSignedUrl ? 'S3 pre-signed URL (PUT)' : 'B2 native API (POST)'}`);
753
+ console.log(`[DEBUG] File name: ${fileName}`);
754
+ console.log(`[DEBUG] File SHA1: ${sha1Hex}`);
755
+ }
756
+ // Build headers based on upload method
757
+ const headers = {
758
+ 'Content-Length': body.length.toString(),
759
+ 'Content-Type': source.contentType || 'application/octet-stream',
760
+ 'X-Bz-Content-Sha1': sha1Hex,
761
+ };
762
+ // S3 pre-signed URLs have auth embedded in URL, native B2 uses Authorization header
763
+ if (!isS3PreSignedUrl) {
764
+ headers.Authorization = authorizationToken;
765
+ headers['X-Bz-File-Name'] = encodeURIComponent(fileName);
766
+ }
767
+ // No user-facing warning on a failure: validateUploadResults raises the
768
+ // only user-facing error, and only when every strategy fails. The thrown
769
+ // error reaches it through handleBackblazeUpload.
770
+ await withB2Retry(async () => assertB2Ok(await fetch(uploadUrl, {
771
+ // Zero-copy view over the buffer (new Uint8Array(buffer) would clone it).
772
+ body: new Uint8Array(body.buffer, body.byteOffset, body.byteLength),
773
+ headers,
774
+ method: isS3PreSignedUrl ? 'PUT' : 'POST',
775
+ }), 'Backblaze upload'), {
776
+ onRetry(attempt, error, delayMs) {
801
777
  if (debug) {
802
- console.error('[DEBUG] Network error detected - could be DNS, connection, or SSL issue');
778
+ console.error(`[DEBUG] Backblaze upload attempt ${attempt} failed (${describeB2Error(error)}); retrying in ${delayMs}ms`);
803
779
  }
804
- }
805
- // Don't throw and don't warn — the Supabase fallback usually recovers, and
806
- // validateUploadResults raises a user-facing error only if all fail.
807
- return false;
780
+ },
781
+ });
782
+ if (debug) {
783
+ console.log('[DEBUG] Backblaze upload successful');
808
784
  }
785
+ return true;
786
+ }
787
+ /** One line for a failed B2 attempt, including the response body when there is one. */
788
+ function describeB2Error(error) {
789
+ if (error instanceof B2HttpError)
790
+ return `${error.message}${error.body ? `: ${error.body.slice(0, 300)}` : ''}`;
791
+ if (error instanceof Error) {
792
+ const cause = error.cause instanceof Error ? ` (${error.cause.message})` : '';
793
+ return `${error.message}${cause}`;
794
+ }
795
+ return String(error);
809
796
  }
810
797
  /**
811
798
  * Helper function to read a chunk from a file stream
@@ -840,33 +827,48 @@ function calculateSha1(buffer) {
840
827
  return sha1.digest('hex');
841
828
  }
842
829
  /**
843
- * Uploads a single part to Backblaze
830
+ * Picks the upload URL for one attempt at one part. The API mints one URL per
831
+ * part, but each is bound to the large file rather than to a part number (the
832
+ * part number travels in `X-Bz-Part-Number`), so any of them can carry any
833
+ * part. A retry moves on to the next one, which is what B2 asks for after a
834
+ * 503 or a dropped connection. Parts upload one at a time, so no URL is ever
835
+ * in use twice at once.
836
+ */
837
+ export function partUploadUrlFor(urls, partNumber, attempt) {
838
+ return urls[(partNumber - 1 + attempt - 1) % urls.length];
839
+ }
840
+ /**
841
+ * Uploads a single part to Backblaze, retrying transient failures on a
842
+ * different upload URL each time
844
843
  * @param config - Configuration for the part upload
845
844
  * @returns Promise that resolves when upload completes
846
845
  */
847
846
  async function uploadPartToBackblaze(config) {
848
- const { uploadUrl, authorizationToken, partBuffer, partLength, sha1Hex, partNumber, totalParts, debug } = config;
847
+ const { uploadPartUrls, partBuffer, partLength, sha1Hex, partNumber, totalParts, debug } = config;
849
848
  if (debug) {
850
849
  console.log(`[DEBUG] Uploading part ${partNumber}/${totalParts} (${(partLength / 1024 / 1024).toFixed(2)} MB, SHA1: ${sha1Hex})`);
851
850
  }
852
851
  try {
853
- const response = await fetch(uploadUrl, {
854
- body: new Uint8Array(partBuffer),
855
- headers: {
856
- Authorization: authorizationToken,
857
- 'Content-Length': partLength.toString(),
858
- 'X-Bz-Content-Sha1': sha1Hex,
859
- 'X-Bz-Part-Number': partNumber.toString(),
852
+ await withB2Retry(async (attempt) => {
853
+ const { authorizationToken, uploadUrl } = partUploadUrlFor(uploadPartUrls, partNumber, attempt);
854
+ return assertB2Ok(await fetch(uploadUrl, {
855
+ body: new Uint8Array(partBuffer),
856
+ headers: {
857
+ Authorization: authorizationToken,
858
+ 'Content-Length': partLength.toString(),
859
+ 'X-Bz-Content-Sha1': sha1Hex,
860
+ 'X-Bz-Part-Number': partNumber.toString(),
861
+ },
862
+ method: 'POST',
863
+ }), `Part ${partNumber} upload`);
864
+ }, {
865
+ onRetry(attempt, error, delayMs) {
866
+ if (debug) {
867
+ console.error(`[DEBUG] Part ${partNumber} attempt ${attempt} failed (${describeB2Error(error)}); retrying on another upload URL in ${delayMs}ms`);
868
+ }
860
869
  },
861
- method: 'POST',
870
+ rotatesUrl: true,
862
871
  });
863
- if (!response.ok) {
864
- const errorText = await response.text();
865
- if (debug) {
866
- console.error(`[DEBUG] Part ${partNumber} upload failed with status ${response.status}: ${errorText}`);
867
- }
868
- throw new Error(`Part ${partNumber} upload failed with status ${response.status}`);
869
- }
870
872
  }
871
873
  catch (error) {
872
874
  if (error instanceof TypeError && error.message === 'fetch failed') {
@@ -883,78 +885,54 @@ async function uploadPartToBackblaze(config) {
883
885
  console.log(`[DEBUG] Part ${partNumber}/${totalParts} uploaded successfully`);
884
886
  }
885
887
  }
886
- /**
887
- * Logs detailed error information for Backblaze upload failures
888
- * @param error - The error that occurred
889
- * @param debug - Whether debug logging is enabled
890
- * @returns void
891
- */
892
- function logBackblazeUploadError(error, debug) {
893
- if (debug) {
894
- console.error('[DEBUG] === BACKBLAZE LARGE FILE UPLOAD EXCEPTION ===');
895
- console.error('[DEBUG] Large file upload exception:', error);
896
- console.error(`[DEBUG] Error type: ${error instanceof Error ? error.name : typeof error}`);
897
- console.error(`[DEBUG] Error message: ${error instanceof Error ? error.message : String(error)}`);
898
- if (error instanceof Error && error.stack) {
899
- console.error(`[DEBUG] Stack trace:\n${error.stack}`);
900
- }
901
- }
902
- // No user-facing warning: Backblaze is the primary attempt and the Supabase
903
- // fallback usually recovers; validateUploadResults raises the only
904
- // user-facing error, and only when every strategy fails.
905
- }
906
888
  /**
907
889
  * Upload large file to Backblaze using multi-part upload with streaming (for files >= 5MB)
908
890
  * Uses file streaming to avoid loading entire file into memory, preventing OOM errors on large files
909
891
  * @param config - Configuration object for the large file upload
910
- * @returns Promise that resolves when upload completes or fails gracefully
892
+ * @returns Promise resolving to true once the upload succeeds; throws the
893
+ * error of the part (or finish call) that failed. No user-facing warning:
894
+ * validateUploadResults raises the only user-facing error, and only when
895
+ * every strategy fails.
911
896
  */
912
897
  async function uploadLargeFileToBackblaze(config) {
913
898
  const { apiUrl, auth, fileId, uploadPartUrls, filePath, fileSize, debug } = config;
914
- try {
915
- const partSha1Array = [];
916
- const partSize = Math.ceil(fileSize / uploadPartUrls.length);
917
- if (debug) {
918
- console.log(`[DEBUG] Uploading large file in ${uploadPartUrls.length} parts (streaming mode)`);
919
- console.log(`[DEBUG] Part size: ${(partSize / 1024 / 1024).toFixed(2)} MB`);
920
- console.log(`[DEBUG] Reading from: ${filePath}`);
921
- }
922
- // Upload each part using streaming to avoid loading entire file into memory
923
- for (let i = 0; i < uploadPartUrls.length; i++) {
924
- const partNumber = i + 1;
925
- const start = i * partSize;
926
- const end = Math.min(start + partSize, fileSize);
927
- const partLength = end - start;
928
- if (debug) {
929
- console.log(`[DEBUG] Reading part ${partNumber}/${uploadPartUrls.length} bytes ${start}-${end}`);
930
- }
931
- const partBuffer = await readFileChunk(filePath, start, end);
932
- const sha1Hex = calculateSha1(partBuffer);
933
- partSha1Array.push(sha1Hex);
934
- await uploadPartToBackblaze({
935
- authorizationToken: uploadPartUrls[i].authorizationToken,
936
- debug,
937
- partBuffer,
938
- partLength,
939
- partNumber,
940
- sha1Hex,
941
- totalParts: uploadPartUrls.length,
942
- uploadUrl: uploadPartUrls[i].uploadUrl,
943
- });
944
- }
899
+ const partSha1Array = [];
900
+ const partSize = Math.ceil(fileSize / uploadPartUrls.length);
901
+ if (debug) {
902
+ console.log(`[DEBUG] Uploading large file in ${uploadPartUrls.length} parts (streaming mode)`);
903
+ console.log(`[DEBUG] Part size: ${(partSize / 1024 / 1024).toFixed(2)} MB`);
904
+ console.log(`[DEBUG] Reading from: ${filePath}`);
905
+ }
906
+ // Upload each part using streaming to avoid loading entire file into memory
907
+ for (let i = 0; i < uploadPartUrls.length; i++) {
908
+ const partNumber = i + 1;
909
+ const start = i * partSize;
910
+ const end = Math.min(start + partSize, fileSize);
911
+ const partLength = end - start;
945
912
  if (debug) {
946
- console.log('[DEBUG] Finishing large file upload...');
947
- console.log(`[DEBUG] Finalizing ${partSha1Array.length} parts with fileId: ${fileId}`);
913
+ console.log(`[DEBUG] Reading part ${partNumber}/${uploadPartUrls.length} bytes ${start}-${end}`);
948
914
  }
949
- await ApiGateway.finishLargeFile(apiUrl, auth, fileId, partSha1Array);
950
- if (debug)
951
- console.log('[DEBUG] Large file upload completed successfully');
952
- return true;
915
+ const partBuffer = await readFileChunk(filePath, start, end);
916
+ const sha1Hex = calculateSha1(partBuffer);
917
+ partSha1Array.push(sha1Hex);
918
+ await uploadPartToBackblaze({
919
+ debug,
920
+ partBuffer,
921
+ partLength,
922
+ partNumber,
923
+ sha1Hex,
924
+ totalParts: uploadPartUrls.length,
925
+ uploadPartUrls,
926
+ });
953
927
  }
954
- catch (error) {
955
- logBackblazeUploadError(error, debug);
956
- return false;
928
+ if (debug) {
929
+ console.log('[DEBUG] Finishing large file upload...');
930
+ console.log(`[DEBUG] Finalizing ${partSha1Array.length} parts with fileId: ${fileId}`);
957
931
  }
932
+ await ApiGateway.finishLargeFile(apiUrl, auth, fileId, partSha1Array);
933
+ if (debug)
934
+ console.log('[DEBUG] Large file upload completed successfully');
935
+ return true;
958
936
  }
959
937
  async function getFileHashFromPath(filePath) {
960
938
  const hash = createHash('sha256');
@@ -71,7 +71,7 @@ export class DeviceValidationService {
71
71
  // Mirrors the API, which applies these same global defaults to a
72
72
  // request that omits either half (execution-planner.service.ts)
73
73
  // and then rejects an incompatible pair.
74
- defaultDevice: 'pixel-7',
74
+ defaultDevice: 'pixel-10',
75
75
  defaultVersion: '36',
76
76
  device,
77
77
  deviceArg: argNames.androidDevice,
@@ -1,5 +1,10 @@
1
+ export type CpuArchitecture = 'arm' | 'x86';
1
2
  export interface TAppMetadata {
3
+ /** APK only: the native ABIs shipped under `lib/<abi>/`, sorted. */
4
+ abis?: string[];
2
5
  appId: string;
6
+ /** APK only: the CPU families the APK can run on. See `apkArchitectures`. */
7
+ architectures?: CpuArchitecture[];
3
8
  platform: 'android' | 'ios';
4
9
  }
5
10
  /**
@@ -9,6 +14,14 @@ export interface IMetadataExtractor {
9
14
  canHandle(filePath: string): boolean;
10
15
  extract(filePath: string): Promise<TAppMetadata>;
11
16
  }
17
+ /** The native ABIs in an APK: each `lib/<abi>/` directory that holds a file. */
18
+ export declare function apkAbis(entryNames: string[]): string[];
19
+ /**
20
+ * The CPU families an APK can run on, from its native ABIs. An APK with no
21
+ * native code runs on both. ABIs outside arm and x86 (mips, riscv64) are
22
+ * ignored, so an APK that ships only those gets an empty list.
23
+ */
24
+ export declare function apkArchitectures(abis: string[]): CpuArchitecture[];
12
25
  /**
13
26
  * Extracts metadata from Android APK files
14
27
  */
@@ -23,6 +23,34 @@ function parseInfoPlist(buffer) {
23
23
  }
24
24
  return data;
25
25
  }
26
+ const ABI_ARCHITECTURE = {
27
+ armeabi: 'arm',
28
+ 'armeabi-v7a': 'arm',
29
+ 'arm64-v8a': 'arm',
30
+ x86: 'x86',
31
+ x86_64: 'x86',
32
+ };
33
+ /** The native ABIs in an APK: each `lib/<abi>/` directory that holds a file. */
34
+ export function apkAbis(entryNames) {
35
+ const abis = new Set();
36
+ for (const name of entryNames) {
37
+ const match = /^lib\/([^/]+)\/[^/]+$/.exec(name);
38
+ if (match)
39
+ abis.add(match[1]);
40
+ }
41
+ return [...abis].sort();
42
+ }
43
+ /**
44
+ * The CPU families an APK can run on, from its native ABIs. An APK with no
45
+ * native code runs on both. ABIs outside arm and x86 (mips, riscv64) are
46
+ * ignored, so an APK that ships only those gets an empty list.
47
+ */
48
+ export function apkArchitectures(abis) {
49
+ if (abis.length === 0)
50
+ return ['arm', 'x86'];
51
+ const found = new Set(abis.map((abi) => ABI_ARCHITECTURE[abi]).filter(Boolean));
52
+ return ['arm', 'x86'].filter((arch) => found.has(arch));
53
+ }
26
54
  /**
27
55
  * Extracts metadata from Android APK files
28
56
  */
@@ -34,7 +62,13 @@ export class AndroidMetadataExtractor {
34
62
  const zip = new StreamZip.async({ file: filePath });
35
63
  try {
36
64
  const manifest = await zip.entryData('AndroidManifest.xml');
37
- return { appId: readManifestPackage(manifest), platform: 'android' };
65
+ const abis = apkAbis(Object.keys(await zip.entries()));
66
+ return {
67
+ abis,
68
+ appId: readManifestPackage(manifest),
69
+ architectures: apkArchitectures(abis),
70
+ platform: 'android',
71
+ };
38
72
  }
39
73
  finally {
40
74
  await zip.close().catch(() => { });
@@ -30,9 +30,7 @@ export declare enum EiOSDevices {
30
30
  export declare enum EAndroidDevices {
31
31
  'generic-tablet' = "generic-tablet",
32
32
  'pixel-6' = "pixel-6",
33
- 'pixel-6-pro' = "pixel-6-pro",
34
33
  'pixel-7' = "pixel-7",
35
- 'pixel-7-pro' = "pixel-7-pro",
36
34
  'pixel-8' = "pixel-8",
37
35
  'pixel-10' = "pixel-10",
38
36
  'pixel-10-pro' = "pixel-10-pro",
@@ -32,9 +32,7 @@ export var EAndroidDevices;
32
32
  (function (EAndroidDevices) {
33
33
  EAndroidDevices["generic-tablet"] = "generic-tablet";
34
34
  EAndroidDevices["pixel-6"] = "pixel-6";
35
- EAndroidDevices["pixel-6-pro"] = "pixel-6-pro";
36
35
  EAndroidDevices["pixel-7"] = "pixel-7";
37
- EAndroidDevices["pixel-7-pro"] = "pixel-7-pro";
38
36
  EAndroidDevices["pixel-8"] = "pixel-8";
39
37
  EAndroidDevices["pixel-10"] = "pixel-10";
40
38
  EAndroidDevices["pixel-10-pro"] = "pixel-10-pro";
package/dist/types.d.ts CHANGED
@@ -1,6 +1,17 @@
1
+ import type { CpuArchitecture } from './services/metadata-extractor.service.js';
1
2
  import type { BinaryEnvelope } from './utils/envelope.js';
2
3
  export type TAppMetadata = {
4
+ /**
5
+ * APK only: the native ABIs under `lib/<abi>/` (e.g. `arm64-v8a`, `x86_64`).
6
+ * Stored on `binaries.metadata.abis`. Empty when the APK has no native code.
7
+ */
8
+ abis?: string[];
3
9
  appId: string;
10
+ /**
11
+ * APK only: the CPU families the APK can run on, `arm`, `x86` or both.
12
+ * Stored on `binaries.metadata.architectures`. Both when it has no native code.
13
+ */
14
+ architectures?: CpuArchitecture[];
4
15
  platform: 'android' | 'ios';
5
16
  /**
6
17
  * Present when the binary was client-side envelope-encrypted before upload
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Retries for direct-to-Backblaze uploads.
3
+ *
4
+ * B2 expects clients to retry: an upload can be answered with 408, 429 or a
5
+ * 5xx, or have its connection dropped, and B2's own guidance is to back off
6
+ * and try again (for a large-file part, on a different upload URL). The CLI
7
+ * used to make exactly one attempt, so a single dropped B2 request failed the
8
+ * B2 upload outright and left the Supabase upload as the only path.
9
+ */
10
+ export declare const B2_RETRY: {
11
+ /** Total attempts per request, the first included. */
12
+ attempts: number;
13
+ baseDelayMs: number;
14
+ maxDelayMs: number;
15
+ };
16
+ /** A B2 (or S3-compatible) response that was not 2xx. */
17
+ export declare class B2HttpError extends Error {
18
+ readonly status: number;
19
+ readonly body: string;
20
+ constructor(message: string, status: number, body: string);
21
+ }
22
+ /**
23
+ * Whether a failed attempt is worth repeating. Network errors (fetch throws a
24
+ * TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
25
+ * the next attempt uses a different upload URL, which B2 hands out with its
26
+ * own token: on the same URL it would fail the same way.
27
+ */
28
+ export declare function isRetryableB2Error(error: unknown, opts?: {
29
+ rotatesUrl?: boolean;
30
+ }): boolean;
31
+ /** Exponential backoff with full jitter, capped at `maxDelayMs`. */
32
+ export declare function b2RetryDelayMs(attempt: number, random?: () => number): number;
33
+ export interface B2RetryOptions {
34
+ /** Each attempt gets a fresh upload URL, so a 401 is worth retrying. */
35
+ rotatesUrl?: boolean;
36
+ /** Called before each retry; the debug logging hook. */
37
+ onRetry?: (attempt: number, error: unknown, delayMs: number) => void;
38
+ /** Test seam. */
39
+ sleep?: (ms: number) => Promise<void>;
40
+ }
41
+ /**
42
+ * Run `attemptFn` until it resolves, a non-retryable error is thrown, or
43
+ * `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
44
+ * number so a caller can pick a different upload URL each time. The last
45
+ * error is rethrown unchanged.
46
+ */
47
+ export declare function withB2Retry<T>(attemptFn: (attempt: number) => Promise<T>, opts?: B2RetryOptions): Promise<T>;
48
+ /** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
49
+ export declare function assertB2Ok(response: Response, what: string): Promise<Response>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Retries for direct-to-Backblaze uploads.
3
+ *
4
+ * B2 expects clients to retry: an upload can be answered with 408, 429 or a
5
+ * 5xx, or have its connection dropped, and B2's own guidance is to back off
6
+ * and try again (for a large-file part, on a different upload URL). The CLI
7
+ * used to make exactly one attempt, so a single dropped B2 request failed the
8
+ * B2 upload outright and left the Supabase upload as the only path.
9
+ */
10
+ export const B2_RETRY = {
11
+ /** Total attempts per request, the first included. */
12
+ attempts: 4,
13
+ baseDelayMs: 1000,
14
+ maxDelayMs: 8000,
15
+ };
16
+ /** A B2 (or S3-compatible) response that was not 2xx. */
17
+ export class B2HttpError extends Error {
18
+ status;
19
+ body;
20
+ constructor(message, status, body) {
21
+ super(message);
22
+ this.status = status;
23
+ this.body = body;
24
+ this.name = 'B2HttpError';
25
+ }
26
+ }
27
+ /**
28
+ * Whether a failed attempt is worth repeating. Network errors (fetch throws a
29
+ * TypeError) and 408 / 429 / 5xx are transient. A 401 is retryable only where
30
+ * the next attempt uses a different upload URL, which B2 hands out with its
31
+ * own token: on the same URL it would fail the same way.
32
+ */
33
+ export function isRetryableB2Error(error, opts = {}) {
34
+ if (error instanceof B2HttpError) {
35
+ const { status } = error;
36
+ if (status === 401)
37
+ return Boolean(opts.rotatesUrl);
38
+ return status === 408 || status === 429 || status >= 500;
39
+ }
40
+ return error instanceof TypeError;
41
+ }
42
+ /** Exponential backoff with full jitter, capped at `maxDelayMs`. */
43
+ export function b2RetryDelayMs(attempt, random = Math.random) {
44
+ const ceiling = Math.min(B2_RETRY.maxDelayMs, B2_RETRY.baseDelayMs * 2 ** (attempt - 1));
45
+ return Math.round(ceiling / 2 + (random() * ceiling) / 2);
46
+ }
47
+ const defaultSleep = (ms) => new Promise((resolve) => {
48
+ setTimeout(resolve, ms);
49
+ });
50
+ /**
51
+ * Run `attemptFn` until it resolves, a non-retryable error is thrown, or
52
+ * `B2_RETRY.attempts` is used up. `attemptFn` gets the 1-based attempt
53
+ * number so a caller can pick a different upload URL each time. The last
54
+ * error is rethrown unchanged.
55
+ */
56
+ export async function withB2Retry(attemptFn, opts = {}) {
57
+ const sleep = opts.sleep ?? defaultSleep;
58
+ for (let attempt = 1;; attempt++) {
59
+ try {
60
+ return await attemptFn(attempt);
61
+ }
62
+ catch (error) {
63
+ if (attempt >= B2_RETRY.attempts || !isRetryableB2Error(error, opts))
64
+ throw error;
65
+ const delayMs = b2RetryDelayMs(attempt);
66
+ opts.onRetry?.(attempt, error, delayMs);
67
+ await sleep(delayMs);
68
+ }
69
+ }
70
+ }
71
+ /** Throw a `B2HttpError` for a non-2xx response; return it otherwise. */
72
+ export async function assertB2Ok(response, what) {
73
+ if (response.ok)
74
+ return response;
75
+ const body = await response.text().catch(() => '');
76
+ throw new B2HttpError(`${what} failed with status ${response.status}`, response.status, body);
77
+ }
@@ -54,7 +54,7 @@ export function parseDeviceMatrix(iosConfigs, androidConfigs) {
54
54
  !parts[0] ||
55
55
  !parts[1] ||
56
56
  (parts.length === 3 && parts[2] !== 'play')) {
57
- throw new CliError(`Invalid --android-device-matrix "${raw}". Expected <device>:<apiLevel> or <device>:<apiLevel>:play, e.g. pixel-7:34 or pixel-7:34:play.`);
57
+ throw new CliError(`Invalid --android-device-matrix "${raw}". Expected <device>:<apiLevel> or <device>:<apiLevel>:play, e.g. pixel-8:34 or pixel-8:34:play.`);
58
58
  }
59
59
  configs.push({
60
60
  androidDevice: parts[0],
package/package.json CHANGED
@@ -68,7 +68,7 @@
68
68
  "test:unit": "node scripts/test-runner.mjs --unit",
69
69
  "typecheck": "tsc --noEmit -p tsconfig.test.json"
70
70
  },
71
- "version": "5.11.0-beta.4",
71
+ "version": "5.11.0-beta.6",
72
72
  "bugs": {
73
73
  "url": "https://discord.gg/gm3mJwcNw8"
74
74
  },