@zharp/cli 0.2.0 → 0.3.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.
package/dist/index.mjs CHANGED
@@ -23,7 +23,7 @@ function resolveConnection(options) {
23
23
  function artifactsUrl(connection) {
24
24
  return `${connection.url}/api/v1/applications/${encodeURIComponent(String(connection.app))}/artifacts`;
25
25
  }
26
- var sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
26
+ var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
27
27
  async function uploadArtifact(connection, artifact, options = {}) {
28
28
  const doFetch = options.fetch ?? fetch;
29
29
  const retries = options.retries ?? 3;
@@ -454,8 +454,143 @@ function formatUuid(bytes) {
454
454
  }
455
455
 
456
456
  // src/native.ts
457
- import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, statSync as statSync3 } from "fs";
458
- import { basename, dirname as dirname2, join as join3, resolve as resolve2 } from "path";
457
+ import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync4 } from "fs";
458
+ import { basename, dirname as dirname3, join as join4, resolve as resolve3 } from "path";
459
+
460
+ // src/swift-names.ts
461
+ import { spawnSync } from "child_process";
462
+ import { readFileSync as readFileSync2 } from "fs";
463
+ var xcrun = (tool, args, input) => {
464
+ const result = spawnSync("xcrun", [tool, ...args], { input, encoding: "utf8", maxBuffer: 512 * 1024 * 1024 });
465
+ return result.status === 0 && typeof result.stdout === "string" ? result.stdout : null;
466
+ };
467
+ var SWIFT = /\$s[0-9A-Za-z_$]{3,}/g;
468
+ var NOT_CODE = /^(type metadata(?! accessor)|full type metadata|(nominal type|protocol|protocol conformance|associated (type|conformance)|method|property|module|extension|anonymous|reflection metadata|opaque type) descriptor|reflection metadata|protocol (requirements base|witness table)(?! accessor)|value witness table|field offset|enum case for|lazy cache variable|demangling cache variable|flag for loading|metaclass for|class metadata base offset|objc metaclass|type metadata (pattern|completion|instantiation cache)|generic (type|protocol witness table) (instantiation cache|pattern))/;
469
+ function mangledNamesIn(data) {
470
+ return new Set(data.toString("latin1").match(SWIFT) ?? []);
471
+ }
472
+ function swiftNames(files, tool = process.platform === "darwin" ? xcrun : null, read = readFileSync2) {
473
+ if (!tool) return null;
474
+ const symbols = /* @__PURE__ */ new Set();
475
+ for (const file of new Set(files)) {
476
+ for (const name of mangledNamesIn(read(file))) symbols.add(name);
477
+ }
478
+ if (!symbols.size) return {};
479
+ const mangled = [...symbols];
480
+ const decoded = tool("swift-demangle", ["--simplified", "--compact"], `${mangled.join("\n")}
481
+ `);
482
+ if (decoded === null) return null;
483
+ const lines = decoded.split("\n");
484
+ const out = {};
485
+ mangled.forEach((name, i) => {
486
+ const readable = lines[i]?.trim();
487
+ if (readable && readable !== name && !NOT_CODE.test(readable)) out[name] = readable;
488
+ });
489
+ return out;
490
+ }
491
+
492
+ // src/source-bundle.ts
493
+ import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync3 } from "fs";
494
+ import { dirname as dirname2, join as join3, resolve as resolve2 } from "path";
495
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
496
+ "node_modules",
497
+ ".git",
498
+ ".svn",
499
+ ".hg",
500
+ "build",
501
+ ".build",
502
+ ".dart_tool",
503
+ ".pub-cache",
504
+ ".gradle",
505
+ ".idea",
506
+ ".vscode",
507
+ "test",
508
+ "integration_test",
509
+ "Pods",
510
+ "Carthage",
511
+ "DerivedData",
512
+ "xcuserdata",
513
+ ".swiftpm",
514
+ "SourcePackages",
515
+ "vendor",
516
+ ".fvm",
517
+ ".symlinks",
518
+ "ephemeral"
519
+ ]);
520
+ var MAX_FILE_BYTES = 1024 * 1024;
521
+ var MAX_TOTAL_BYTES = 50 * 1024 * 1024;
522
+ var MAX_FILES = 2e4;
523
+ function collectSources(root, extensions, skipDirs = []) {
524
+ const skip = /* @__PURE__ */ new Set([...SKIP_DIRS, ...skipDirs]);
525
+ const wanted = new Set(extensions.map((e) => e.toLowerCase()));
526
+ const out = { root, files: {}, count: 0, bytes: 0, skipped: 0 };
527
+ const visit = (dir) => {
528
+ let entries;
529
+ try {
530
+ entries = readdirSync2(dir, { withFileTypes: true });
531
+ } catch {
532
+ return;
533
+ }
534
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
535
+ const full = join3(dir, entry.name);
536
+ if (entry.isDirectory()) {
537
+ if (!skip.has(entry.name) && !/\.(xcassets|dSYM)$|Tests$/.test(entry.name)) visit(full);
538
+ continue;
539
+ }
540
+ if (!entry.isFile()) continue;
541
+ const dot = entry.name.lastIndexOf(".");
542
+ if (dot < 0 || !wanted.has(entry.name.slice(dot).toLowerCase())) continue;
543
+ const size = statSync3(full).size;
544
+ if (size > MAX_FILE_BYTES || out.bytes + size > MAX_TOTAL_BYTES || out.count >= MAX_FILES) {
545
+ out.skipped += 1;
546
+ continue;
547
+ }
548
+ out.files[relativePath(root, full)] = readFileSync3(full, "utf8");
549
+ out.count += 1;
550
+ out.bytes += size;
551
+ }
552
+ };
553
+ visit(root);
554
+ return out;
555
+ }
556
+ function sourceBundleArtifacts(sources, buildIds, release) {
557
+ if (!sources.count) return [];
558
+ const data = Buffer.from(JSON.stringify({ files: sources.files }), "utf8");
559
+ return [...new Set(buildIds)].map((debugId) => ({ kind: "source-bundle", debugId, name: "sources.json", release, data, gzip: true }));
560
+ }
561
+ function projectRoot(from, marker) {
562
+ let dir = resolve2(from);
563
+ for (; ; ) {
564
+ if (marker(dir)) return dir;
565
+ const parent = dirname2(dir);
566
+ if (parent === dir) return null;
567
+ dir = parent;
568
+ }
569
+ }
570
+ var FLUTTER_SOURCES = [".dart"];
571
+ var APPLE_SOURCES = [".swift", ".m", ".mm", ".h", ".c", ".cc", ".cpp", ".hpp"];
572
+ var isFlutterRoot = (dir) => existsSync2(join3(dir, "pubspec.yaml"));
573
+ var isAppleRoot = (dir) => {
574
+ try {
575
+ return existsSync2(join3(dir, "Package.swift")) || readdirSync2(dir).some((name) => name.endsWith(".xcodeproj") || name.endsWith(".xcworkspace"));
576
+ } catch {
577
+ return false;
578
+ }
579
+ };
580
+
581
+ // src/native.ts
582
+ function withSources(kind, buildIds, options, logger) {
583
+ if (options.sources === false || !buildIds.length) return [];
584
+ const root = typeof options.sources === "string" ? resolve3(options.sources) : kind === "apple" && process.env.SRCROOT ? process.env.SRCROOT : projectRoot(process.cwd(), kind === "flutter" ? isFlutterRoot : isAppleRoot);
585
+ if (!root || !existsSync3(root)) {
586
+ logger.info(`Sources: no ${kind === "flutter" ? "Flutter project (pubspec.yaml)" : "Xcode project"} found from ${process.cwd()} \u2014 pass --sources <project folder>, or --no-sources.`);
587
+ return [];
588
+ }
589
+ const sources = collectSources(root, kind === "flutter" ? FLUTTER_SOURCES : APPLE_SOURCES);
590
+ if (!sources.count) return [];
591
+ logger.info(`With the app's sources: ${sources.count} file(s), ${formatBytes(sources.bytes)} from ${root}${sources.skipped ? ` (${sources.skipped} over the size caps left out)` : ""} \u2014 errors show the code of this build. --no-sources to leave them out.`);
592
+ return sourceBundleArtifacts(sources, buildIds, options.release);
593
+ }
459
594
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
460
595
  async function send(connection, artifacts, options) {
461
596
  const logger = options.logger ?? consoleLogger();
@@ -473,16 +608,16 @@ async function send(connection, artifacts, options) {
473
608
  }
474
609
  async function uploadProguard(mappingFile, uuid, connection, options = {}) {
475
610
  if (!UUID.test(uuid)) throw new Error(`--uuid must be a UUID, got "${uuid}".`);
476
- const data = readFileSync2(mappingFile);
611
+ const data = readFileSync4(mappingFile);
477
612
  return send(connection, [{ kind: "proguard", debugId: uuid.toLowerCase(), name: basename(mappingFile), release: options.release, data, gzip: true }], options);
478
613
  }
479
614
  var DART_ARCH = { x86_64: "x64", x86: "ia32" };
480
615
  function findDartSymbols(path, logger = consoleLogger()) {
481
- const files = statSync3(path).isDirectory() ? walk(resolve2(path)) : [resolve2(path)];
616
+ const files = statSync4(path).isDirectory() ? walk(resolve3(path)) : [resolve3(path)];
482
617
  const out = [];
483
618
  for (const file of files) {
484
619
  const named = /\.symbols$/.test(file);
485
- const data = readFileSync2(file);
620
+ const data = readFileSync4(file);
486
621
  if (!isElf(data)) {
487
622
  if (named) logger.warn(`Skipped ${basename(file)}: not an ELF file.`);
488
623
  continue;
@@ -498,21 +633,21 @@ function findDartSymbols(path, logger = consoleLogger()) {
498
633
  return out;
499
634
  }
500
635
  function findObfuscationMap(symbolsPath) {
501
- const dir = statSync3(symbolsPath).isDirectory() ? resolve2(symbolsPath) : dirname2(resolve2(symbolsPath));
502
- for (const where of [dir, dirname2(dir)]) {
636
+ const dir = statSync4(symbolsPath).isDirectory() ? resolve3(symbolsPath) : dirname3(resolve3(symbolsPath));
637
+ for (const where of [dir, dirname3(dir)]) {
503
638
  let names;
504
639
  try {
505
- names = readdirSync2(where).sort();
640
+ names = readdirSync3(where).sort();
506
641
  } catch {
507
642
  continue;
508
643
  }
509
644
  const found = names.find((n) => n === "obfuscation.json") ?? names.find((n) => n.endsWith(".obfuscation.json"));
510
- if (found && statSync3(join3(where, found)).isFile()) return join3(where, found);
645
+ if (found && statSync4(join4(where, found)).isFile()) return join4(where, found);
511
646
  }
512
647
  return void 0;
513
648
  }
514
649
  function readObfuscationMap(file) {
515
- const data = readFileSync2(file);
650
+ const data = readFileSync4(file);
516
651
  let parsed;
517
652
  try {
518
653
  parsed = JSON.parse(data.toString("utf8"));
@@ -533,10 +668,10 @@ async function uploadDartSymbols(path, connection, options = {}) {
533
668
  name: basename(f.path),
534
669
  arch: f.arch,
535
670
  release: options.release,
536
- data: readFileSync2(f.path),
671
+ data: readFileSync4(f.path),
537
672
  gzip: true
538
673
  }));
539
- if (options.obfuscationMap && !existsSync2(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);
674
+ if (options.obfuscationMap && !existsSync3(options.obfuscationMap)) throw new Error(`${options.obfuscationMap} does not exist.`);
540
675
  const mapFile = options.obfuscationMap ?? findObfuscationMap(path);
541
676
  if (mapFile) {
542
677
  const data = readObfuscationMap(mapFile);
@@ -548,14 +683,15 @@ async function uploadDartSymbols(path, connection, options = {}) {
548
683
  } else {
549
684
  logger.info("No obfuscation map found (build with --extra-gen-snapshot-options=--save-obfuscation-map=build/obfuscation.json, or pass --obfuscation-map): obfuscated names in error messages stay as they are.");
550
685
  }
686
+ artifacts.push(...withSources("flutter", [...new Set(files.map((f) => f.buildId))], options, logger));
551
687
  return send(connection, artifacts, options);
552
688
  }
553
689
  function findDsymImages(path) {
554
- const root = resolve2(path);
555
- const candidates = statSync3(root).isDirectory() ? walk(root).filter((f) => /[\\/]Contents[\\/]Resources[\\/]DWARF[\\/][^\\/]+$/.test(f)) : [root];
690
+ const root = resolve3(path);
691
+ const candidates = statSync4(root).isDirectory() ? walk(root).filter((f) => /[\\/]Contents[\\/]Resources[\\/]DWARF[\\/][^\\/]+$/.test(f)) : [root];
556
692
  const out = [];
557
693
  for (const file of candidates) {
558
- const data = readFileSync2(file);
694
+ const data = readFileSync4(file);
559
695
  if (!isMachO(data)) continue;
560
696
  for (const image of readMachO(data)) out.push({ path: file, ...image });
561
697
  }
@@ -569,7 +705,7 @@ async function uploadDsyms(path, connection, options = {}) {
569
705
  const cache = /* @__PURE__ */ new Map();
570
706
  const artifacts = images.map((image) => {
571
707
  let data = cache.get(image.path);
572
- if (!data) cache.set(image.path, data = readFileSync2(image.path));
708
+ if (!data) cache.set(image.path, data = readFileSync4(image.path));
573
709
  return {
574
710
  kind: "dsym",
575
711
  debugId: image.uuid,
@@ -581,17 +717,28 @@ async function uploadDsyms(path, connection, options = {}) {
581
717
  gzip: true
582
718
  };
583
719
  });
720
+ const names = swiftNames(images.map((image) => image.path), options.xcodeTool === void 0 ? void 0 : options.xcodeTool);
721
+ if (names && Object.keys(names).length) {
722
+ const data = Buffer.from(JSON.stringify({ names }), "utf8");
723
+ logger.info(`With readable names for ${Object.keys(names).length} Swift symbol(s)`);
724
+ for (const uuid of new Set(images.map((image) => image.uuid))) {
725
+ artifacts.push({ kind: "symbol-names", debugId: uuid, name: "swift-names.json", release: options.release, data, gzip: true });
726
+ }
727
+ } else if (names === null) {
728
+ logger.info("Swift names stay mangled: run the upload on a Mac with Xcode (xcrun swift-demangle) to send readable ones.");
729
+ }
730
+ artifacts.push(...withSources("apple", [...new Set(images.map((image) => image.uuid))], options, logger));
584
731
  return send(connection, artifacts, options);
585
732
  }
586
733
 
587
734
  // src/sourcemaps.ts
588
- import { existsSync as existsSync3, readFileSync as readFileSync3, unlinkSync, writeFileSync } from "fs";
589
- import { dirname as dirname3, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
735
+ import { existsSync as existsSync4, readFileSync as readFileSync5, unlinkSync, writeFileSync } from "fs";
736
+ import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve4 } from "path";
590
737
  var JS_FILE = /\.(?:js|mjs|cjs)$/;
591
738
  function mapFor(file, code) {
592
739
  const sibling = `${file}.map`;
593
- if (existsSync3(sibling)) return sibling;
594
- const url = sourceMappingUrl(code ?? readFileSync3(file, "utf8"));
740
+ if (existsSync4(sibling)) return sibling;
741
+ const url = sourceMappingUrl(code ?? readFileSync5(file, "utf8"));
595
742
  if (!url || /^[a-z][a-z0-9+.-]*:/i.test(url)) return void 0;
596
743
  let path;
597
744
  try {
@@ -599,16 +746,16 @@ function mapFor(file, code) {
599
746
  } catch {
600
747
  return void 0;
601
748
  }
602
- const full = isAbsolute2(path) ? path : resolve3(dirname3(file), path);
603
- return existsSync3(full) ? full : void 0;
749
+ const full = isAbsolute2(path) ? path : resolve4(dirname4(file), path);
750
+ return existsSync4(full) ? full : void 0;
604
751
  }
605
752
  function findSourceFiles(dir, options = {}) {
606
- const root = resolve3(dir);
753
+ const root = resolve4(dir);
607
754
  const keep = pathFilter(options.include, options.exclude);
608
- const candidates = options.files ? options.files.map((f) => resolve3(f)) : walk(root);
755
+ const candidates = options.files ? options.files.map((f) => resolve4(f)) : walk(root);
609
756
  const out = [];
610
757
  for (const file of candidates) {
611
- if (!JS_FILE.test(file) || !existsSync3(file)) continue;
758
+ if (!JS_FILE.test(file) || !existsSync4(file)) continue;
612
759
  const name = relativePath(root, file);
613
760
  if (!keep(name)) continue;
614
761
  const map = mapFor(file);
@@ -622,11 +769,11 @@ function injectDirectory(dir, options = {}) {
622
769
  const out = [];
623
770
  const noSourcesContent = [];
624
771
  for (const source of files) {
625
- const code = readFileSync3(source.file, "utf8");
772
+ const code = readFileSync5(source.file, "utf8");
626
773
  const injected = injectCode(code, { stripSourceMappingUrl: options.stripSourceMappingUrl });
627
774
  let map;
628
775
  try {
629
- map = injectMap(readFileSync3(source.map, "utf8"), injected.debugId, source.map);
776
+ map = injectMap(readFileSync5(source.map, "utf8"), injected.debugId, source.map);
630
777
  } catch (error) {
631
778
  logger.warn(`Skipped ${source.name}: ${source.mapName} is not a readable source map (${error.message}).`);
632
779
  continue;
@@ -654,13 +801,13 @@ async function uploadSourcemaps(dir, connection, options = {}) {
654
801
  const result = { files: 0, artifacts: 0, bytes: 0, deleted: [], skipped: [] };
655
802
  const work = [];
656
803
  for (const source of files) {
657
- const code = readFileSync3(source.file);
804
+ const code = readFileSync5(source.file);
658
805
  const debugId = existingDebugId(code.toString("utf8"));
659
806
  if (!debugId) {
660
807
  result.skipped.push(source.name);
661
808
  continue;
662
809
  }
663
- work.push({ source, debugId, code, map: readFileSync3(source.map) });
810
+ work.push({ source, debugId, code, map: readFileSync5(source.map) });
664
811
  }
665
812
  if (result.skipped.length) {
666
813
  logger.warn(`${result.skipped.length} file(s) have a source map but no debug ID \u2014 run \`zharp sourcemaps inject\` first: ${result.skipped.slice(0, 3).join(", ")}${result.skipped.length > 3 ? ", \u2026" : ""}`);
@@ -697,12 +844,12 @@ async function uploadSourcemaps(dir, connection, options = {}) {
697
844
  function deleteSourcemaps(files, options = {}) {
698
845
  const deleted = [];
699
846
  for (const source of files) {
700
- if (options.stripSourceMappingUrl && existsSync3(source.file)) {
701
- const code = readFileSync3(source.file, "utf8");
847
+ if (options.stripSourceMappingUrl && existsSync4(source.file)) {
848
+ const code = readFileSync5(source.file, "utf8");
702
849
  const stripped = withoutSourceMappingUrl(code);
703
850
  if (stripped !== code) writeFileSync(source.file, stripped);
704
851
  }
705
- if (existsSync3(source.map)) {
852
+ if (existsSync4(source.map)) {
706
853
  unlinkSync(source.map);
707
854
  deleted.push(source.mapName);
708
855
  }
@@ -711,7 +858,7 @@ function deleteSourcemaps(files, options = {}) {
711
858
  }
712
859
 
713
860
  // src/version.ts
714
- var VERSION = "0.2.0";
861
+ var VERSION = "0.3.0";
715
862
 
716
863
  // src/build.ts
717
864
  function defaultRelease(options) {