@qawolf/ci-sdk 3.6.0 → 3.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.
package/README.md CHANGED
@@ -22,7 +22,7 @@ to determine the status of your CI/CD step/job/action.
22
22
  - [Read a Promotion](#promotion-get)
23
23
  - [Upload an App Build](#upload-build)
24
24
  - [Notify a Terminated Ephemeral Environment (deprecated)](#notify-terminated-ephemeral-environment)
25
- - [Upload Run Input Artifacts](#upload-artifacts)
25
+ - [Upload Run Input Artifacts (deprecated for Android and iOS builds)](#upload-artifacts)
26
26
  - [Requirements](#requirements)
27
27
  - [Versioning](#versioning)
28
28
  - [Changelog](#changelog)
@@ -208,6 +208,31 @@ const detected = detectProviderDeploymentId({
208
208
 
209
209
  `deployment.reportStatus` requires `workspaceId` for every key kind; a workspace API key must name its own workspace. See [API Keys and Workspaces](#api-keys).
210
210
 
211
+ ### `changes`
212
+
213
+ A trigger where QA Wolf chooses the flows reads what a deployment changed. Without a pull request, and without QA Wolf's GitHub or GitLab integration, your pipeline can send that summary itself: each merged pull request or pushed commit with its title, and optionally its description and changed file paths, plus release notes. Code is never accepted. `deployment.collectCommitChanges` builds it from the local git history, so you can check or edit it before sending (renamed from `collectChanges` in 3.7.0):
214
+
215
+ ```javascript
216
+ const collected = await deployment.collectCommitChanges({
217
+ include: ["titles", "paths"],
218
+ since: "v1.2.0", // the commit or tag the environment ran before
219
+ });
220
+ if (
221
+ collected.outcome === "history-unavailable" ||
222
+ collected.outcome === "since-not-found"
223
+ )
224
+ throw Error(collected.fix);
225
+ if (collected.outcome === "git-failed") throw Error(collected.message);
226
+ if (collected.outcome === "collected") {
227
+ await deployment.reportStatus({
228
+ /* ... */ changes: collected.changes,
229
+ status: "success",
230
+ });
231
+ }
232
+ ```
233
+
234
+ Each commit on the first-parent line after `since` becomes one change. A GitHub or GitLab merge commit, or a GitHub squash-merge commit (its subject ends in `(#123)`), becomes a pull request titled from its message, and any other commit stays a commit. `"descriptions"` adds each change's message body, and `"paths"` adds the file paths it changed, as many as fit beside the other changes. It never reads diffs or file contents. It reads at most the 250 newest commits; older ones, and any left out to fit the API's limits, are counted in `omittedCount`. On a shallow clone it returns `history-unavailable` instead of sending part of the range, and when `since` names no commit it returns `since-not-found`. Send `changes` on the first `success` report or earlier.
235
+
211
236
  ### Result
212
237
 
213
238
  `deployment.reportStatus` returns a discriminated union and never throws for an outcome you are expected to branch on. Branch on `outcome` alone:
@@ -264,6 +289,8 @@ Four things move: `deploymentType` becomes `environment.name`; `branch` / `sha`
264
289
 
265
290
  `deployment.waitForVerdict` blocks until QA Wolf can say whether a deployment's tests passed. Give it the deployment id [the report](#report-deployment) returned; working out which runs the deployment produced happens inside.
266
291
 
292
+ On GitHub Actions, [`qawolf/wait-for-verdict-action`](https://github.com/qawolf/wait-for-verdict-action) runs this wait as a workflow step and writes a job summary with a link to each run.
293
+
267
294
  > ⚠️ Set `timeout` below your CI job's own ceiling. When the job's ceiling fires first, the job is killed with no run link and no explanation. When ours fires first, you get `timed-out` with the stage, the elapsed time, and every run URL we know about.
268
295
 
269
296
  ### Example
@@ -745,7 +772,7 @@ A promotion usually settles within a minute or two. The SDK has no wait helper f
745
772
 
746
773
  ## Upload an App Build
747
774
 
748
- `uploadBuild` uploads an Android `.apk` or `.aab`, or an iOS `.ipa` file, up to 500 MB, and registers it as a QA Wolf build. QA Wolf reads the app ID, version and build number from the file, and runs that launch the app install the build.
775
+ `uploadBuild` uploads an Android `.apk` or `.aab`, or an iOS `.ipa` file, up to 1 GB by default, and registers it as a QA Wolf build. QA Wolf reads the app ID, version and build number from the file, and runs that launch the app install the build.
749
776
 
750
777
  ```ts
751
778
  import { makeQaWolfSdk } from "@qawolf/ci-sdk";
@@ -775,12 +802,12 @@ The parameters other than `filePath` are the input of the `build.create` contrac
775
802
 
776
803
  `uploadBuild` answers `{ outcome: "uploaded", build }`, where `build` carries the build's `id`, `appId`, `appName`, `platform`, `version`, `buildNumber`, `fileName`, `sizeBytes` and `url`. It never throws.
777
804
 
778
- | `outcome` | Meaning |
779
- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
780
- | `file-unreadable` | `filePath` does not name a readable file. Nothing was sent to QA Wolf. Carries `filePath`. |
781
- | `upload-rejected` | Storage refused the file's bytes, for example because the upload URL expired. Carries `buildId` and `httpStatus`. |
782
- | `upload-network-error` | The file's bytes never reached storage, or the connection dropped. Carries `buildId`. |
783
- | `invalid-request`, `unauthorized`, `not-found`, `conflict`, `server-error`, `unexpected-status`, `network-error`, `invalid-response-body` | QA Wolf refused or failed one of the two calls. `failedStep` says which: `request-upload` (for `invalid-request`, a file that is not an `.apk`, `.aab` or `.ipa`, or is over 500 MB) or `create` (for `invalid-request`, a file that is not an app, which also carries `buildId`). Same meanings as for `deployment.reportStatus`. |
805
+ | `outcome` | Meaning |
806
+ | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
807
+ | `file-unreadable` | `filePath` does not name a readable file. Nothing was sent to QA Wolf. Carries `filePath`. |
808
+ | `upload-rejected` | Storage refused the file's bytes, for example because the upload URL expired. Carries `buildId` and `httpStatus`. |
809
+ | `upload-network-error` | The file's bytes never reached storage, or the connection dropped. Carries `buildId`. |
810
+ | `invalid-request`, `unauthorized`, `not-found`, `conflict`, `server-error`, `unexpected-status`, `network-error`, `invalid-response-body` | QA Wolf refused or failed one of the two calls. `failedStep` says which: `request-upload` (for `invalid-request`, a file that is not an `.apk`, `.aab` or `.ipa`, or is over the workspace's limit, 1 GB by default) or `create` (for `invalid-request`, a file that is not an app, which also carries `buildId`). Same meanings as for `deployment.reportStatus`. |
784
811
 
785
812
  A failed call creates no build. To retry, call `uploadBuild` again: each call uploads the file under a new build.
786
813
 
@@ -837,12 +864,15 @@ const { notifyTerminatedEphemeralEnvironment } = makeQaWolfSdk({
837
864
 
838
865
  ## Upload Run Input Artifacts
839
866
 
867
+ > ⚠️ **Deprecated for Android and iOS builds.** Upload them with [`uploadBuild`](#upload-build) instead, so every run records which build it tested. See [Move from legacy uploads](https://docs.qawolf.com/upload-builds#move-from-legacy-uploads). `generateSignedUrlForRunInputsExecutablesStorage` keeps working and has no removal date. Windows and Linux app files still take this path.
868
+
840
869
  ```ts
841
- import { type DeployConfig, makeQaWolfSdk } from "@qawolf/ci-sdk";
842
870
  import fs from "fs/promises";
843
871
  import path from "path";
844
872
 
845
- const { generateSignedUrlForTempTeamStorage, attemptNotifyDeploy } =
873
+ import { type DeployConfig, makeQaWolfSdk } from "@qawolf/ci-sdk";
874
+
875
+ const { generateSignedUrlForRunInputsExecutablesStorage, attemptNotifyDeploy } =
846
876
  makeQaWolfSdk({
847
877
  apiKey: "qawolf_xxxxx",
848
878
  });
@@ -878,9 +908,10 @@ async function uploadRunArtifact(filePath: string): Promise<string> {
878
908
 
879
909
  // Organization and user API keys must also pass `workspaceId` here, or the
880
910
  // request fails with a 400. See "API Keys and Workspaces" above.
881
- const signedUrlResponse = await generateSignedUrlForTempTeamStorage({
882
- destinationFilePath: fileName,
883
- });
911
+ const signedUrlResponse =
912
+ await generateSignedUrlForRunInputsExecutablesStorage({
913
+ destinationFilePath: fileName,
914
+ });
884
915
 
885
916
  if (
886
917
  signedUrlResponse?.success &&
@@ -960,6 +991,15 @@ This package follows the [SemVer](https://semver.org/) versioning scheme. Additi
960
991
 
961
992
  # Changelog
962
993
 
994
+ ## v3.7.0
995
+
996
+ - `deployment.collectChanges` is renamed to `deployment.collectCommitChanges`, and its `CollectChangesParams` and `CollectChangesResult` types to `CollectCommitChangesParams` and `CollectCommitChangesResult`.
997
+
998
+ ## v3.6.1
999
+
1000
+ - `generateSignedUrlForRunInputsExecutablesStorage` and the [Upload Run Input Artifacts](#upload-artifacts) recipe are deprecated for Android and iOS builds. Use [`uploadBuild`](#upload-build) instead. Both keep working, and Windows and Linux app files still take this path.
1001
+ - The [Upload Run Input Artifacts](#upload-artifacts) recipe now calls `generateSignedUrlForRunInputsExecutablesStorage`, the function that uploads app files. It called `generateSignedUrlForTempTeamStorage` before. No code changes.
1002
+
963
1003
  ## v3.6.0
964
1004
 
965
1005
  - `deployment.waitForVerdict` answers `needs-review` when a run's failures wait for a person: QA Wolf asked a question about each of them, or the workspace does not investigate runs. Before, such a run read `running`, so the wait polled until `timeout` and answered `timed-out`. `needs-review` carries `runs` with each run's URL, and it is not a pass. A caller that switches exhaustively on `outcome` has one more case to handle. The recipe's `["passed", "not-tested"].includes(...)` check needs no change. See [Wait for a Verdict](#wait-for-verdict).
package/dist/index.js CHANGED
@@ -123,7 +123,7 @@ var defaultServiceBase = "https://app.qawolf.com/";
123
123
  // package.json
124
124
  var package_default = {
125
125
  name: "@qawolf/ci-sdk",
126
- version: "3.6.0",
126
+ version: "3.7.0",
127
127
  private: false,
128
128
  description: "A simple SDK for interacting with QAWolf in CI scripts.",
129
129
  keywords: [],
@@ -162,7 +162,7 @@ var package_default = {
162
162
  "@sinonjs/fake-timers": "^10.3.0",
163
163
  superjson: "^2.2.6",
164
164
  tslib: "^2.6.2",
165
- zod: "^4.1.11"
165
+ zod: "^4.6.6"
166
166
  },
167
167
  devDependencies: {
168
168
  "@qawolf/platform-builder": "^1.2.7",
@@ -506,6 +506,192 @@ async function handleErrorResponse(response, log) {
506
506
  }
507
507
  __name(handleErrorResponse, "handleErrorResponse");
508
508
 
509
+ // src/lib/sdk/domain/collectCommitChanges/gitDriver.ts
510
+ import { execFile } from "node:child_process";
511
+ var maxBuffer = 64 * 1024 * 1024;
512
+ var defaultGitDriver = /* @__PURE__ */ __name((args, cwd) => new Promise((resolve) => {
513
+ execFile("git", args, { cwd, maxBuffer }, (error, stdout, stderr) => {
514
+ resolve(
515
+ error ? {
516
+ ok: false,
517
+ stderr: stderr && !error.message.includes(stderr) ? `${error.message}
518
+ ${stderr}` : error.message
519
+ } : { ok: true, stdout }
520
+ );
521
+ });
522
+ }), "defaultGitDriver");
523
+
524
+ // src/lib/sdk/domain/collectCommitChanges/parseLog.ts
525
+ var logFormat = "%H%x00%s%x00%b%x00";
526
+ var hashPattern = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u;
527
+ var fieldsBeforePaths = 4;
528
+ function parseLog(stdout) {
529
+ const tokens = stdout.split("\0");
530
+ const starts = tokens.reduce((found, token, index) => {
531
+ const previous = found.at(-1);
532
+ const canStart = previous === void 0 ? index === 0 : index >= previous + fieldsBeforePaths;
533
+ return canStart && hashPattern.test(token) ? [...found, index] : found;
534
+ }, []);
535
+ return starts.map((start, position) => {
536
+ const [, subject = "", body = "", , ...paths] = tokens.slice(
537
+ start,
538
+ starts[position + 1] ?? tokens.length
539
+ );
540
+ return {
541
+ body: body.trim(),
542
+ paths: paths.map((path) => path.replace(/^\n/u, "")).filter((path) => path.length > 0),
543
+ subject: subject.trim()
544
+ };
545
+ });
546
+ }
547
+ __name(parseLog, "parseLog");
548
+
549
+ // src/lib/sdk/domain/collectCommitChanges/summarizeCommits.ts
550
+ var maxItems = 250;
551
+ var maxTitleLength = 512;
552
+ var maxDescriptionLength = 4e3;
553
+ var maxPathsPerItem = 1e3;
554
+ var maxPathLength = 1024;
555
+ var maxReleaseNotesLength = 16e3;
556
+ var maxBytes = 256 * 1024;
557
+ var maxBytesPerItem = maxBytes / 8;
558
+ var cut = /* @__PURE__ */ __name((text, max) => text.length > max ? text.slice(0, max) : text, "cut");
559
+ var byteLengthOf = /* @__PURE__ */ __name((value) => new TextEncoder().encode(JSON.stringify(value)).length, "byteLengthOf");
560
+ var mergeSubjectPattern = /^Merge (pull request #\d+|branch .+ into )/u;
561
+ var squashSubjectPattern = /\(#\d+\)$/u;
562
+ var mergeRequestTrailerPattern = /^See merge request \S+$/mu;
563
+ function readMessage({ body, subject }) {
564
+ if (mergeSubjectPattern.test(subject) && body.length > 0) {
565
+ const [firstLine = "", ...rest] = body.replace(mergeRequestTrailerPattern, "").trim().split("\n");
566
+ return {
567
+ description: rest.join("\n").trim(),
568
+ kind: "pull-request",
569
+ // A GitLab merge commit can hold only the trailer.
570
+ title: firstLine.trim() || subject
571
+ };
572
+ }
573
+ return {
574
+ description: body,
575
+ kind: squashSubjectPattern.test(subject) ? "pull-request" : "commit",
576
+ title: subject
577
+ };
578
+ }
579
+ __name(readMessage, "readMessage");
580
+ function toItem(commit, { descriptions, paths }) {
581
+ const { description, kind, title } = readMessage(commit);
582
+ const keptPaths = commit.paths.filter((path) => path.length <= maxPathLength).slice(0, maxPathsPerItem);
583
+ const withPaths = /* @__PURE__ */ __name((count) => ({
584
+ ...paths && count > 0 && { changedPaths: keptPaths.slice(0, count) },
585
+ ...descriptions && description.length > 0 && {
586
+ description: cut(description, maxDescriptionLength)
587
+ },
588
+ kind,
589
+ title: cut(title, maxTitleLength)
590
+ }), "withPaths");
591
+ const fits = /* @__PURE__ */ __name((count) => byteLengthOf(withPaths(count)) <= maxBytesPerItem, "fits");
592
+ return withPaths(
593
+ fits(keptPaths.length) ? keptPaths.length : largestFittingCount(keptPaths.length, fits)
594
+ );
595
+ }
596
+ __name(toItem, "toItem");
597
+ function summarizeCommits({
598
+ commits,
599
+ includeDescriptions,
600
+ includePaths,
601
+ releaseNotes,
602
+ totalCount
603
+ }) {
604
+ const items = commits.filter(({ subject }) => subject.length > 0).map(
605
+ (commit) => toItem(commit, {
606
+ descriptions: includeDescriptions,
607
+ paths: includePaths
608
+ })
609
+ );
610
+ const notes = releaseNotes?.trim();
611
+ const summaryOf = /* @__PURE__ */ __name((count) => {
612
+ const omittedCount = Math.max(totalCount, items.length) - count;
613
+ return {
614
+ ...count > 0 && { items: items.slice(0, count) },
615
+ ...omittedCount > 0 && { omittedCount },
616
+ ...notes && { releaseNotes: cut(notes, maxReleaseNotesLength) }
617
+ };
618
+ }, "summaryOf");
619
+ return summaryOf(
620
+ largestFittingCount(
621
+ Math.min(items.length, maxItems),
622
+ (count) => byteLengthOf(summaryOf(count)) <= maxBytes
623
+ )
624
+ );
625
+ }
626
+ __name(summarizeCommits, "summarizeCommits");
627
+ function largestFittingCount(max, fits) {
628
+ const search = /* @__PURE__ */ __name((low, high) => {
629
+ if (low >= high) return low;
630
+ const middle = Math.ceil((low + high) / 2);
631
+ return fits(middle) ? search(middle, high) : search(low, middle - 1);
632
+ }, "search");
633
+ return search(0, max);
634
+ }
635
+ __name(largestFittingCount, "largestFittingCount");
636
+
637
+ // src/lib/sdk/domain/collectCommitChanges/index.ts
638
+ var historyFix = "Fetch the full history before collecting changes, e.g. `fetch-depth: 0` on actions/checkout, or `git fetch --unshallow`.";
639
+ var sinceFix = /* @__PURE__ */ __name((since) => `Check that ${JSON.stringify(since)} names a commit or tag, and fetch it first if it's a tag, e.g. \`git fetch --tags\`.`, "sinceFix");
640
+ async function collectCommitChanges(git, {
641
+ cwd = process.cwd(),
642
+ include = ["titles"],
643
+ releaseNotes,
644
+ since
645
+ }) {
646
+ const shallow = await git(["rev-parse", "--is-shallow-repository"], cwd);
647
+ if (!shallow.ok) return { message: shallow.stderr, outcome: "git-failed" };
648
+ if (shallow.stdout.trim() === "true")
649
+ return { fix: historyFix, outcome: "history-unavailable" };
650
+ const base = await git(
651
+ [
652
+ "rev-parse",
653
+ "--verify",
654
+ "--quiet",
655
+ "--end-of-options",
656
+ `${since}^{commit}`
657
+ ],
658
+ cwd
659
+ );
660
+ if (!base.ok) return { fix: sinceFix(since), outcome: "since-not-found" };
661
+ const range = `${base.stdout.trim()}..HEAD`;
662
+ const count = await git(
663
+ ["rev-list", "--count", "--first-parent", range],
664
+ cwd
665
+ );
666
+ if (!count.ok) return { message: count.stderr, outcome: "git-failed" };
667
+ const includePaths = include.includes("paths");
668
+ const log = await git(
669
+ [
670
+ "log",
671
+ "--first-parent",
672
+ `--max-count=${maxItems}`,
673
+ "-z",
674
+ `--format=${logFormat}`,
675
+ // A merge lists the paths its pull request changed.
676
+ ...includePaths ? ["--name-only", "-m"] : [],
677
+ range
678
+ ],
679
+ cwd
680
+ );
681
+ if (!log.ok) return { message: log.stderr, outcome: "git-failed" };
682
+ return {
683
+ changes: summarizeCommits({
684
+ commits: parseLog(log.stdout),
685
+ includeDescriptions: include.includes("descriptions"),
686
+ includePaths,
687
+ releaseNotes,
688
+ totalCount: Number(count.stdout.trim())
689
+ }),
690
+ outcome: "collected"
691
+ };
692
+ }
693
+ __name(collectCommitChanges, "collectCommitChanges");
694
+
509
695
  // src/lib/sdk/domain/environment/promote.ts
510
696
  import { publicContractsV1 } from "@qawolf/api-contracts";
511
697
 
@@ -2002,6 +2188,7 @@ function makeQaWolfSdk({
2002
2188
  }, {
2003
2189
  clock = defaultClock,
2004
2190
  fetch = defaultFetch,
2191
+ git = defaultGitDriver,
2005
2192
  log = defaultLogDriver
2006
2193
  } = {}) {
2007
2194
  if (typeof fetch !== "function") {
@@ -2026,6 +2213,8 @@ We recommend 'undici' package for that purpose. See the Requirement section of o
2026
2213
  */
2027
2214
  attemptNotifyDeploy: attemptNotifyDeploy.bind(null, deps, apiConfig),
2028
2215
  deployment: {
2216
+ /** Builds `changes` for `reportStatus` from the local git history; sends nothing itself. */
2217
+ collectCommitChanges: collectCommitChanges.bind(null, git),
2029
2218
  reportStatus: reportDeployment.bind(null, deps, apiConfig),
2030
2219
  waitForVerdict: waitForVerdict.bind(null, deps, apiConfig)
2031
2220
  },
@@ -2033,6 +2222,11 @@ We recommend 'undici' package for that purpose. See the Requirement section of o
2033
2222
  promote: promoteEnvironment.bind(null, deps, apiConfig),
2034
2223
  terminate: terminateEnvironment.bind(null, deps, apiConfig)
2035
2224
  },
2225
+ /**
2226
+ * Deprecated for Android and iOS builds: use `uploadBuild`, whose runs
2227
+ * record which build they tested. Still the way to upload Windows and
2228
+ * Linux app files.
2229
+ */
2036
2230
  generateSignedUrlForRunInputsExecutablesStorage: generateSignedUrlForRunInputsExecutablesStorage.bind(
2037
2231
  null,
2038
2232
  deps,