Open source CapCut alternative.
TypeScript
chore: TestFlight ships without the distribute step
David Leba236931bdf8
diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.mdindex 648b27c1..4dcf56ca 100644--- a/docs/guides/ios-app.md+++ b/docs/guides/ios-app.md@@ -177,30 +177,13 @@ scripts/ship-ios-testflight.shIt archives the app and uploads it to App Store Connect; Xcode manages thebuild number so repeat uploads never collide. Auth comes from the Apple ID-signed into Xcode, or from a `DONKEY_ASC_KEY_*` App Store Connect API key for-unattended runs (the variables are documented in the script header). Once-processing finishes, internal testers in App Store Connect → TestFlight get-the build without review.--External testers are served by the same command. Processing outlives the-upload, so the ship hands off to `scripts/asc-distribute.mjs` in the-background: it polls until the build is processed, adds it to every external-group on the app, turns on the tester notification, and submits it for beta-review, which is the step external testers wait on. Apple releases the build-to them the moment review passes, and nobody opens App Store Connect.--Apple reviews one build of an app at a time, so shipping twice in an afternoon-leaves the second build waiting on the first. The script waits the slot out and-submits, which is the difference between a build that reaches testers and one-parked in the group.--That handoff needs the App Store Connect API key — the Apple ID session Xcode-holds cannot reach the API. Create one under Users and Access → Integrations →-App Store Connect API with the App Manager role, then either export the-`DONKEY_ASC_KEY_*` variables or drop `AuthKey_XXXX.p8` in-`~/.appstoreconnect/private_keys/` with the issuer id in an `issuer_id` file-beside it. Without a key the ship still uploads and says the build is waiting-for a manual release; `--no-distribute` asks for that on purpose.+signed into Xcode. Once processing finishes, internal testers in App Store+Connect → TestFlight get the build without review.++External testers are served from App Store Connect: add the processed build to+the tester groups and submit it for beta review, which is the step external+testers wait on. Apple reviews one build of an app at a time, so shipping twice+in an afternoon leaves the second build waiting on the first.A build that testers install has to be a build you can go back to, so thearchive is cut from a commit: the script checks the ref out into a worktree ofdiff --git a/scripts/asc-distribute.mjs b/scripts/asc-distribute.mjsdeleted file mode 100755index 1e7ccc89..00000000--- a/scripts/asc-distribute.mjs+++ /dev/null@@ -1,229 +0,0 @@-#!/usr/bin/env node-// Hands the build that was just uploaded to every external TestFlight group,-// so testers get each ship without anyone opening App Store Connect.-//-// node scripts/asc-distribute.mjs [--uploaded-after <epoch-seconds>]-// [--wait-minutes 60] [--bundle-id <id>]-//-// App Store Connect takes a few minutes to process an upload, so the script-// polls for the newest build, waits for it to go VALID, turns on the "new-// build" notification, adds it to the external groups, and submits it for-// beta review. Apple releases it to the testers the moment review passes.-//-// Credentials come from an App Store Connect API key (Users and Access →-// Integrations → App Store Connect API, role App Manager):-//-// DONKEY_ASC_KEY_P8_PATH=/path/AuthKey_XXXX.p8-// DONKEY_ASC_KEY_ID=XXXX-// DONKEY_ASC_ISSUER_ID=uuid-//-// With the key dropped in ~/.appstoreconnect/private_keys/AuthKey_XXXX.p8 the-// path and id are read from the filename, and the issuer id from-// ~/.appstoreconnect/private_keys/issuer_id.--import { createSign } from "node:crypto"-import { existsSync, readFileSync, readdirSync } from "node:fs"-import { homedir } from "node:os"-import { join } from "node:path"--const API = "https://api.appstoreconnect.apple.com"-const KEY_DIR = join(homedir(), ".appstoreconnect", "private_keys")--const args = parseArgs(process.argv.slice(2))-const bundleId = args["bundle-id"] ?? "com.donkeycut.donkeycut"-const uploadedAfter = Number(args["uploaded-after"] ?? 0) * 1000-const waitMs = Number(args["wait-minutes"] ?? 60) * 60_000-// Beta review runs on Apple's clock, so the wait for the slot is measured in-// hours rather than minutes.-const reviewWaitMs = Number(args["review-wait-minutes"] ?? 720) * 60_000--let token = ""--try {- await distribute()-} catch (error) {- process.stderr.write(`${error.message}\n`)- process.exit(1)-}--async function distribute() {- token = mintToken(resolveCredentials())-- const app = (await api(`/v1/apps?filter[bundleId]=${bundleId}&limit=1`)).data[0]- if (!app) throw new Error(`No App Store Connect app for ${bundleId}`)-- const build = await waitForBuild(app.id)- log(`Build ${build.attributes.version} is processed`)-- const groups = (await api(`/v1/apps/${app.id}/betaGroups?limit=200`)).data.filter(- (group) => !group.attributes.isInternalGroup- )- if (groups.length === 0) {- log("No external groups on this app; nothing to distribute")- return- }-- const detail = (await api(`/v1/builds/${build.id}/buildBetaDetail`)).data- await api(`/v1/buildBetaDetails/${detail.id}`, {- method: "PATCH",- body: {- data: {- type: "buildBetaDetails",- id: detail.id,- attributes: { autoNotifyEnabled: true },- },- },- })-- for (const group of groups) {- await api(`/v1/betaGroups/${group.id}/relationships/builds`, {- method: "POST",- body: { data: [{ type: "builds", id: build.id }] },- // Re-running a ship over a build the group already holds is a no-op.- allow: [409],- })- log(`Added ${build.attributes.version} to "${group.attributes.name}"`)- }-- await submitForReview(build)-}--// External testers only see a build once beta review clears it, and Apple-// reviews one build of an app at a time: shipping twice in an afternoon leaves-// the second build waiting on the first. The script waits that out rather than-// leaving the newer build parked in the group.-async function submitForReview(build) {- const deadline = Date.now() + reviewWaitMs- let waiting = false- for (;;) {- const failure = await api(`/v1/betaAppReviewSubmissions`, {- method: "POST",- body: {- data: {- type: "betaAppReviewSubmissions",- relationships: { build: { data: { type: "builds", id: build.id } } },- },- },- soft: true,- })- if (!failure) {- log("Submitted for beta review; testers get it as soon as review passes")- return- }- if (!/already in review|another build/i.test(failure)) {- if (/already exists|ENTITY_ERROR.RELATIONSHIP/i.test(failure)) {- log("Already submitted for beta review")- return- }- throw new Error(failure)- }- if (!waiting) {- log("An earlier build holds the review slot; waiting for it to clear")- waiting = true- }- if (Date.now() > deadline) {- throw new Error("The review slot never cleared; submit this build from App Store Connect")- }- await new Promise((resolve) => setTimeout(resolve, 5 * 60_000))- }-}--function parseArgs(argv) {- const parsed = {}- for (let i = 0; i < argv.length; i += 1) {- if (!argv[i].startsWith("--")) continue- parsed[argv[i].slice(2)] = argv[i + 1]- i += 1- }- return parsed-}--function resolveCredentials() {- let path = process.env.DONKEY_ASC_KEY_P8_PATH- let keyId = process.env.DONKEY_ASC_KEY_ID- let issuerId = process.env.DONKEY_ASC_ISSUER_ID- if (!path) {- const file = (existsSync(KEY_DIR) ? readdirSync(KEY_DIR) : []).find((name) =>- /^AuthKey_.+\.p8$/.test(name)- )- if (!file) {- throw new Error(- `No App Store Connect API key. Set DONKEY_ASC_KEY_P8_PATH or drop AuthKey_XXXX.p8 in ${KEY_DIR}`- )- }- path = join(KEY_DIR, file)- keyId ??= file.slice("AuthKey_".length, -".p8".length)- }- if (!issuerId) {- issuerId = readFileSync(join(KEY_DIR, "issuer_id"), "utf8").trim()- }- return { privateKey: readFileSync(path, "utf8"), keyId, issuerId }-}--function mintToken({ privateKey, keyId, issuerId }) {- const issuedAt = Math.floor(Date.now() / 1000)- const header = { alg: "ES256", kid: keyId, typ: "JWT" }- const payload = {- iss: issuerId,- iat: issuedAt,- exp: issuedAt + 20 * 60,- aud: "appstoreconnect-v1",- }- const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`- const signature = createSign("SHA256")- .update(signingInput)- .sign({ key: privateKey, dsaEncoding: "ieee-p1363" })- return `${signingInput}.${signature.toString("base64url")}`-}--function base64url(value) {- return Buffer.from(value).toString("base64url")-}--// Returns the parsed body, or — with `soft` — the failure text for the caller-// to read, since App Store Connect says why in the error detail.-async function api(path, { method = "GET", body, allow = [], soft = false } = {}) {- const response = await fetch(`${API}${path}`, {- method,- headers: {- Authorization: `Bearer ${token}`,- ...(body ? { "Content-Type": "application/json" } : {}),- },- body: body ? JSON.stringify(body) : undefined,- })- if (allow.includes(response.status)) return null- if (!response.ok) {- const failure = `${method} ${path} → ${response.status} ${await response.text()}`- if (soft) return failure- throw new Error(failure)- }- if (soft) return null- return response.status === 204 ? null : response.json()-}--async function waitForBuild(appId) {- const deadline = Date.now() + waitMs- let announced = ""- for (;;) {- const builds = await api(- `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=5`- )- const build = builds.data.find(- (candidate) => Date.parse(candidate.attributes.uploadedDate) >= uploadedAfter- )- if (build?.attributes.processingState === "VALID") return build- const state = build ? `${build.attributes.version} ${build.attributes.processingState}` : "upload"- if (state !== announced) {- log(`Waiting on ${state}`)- announced = state- }- if (Date.now() > deadline) {- throw new Error("Timed out waiting for App Store Connect to process the upload")- }- await new Promise((resolve) => setTimeout(resolve, 30_000))- }-}--function log(message) {- process.stdout.write(`${message}\n`)-}diff --git a/scripts/ship-ios-testflight.sh b/scripts/ship-ios-testflight.shindex e4b30b9c..30745505 100755--- a/scripts/ship-ios-testflight.sh+++ b/scripts/ship-ios-testflight.sh@@ -5,7 +5,6 @@# number against App Store Connect so repeat uploads never collide.## scripts/ship-ios-testflight.sh [--ref <git-ref>] [--working-tree]-# [--no-distribute]## A TestFlight build has to be reproducible, so the archive is cut from a# committed tree: the script checks the ref out into its own worktree under@@ -13,16 +12,9 @@# of it. --working-tree archives the checkout as it stands instead, for trying# a build before committing it.#-# Auth uses the Apple ID session stored by Xcode. To run unattended (CI),-# provide an App Store Connect API key instead:-# DONKEY_ASC_KEY_P8_PATH=/path/AuthKey_XXXX.p8-# DONKEY_ASC_KEY_ID=XXXX-# DONKEY_ASC_ISSUER_ID=uuid-#-# With that key present the ship also hands the build to the external testers:-# scripts/asc-distribute.mjs runs on after processing finishes, adds the build-# to every external group, and submits it for beta review. --no-distribute-# leaves the build for App Store Connect.+# The upload lands the build in App Store Connect → TestFlight. Internal+# testers get it once processing finishes; releasing it to external groups is+# done in App Store Connect.set -euo pipefailROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"@@ -34,13 +26,11 @@ LOCAL_INPUTS=(apps/ios/Config/Donkey.local.xcconfig)REF="HEAD"WORKING_TREE=0-DISTRIBUTE=1while [[ $# -gt 0 ]]; docase "$1" in--ref) REF="${2:?--ref needs a git ref}"; shift 2 ;;--working-tree) WORKING_TREE=1; shift ;;- --no-distribute) DISTRIBUTE=0; shift ;;- -h|--help) sed -n '2,25p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;+ -h|--help) sed -n '2,17p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;*) echo "Unknown option: $1" >&2; exit 2 ;;esacdone@@ -94,15 +84,6 @@ cat > "$EXPORT_PLIST" <<'PLIST'</plist>PLIST-AUTH_ARGS=()-if [[ -n "${DONKEY_ASC_KEY_P8_PATH:-}" ]]; then- AUTH_ARGS=(- -authenticationKeyPath "$DONKEY_ASC_KEY_P8_PATH"- -authenticationKeyID "$DONKEY_ASC_KEY_ID"- -authenticationKeyIssuerID "$DONKEY_ASC_ISSUER_ID"- )-fi-echo "==> Archiving"rm -rf "$ARCHIVE"xcodebuild archive \@@ -113,30 +94,12 @@ xcodebuild archive \-archivePath "$ARCHIVE" \-derivedDataPath "$DERIVED" \-allowProvisioningUpdates \- ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"} \-quietecho "==> Uploading to App Store Connect"-UPLOAD_START="$(date +%s)"xcodebuild -exportArchive \-archivePath "$ARCHIVE" \-exportOptionsPlist "$EXPORT_PLIST" \- -allowProvisioningUpdates \- ${AUTH_ARGS[@]+"${AUTH_ARGS[@]}"}+ -allowProvisioningUpdatesecho "==> Uploaded. The build appears in App Store Connect → TestFlight after processing."--# Processing runs for minutes after the upload returns, so handing the build to-# the testers happens on its own clock: the ship ends here and the distributor-# keeps polling in the background.-if (( DISTRIBUTE )); then- if [[ -n "${DONKEY_ASC_KEY_P8_PATH:-}" ]] || compgen -G "$HOME/.appstoreconnect/private_keys/AuthKey_*.p8" >/dev/null; then- DIST_LOG="$ROOT/dist/asc-distribute.log"- nohup node "$ROOT/scripts/asc-distribute.mjs" \- --uploaded-after "$UPLOAD_START" >"$DIST_LOG" 2>&1 &- echo "==> Handing the build to the external testers in the background ($DIST_LOG)"- else- echo "==> No App Store Connect API key; the build waits for a manual release." >&2- echo " Add one (Users and Access → Integrations) to distribute every ship." >&2- fi-fi