@devicecloud.dev/dcd 5.11.0-beta.1 → 5.11.0-beta.10

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 (59) hide show
  1. package/README.md +75 -3
  2. package/dist/commands/cloud.d.ts +1 -1
  3. package/dist/commands/cloud.js +7 -6
  4. package/dist/commands/device.d.ts +36 -0
  5. package/dist/commands/device.js +1151 -0
  6. package/dist/commands/live.d.ts +2 -0
  7. package/dist/commands/live.js +10 -1
  8. package/dist/commands/login.js +2 -17
  9. package/dist/commands/mcp.d.ts +13 -0
  10. package/dist/commands/mcp.js +180 -0
  11. package/dist/commands/upload.js +2 -8
  12. package/dist/config/flags/device.flags.d.ts +1 -1
  13. package/dist/config/flags/device.flags.js +1 -1
  14. package/dist/constants.d.ts +1 -1
  15. package/dist/gateways/device-gateway.d.ts +88 -0
  16. package/dist/gateways/device-gateway.js +140 -0
  17. package/dist/index.js +4 -0
  18. package/dist/mcp/bridge.d.ts +52 -0
  19. package/dist/mcp/bridge.js +288 -0
  20. package/dist/mcp/tools/run-cloud-test.d.ts +13 -0
  21. package/dist/mcp/tools/run-cloud-test.js +18 -8
  22. package/dist/methods.d.ts +24 -0
  23. package/dist/methods.js +147 -169
  24. package/dist/services/device-validation.service.js +1 -1
  25. package/dist/services/execution-plan.service.d.ts +27 -0
  26. package/dist/services/execution-plan.service.js +9 -1
  27. package/dist/services/metadata-extractor.service.d.ts +13 -0
  28. package/dist/services/metadata-extractor.service.js +35 -1
  29. package/dist/services/moropo.service.js +1 -1
  30. package/dist/services/results-polling.service.js +1 -1
  31. package/dist/types/domain/device-session.types.d.ts +211 -0
  32. package/dist/types/domain/device-session.types.js +5 -0
  33. package/dist/types/domain/device.types.d.ts +0 -2
  34. package/dist/types/domain/device.types.js +0 -2
  35. package/dist/types.d.ts +11 -0
  36. package/dist/utils/app-upload.d.ts +19 -0
  37. package/dist/utils/app-upload.js +63 -0
  38. package/dist/utils/auth.d.ts +0 -8
  39. package/dist/utils/auth.js +31 -27
  40. package/dist/utils/b2-retry.d.ts +49 -0
  41. package/dist/utils/b2-retry.js +77 -0
  42. package/dist/utils/browser.d.ts +16 -0
  43. package/dist/utils/browser.js +48 -0
  44. package/dist/utils/compatibility.d.ts +5 -7
  45. package/dist/utils/compatibility.js +5 -13
  46. package/dist/utils/device-artifacts.d.ts +55 -0
  47. package/dist/utils/device-artifacts.js +211 -0
  48. package/dist/utils/device-bundle.d.ts +35 -0
  49. package/dist/utils/device-bundle.js +162 -0
  50. package/dist/utils/device-matrix.js +1 -1
  51. package/dist/utils/device-output.d.ts +81 -0
  52. package/dist/utils/device-output.js +204 -0
  53. package/dist/utils/device-run.d.ts +29 -0
  54. package/dist/utils/device-run.js +113 -0
  55. package/dist/utils/mcp-install.d.ts +50 -0
  56. package/dist/utils/mcp-install.js +132 -0
  57. package/dist/utils/progress.d.ts +4 -0
  58. package/dist/utils/progress.js +45 -21
  59. package/package.json +2 -2
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 = {
@@ -125,7 +126,7 @@ export const uploadBinary = async (config) => {
125
126
  if (exists && binaryId) {
126
127
  if (log) {
127
128
  ux.info(colors.dim('SHA hash matches existing binary with ID: ') + formatId(binaryId) + colors.dim(', skipping upload. Force upload with --ignore-sha-check'));
128
- ux.action.stop(colors.info('Skipping upload'));
129
+ ux.action.stop('Skipping upload');
129
130
  }
130
131
  return binaryId;
131
132
  }
@@ -158,13 +159,13 @@ export const uploadBinary = async (config) => {
158
159
  startTime,
159
160
  });
160
161
  if (log) {
161
- ux.action.stop(colors.success('\n✓ Binary uploaded with ID: ') + formatId(uploadId));
162
+ ux.action.stop(colors.success('Binary uploaded with ID: ') + formatId(uploadId));
162
163
  }
163
164
  return uploadId;
164
165
  }
