diff --git a/.agents/skills/desktop-release/SKILL.md b/.agents/skills/desktop-release/SKILL.md index 2ccd56207..abcdb699a 100644 --- a/.agents/skills/desktop-release/SKILL.md +++ b/.agents/skills/desktop-release/SKILL.md @@ -1,23 +1,45 @@ --- name: desktop-release -description: Perform a regular desktop release from the dev branch. Gathers commits since last release, updates changelog, evaluates mainHash changes, bumps version, and creates release PR. +description: Perform a regular desktop release from the dev branch. Gather changes since the last desktop tag, update the changelog, choose the desktop release mode in release-plan.json, bump the version, and prepare the release PR. disable-model-invocation: true allowed-tools: Bash, Read, Write, Edit, Glob, Grep --- # Desktop Regular Release -Perform a regular desktop release. This skill handles the full release workflow from the `dev` branch. +Perform a regular desktop release from the `dev` branch. + +This workflow is now file-driven: + +- `apps/desktop/changelog/next.md` is the human-edited changelog draft. +- `apps/desktop/release-plan.json` is the human-edited release intent. +- `pnpm --dir apps/desktop bump` applies both inputs, writes `apps/desktop/release.json`, resets `apps/desktop/release-plan.json`, bumps the version, creates `release/desktop/{NEW_VERSION}`, pushes it, and opens the PR. + +Important notes: + +- `mainHash` is still regenerated automatically, but it is **not** the OTA compatibility switch anymore. Do not use it as the release decision point. +- `runtimeVersion` in `apps/desktop/package.json` is the desktop OTA compatibility key. `apps/desktop/scripts/apply-release-config.impl.ts` writes it during bump. +- This skill covers the normal `build` and `ota` desktop release flow. +- Do not recommend or write any other mode. The current implementation only supports `build` and `ota`. ## Pre-flight checks 1. Confirm the current branch is `dev`. If not, abort with a warning. 2. Run `git pull --rebase` in the repo root to ensure the local branch is up to date. -3. Read `apps/desktop/package.json` to get the current `version` and `mainHash`. +3. Read: + - `apps/desktop/package.json` + - `apps/desktop/release-plan.json` + - `apps/desktop/release.json` + - `apps/desktop/bump.config.ts` +4. Record the current: + - `version` + - `runtimeVersion` + - `release-plan.json` contents +5. Note that `pnpm --dir apps/desktop bump` will push a branch and open a PR. Do not run it without explicit user approval. -## Step 1: Gather changes since last release +## Step 1: Gather changes since last desktop release -1. Find the last release tag: +1. Find the last desktop release tag: ```bash git tag --sort=-creatordate | grep '^desktop/v' | head -1 ``` @@ -26,138 +48,170 @@ Perform a regular desktop release. This skill handles the full release workflow git log ..HEAD --oneline --no-merges ``` 3. Categorize commits into: - - **Shiny new things** (feat: commits, new features) - - **Improvements** (refactor:, perf:, chore: improvements, dependency updates) - - **No longer broken** (fix: commits, bug fixes) - - **Thanks** (identify external contributor GitHub usernames from commits) + - **Shiny new things** + - **Improvements** + - **No longer broken** + - **Thanks** -## Step 2: Update changelog +## Step 2: Update changelog draft 1. Read `apps/desktop/changelog/next.md`. -2. Present the categorized changes to the user and draft the changelog content. -3. Wait for user confirmation or edits before writing. -4. Write the final content to `apps/desktop/changelog/next.md`, following the template format: +2. Draft the changelog content from the categorized commits. +3. Present the draft to the user. +4. Wait for user confirmation or edits before writing. +5. Write the final content to `apps/desktop/changelog/next.md` using the existing template structure. +6. Keep `NEXT_VERSION` as the placeholder. `apps/desktop/scripts/apply-changelog.ts` replaces it during bump. - ```markdown - # What's new in vNEXT_VERSION +## Step 3: Choose the desktop release mode - ## Shiny new things +This replaces the old `mainHash` decision. - - description of new feature +Inspect runtime-affecting changes since the last desktop tag: - ## Improvements +```bash +git diff ..HEAD --name-only -- \ + apps/desktop/layer/main/ \ + apps/desktop/layer/preload/ \ + apps/desktop/forge.config.cts \ + apps/desktop/resources/ \ + apps/desktop/scripts/ \ + apps/desktop/package.json +``` - - description of improvement +Use this decision table: - ## No longer broken +- `build` + Use this when the release requires a new binary. + Typical triggers: + - main process changes + - preload or IPC changes + - updater flow changes + - Electron / Forge / packaging / signing changes + - native resource changes + - dependency or package changes that affect runtime behavior - - description of fix +- `ota` + Use this when the release is renderer-compatible with an already-installed binary. + Typical triggers: + - renderer UI changes + - web behavior changes + - shared frontend logic changes that do not require a new desktop binary - ## Thanks + For `ota`, you must choose: + - `runtimeVersion`: the newest installed desktop binary version that this renderer update is compatible with + - `channel`: usually `stable` - Special thanks to volunteer contributors @username for their valuable contributions - ``` + If you are unsure whether a change is binary-compatible, prefer `build`. -5. Keep `NEXT_VERSION` as the placeholder - it will be replaced by `apply-changelog.ts` during bump. +Present the analysis to the user with: -## Step 3: Commit changelog updates before bump +- changed runtime-affecting files +- summary of what changed +- recommended mode: `build` or `ota` +- recommended `release-plan.json` +- explicit request for confirmation -`nbump` requires a clean working tree. Commit changelog edits before running bump. +## Step 4: Update release inputs -1. Stage the changelog update: - ```bash - git add apps/desktop/changelog/next.md - ``` -2. Commit it on `dev`: - ```bash - git commit -m "docs(desktop): prepare release changelog" - ``` -3. If there are no changes to commit, continue without creating an extra commit. +1. Edit `apps/desktop/changelog/next.md`. +2. Edit `apps/desktop/release-plan.json`. +3. Do **not** edit `apps/desktop/release.json` directly. It is generated during bump. +4. Because `nbump` requires a clean working tree, commit the release inputs before bump. -## Step 4: Evaluate mainHash +Stage the inputs: -This is critical for determining whether users need a full app update or can use the lightweight renderer hot update. +```bash +git add apps/desktop/changelog/next.md apps/desktop/release-plan.json +``` -1. Check what files changed in `apps/desktop/layer/main/` since the last release tag: - ```bash - git diff ..HEAD --name-only -- apps/desktop/layer/main/ - ``` -2. Also check changes to `apps/desktop/package.json` fields other than version/mainHash (since package.json is included in the hash calculation): - ```bash - git diff ..HEAD -- apps/desktop/package.json - ``` +Commit them on `dev`: -**Decision logic:** +```bash +git commit -m "docs(desktop): prepare release inputs" +``` -- If there are **NO changes** in `layer/main/` and no meaningful `package.json` changes (only version/mainHash/changelog-related), then mainHash should NOT be updated. Users will get a fast renderer-only hot update. -- If there are **trivial changes** in `layer/main/` (typo fixes, comment changes, logging tweaks) that don't affect runtime behavior, recommend NOT updating mainHash. Present the changes to the user and ask for confirmation. -- If there are **meaningful changes** in `layer/main/` (new features, bug fixes, dependency changes, API changes), mainHash MUST be updated. Users will need a full app update. +If there are no changes to commit, continue. -Present your analysis to the user with: +## Step 5: Run the bump -- List of changed files in `layer/main/` -- A summary of what changed -- Your recommendation (update or skip mainHash) -- Ask for explicit confirmation +Do not execute this step until the user explicitly approves pushing code. -## Step 5: Save old mainHash and execute bump +Run: -1. Save the current mainHash from `apps/desktop/package.json` for later comparison. -2. Verify working tree is clean before bump: - ```bash - git status --short - ``` -3. Change directory to `apps/desktop/` and run the bump: - ```bash - cd apps/desktop && pnpm bump - ``` -4. This command will: - - Pull latest changes - - Apply changelog (rename next.md to {version}.md, create new next.md) - - Recalculate mainHash and write to package.json - - Format package.json - - Bump minor version - - Commit with message `release(desktop): release v{NEW_VERSION}` - - Create branch `release/desktop/{NEW_VERSION}` - - Push branch and create PR to `main` +```bash +pnpm --dir apps/desktop bump +``` -## Step 6: Restore mainHash if skipping update +This command currently does all of the following: -If Step 4 decided mainHash should NOT be updated, restore the old value now. The bump has already committed, pushed, and created the PR on a new release branch, so we amend the commit and force push. This is safe because the release branch was just created. +- pulls latest changes +- applies the changelog +- regenerates `mainHash` +- runs `apps/desktop/scripts/apply-release-config.ts ${NEW_VERSION}` +- writes `apps/desktop/release.json` +- updates `apps/desktop/package.json` `runtimeVersion` +- resets `apps/desktop/release-plan.json` back to the default `build` template +- commits `release(desktop): release v{NEW_VERSION}` +- creates `release/desktop/{NEW_VERSION}` +- pushes the branch +- creates a PR to `main` -1. Change back to the repo root first (Step 5 left the working directory at `apps/desktop/`): - ```bash - cd ../.. - ``` -2. Ensure you are on the `release/desktop/{NEW_VERSION}` branch (bump should have switched to it). -3. Replace the recalculated mainHash with the saved old value in `apps/desktop/package.json`. -4. Stage and amend the release commit: - ```bash - git add apps/desktop/package.json && git commit --amend --no-edit - ``` -5. Force push the release branch: - ```bash - git push --force origin release/desktop/{NEW_VERSION} - ``` +## Step 6: Verify the generated release state -If Step 4 decided mainHash SHOULD be updated, skip this step entirely — the bump already wrote the correct new value. +After bump completes, verify: -## Step 7: Verify +1. Current branch is `release/desktop/{NEW_VERSION}`. +2. `apps/desktop/package.json` has the expected: + - `version` + - `runtimeVersion` +3. `apps/desktop/release.json` matches the intended mode and release settings. +4. `apps/desktop/release-plan.json` was reset to the default template. +5. The PR was created successfully. -1. Confirm the PR was created successfully by checking the output. -2. Report the new version number and PR URL to the user. -3. Summarize: - - New version: v{NEW_VERSION} - - mainHash updated: yes/no (and why) - - Changelog highlights - - PR URL +Also note what will happen after merge: + +- merging the PR to `main` triggers `.github/workflows/tag.yml` +- `tag.yml` creates `desktop/v{NEW_VERSION}` +- `tag.yml` dispatches `.github/workflows/build-desktop.yml` +- `build-desktop.yml` publishes the desktop release draft + +Expected release artifacts by mode: + +- `build` + publishes binary artifacts and desktop binary metadata (`ota-release.json`) + +- `ota` + publishes binary artifacts, desktop binary metadata, and renderer OTA assets such as: + - `apps/desktop/dist/manifest.yml` + - `apps/desktop/dist/*.tar.gz` + - `apps/desktop/dist/ota-release.json` + - `apps/desktop/dist.tar.zst` + +## Step 7: Report back to the user + +Summarize: + +- new version: `v{NEW_VERSION}` +- release mode: `build` or `ota` +- `runtimeVersion` +- renderer OTA included: yes or no +- release branch +- PR URL +- short changelog highlights + +When mentioning `mainHash`, only describe it as "regenerated automatically", never as the release decision mechanism. ## Reference - Bump config: `apps/desktop/bump.config.ts` - Changelog dir: `apps/desktop/changelog/` - Changelog template: `apps/desktop/changelog/next.template.md` -- mainHash generator: `apps/desktop/plugins/vite/generate-main-hash.ts` -- Hot updater logic: `apps/desktop/layer/main/src/updater/hot-updater.ts` -- CI build workflow: `.github/workflows/build-desktop.yml` -- Tag workflow: `.github/workflows/tag.yml` +- Changelog apply script: `apps/desktop/scripts/apply-changelog.ts` +- Release plan input: `apps/desktop/release-plan.json` +- Generated release config: `apps/desktop/release.json` +- Release config apply script: `apps/desktop/scripts/apply-release-config.impl.ts` +- Desktop release config resolver: `.github/scripts/resolve-desktop-release-config.mjs` +- Desktop OTA metadata builder: `.github/scripts/build-ota-release.mjs` +- Desktop build workflow: `.github/workflows/build-desktop.yml` +- Tag orchestrator: `.github/workflows/tag.yml` +- Desktop hot updater: `apps/desktop/layer/main/src/updater/hot-updater.ts` diff --git a/.agents/skills/mobile-release/SKILL.md b/.agents/skills/mobile-release/SKILL.md index 308abb965..8c30f1a72 100644 --- a/.agents/skills/mobile-release/SKILL.md +++ b/.agents/skills/mobile-release/SKILL.md @@ -1,132 +1,205 @@ --- name: mobile-release -description: Perform a regular mobile release from the dev branch. Gathers commits since last release, updates changelog, bumps version, updates iOS Info.plist, and creates release PR to mobile-main. +description: Use when preparing a mobile release from the dev branch and deciding whether changes should ship through the app stores or through the OTA pipeline before creating the release PR to mobile-main. disable-model-invocation: true allowed-tools: Bash, Read, Write, Edit, Glob, Grep --- -# Mobile Regular Release +# Mobile Release -Perform a regular mobile release. This skill handles the full release workflow from the `dev` branch. +Perform a mobile release from `dev`, with an explicit release-mode decision before the bump. + +The skill must recommend one of these modes, explain why, ask the user to confirm, and then write `apps/mobile/release-plan.json` before running the bump: + +- `store`: normal App Store / Google Play release +- `ota`: OTA-only publish, no store builds + +Do not recommend or write any other mode. The current implementation only supports `store` and `ota`. + +The CI release flow is file-driven: + +- `apps/mobile/release-plan.json` is the editable plan on `dev` +- `pnpm bump` runs `apps/mobile/scripts/apply-release-config.ts` +- that script writes `apps/mobile/release.json` for the new version and resets the plan back to a safe default +- GitHub Actions reads `apps/mobile/release.json` after merge to decide which pipelines to trigger ## Pre-flight checks 1. Confirm the current branch is `dev`. If not, abort with a warning. -2. Run `git pull --rebase` in the repo root to ensure the local branch is up to date. -3. Read `apps/mobile/package.json` to get the current `version`. +2. Run `git pull --rebase` in the repo root. +3. Read: + - `apps/mobile/package.json` + - `apps/mobile/release-plan.json` + - `.github/workflows/tag.yml` + - `.github/workflows/publish-ota.yml` ## Step 1: Gather changes since last release -1. Find the last release tag (both old `mobile@` and new `mobile/v` prefixes exist): +1. Find the last mobile tag: ```bash git tag --sort=-creatordate | grep -E '^mobile[@/]' | head -1 ``` -2. If no tag found, find the last release commit by matching only the subject line: +2. If no tag exists, fall back to the last release commit subject: ```bash - git log --format="%H %s" | grep "^[a-f0-9]* release(mobile): release v" | head -1 | awk '{print $1}' + git log --format="%H %s" | grep -Ei "^[a-f0-9]* release\\(mobile\\): release v" | head -1 | awk '{print $1}' ``` -3. Get all commits since the last release on the current branch: +3. Collect commits since that point: ```bash git log ..HEAD --oneline --no-merges ``` -4. Categorize commits into: - - **Shiny new things** (feat: commits, new features) - - **Improvements** (refactor:, perf:, chore: improvements, dependency updates) - - **No longer broken** (fix: commits, bug fixes) - - **Thanks** (identify external contributor GitHub usernames from commits) +4. Collect changed files: + ```bash + git diff --name-only ..HEAD + ``` +5. Categorize commits into: + - `Shiny new things` + - `Improvements` + - `No longer broken` + - `Thanks` -## Step 2: Update changelog +## Step 2: Recommend a release mode + +### Recommend `store` when: + +- any native or binary-affecting paths changed, for example: + - `apps/mobile/ios/**` + - `apps/mobile/android/**` + - `apps/mobile/native/**` + - `apps/mobile/package.json` + - `apps/mobile/app.config.ts` + - `apps/mobile/app.config.base.ts` + - `apps/mobile/eas.json` + - `apps/mobile/ios/Folo/Info.plist` + - `.github/workflows/build-ios.yml` + - `.github/workflows/build-android.yml` +- Expo / React Native / native dependency changes require a new binary +- permissions, entitlements, icons, splash, Firebase config, or build configuration changed + +### Recommend `ota` when: + +- changes are limited to JS/TS/assets that the current binary can already run +- no native or runtime-affecting paths changed +- the goal is to ship without store review + +### Determine the target runtime + +If recommending `ota`, derive the target store binary version from recent `origin/mobile-main` releases and propose it as the `runtimeVersion`. + +If you cannot determine the runtime confidently, stop and ask the user to confirm it. + +### Confirmation gate + +Present: + +- the recommended mode +- rationale based on changed files and commits +- for `ota`, the proposed `runtimeVersion` +- for `ota`, the proposed `channel` + +Wait for explicit user confirmation before continuing. + +## Step 3: Write the release plan file + +Update `apps/mobile/release-plan.json` to match the confirmed mode. + +Examples: + +### Store release + +```json +{ + "mode": "store", + "runtimeVersion": null, + "channel": null +} +``` + +### OTA release + +```json +{ + "mode": "ota", + "runtimeVersion": "0.4.1", + "channel": "production" +} +``` + +## Step 4: Update changelog 1. Read `apps/mobile/changelog/next.md`. -2. Present the categorized changes to the user and draft the changelog content. +2. Present the categorized changes and draft changelog content. 3. Wait for user confirmation or edits before writing. -4. Write the final content to `apps/mobile/changelog/next.md`, following the template format: +4. Write the final content to `apps/mobile/changelog/next.md`. - ```markdown - # What's New in vNEXT_VERSION +## Step 5: Commit pre-bump files before bump - ## Shiny new things +`nbump` requires a clean working tree. - - description of new feature - - ## Improvements - - - description of improvement - - ## No longer broken - - - description of fix - - ## Thanks - - Special thanks to volunteer contributors @username for their valuable contributions - ``` - -5. Keep `NEXT_VERSION` as the placeholder - it will be replaced by `apply-changelog.ts` during bump. - -## Step 3: Commit changelog updates before bump - -`nbump` requires a clean working tree. Commit changelog edits before running bump. - -1. Stage the changelog update: +1. Stage: ```bash - git add apps/mobile/changelog/next.md + git add apps/mobile/changelog/next.md apps/mobile/release-plan.json ``` -2. Commit it on `dev`: +2. Commit: ```bash - git commit -m "docs(mobile): prepare release changelog" + git commit -m "docs(mobile): prepare release metadata" ``` -3. If there are no changes to commit, continue without creating an extra commit. +3. If nothing changed, continue. -## Step 4: Execute bump +## Step 6: Execute bump -1. Verify working tree is clean before bump: +1. Verify the working tree is clean: ```bash git status --short ``` -2. Change directory to `apps/mobile/` and run the bump: +2. Run: ```bash cd apps/mobile && pnpm bump ``` -3. This is an interactive `nbump` command that prompts for version selection. It will: - - Pull latest changes - - Apply changelog (rename next.md to {version}.md, create new next.md from template) - - Format package.json with eslint + prettier - - Bump version in `package.json` - - Update `ios/Folo/Info.plist`: - - Set `CFBundleShortVersionString` to the new version - - Increment `CFBundleVersion` (build number) by 1 - - Commit with message `release(mobile): release v{NEW_VERSION}` - - Create branch `release/mobile/{NEW_VERSION}` - - Push branch and create PR to `mobile-main` +3. `pnpm bump` will: + - apply changelog + - bump `package.json` + - update `ios/Folo/Info.plist` + - run `tsx scripts/apply-release-config.ts ${NEW_VERSION}` + - write `apps/mobile/release.json` + - reset `apps/mobile/release-plan.json` back to the safe default `store` + - create the release branch + - push the branch + - open a PR to `mobile-main` -## Step 5: Verify +## Step 7: Verify and report -1. Confirm the PR was created successfully by checking the output. -2. Report the new version number and PR URL to the user. -3. Summarize: - - New version: v{NEW_VERSION} - - Changelog highlights +1. Confirm the PR was created successfully. +2. Read `apps/mobile/release.json` on the release branch and report: + - new version + - final release mode + - runtimeVersion and channel if present - PR URL +3. Summarize expected post-merge automation: -## Post-release (manual steps, inform user) +### `mode=store` -After the release PR is merged to `mobile-main`: +- create mobile tag +- trigger preview Android build +- trigger production Android build +- trigger production iOS build +- no OTA publish -1. **Trigger production builds** via GitHub Actions `workflow_dispatch`: - - Go to "Build iOS" workflow, select `mobile-main` branch, profile = `production` - - Go to "Build Android" workflow, select `mobile-main` branch, profile = `production` -2. Production builds auto-submit to App Store (via `eas submit`) and Google Play (as draft). -3. After submission, go to App Store Connect and Google Play Console to complete the review/release process. +### `mode=ota` -## Reference +- create mobile tag +- trigger OTA publish only +- no store builds + +## References - Bump config: `apps/mobile/bump.config.ts` +- Release plan: `apps/mobile/release-plan.json` +- Release config: `apps/mobile/release.json` +- Apply release config script: `apps/mobile/scripts/apply-release-config.ts` - Changelog dir: `apps/mobile/changelog/` -- Changelog template: `apps/mobile/changelog/next.template.md` - Apply changelog script: `apps/mobile/scripts/apply-changelog.ts` -- EAS config: `apps/mobile/eas.json` +- Release config resolver: `.github/scripts/resolve-mobile-release-config.mjs` +- Tag orchestration: `.github/workflows/tag.yml` +- OTA publish workflow: `.github/workflows/publish-ota.yml` - App config: `apps/mobile/app.config.ts` - iOS Info.plist: `apps/mobile/ios/Folo/Info.plist` -- CI build iOS: `.github/workflows/build-ios.yml` -- CI build Android: `.github/workflows/build-android.yml` diff --git a/.github/scripts/build-ota-release.mjs b/.github/scripts/build-ota-release.mjs new file mode 100644 index 000000000..dc5a8a451 --- /dev/null +++ b/.github/scripts/build-ota-release.mjs @@ -0,0 +1,925 @@ +#!/usr/bin/env node + +import { spawn, spawnSync } from "node:child_process" +import { createHash } from "node:crypto" +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs" +import { mkdir, readFile, writeFile } from "node:fs/promises" +import { fileURLToPath } from "node:url" + +import yaml from "js-yaml" +import { dirname, extname, join, resolve } from "pathe" + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = resolve(SCRIPT_DIR, "..", "..") +const DEFAULT_MOBILE_PROJECT_DIR = join(REPO_ROOT, "apps", "mobile") +const DEFAULT_DESKTOP_PROJECT_DIR = join(REPO_ROOT, "apps", "desktop") +const OTA_PLATFORMS = ["ios", "android"] +const DESKTOP_PLATFORMS = new Set(["macos", "windows", "linux"]) +const DESKTOP_DEFAULT_CHANNEL = "stable" +const CONTENT_TYPES = new Map([ + [".aac", "audio/aac"], + [".bmp", "image/bmp"], + [".bundle", "application/javascript"], + [".css", "text/css"], + [".gif", "image/gif"], + [".gz", "application/gzip"], + [".hbc", "application/javascript"], + [".html", "text/html"], + [".jpeg", "image/jpeg"], + [".jpg", "image/jpeg"], + [".js", "application/javascript"], + [".json", "application/json"], + [".m4a", "audio/mp4"], + [".mp3", "audio/mpeg"], + [".mp4", "video/mp4"], + [".otf", "font/otf"], + [".pdf", "application/pdf"], + [".png", "image/png"], + [".svg", "image/svg+xml"], + [".ttf", "font/ttf"], + [".txt", "text/plain; charset=utf-8"], + [".wav", "audio/wav"], + [".webm", "video/webm"], + [".webp", "image/webp"], + [".woff", "font/woff"], + [".woff2", "font/woff2"], + [".xml", "application/xml"], +]) +const DESKTOP_MANIFEST_FILE_NAMES = new Set(["latest.yml", "latest-mac.yml", "latest-linux.yml"]) + +/** + * @typedef {{ + * path: string + * ext?: string + * }} ExportAssetMetadata + */ + +/** + * @typedef {{ + * path: string + * sha256: string + * contentType: string + * }} OtaAsset + */ + +/** + * @typedef {{ + * bundle: string + * assets?: unknown[] + * }} ExportPlatformMetadata + */ + +/** + * @typedef {{ + * fileMetadata?: Partial> + * }} ExportMetadata + */ + +/** + * @typedef {{ + * product: string + * channel: string + * releaseVersion: string + * releaseKind: string + * runtimeVersion: string + * gitTag: string + * gitCommit: string + * publishedAt: string + * policy: { + * storeRequired: boolean + * minSupportedBinaryVersion: string + * message: string | null + * } + * metadata: ExportMetadata + * resolveAsset: (asset: ExportAssetMetadata) => Promise + * }} BuildOtaMetadataInput + */ + +/** + * @param {BuildOtaMetadataInput} input + */ +export async function buildOtaMetadata(input) { + /** @type {Record} */ + const platforms = {} + + if (input.releaseKind === "ota") { + const fileMetadata = resolveExportFileMetadata(input.metadata) + + for (const platform of OTA_PLATFORMS) { + const platformMetadata = resolvePlatformMetadata(fileMetadata, platform) + const launchAsset = { path: normalizeAssetPath(platformMetadata.bundle) } + const assets = collectAssets(platformMetadata.assets, platform) + + platforms[platform] = { + launchAsset: await input.resolveAsset(launchAsset), + assets: await Promise.all(assets.map((asset) => input.resolveAsset(asset))), + } + } + } + + return { + schemaVersion: 1, + updateId: createDeterministicUuid( + `${input.product}:${input.channel}:${input.releaseVersion}:${input.runtimeVersion}:${input.gitTag}:${input.gitCommit}`, + ), + product: input.product, + channel: input.channel, + releaseVersion: input.releaseVersion, + releaseKind: input.releaseKind, + runtimeVersion: input.runtimeVersion, + publishedAt: input.publishedAt, + git: { + tag: input.gitTag, + commit: input.gitCommit, + }, + policy: input.policy, + platforms, + } +} + +function createDeterministicUuid(seed) { + const digest = createHash("sha1").update(seed).digest() + const bytes = Buffer.from(digest.subarray(0, 16)) + + bytes[6] = (bytes[6] & 0x0f) | 0x50 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + + const hex = bytes.toString("hex") + return [ + hex.slice(0, 8), + hex.slice(8, 12), + hex.slice(12, 16), + hex.slice(16, 20), + hex.slice(20, 32), + ].join("-") +} + +export async function buildReleaseAssets(options = {}) { + const projectDir = resolveMobileProjectDir(options.projectDir) + const distDir = join(projectDir, "dist") + const metadataPath = join(distDir, "metadata.json") + const archivePath = join(projectDir, "dist.tar.zst") + + const packageJson = await readJson(join(projectDir, "package.json")) + const product = process.env.OTA_PRODUCT ?? "mobile" + const channel = process.env.OTA_CHANNEL ?? "production" + const releaseVersion = process.env.OTA_RELEASE_VERSION ?? packageJson.version + const releaseKind = process.env.OTA_RELEASE_KIND ?? "ota" + const runtimeVersion = process.env.OTA_RUNTIME_VERSION ?? packageJson.version + const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}` + const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT) + const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString() + + if (releaseKind === "ota" && !existsSync(metadataPath)) { + throw new Error( + `Missing Expo export metadata at ${metadataPath}. Run "pnpm --dir apps/mobile run update:export" first.`, + ) + } + + const metadata = releaseKind === "ota" ? await readJson(metadataPath) : { fileMetadata: {} } + + const otaMetadata = await buildOtaMetadata({ + product, + channel, + releaseVersion, + releaseKind, + runtimeVersion, + gitTag, + gitCommit, + publishedAt, + policy: { + storeRequired: parseBooleanEnv("OTA_STORE_REQUIRED", false), + minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? runtimeVersion, + message: parseNullableEnv("OTA_POLICY_MESSAGE"), + }, + metadata, + resolveAsset: async (asset) => { + const assetFilePath = join(distDir, asset.path) + let assetBuffer + + try { + assetBuffer = await readFile(assetFilePath) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error( + `Failed to read exported asset "${asset.path}" at ${assetFilePath}: ${reason}`, + ) + } + + return { + path: asset.path, + sha256: createHash("sha256").update(assetBuffer).digest("hex"), + contentType: resolveContentType(asset), + } + }, + }) + + const outputPath = join(distDir, "ota-release.json") + + await mkdir(distDir, { recursive: true }) + await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8") + + if (releaseKind === "ota") { + await createTarZstArchive({ distDir, archivePath }) + } + + return { + projectDir, + distDir, + metadataPath, + outputPath, + archivePath: releaseKind === "ota" ? archivePath : null, + otaMetadata, + } +} + +export async function buildDesktopReleaseAssets(options = {}) { + const projectDir = resolveDesktopProjectDir(options.projectDir) + const distDir = join(projectDir, "dist") + const outputPath = join(distDir, "ota-release.json") + const archivePath = join(projectDir, "dist.tar.zst") + const releaseConfig = await readJson(join(projectDir, "release.json")) + const packageJson = await readJson(join(projectDir, "package.json")) + const releaseVersion = releaseConfig.version ?? packageJson.version + const product = process.env.OTA_PRODUCT ?? "desktop" + const gitTag = process.env.OTA_GIT_TAG ?? `${product}/v${releaseVersion}` + const gitCommit = process.env.OTA_GIT_COMMIT ?? execGit(["rev-parse", "HEAD"], REPO_ROOT) + const publishedAt = process.env.OTA_PUBLISHED_AT ?? new Date().toISOString() + const [owner, repo] = resolveRepository(options) + const releaseKind = releaseConfig.mode === "ota" ? "ota" : "binary" + const runtimeVersion = releaseConfig.mode === "ota" ? releaseConfig.runtimeVersion : null + const channel = releaseConfig.channel ?? DESKTOP_DEFAULT_CHANNEL + const desktopApp = await collectDesktopAppPayload({ + projectDir, + owner, + repo, + gitTag, + }) + + if (!desktopApp) { + throw new Error( + `Desktop ${releaseConfig.mode} mode requires direct installer manifests in ${join(projectDir, "out", "make")}`, + ) + } + const desktopRenderer = + releaseConfig.mode === "ota" + ? await collectDesktopRendererPayload({ + projectDir, + owner, + repo, + gitTag, + }) + : null + + await mkdir(distDir, { recursive: true }) + + const otaMetadata = { + schemaVersion: 2, + product, + channel, + releaseVersion, + releaseKind, + runtimeVersion, + publishedAt, + git: { + tag: gitTag, + commit: gitCommit, + }, + policy: { + required: false, + minSupportedBinaryVersion: process.env.OTA_MIN_SUPPORTED_BINARY_VERSION ?? releaseVersion, + message: null, + distributions: {}, + }, + desktop: { + renderer: desktopRenderer, + app: desktopApp, + }, + } + + await writeFile(outputPath, `${JSON.stringify(otaMetadata, null, 2)}\n`, "utf8") + + if (releaseConfig.mode === "ota") { + await createTarZstArchive({ distDir, archivePath }) + } + + return { + projectDir, + distDir, + outputPath, + archivePath: releaseConfig.mode === "ota" ? archivePath : null, + otaMetadata, + } +} + +async function main() { + try { + const result = + (process.env.OTA_PRODUCT ?? "mobile") === "desktop" + ? await buildDesktopReleaseAssets() + : await buildReleaseAssets() + + console.info(`Wrote OTA metadata: ${result.outputPath}`) + if (result.archivePath) { + console.info(`Wrote OTA archive: ${result.archivePath}`) + } + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +/** + * @param {unknown} value + */ +function resolveExportFileMetadata(metadata) { + if (!metadata || typeof metadata !== "object") { + throw new Error("Expo export metadata is missing fileMetadata") + } + + if (!metadata.fileMetadata || typeof metadata.fileMetadata !== "object") { + throw new Error("Expo export metadata is missing fileMetadata") + } + + return metadata.fileMetadata +} + +function resolvePlatformMetadata(fileMetadata, platform) { + const platformMetadata = fileMetadata[platform] + + if (!platformMetadata || typeof platformMetadata !== "object") { + throw new Error(`Expo export metadata is missing ${platform} platform metadata`) + } + + if (typeof platformMetadata.bundle !== "string" || platformMetadata.bundle.length === 0) { + throw new Error(`Expo export metadata is missing ${platform} bundle metadata`) + } + + return platformMetadata +} + +function collectAssets(value, platform) { + if (value == null) { + throw new TypeError(`Expo export metadata is missing ${platform} assets metadata`) + } + + if (!Array.isArray(value)) { + throw new TypeError(`Expo export metadata has invalid ${platform} assets metadata`) + } + + /** @type {Map} */ + const dedupedAssets = new Map() + + for (const asset of value) { + const normalizedAsset = normalizeExportAsset(asset) + const existingAsset = dedupedAssets.get(normalizedAsset.path) + + if (!existingAsset || (!existingAsset.ext && normalizedAsset.ext)) { + dedupedAssets.set(normalizedAsset.path, normalizedAsset) + continue + } + + if (existingAsset.ext && normalizedAsset.ext && existingAsset.ext !== normalizedAsset.ext) { + throw new Error( + `Expo export metadata has conflicting ext values for asset "${normalizedAsset.path}"`, + ) + } + } + + return [...dedupedAssets.values()] +} + +/** + * @param {unknown} asset + */ +function normalizeExportAsset(asset) { + if (typeof asset === "string") { + return { path: normalizeAssetPath(asset) } + } + + if (!asset || typeof asset !== "object") { + throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`) + } + + const assetPath = + "path" in asset && typeof asset.path === "string" + ? asset.path + : "file" in asset && typeof asset.file === "string" + ? asset.file + : null + + if (!assetPath) { + throw new Error(`Unsupported Expo asset metadata entry: ${JSON.stringify(asset)}`) + } + + return { + path: normalizeAssetPath(assetPath), + ...("ext" in asset && asset.ext != null ? { ext: normalizeAssetExtension(asset.ext) } : {}), + } +} + +function normalizeAssetExtension(ext) { + if (typeof ext !== "string") { + throw new TypeError(`Unsupported Expo asset ext metadata: ${JSON.stringify(ext)}`) + } + + const normalizedExt = ext.trim().replace(/^\.+/, "").toLowerCase() + + if (!normalizedExt) { + throw new Error(`Invalid exported asset ext "${ext}"`) + } + + return normalizedExt +} + +function resolveMobileProjectDir(projectDir) { + if (projectDir) { + return resolve(projectDir) + } + + const cwd = resolve(process.cwd()) + + if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "scripts", "expo-update.ts"))) { + return cwd + } + + if (existsSync(join(cwd, "apps", "mobile", "package.json"))) { + return join(cwd, "apps", "mobile") + } + + return DEFAULT_MOBILE_PROJECT_DIR +} + +function resolveDesktopProjectDir(projectDir) { + if (projectDir) { + return resolve(projectDir) + } + + const cwd = resolve(process.cwd()) + + if (existsSync(join(cwd, "package.json")) && existsSync(join(cwd, "release.json"))) { + return cwd + } + + if (existsSync(join(cwd, "apps", "desktop", "package.json"))) { + return join(cwd, "apps", "desktop") + } + + return DEFAULT_DESKTOP_PROJECT_DIR +} + +function normalizeAssetPath(assetPath) { + const normalized = assetPath + .replaceAll("\\", "/") + .replace(/^\/+/, "") + .replace(/^(\.\/)+/, "") + .replaceAll(/\/{2,}/g, "/") + + if (!normalized || normalized.split("/").includes("..")) { + throw new Error(`Invalid exported asset path "${assetPath}"`) + } + + return normalized +} + +function resolveContentType(asset) { + const normalizedPath = String(asset.path).toLowerCase() + const pathExtension = normalizedPath.endsWith(".tar.gz") + ? ".gz" + : extname(normalizedPath).toLowerCase() + const metadataExtension = asset.ext ? `.${asset.ext}` : "" + const extension = pathExtension || metadataExtension + + return CONTENT_TYPES.get(extension) ?? "application/octet-stream" +} + +async function createTarZstArchive({ distDir, archivePath }) { + const zstdBinary = resolveZstdBinary() + + await new Promise((resolvePromise, rejectPromise) => { + let tarExited = false + let zstdExited = false + + const tarProcess = spawn("tar", ["-cf", "-", "-C", distDir, "."], { + stdio: ["ignore", "pipe", "inherit"], + }) + const zstdProcess = spawn(zstdBinary, ["-q", "-f", "-o", archivePath], { + stdio: ["pipe", "inherit", "inherit"], + }) + + const rejectOnce = once((error) => rejectPromise(error)) + const resolveIfComplete = () => { + if (tarExited && zstdExited) { + resolvePromise(void 0) + } + } + + tarProcess.on("error", (error) => { + rejectOnce(new Error(`Failed to run tar: ${error.message}`)) + }) + zstdProcess.on("error", (error) => { + rejectOnce(new Error(`Failed to run zstd: ${error.message}`)) + }) + + tarProcess.stdout.on("error", (error) => { + rejectOnce(new Error(`Failed to stream tar output: ${error.message}`)) + }) + zstdProcess.stdin.on("error", (error) => { + rejectOnce(new Error(`Failed to stream zstd input: ${error.message}`)) + }) + + tarProcess.stdout.pipe(zstdProcess.stdin) + + tarProcess.on("close", (code) => { + if (code !== 0) { + rejectOnce(new Error(`tar exited with code ${code}`)) + return + } + + tarExited = true + resolveIfComplete() + }) + + zstdProcess.on("close", (code) => { + if (code !== 0) { + rejectOnce(new Error(`zstd exited with code ${code}`)) + return + } + + zstdExited = true + resolveIfComplete() + }) + }) +} + +function resolveZstdBinary() { + const candidates = [process.env.ZSTD_BIN, "zstd", "/opt/homebrew/bin/zstd"].filter(Boolean) + + for (const candidate of candidates) { + const args = candidate === "/opt/homebrew/bin/zstd" ? ["--version"] : ["--version"] + const result = spawnSync(candidate, args, { stdio: "ignore" }) + + if (result.status === 0) { + return candidate + } + } + + throw new Error('Unable to find "zstd". Set ZSTD_BIN or install zstd in PATH.') +} + +function execGit(args, cwd) { + const result = spawnSync("git", args, { + cwd, + encoding: "utf8", + }) + + if (result.status !== 0) { + throw new Error(result.stderr?.trim() || `git ${args.join(" ")} failed`) + } + + return result.stdout.trim() +} + +async function readJson(path) { + try { + return JSON.parse(await readFile(path, "utf8")) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to read JSON at ${path}: ${reason}`) + } +} + +async function collectDesktopRendererPayload(input) { + const rendererManifestPath = join(input.projectDir, "dist", "manifest.yml") + + if (!existsSync(rendererManifestPath)) { + throw new Error(`Missing desktop renderer manifest at ${rendererManifestPath}`) + } + + const rendererManifest = parseYamlFile(rendererManifestPath) + + if (typeof rendererManifest.version !== "string" || !rendererManifest.version) { + throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing version`) + } + + if (typeof rendererManifest.commit !== "string" || !rendererManifest.commit) { + throw new Error(`Desktop renderer manifest at ${rendererManifestPath} is missing commit`) + } + + const filename = + typeof rendererManifest.filename === "string" && rendererManifest.filename + ? rendererManifest.filename + : "render-asset.tar.gz" + const rendererArchivePath = join(input.projectDir, "dist", filename) + + if (!existsSync(rendererArchivePath)) { + throw new Error(`Missing desktop renderer archive at ${rendererArchivePath}`) + } + + return { + version: rendererManifest.version, + commit: rendererManifest.commit, + manifest: { + name: "manifest.yml", + downloadUrl: buildGitHubAssetUrl({ + owner: input.owner, + repo: input.repo, + tag: input.gitTag, + filename: "manifest.yml", + }), + }, + launchAsset: await resolveFileAsset({ + sourcePath: rendererArchivePath, + metadataPath: filename, + }), + assets: [], + } +} + +async function collectDesktopAppPayload(input) { + const makeDir = join(input.projectDir, "out", "make") + + if (!existsSync(makeDir)) { + return null + } + + const platformEntries = await collectDesktopPlatformEntries({ + makeDir, + owner: input.owner, + repo: input.repo, + gitTag: input.gitTag, + }) + + if (Object.keys(platformEntries).length === 0) { + return null + } + + return { + platforms: platformEntries, + } +} + +async function collectDesktopPlatformEntries(input) { + /** @type {Record} */ + const result = {} + + for (const manifestPath of walkFiles(input.makeDir)) { + const fileName = manifestPath.split("/").at(-1) + if (!fileName || !DESKTOP_MANIFEST_FILE_NAMES.has(fileName)) { + continue + } + + const manifest = parseYamlFile(manifestPath) + const platformKey = inferDesktopPlatformKey(manifestPath, fileName) + + if (!platformKey || !DESKTOP_PLATFORMS.has(platformKey)) { + continue + } + + const files = normalizeDesktopManifestFiles(manifest.files, manifestPath) + if (files.length === 0) { + continue + } + + const nextEntry = { + platform: inferDesktopPlatformIdentifier(platformKey, manifestPath), + releaseDate: normalizeDesktopReleaseDate(manifest.releaseDate), + manifest: { + name: fileName, + path: fileName, + downloadUrl: buildGitHubAssetUrl({ + owner: input.owner, + repo: input.repo, + tag: input.gitTag, + filename: fileName, + }), + }, + files: files.map((file) => ({ + filename: file.url, + sha512: file.sha512, + size: file.size, + downloadUrl: buildGitHubAssetUrl({ + owner: input.owner, + repo: input.repo, + tag: input.gitTag, + filename: file.url, + }), + })), + } + + result[platformKey] = result[platformKey] + ? mergeDesktopPlatformEntries(result[platformKey], nextEntry) + : nextEntry + } + + return result +} + +function inferDesktopPlatformKey(manifestPath, fileName) { + const normalized = manifestPath.replaceAll("\\", "/").toLowerCase() + + if ( + fileName === "latest-mac.yml" || + normalized.includes("/darwin") || + normalized.includes("/mac") + ) { + return "macos" + } + + if (fileName === "latest-linux.yml" || normalized.includes("/linux")) { + return "linux" + } + + if ( + fileName === "latest.yml" || + normalized.includes("/windows") || + normalized.includes("/squirrel.windows") + ) { + return "windows" + } + + return null +} + +function inferDesktopPlatformIdentifier(platformKey, manifestPath) { + const normalized = manifestPath.replaceAll("\\", "/").toLowerCase() + const arch = normalized.includes("/arm64") ? "arm64" : normalized.includes("/x64") ? "x64" : null + + if (!arch) { + return platformKey + } + + return `${platformKey}-${arch}` +} + +function normalizeDesktopManifestFiles(files, manifestPath) { + if (!Array.isArray(files)) { + throw new TypeError(`Desktop manifest at ${manifestPath} is missing files`) + } + + return files.map((file, index) => { + const url = typeof file?.url === "string" ? file.url : null + const sha512 = typeof file?.sha512 === "string" ? file.sha512 : null + const size = + typeof file?.size === "number" ? file.size : Number.parseInt(String(file?.size ?? 0), 10) + + if (!url || !sha512 || !Number.isFinite(size) || size < 0) { + throw new Error(`Desktop manifest at ${manifestPath} has invalid files[${index}] entry`) + } + + return { + url, + sha512, + size, + } + }) +} + +function normalizeDesktopReleaseDate(value) { + if (typeof value === "string") { + return value + } + + if (value instanceof Date) { + return value.toISOString() + } + + return null +} + +function mergeDesktopPlatformEntries(currentEntry, nextEntry) { + const fileByName = new Map(currentEntry.files.map((file) => [file.filename, file])) + + for (const file of nextEntry.files) { + fileByName.set(file.filename, file) + } + + const mergedReleaseDate = pickLatestReleaseDate(currentEntry.releaseDate, nextEntry.releaseDate) + + return { + platform: + currentEntry.platform === nextEntry.platform + ? currentEntry.platform + : (currentEntry.platform.split("-")[0] ?? currentEntry.platform), + releaseDate: mergedReleaseDate, + manifest: currentEntry.manifest, + files: [...fileByName.values()], + } +} + +function pickLatestReleaseDate(currentValue, nextValue) { + const currentTime = currentValue ? Date.parse(currentValue) : Number.NaN + const nextTime = nextValue ? Date.parse(nextValue) : Number.NaN + + if (Number.isFinite(currentTime) && Number.isFinite(nextTime)) { + return currentTime >= nextTime ? currentValue : nextValue + } + + return nextValue ?? currentValue ?? null +} + +function parseYamlFile(path) { + try { + const content = readFileSync(path, "utf8") + return yaml.load(String(content)) ?? {} + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error(`Failed to parse YAML at ${path}: ${reason}`) + } +} + +async function resolveFileAsset(input) { + const buffer = await readFile(input.sourcePath) + return { + path: normalizeAssetPath(input.metadataPath), + sha256: createHash("sha256").update(buffer).digest("hex"), + contentType: resolveContentType({ path: input.metadataPath }), + } +} + +function buildGitHubAssetUrl({ owner, repo, tag, filename }) { + return `https://github.com/${owner}/${repo}/releases/download/${tag}/${filename}` +} + +function resolveRepository(options) { + if (options.owner && options.repo) { + return [options.owner, options.repo] + } + + const repository = process.env.GITHUB_REPOSITORY + if (repository && repository.includes("/")) { + return repository.split("/", 2) + } + + return ["RSSNext", "Folo"] +} + +function walkFiles(rootDir) { + /** @type {string[]} */ + const results = [] + /** @type {string[]} */ + const pending = [rootDir] + + while (pending.length > 0) { + const current = pending.pop() + if (!current) continue + + for (const entryName of readdirSync(current)) { + const entry = join(current, entryName) + if (!existsSync(entry)) continue + + if (statSync(entry).isDirectory()) { + pending.push(entry) + } else { + results.push(entry) + } + } + } + + return results.sort() +} + +function parseBooleanEnv(name, defaultValue) { + const value = process.env[name] + + if (value == null) { + return defaultValue + } + + if (value === "1" || value.toLowerCase() === "true") { + return true + } + + if (value === "0" || value.toLowerCase() === "false") { + return false + } + + throw new Error(`${name} must be "true", "false", "1", or "0"`) +} + +function parseNullableEnv(name) { + const value = process.env[name] + + if (value == null || value.length === 0) { + return null + } + + return value +} + +function once(callback) { + let called = false + + return (...args) => { + if (called) { + return + } + + called = true + callback(...args) + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) { + await main() +} diff --git a/.github/scripts/build-ota-release.test.ts b/.github/scripts/build-ota-release.test.ts new file mode 100644 index 000000000..1a619d929 --- /dev/null +++ b/.github/scripts/build-ota-release.test.ts @@ -0,0 +1,640 @@ +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" + +import { join } from "pathe" +import { afterEach, describe, expect, it } from "vitest" + +type InputAsset = string | { path: string; ext?: string } + +const tempDirs: string[] = [] + +afterEach(async () => { + await Promise.all( + tempDirs.splice(0).map((directory) => rm(directory, { recursive: true, force: true })), + ) + delete process.env.OTA_RELEASE_KIND + delete process.env.OTA_RELEASE_VERSION + delete process.env.OTA_RUNTIME_VERSION + delete process.env.OTA_CHANNEL + delete process.env.OTA_PRODUCT + delete process.env.OTA_GIT_TAG + delete process.env.OTA_GIT_COMMIT + delete process.env.OTA_PUBLISHED_AT + delete process.env.OTA_STORE_REQUIRED + delete process.env.GITHUB_REPOSITORY +}) + +describe("buildOtaMetadata", () => { + it("preserves releaseVersion, runtimeVersion, and scoped git tag", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + } + }, + }) + + expect(result.releaseVersion).toBe("0.4.2") + expect(result.runtimeVersion).toBe("0.4.1") + expect(result.git.tag).toBe("mobile/v0.4.2") + expect(result.updateId).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ) + }) + + it("uses asset ext metadata when exported asset paths have no suffix", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [{ path: "assets/splash", ext: "png" }], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + const ext = typeof asset === "string" ? undefined : asset.ext + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: ext === "png" ? "image/png" : "application/octet-stream", + } + }, + }) + + expect(result.platforms.ios.assets).toEqual([ + expect.objectContaining({ + path: "assets/splash", + contentType: "image/png", + }), + ]) + }) + + it("fails when a platform bundle is missing from export metadata", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + await expect( + buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + } + }, + }), + ).rejects.toThrow(/android/i) + }) + + it("fails when a platform assets array is missing from export metadata", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + await expect( + buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "application/octet-stream", + } + }, + }), + ).rejects.toThrow(/ios.*assets/i) + }) + + it("deduplicates repeated asset entries after path normalization", async () => { + const { buildOtaMetadata } = await import("./build-ota-release.mjs") + + const resolvedAssets: InputAsset[] = [] + + const result = await buildOtaMetadata({ + product: "mobile", + channel: "production", + releaseVersion: "0.4.2", + releaseKind: "ota", + runtimeVersion: "0.4.1", + gitTag: "mobile/v0.4.2", + gitCommit: "abcdef1234567890", + publishedAt: "2026-04-10T12:00:00.000Z", + policy: { + storeRequired: false, + minSupportedBinaryVersion: "0.4.1", + message: null, + }, + metadata: { + fileMetadata: { + ios: { + bundle: "_expo/static/js/ios/main.hbc", + assets: ["./assets/icon.png", { path: "assets/icon.png" }], + }, + android: { + bundle: "_expo/static/js/android/main.hbc", + assets: [], + }, + }, + }, + resolveAsset: async (asset: InputAsset) => { + resolvedAssets.push(asset) + const assetPath = typeof asset === "string" ? asset : asset.path + + return { + path: assetPath, + sha256: `${assetPath}-sha256`.padEnd(64, "0").slice(0, 64), + contentType: "image/png", + } + }, + }) + + expect(result.platforms.ios.assets).toHaveLength(1) + expect( + resolvedAssets.filter((asset) => { + const assetPath = typeof asset === "string" ? asset : asset.path + + return assetPath === "assets/icon.png" + }), + ).toHaveLength(1) + }) +}) + +describe("buildReleaseAssets", () => { + it("builds metadata-only assets for store releases without Expo export output", async () => { + const { buildReleaseAssets } = await import("./build-ota-release.mjs") + + const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-store-test-")) + tempDirs.push(projectDir) + + await writeFile( + join(projectDir, "package.json"), + JSON.stringify({ name: "@follow/mobile-test", version: "0.4.3" }), + "utf8", + ) + + process.env.OTA_RELEASE_KIND = "store" + process.env.OTA_RELEASE_VERSION = "0.4.3" + process.env.OTA_RUNTIME_VERSION = "0.4.3" + process.env.OTA_CHANNEL = "production" + process.env.OTA_STORE_REQUIRED = "true" + + const result = await buildReleaseAssets({ projectDir }) + + expect(result.otaMetadata.releaseKind).toBe("store") + expect(result.otaMetadata.policy.storeRequired).toBe(true) + expect(result.otaMetadata.platforms).toEqual({}) + expect(result.archivePath).toBeNull() + }) + + it("includes the JSON file path when export metadata cannot be parsed", async () => { + const { buildReleaseAssets } = await import("./build-ota-release.mjs") + + const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-test-")) + const distDir = join(projectDir, "dist") + const metadataPath = join(distDir, "metadata.json") + tempDirs.push(projectDir) + + await mkdir(distDir, { recursive: true }) + await writeFile( + join(projectDir, "package.json"), + JSON.stringify({ name: "@follow/mobile-test", version: "0.4.2" }), + "utf8", + ) + await writeFile(metadataPath, "{invalid", "utf8") + + await expect(buildReleaseAssets({ projectDir })).rejects.toThrow(metadataPath) + }) +}) + +describe("buildDesktopReleaseAssets", () => { + it("builds schemaVersion 2 desktop build metadata with direct app payloads only", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + manifests: [ + { + relativeDir: join("out", "make", "squirrel.windows", "x64"), + manifestName: "latest.yml", + contents: ` +version: 1.5.1 +files: + - url: Folo-1.5.1-windows-x64.exe + sha512: ${"a".repeat(88)} + size: 123456 +releaseDate: 2026-04-11T10:00:00.000Z +`, + }, + ], + }) + + const result = await buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }) + + expect(result.otaMetadata.schemaVersion).toBe(2) + expect(result.otaMetadata.product).toBe("desktop") + expect(result.otaMetadata.releaseKind).toBe("binary") + expect(result.otaMetadata.runtimeVersion).toBeNull() + expect(result.otaMetadata.channel).toBe("stable") + expect(result.otaMetadata.desktop.renderer).toBeNull() + expect(result.otaMetadata.policy.distributions).toEqual({}) + expect(result.otaMetadata.desktop.app.platforms.windows).toEqual( + expect.objectContaining({ + platform: "windows-x64", + releaseDate: "2026-04-11T10:00:00.000Z", + manifest: { + name: "latest.yml", + path: "latest.yml", + downloadUrl: expect.stringContaining("/desktop/v1.5.1/latest.yml"), + }, + files: [ + expect.objectContaining({ + filename: "Folo-1.5.1-windows-x64.exe", + sha512: "a".repeat(88), + size: 123456, + downloadUrl: expect.stringContaining("/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe"), + }), + ], + }), + ) + expect(result.archivePath).toBeNull() + + const written = JSON.parse(await readFile(result.outputPath, "utf8")) + expect(written.schemaVersion).toBe(2) + expect(written.desktop.renderer).toBeNull() + }) + + it("builds schemaVersion 2 desktop ota metadata with renderer and direct app payloads", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "ota", + runtimeVersion: "1.5.0", + channel: "stable", + }, + rendererArchiveContents: "renderer archive", + rendererManifestContents: ` +version: 1.5.1 +hash: ${"b".repeat(64)} +mainHash: ${"c".repeat(40)} +commit: abcdef1234567890 +filename: custom-renderer.tar.gz +`, + manifests: [ + { + relativeDir: join("out", "make", "squirrel.windows", "x64"), + manifestName: "latest.yml", + contents: ` +version: 1.5.1 +files: + - url: Folo-1.5.1-windows-x64.exe + sha512: ${"d".repeat(88)} + size: 654321 +releaseDate: 2026-04-11T10:00:00.000Z +`, + }, + ], + }) + + const result = await buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }) + + expect(result.otaMetadata.schemaVersion).toBe(2) + expect(result.otaMetadata.releaseKind).toBe("ota") + expect(result.otaMetadata.runtimeVersion).toBe("1.5.0") + expect(result.otaMetadata.channel).toBe("stable") + expect(result.otaMetadata.desktop.renderer).toEqual( + expect.objectContaining({ + version: "1.5.1", + commit: "abcdef1234567890", + manifest: { + name: "manifest.yml", + downloadUrl: + "https://github.com/RSSNext/Folo/releases/download/desktop/v1.5.1/manifest.yml", + }, + launchAsset: expect.objectContaining({ + path: "custom-renderer.tar.gz", + contentType: "application/gzip", + }), + }), + ) + expect(result.otaMetadata.desktop.renderer.launchAsset.sha256).toHaveLength(64) + expect(result.otaMetadata.desktop.app.platforms.windows.files[0]?.downloadUrl).toContain( + "/desktop/v1.5.1/Folo-1.5.1-windows-x64.exe", + ) + expect(result.archivePath).not.toBeNull() + }) + + it("fails when a desktop manifest contains an invalid file entry", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + manifests: [ + { + relativeDir: join("out", "make", "squirrel.windows", "x64"), + manifestName: "latest.yml", + contents: ` +version: 1.5.1 +files: + - url: Folo-1.5.1-windows-x64.exe + size: 123456 +releaseDate: 2026-04-11T10:00:00.000Z +`, + }, + ], + }) + + await expect( + buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }), + ).rejects.toThrow(/invalid files\[0\] entry/i) + }) + + it("fails for build mode when direct installer manifests are missing", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + }) + + await expect( + buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }), + ).rejects.toThrow(/requires direct installer manifests/i) + }) + + it("fails for ota mode when direct installer manifests are missing", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "ota", + runtimeVersion: "1.5.0", + channel: "stable", + }, + rendererArchiveContents: "renderer archive", + rendererManifestContents: ` +version: 1.5.1 +hash: ${"2".repeat(64)} +mainHash: ${"3".repeat(40)} +commit: abcdef1234567890 +filename: custom-renderer.tar.gz +`, + }) + + await expect( + buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }), + ).rejects.toThrow(/requires direct installer manifests/i) + }) + + it("merges duplicate desktop platform manifests instead of overwriting them", async () => { + const { buildDesktopReleaseAssets } = await import("./build-ota-release.mjs") + const projectDir = await createDesktopProjectFixture({ + version: "1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + manifests: [ + { + relativeDir: join("out", "make", "squirrel.windows", "x64"), + manifestName: "latest.yml", + contents: ` +version: 1.5.1 +files: + - url: Folo-1.5.1-windows-x64.exe + sha512: ${"e".repeat(88)} + size: 123456 +releaseDate: 2026-04-11T10:00:00.000Z +`, + }, + { + relativeDir: join("out", "make", "squirrel.windows", "arm64"), + manifestName: "latest.yml", + contents: ` +version: 1.5.1 +files: + - url: Folo-1.5.1-windows-arm64.exe + sha512: ${"f".repeat(88)} + size: 234567 +releaseDate: 2026-04-11T11:00:00.000Z +`, + }, + ], + }) + + const result = await buildDesktopReleaseAssets({ + projectDir, + owner: "RSSNext", + repo: "Folo", + }) + + expect(result.otaMetadata.desktop.app.platforms.windows.files).toHaveLength(2) + expect(result.otaMetadata.desktop.app.platforms.windows.releaseDate).toBe( + "2026-04-11T11:00:00.000Z", + ) + }) +}) + +async function createDesktopProjectFixture(input: { + version: string + releaseConfig: { + version: string + mode: "build" | "ota" + runtimeVersion: string | null + channel: "stable" | "beta" | "alpha" | null + } + manifests?: Array<{ + relativeDir: string + manifestName: string + contents: string + }> + rendererArchiveContents?: string + rendererManifestContents?: string +}) { + const projectDir = await mkdtemp(join(tmpdir(), "build-ota-release-desktop-test-")) + tempDirs.push(projectDir) + + await writeFile( + join(projectDir, "package.json"), + JSON.stringify({ name: "@follow/desktop-test", version: input.version }), + "utf8", + ) + await writeFile( + join(projectDir, "release.json"), + `${JSON.stringify(input.releaseConfig, null, 2)}\n`, + "utf8", + ) + + if (input.rendererArchiveContents != null || input.rendererManifestContents != null) { + await mkdir(join(projectDir, "dist"), { recursive: true }) + } + + if (input.rendererArchiveContents != null) { + await writeFile( + join( + projectDir, + "dist", + input.rendererManifestContents?.includes("custom-renderer.tar.gz") + ? "custom-renderer.tar.gz" + : "render-asset.tar.gz", + ), + input.rendererArchiveContents, + "utf8", + ) + } + + if (input.rendererManifestContents != null) { + await writeFile( + join(projectDir, "dist", "manifest.yml"), + input.rendererManifestContents.trimStart(), + "utf8", + ) + } + + for (const manifest of input.manifests ?? []) { + await mkdir(join(projectDir, manifest.relativeDir), { recursive: true }) + await writeFile( + join(projectDir, manifest.relativeDir, manifest.manifestName), + manifest.contents.trimStart(), + "utf8", + ) + } + + return projectDir +} diff --git a/.github/scripts/resolve-desktop-release-config.mjs b/.github/scripts/resolve-desktop-release-config.mjs new file mode 100644 index 000000000..0aa87ccd0 --- /dev/null +++ b/.github/scripts/resolve-desktop-release-config.mjs @@ -0,0 +1,94 @@ +#!/usr/bin/env node + +import { appendFileSync } from "node:fs" +import { readFile } from "node:fs/promises" +import { pathToFileURL } from "node:url" + +const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/ +const VALID_MODES = new Set(["build", "ota"]) +const VALID_CHANNELS = new Set(["stable", "beta", "alpha"]) + +export function resolveDesktopReleaseConfig(input) { + const normalizedReleaseVersion = input.releaseVersion.replace(/^v/, "") + const config = input.releaseConfig + + if (config.version !== normalizedReleaseVersion) { + throw new Error( + `apps/desktop/release.json version ${config.version} does not match release version ${normalizedReleaseVersion}.`, + ) + } + + if (!VALID_MODES.has(config.mode)) { + throw new Error("apps/desktop/release.json mode must be build or ota.") + } + + if (config.mode === "build") { + if (config.runtimeVersion !== null || config.channel !== null) { + throw new Error("desktop build mode must not set runtimeVersion or channel") + } + + return { + triggerDirectBuild: true, + triggerStoreBuilds: true, + runtimeVersion: null, + channel: null, + releaseVersion: normalizedReleaseVersion, + } + } + + if (config.mode === "ota") { + if (!config.runtimeVersion || !SEMVER_PATTERN.test(config.runtimeVersion)) { + throw new Error("apps/desktop/release.json runtimeVersion must be a plain x.y.z version.") + } + + if (!config.channel || !VALID_CHANNELS.has(config.channel)) { + throw new Error("apps/desktop/release.json channel must be stable, beta, or alpha.") + } + + return { + triggerDirectBuild: true, + triggerStoreBuilds: true, + runtimeVersion: config.runtimeVersion, + channel: config.channel, + releaseVersion: normalizedReleaseVersion, + } + } +} + +async function readReleaseConfig(path) { + const raw = await readFile(path, "utf8") + return JSON.parse(raw) +} + +function setGitHubOutput(key, value) { + if (!process.env.GITHUB_OUTPUT) { + return + } + + const delimiter = `__GITHUB_OUTPUT_${key}_${Date.now()}_${Math.random().toString(16).slice(2)}__` + appendFileSync(process.env.GITHUB_OUTPUT, `${key}<<${delimiter}\n${value}\n${delimiter}\n`) +} + +async function main() { + try { + const configPath = process.env.RELEASE_CONFIG_PATH ?? "apps/desktop/release.json" + const releaseConfig = await readReleaseConfig(configPath) + const result = resolveDesktopReleaseConfig({ + releaseVersion: process.env.RELEASE_VERSION ?? "", + releaseConfig, + }) + + setGitHubOutput("triggerDirectBuild", String(result.triggerDirectBuild)) + setGitHubOutput("triggerStoreBuilds", String(result.triggerStoreBuilds)) + setGitHubOutput("runtimeVersion", result.runtimeVersion ?? "") + setGitHubOutput("channel", result.channel ?? "") + setGitHubOutput("releaseVersion", result.releaseVersion) + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main() +} diff --git a/.github/scripts/resolve-desktop-release-config.test.ts b/.github/scripts/resolve-desktop-release-config.test.ts new file mode 100644 index 000000000..55f2974ad --- /dev/null +++ b/.github/scripts/resolve-desktop-release-config.test.ts @@ -0,0 +1,132 @@ +import { execFile } from "node:child_process" +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { promisify } from "node:util" + +import { join } from "pathe" +import { describe, expect, it } from "vitest" + +const execFileAsync = promisify(execFile) + +describe("resolveDesktopReleaseConfig", () => { + it("triggers direct and store builds for build mode", async () => { + const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs") + + expect( + resolveDesktopReleaseConfig({ + releaseVersion: "v1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + }), + ).toEqual({ + triggerDirectBuild: true, + triggerStoreBuilds: true, + runtimeVersion: null, + channel: null, + releaseVersion: "1.5.1", + }) + }) + + it("triggers direct and store builds for ota mode", async () => { + const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs") + + expect( + resolveDesktopReleaseConfig({ + releaseVersion: "v1.5.1", + releaseConfig: { + version: "1.5.1", + mode: "ota", + runtimeVersion: "1.5.0", + channel: "stable", + }, + }), + ).toEqual({ + triggerDirectBuild: true, + triggerStoreBuilds: true, + runtimeVersion: "1.5.0", + channel: "stable", + releaseVersion: "1.5.1", + }) + }) + + it("rejects a release config that does not match the release version", async () => { + const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs") + + expect(() => + resolveDesktopReleaseConfig({ + releaseVersion: "v1.5.2", + releaseConfig: { + version: "1.5.1", + mode: "build", + runtimeVersion: null, + channel: null, + }, + }), + ).toThrow(/does not match release version/i) + }) + + it("rejects build mode when runtimeVersion or channel is set", async () => { + const { resolveDesktopReleaseConfig } = await import("./resolve-desktop-release-config.mjs") + + expect(() => + resolveDesktopReleaseConfig({ + releaseVersion: "v1.5.2", + releaseConfig: { + version: "1.5.2", + mode: "build", + runtimeVersion: "1.5.1", + channel: "stable", + }, + }), + ).toThrow(/must not set runtimeVersion or channel/i) + }) + + it("writes GitHub outputs for ota mode", async () => { + const projectDir = await mkdtemp(join(tmpdir(), "desktop-release-config-output-")) + + try { + const releaseConfigPath = join(projectDir, "release.json") + const githubOutputPath = join(projectDir, "github-output.txt") + + await writeFile( + releaseConfigPath, + `${JSON.stringify( + { + version: "1.5.2", + mode: "ota", + runtimeVersion: "1.5.1", + channel: "beta", + }, + null, + 2, + )}\n`, + "utf8", + ) + + await execFileAsync("node", [".github/scripts/resolve-desktop-release-config.mjs"], { + cwd: process.cwd(), + env: { + ...process.env, + RELEASE_VERSION: "1.5.2", + RELEASE_CONFIG_PATH: releaseConfigPath, + GITHUB_OUTPUT: githubOutputPath, + }, + }) + + const output = await readFile(githubOutputPath, "utf8") + + expect(output).toContain("triggerDirectBuild=true") + expect(output).toContain("triggerStoreBuilds=true") + expect(output).toContain("runtimeVersion<<") + expect(output).toContain("1.5.1") + expect(output).toContain("channel<<") + expect(output).toContain("beta") + } finally { + await rm(projectDir, { recursive: true, force: true }) + } + }) +}) diff --git a/.github/scripts/resolve-mobile-release-config.mjs b/.github/scripts/resolve-mobile-release-config.mjs new file mode 100644 index 000000000..c79808067 --- /dev/null +++ b/.github/scripts/resolve-mobile-release-config.mjs @@ -0,0 +1,87 @@ +#!/usr/bin/env node + +import { appendFileSync } from "node:fs" +import { readFile } from "node:fs/promises" +import { pathToFileURL } from "node:url" + +const SEMVER_PATTERN = /^\d+\.\d+\.\d+$/ +const VALID_MODES = new Set(["store", "ota"]) +const VALID_CHANNELS = new Set(["production", "preview"]) + +export function resolveMobileReleaseConfig(input) { + const normalizedReleaseVersion = input.releaseVersion.replace(/^v/, "") + const config = input.releaseConfig + + if (config.version !== normalizedReleaseVersion) { + throw new Error( + `apps/mobile/release.json version ${config.version} does not match release version ${normalizedReleaseVersion}.`, + ) + } + + if (!VALID_MODES.has(config.mode)) { + throw new Error("apps/mobile/release.json mode must be store or ota.") + } + + if (config.mode === "store") { + return { + triggerStoreBuilds: true, + triggerOtaPublish: false, + runtimeVersion: null, + channel: null, + releaseVersion: normalizedReleaseVersion, + } + } + + if (!config.runtimeVersion || !SEMVER_PATTERN.test(config.runtimeVersion)) { + throw new Error("apps/mobile/release.json runtimeVersion must be a plain x.y.z version.") + } + + if (!config.channel || !VALID_CHANNELS.has(config.channel)) { + throw new Error("apps/mobile/release.json channel must be production or preview.") + } + + return { + triggerStoreBuilds: false, + triggerOtaPublish: true, + runtimeVersion: config.runtimeVersion, + channel: config.channel, + releaseVersion: normalizedReleaseVersion, + } +} + +async function readReleaseConfig(path) { + const raw = await readFile(path, "utf8") + return JSON.parse(raw) +} + +function setGitHubOutput(key, value) { + if (!process.env.GITHUB_OUTPUT) { + return + } + + appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`) +} + +async function main() { + try { + const configPath = process.env.RELEASE_CONFIG_PATH ?? "apps/mobile/release.json" + const releaseConfig = await readReleaseConfig(configPath) + const result = resolveMobileReleaseConfig({ + releaseVersion: process.env.RELEASE_VERSION ?? "", + releaseConfig, + }) + + setGitHubOutput("trigger_store_builds", String(result.triggerStoreBuilds)) + setGitHubOutput("trigger_ota_publish", String(result.triggerOtaPublish)) + setGitHubOutput("runtime_version", result.runtimeVersion ?? "") + setGitHubOutput("channel", result.channel ?? "") + setGitHubOutput("release_version", result.releaseVersion) + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main() +} diff --git a/.github/scripts/resolve-mobile-release-config.test.ts b/.github/scripts/resolve-mobile-release-config.test.ts new file mode 100644 index 000000000..f83c73982 --- /dev/null +++ b/.github/scripts/resolve-mobile-release-config.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest" + +describe("resolveMobileReleaseConfig", () => { + it("defaults to store builds when release.json mode is store", async () => { + const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs") + + expect( + resolveMobileReleaseConfig({ + releaseVersion: "v0.4.2", + releaseConfig: { + version: "0.4.2", + mode: "store", + runtimeVersion: null, + channel: null, + }, + }), + ).toEqual({ + triggerStoreBuilds: true, + triggerOtaPublish: false, + runtimeVersion: null, + channel: null, + releaseVersion: "0.4.2", + }) + }) + + it("triggers OTA publish only for ota mode", async () => { + const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs") + + expect( + resolveMobileReleaseConfig({ + releaseVersion: "v0.4.2", + releaseConfig: { + version: "0.4.2", + mode: "ota", + runtimeVersion: "0.4.1", + channel: "production", + }, + }), + ).toEqual({ + triggerStoreBuilds: false, + triggerOtaPublish: true, + runtimeVersion: "0.4.1", + channel: "production", + releaseVersion: "0.4.2", + }) + }) + + it("rejects a release config that does not match the release version", async () => { + const { resolveMobileReleaseConfig } = await import("./resolve-mobile-release-config.mjs") + + expect(() => + resolveMobileReleaseConfig({ + releaseVersion: "v0.4.4", + releaseConfig: { + version: "0.4.3", + mode: "store", + runtimeVersion: null, + channel: null, + }, + }), + ).toThrow(/does not match release version/i) + }) +}) diff --git a/.github/scripts/trigger-ota-sync.mjs b/.github/scripts/trigger-ota-sync.mjs new file mode 100644 index 000000000..70aa6687a --- /dev/null +++ b/.github/scripts/trigger-ota-sync.mjs @@ -0,0 +1,95 @@ +#!/usr/bin/env node + +import { pathToFileURL } from "node:url" + +/** + * @typedef {{ + * baseUrl: string + * token: string + * headerName: string + * timeoutMs?: number + * }} TriggerOtaSyncOptions + */ + +const DEFAULT_TIMEOUT_MS = 10_000 + +/** + * @param {TriggerOtaSyncOptions} options + */ +export async function triggerOtaSync({ + baseUrl, + token, + headerName, + timeoutMs = DEFAULT_TIMEOUT_MS, +}) { + if (!baseUrl) { + throw new TypeError("OTA base URL is required") + } + + if (!token) { + throw new TypeError("OTA sync token is required") + } + + if (!headerName) { + throw new TypeError("OTA sync header name is required") + } + + if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) { + throw new TypeError("OTA sync timeout must be a positive integer") + } + + const normalizedBaseUrl = baseUrl.replace(/\/+$/, "") + const controller = new AbortController() + const timeoutError = new Error(`Timed out while triggering OTA sync after ${timeoutMs}ms`) + const timeoutId = setTimeout(() => { + controller.abort(timeoutError) + }, timeoutMs) + + try { + const response = await fetch(`${normalizedBaseUrl}/internal/sync`, { + method: "POST", + headers: { + [headerName]: token, + }, + signal: controller.signal, + }) + + if (!response.ok) { + const responseText = await response.text() + const detail = responseText ? `: ${responseText}` : "" + + throw new Error( + `Failed to trigger OTA sync (${response.status} ${response.statusText})${detail}`, + ) + } + + return response + } catch (error) { + if (controller.signal.aborted && controller.signal.reason === timeoutError) { + throw timeoutError + } + + throw error + } finally { + clearTimeout(timeoutId) + } +} + +async function main() { + try { + await triggerOtaSync({ + baseUrl: process.env.OTA_BASE_URL ?? "", + token: process.env.OTA_SYNC_TOKEN ?? "", + headerName: process.env.OTA_SYNC_TOKEN_HEADER ?? "", + }) + + console.info("Triggered OTA sync successfully") + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main() +} diff --git a/.github/scripts/trigger-ota-sync.test.ts b/.github/scripts/trigger-ota-sync.test.ts new file mode 100644 index 000000000..21fedbd7d --- /dev/null +++ b/.github/scripts/trigger-ota-sync.test.ts @@ -0,0 +1,136 @@ +import { createServer } from "node:http" + +import { afterEach, describe, expect, it } from "vitest" + +const activeServers = new Set>() + +afterEach(async () => { + await Promise.all( + Array.from( + activeServers, + (server) => + new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error) + return + } + + resolve() + }) + }), + ), + ) + activeServers.clear() +}) + +describe("triggerOtaSync", () => { + it("POSTs to /internal/sync with the configured auth header", async () => { + const requests: Array<{ method?: string; url?: string; headerValue?: string }> = [] + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((request, response) => { + requests.push({ + method: request.method, + url: request.url, + headerValue: request.headers[headerName], + }) + + response.writeHead(204) + response.end() + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + }) + + expect(requests).toEqual([ + { + method: "POST", + url: "/internal/sync", + headerValue: token, + }, + ]) + }) + + it("throws when the sync endpoint responds with a non-OK status", async () => { + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((_request, response) => { + response.writeHead(503, { "content-type": "text/plain" }) + response.end("service unavailable") + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await expect( + triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + }), + ).rejects.toThrow("Failed to trigger OTA sync (503 Service Unavailable): service unavailable") + }) + + it("aborts the request when the timeout is exceeded", async () => { + const headerName = "x-ota-sync-token" + const token = "sync-token-value" + + const server = createServer((_request, _response) => { + // Intentionally never respond so the client must rely on the timeout. + }) + + activeServers.add(server) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + if (!address || typeof address === "string") { + throw new TypeError("Expected the test server to bind to an ephemeral TCP port") + } + + const { triggerOtaSync } = await import("./trigger-ota-sync.mjs") + + await expect( + triggerOtaSync({ + baseUrl: `http://127.0.0.1:${address.port}`, + token, + headerName, + timeoutMs: 25, + }), + ).rejects.toThrow("Timed out while triggering OTA sync after 25ms") + }) +}) diff --git a/.github/scripts/upload-mas-pkg.sh b/.github/scripts/upload-mas-pkg.sh new file mode 100755 index 000000000..189cacd2c --- /dev/null +++ b/.github/scripts/upload-mas-pkg.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash + +set -euo pipefail + +pkg_path="${1:-}" + +if [[ -z "$pkg_path" ]]; then + echo "Usage: $0 " >&2 + exit 1 +fi + +if [[ ! -f "$pkg_path" ]]; then + echo "Mac App Store package not found: $pkg_path" >&2 + exit 1 +fi + +if ! command -v xcrun >/dev/null 2>&1; then + echo "xcrun is required to upload a Mac App Store package." >&2 + exit 1 +fi + +upload_cmd=( + xcrun + altool + --upload-package + "$pkg_path" + --wait + --show-progress + --output-format + json +) + +if [[ -z "${APPLE_ID:-}" || -z "${APPLE_PASSWORD:-}" ]]; then + echo "APPLE_ID and APPLE_PASSWORD must be set." >&2 + exit 1 +fi + +upload_cmd+=( + -u + "$APPLE_ID" + -p + "@env:APPLE_PASSWORD" +) + +run_upload() { + local output + local exit_code + + set +e + output="$("${upload_cmd[@]}" 2>&1)" + exit_code=$? + set -e + + printf '%s\n' "$output" + return "$exit_code" +} + +echo "Uploading Mac App Store package with Apple ID: ${pkg_path}" +if run_upload; then + exit 0 +fi + +echo "Upload failed without provider selection. Checking App Store Connect providers..." +set +e +providers_output="$( + xcrun altool --list-providers -u "$APPLE_ID" -p "@env:APPLE_PASSWORD" 2>&1 +)" +providers_exit=$? +set -e + +printf '%s\n' "$providers_output" + +if [[ $providers_exit -ne 0 ]]; then + echo "Failed to list providers after upload failure." >&2 + exit 1 +fi + +mapfile -t provider_ids < <( + printf '%s\n' "$providers_output" \ + | perl -ne 'print "$1\n" if /publicid[^[:alnum:]]+([[:alnum:]-]+)/i' \ + | awk '!seen[$0]++' +) + +if [[ ${#provider_ids[@]} -ne 1 ]]; then + cat >&2 <<'EOF' +Unable to infer a single App Store Connect provider for this Apple ID. +Use an Apple ID that only belongs to one provider, or upload once manually to confirm which provider should receive the build. +EOF + exit 1 +fi + +upload_cmd+=( + --provider-public-id + "${provider_ids[0]}" +) + +echo "Retrying upload with detected provider: ${provider_ids[0]}" +run_upload diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index ebb6765a9..ee5f81662 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -46,7 +46,7 @@ jobs: uses: actions/checkout@v6 - name: 📦 Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6 - name: 🏗 Setup Node.js uses: actions/setup-node@v6 @@ -61,7 +61,7 @@ jobs: distribution: "zulu" - name: Setup Android SDK - uses: android-actions/setup-android@v3 + uses: android-actions/setup-android@v4 - name: 📱 Setup EAS uses: expo/expo-github-action@v8 @@ -75,6 +75,8 @@ jobs: - name: 🔨 Build Android app working-directory: apps/mobile run: eas build --platform android --profile ${{ github.event.inputs.profile || 'preview' }} --local --output=${{ github.workspace }}/build.${{ github.event.inputs.profile == 'production' && 'aab' || 'apk' }} + env: + EAS_NO_FROZEN_LOCKFILE: "1" - name: 📤 Upload apk Artifact if: github.event.inputs.profile != 'production' @@ -126,7 +128,7 @@ jobs: - name: Create Release Draft if: github.event.inputs.release == 'true' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: name: Mobile v${{ steps.version.outputs.APP_VERSION }} draft: true diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index d38d71f7b..3243e5b40 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -17,6 +17,10 @@ on: store: type: boolean description: "Build for Mac App Store and Microsoft Store" + upload_to_app_store: + type: boolean + description: "Upload the Mac App Store pkg to App Store Connect" + default: true build_version: type: string description: "Build Version, only available when mas is true" @@ -68,7 +72,7 @@ jobs: lfs: true - name: Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6 - name: Use Node.js uses: actions/setup-node@v6 @@ -210,6 +214,24 @@ jobs: apps/desktop/out/make/**/*.pkg retention-days: 90 + - name: Upload Mac App Store package to App Store Connect + if: runner.os == 'macOS' && github.event.inputs.store == 'true' && github.event.inputs.upload_to_app_store == 'true' + env: + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + shell: bash + run: | + set -euo pipefail + + pkg_path="$(find apps/desktop/out/make -type f -name '*.pkg' | sort | head -n 1)" + + if [ -z "$pkg_path" ]; then + echo "No Mac App Store package found under apps/desktop/out/make" >&2 + exit 1 + fi + + .github/scripts/upload-mas-pkg.sh "$pkg_path" + - name: Upload file (windows-x64-exe unsigned) uses: actions/upload-artifact@v7 id: upload-unsigned-windows-x64-exe @@ -221,7 +243,7 @@ jobs: apps/desktop/out/make/**/latest.yml retention-days: 90 - - uses: signpath/github-action-submit-signing-request@v2.0 + - uses: signpath/github-action-submit-signing-request@v2.1 continue-on-error: true if: runner.os == 'windows' && env.RELEASE == 'true' && github.event.inputs.store != 'true' with: @@ -267,6 +289,47 @@ jobs: apps/desktop/out/make/**/latest-linux.yml retention-days: 90 + - name: Prepare release assets for aggregation + if: env.RELEASE == 'true' + env: + DESKTOP_RELEASE_ASSET_DIR: ${{ runner.temp }}/desktop-release-assets + run: | + node --input-type=module <<'EOF' + import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs" + import { join } from "node:path" + + const stageDir = process.env.DESKTOP_RELEASE_ASSET_DIR + + if (!stageDir) { + throw new Error("DESKTOP_RELEASE_ASSET_DIR is not set") + } + + rmSync(stageDir, { recursive: true, force: true }) + mkdirSync(join(stageDir, "apps", "desktop", "out"), { recursive: true }) + + const pathsToCopy = [ + ["apps/desktop/out/make", join(stageDir, "apps", "desktop", "out", "make")], + ["apps/desktop/dist", join(stageDir, "apps", "desktop", "dist")], + ] + + for (const [sourcePath, destinationPath] of pathsToCopy) { + if (!existsSync(sourcePath)) { + continue + } + + cpSync(sourcePath, destinationPath, { recursive: true }) + } + EOF + + - name: Upload release assets for aggregation + if: env.RELEASE == 'true' + uses: actions/upload-artifact@v7 + with: + name: desktop-release-assets-${{ runner.os }} + path: ${{ runner.temp }}/desktop-release-assets/apps + if-no-files-found: error + retention-days: 7 + - name: Generate artifact attestation if: env.RELEASE == 'true' continue-on-error: true @@ -281,21 +344,68 @@ jobs: apps/desktop/dist/manifest.yml apps/desktop/dist/*.tar.gz + publish-release: + if: github.secret_source != 'None' && needs.release.result == 'success' && (github.event.inputs.tag_version == 'true' || github.ref_type == 'tag') + needs: release + runs-on: ubuntu-latest + + permissions: + contents: write + + steps: + - name: Check out Git repository Fully + uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + + - name: Use Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: "pnpm" + + - name: Install dependencies + run: pnpm i + + - name: Download release assets + uses: actions/download-artifact@v8 + with: + pattern: desktop-release-assets-* + path: . + merge-multiple: true + + - name: Ensure zstd + shell: bash + run: | + if command -v zstd >/dev/null 2>&1; then + zstd --version + exit 0 + fi + + sudo apt-get update + sudo apt-get install -y zstd + + - name: Build desktop OTA release assets + env: + OTA_PRODUCT: desktop + run: node .github/scripts/build-ota-release.mjs + - run: npx changelogithub - if: env.RELEASE == 'true' continue-on-error: true env: GITHUB_TOKEN: ${{ github.token }} - name: Setup Version - if: env.RELEASE == 'true' id: version uses: ./.github/actions/setup-version with: type: "desktop" - name: Prepare Release Notes - if: env.RELEASE == 'true' id: release_notes shell: bash run: | @@ -315,20 +425,39 @@ jobs: echo "body_path=${release_notes_file}" >> "$GITHUB_OUTPUT" + - name: Prepare release files + id: release_files + shell: bash + run: | + release_files="$RUNNER_TEMP/desktop-release-files.txt" + + cat <<'EOF' > "$release_files" + apps/desktop/out/make/**/Folo-*.dmg + apps/desktop/out/make/**/Folo-*.zip + apps/desktop/out/make/**/Folo-*.exe + apps/desktop/out/make/**/Folo-*.AppImage + apps/desktop/out/make/**/*.yml + apps/desktop/dist/manifest.yml + apps/desktop/dist/*.tar.gz + apps/desktop/dist/ota-release.json + EOF + + if [ -f apps/desktop/dist.tar.zst ]; then + echo "apps/desktop/dist.tar.zst" >> "$release_files" + fi + + { + echo "files<> "$GITHUB_OUTPUT" + - name: Create Release Draft - if: env.RELEASE == 'true' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: name: Desktop v${{ steps.version.outputs.APP_VERSION }} draft: false prerelease: true tag_name: desktop/v${{ steps.version.outputs.APP_VERSION }} body_path: ${{ steps.release_notes.outputs.body_path }} - files: | - apps/desktop/out/make/**/Folo-*.dmg - apps/desktop/out/make/**/Folo-*.zip - apps/desktop/out/make/**/Folo-*.exe - apps/desktop/out/make/**/Folo-*.AppImage - apps/desktop/out/make/**/*.yml - apps/desktop/dist/manifest.yml - apps/desktop/dist/*.tar.gz + files: ${{ steps.release_files.outputs.files }} diff --git a/.github/workflows/build-ios-development.yml b/.github/workflows/build-ios-development.yml index 1529315ef..a67818094 100644 --- a/.github/workflows/build-ios-development.yml +++ b/.github/workflows/build-ios-development.yml @@ -55,6 +55,7 @@ jobs: working-directory: apps/mobile run: eas build --platform ios --profile development --non-interactive --local --output=./build.ipa env: + EAS_NO_FROZEN_LOCKFILE: "1" SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }} CI: true @@ -84,7 +85,7 @@ jobs: uses: ./.github/actions/setup-xcode - name: 📦 Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6 - name: 🏗 Setup Node.js uses: actions/setup-node@v6 @@ -105,6 +106,7 @@ jobs: working-directory: apps/mobile run: eas build --platform ios --profile development --non-interactive --local --output=./build.ipa env: + EAS_NO_FROZEN_LOCKFILE: "1" CI: true SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }} # Optional: Upload artifact @@ -128,7 +130,7 @@ jobs: uses: ./.github/actions/setup-xcode - name: 📦 Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6 - name: 🏗 Setup Node.js uses: actions/setup-node@v6 @@ -149,6 +151,7 @@ jobs: working-directory: apps/mobile run: eas build --platform ios --profile ios-simulator --non-interactive --local --output=./build-simulator.ipa env: + EAS_NO_FROZEN_LOCKFILE: "1" CI: true SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }} # Optional: Upload artifact diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 3ca17f814..7230190c8 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -63,6 +63,7 @@ jobs: working-directory: apps/mobile run: eas build --platform ios --profile ${{ github.event.inputs.profile || 'preview' }} --non-interactive --local --output=./build.ipa env: + EAS_NO_FROZEN_LOCKFILE: "1" SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }} CI: true @@ -97,7 +98,7 @@ jobs: uses: ./.github/actions/setup-xcode - name: 📦 Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v6 - name: 🏗 Setup Node.js uses: actions/setup-node@v6 @@ -118,6 +119,7 @@ jobs: working-directory: apps/mobile run: eas build --platform ios --profile ${{ github.event.inputs.profile || 'preview' }} --non-interactive --local --output=./build.ipa env: + EAS_NO_FROZEN_LOCKFILE: "1" CI: true SENTRY_AUTH_TOKEN: ${{ secrets.RN_SENTRY_AUTH_TOKEN }} # Optional: Upload artifact diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 7bee7824c..883ab3aff 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -31,7 +31,7 @@ jobs: - name: Checkout LFS objects run: git lfs checkout - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v6 diff --git a/.github/workflows/deploy-cloudflare-desktop.yml b/.github/workflows/deploy-cloudflare-desktop.yml index 32df67c3f..db86f8a0e 100644 --- a/.github/workflows/deploy-cloudflare-desktop.yml +++ b/.github/workflows/deploy-cloudflare-desktop.yml @@ -32,7 +32,7 @@ jobs: restore-keys: | ${{ runner.os }}-turbo- - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - name: Use Node.js LTS uses: actions/setup-node@v6 diff --git a/.github/workflows/deploy-cloudflare-landing.yml b/.github/workflows/deploy-cloudflare-landing.yml index e11a61e2f..90077f14c 100644 --- a/.github/workflows/deploy-cloudflare-landing.yml +++ b/.github/workflows/deploy-cloudflare-landing.yml @@ -36,7 +36,7 @@ jobs: restore-keys: | ${{ runner.os }}-turbo- - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - name: Use Node.js LTS uses: actions/setup-node@v6 diff --git a/.github/workflows/deploy-cloudflare-ssr.yml b/.github/workflows/deploy-cloudflare-ssr.yml index 2e88f1022..78e2fdbff 100644 --- a/.github/workflows/deploy-cloudflare-ssr.yml +++ b/.github/workflows/deploy-cloudflare-ssr.yml @@ -39,7 +39,7 @@ jobs: restore-keys: | ${{ runner.os }}-turbo- - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - name: Use Node.js LTS uses: actions/setup-node@v6 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 684111fa0..265abe3e8 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -36,7 +36,7 @@ jobs: - name: Checkout LFS objects run: git lfs checkout - - uses: pnpm/action-setup@v4 + - uses: pnpm/action-setup@v6 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v6 diff --git a/.github/workflows/publish-ota.yml b/.github/workflows/publish-ota.yml new file mode 100644 index 000000000..4cedcf02c --- /dev/null +++ b/.github/workflows/publish-ota.yml @@ -0,0 +1,99 @@ +name: 📡 Publish OTA Release + +on: + workflow_dispatch: + inputs: + release_version: + type: string + required: true + description: "Release version without the v prefix" + runtime_version: + type: string + required: true + description: "Expo runtime version for the OTA bundle" + channel: + type: choice + required: true + options: + - production + - preview + description: "OTA channel embedded in ota-release.json" + +permissions: + contents: write + +jobs: + publish: + if: github.secret_source != 'None' + runs-on: ubuntu-latest + env: + OTA_PRODUCT: mobile + OTA_RELEASE_VERSION: ${{ inputs.release_version }} + OTA_RUNTIME_VERSION: ${{ inputs.runtime_version }} + OTA_CHANNEL: ${{ inputs.channel }} + OTA_GIT_TAG: mobile/v${{ inputs.release_version }} + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Resolve target release tag + run: | + git fetch --tags --force + + if ! git rev-parse --verify "refs/tags/${OTA_GIT_TAG}" >/dev/null 2>&1; then + echo "::error::Required release tag ${OTA_GIT_TAG} does not exist. Create it before publishing OTA assets." + exit 1 + fi + + git checkout --detach "refs/tags/${OTA_GIT_TAG}" + echo "Checked out ${OTA_GIT_TAG} at $(git rev-list -n 1 "refs/tags/${OTA_GIT_TAG}")" + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: "pnpm" + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Export OTA bundle assets + working-directory: apps/mobile + run: pnpm run update:export + + - name: Build OTA release bundle + run: node .github/scripts/build-ota-release.mjs + + - name: Publish GitHub release assets + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + tag_name="mobile/v${OTA_RELEASE_VERSION}" + release_title="Mobile v${OTA_RELEASE_VERSION}" + ota_files=("apps/mobile/dist/ota-release.json") + + if [ -f "apps/mobile/dist.tar.zst" ]; then + ota_files+=("apps/mobile/dist.tar.zst") + fi + + if gh release view "$tag_name" >/dev/null 2>&1; then + gh release upload "$tag_name" "${ota_files[@]}" --clobber + else + gh release create "$tag_name" "${ota_files[@]}" \ + --verify-tag \ + --title "$release_title" \ + --notes "OTA release assets for the ${OTA_CHANNEL} channel." + fi + + - name: Trigger OTA sync + env: + OTA_BASE_URL: ${{ secrets.OTA_BASE_URL }} + OTA_SYNC_TOKEN: ${{ secrets.OTA_SYNC_TOKEN }} + OTA_SYNC_TOKEN_HEADER: ${{ secrets.OTA_SYNC_TOKEN_HEADER }} + run: node .github/scripts/trigger-ota-sync.mjs diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index b6bd67673..14bee2492 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -17,7 +17,7 @@ jobs: - name: Prepare prompt variables id: prepare_input - uses: actions/github-script@v8 + uses: actions/github-script@v9 with: script: | const issue = context.payload.issue || {}; @@ -45,7 +45,7 @@ jobs: - name: Prepare comment body id: prepare - uses: actions/github-script@v8 + uses: actions/github-script@v9 env: AI_RESPONSE: ${{ steps.inference.outputs.response }} with: @@ -93,7 +93,7 @@ jobs: - name: Comment similar issues if: steps.prepare.outputs.has_matches == 'true' - uses: actions/github-script@v8 + uses: actions/github-script@v9 with: script: | const body = ${{ toJson(steps.prepare.outputs.comment_body) }}; diff --git a/.github/workflows/sync.yaml b/.github/workflows/sync.yaml index d22bff603..4ba68e2a1 100644 --- a/.github/workflows/sync.yaml +++ b/.github/workflows/sync.yaml @@ -8,6 +8,7 @@ on: permissions: contents: write + pull-requests: write jobs: sync-to-dev: @@ -16,20 +17,33 @@ jobs: (github.ref == 'refs/heads/main' && contains(github.event.head_commit.message || '', 'release(desktop):')) || (github.ref == 'refs/heads/mobile-main' && contains(github.event.head_commit.message || '', 'release(mobile):')) steps: - - name: Checkout repository - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - - name: Set up Git - run: | - git config --global user.name "github-actions[bot]" - git config --global user.email "github-actions[bot]@users.noreply.github.com" - - - name: Merge source branch into dev + - name: Create or update sync pull request + env: + GH_TOKEN: ${{ github.token }} run: | source_branch="${GITHUB_REF_NAME}" - git fetch origin main mobile-main dev - git checkout dev - git merge --no-ff "origin/${source_branch}" -m "chore(sync): merge ${source_branch} into dev" - git push origin dev + title="chore(sync): merge ${source_branch} into dev" + body=$(cat < - +
- - - - + + + + + +