165
166
  catch (error) {
166
167
  if (log) {
167
- ux.action.stop(colors.error('✗ Failed'));
168
+ ux.action.fail(colors.error('Failed'));
168
169
  }
169
170
  if (debug) {
170
171
  console.error('[DEBUG] === BINARY UPLOAD FAILED ===');
@@ -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,
@@ -37,6 +37,33 @@ interface IFlowSequence {
37
37
  continueOnFailure?: boolean;
38
38
  flows: string[];
39
39
  }
40
+ /**
41
+ * How many flows opt into the extended test runtime (up to 20 minutes, billed
42
+ * accepts: YAML `true` or the string `'true'`.
43
+ * accepts: YAML `true` or the string `'true'`.
44
+ */
45
+ export declare function countExtendedRuntimeFlows(flowOverrides: Record<string, Record<string, unknown>>): number;
46
+ /**
47
+ * Resolve `config.yaml`'s `includedPaths` globs into absolute file paths.
48
+ *
49
+ * This is the general-purpose escape hatch for shipping files the flow
50
+ * commands don't reference: `assertScreenshot` baselines above all, but also
51
+ * fixtures, test data and certificates. Only `addMedia` / `runFlow` /
52
+ * `runScript` arguments are discovered by walking the flows, so without this
53
+ * key such files are silently absent from the uploaded zip.
54
+ *
55
+ * Glob semantics deliberately mirror `flows:` (`applyFlowGlobs`): patterns
56
+ * resolve against the workspace root, never the config file's directory, so
57
+ * `--config ci/workspace.yaml` behaves identically to an auto-detected config.
58
+ *
59
+ * @param workspaceConfig - Validated workspace config
60
+ * @param normalizedInput - Normalized path to the workspace directory
61
+ * @param warn - Sink for non-fatal problems
62
+ * @param debug - Whether to emit debug logging
63
+ * @returns Absolute paths of every matched file, deduped and sorted
64
+ * @throws Error if a pattern escapes the workspace root
65
+ */
66
+ export declare function resolveIncludedPaths(workspaceConfig: IWorkspaceConfig, normalizedInput: string, warn: (message: string) => void, debug?: boolean): string[];
40
67
  /**
41
68
  * Generate execution plan for test flows
42
69
  *
@@ -83,6 +83,14 @@ function extractDeviceCloudOverrides(config) {
83
83
  }
84
84
  return overrides;
85
85
  }
86
+ /**
87
+ * How many flows opt into the extended test runtime (up to 20 minutes, billed
88
+ * accepts: YAML `true` or the string `'true'`.
89
+ * accepts: YAML `true` or the string `'true'`.
90
+ */
91
+ export function countExtendedRuntimeFlows(flowOverrides) {
92
+ return Object.values(flowOverrides).filter(({ EXTENDED_RUNTIME }) => EXTENDED_RUNTIME === true || EXTENDED_RUNTIME === 'true').length;
93
+ }
86
94
  /**
87
95
  * Generate execution plan for a single flow file
88
96
  * @param normalizedInput - Normalized path to the flow file
@@ -210,7 +218,7 @@ const INCLUDED_PATHS_BYTES_WARN_THRESHOLD = 50 * 1024 * 1024;
210
218
  * @returns Absolute paths of every matched file, deduped and sorted
211
219
  * @throws Error if a pattern escapes the workspace root
212
220
  */
213
- function resolveIncludedPaths(workspaceConfig, normalizedInput, warn, debug = false) {
221
+ export function resolveIncludedPaths(workspaceConfig, normalizedInput, warn, debug = false) {
214
222
  const patterns = workspaceConfig.includedPaths;
215
223
  if (!patterns || patterns.length === 0)
216
224
  return [];
@@ -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(() => { });
@@ -59,7 +59,7 @@ export class MoropoService {
59
59
  }
60
60
  catch (error) {
61
61
  if (!quiet && !json) {
62
- ux.action.stop('failed');
62
+ ux.action.fail('failed');
63
63
  }
64
64
  // Remove the temp directory (and any partially-written zip inside it)
65
65
  if (moropoDir) {
@@ -121,7 +121,7 @@ export class ResultsPollingService {
121
121
  // displayFinalResults. Anything else aborts mid-poll with the spinner
122
122
  // still live, which would corrupt the terminal under the error output.
123
123
  if (!options.json && !(error instanceof RunFailedError)) {
124
- ux.action.stop(colors.error('failed'));
124
+ ux.action.fail(colors.error('failed'));
125
125
  }
126
126
  throw error;
127
127
  }