The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
feat: simplify SDK release process and checklist maintenance (#77537)
Mahatthana (Kelvin) Nomsawadibb6977debd1e
diff --git a/.github/workflows/release-embedding-sdk.yml b/.github/workflows/release-embedding-sdk.ymlindex bd7f8b9a696..fc23c172569 100644--- a/.github/workflows/release-embedding-sdk.yml+++ b/.github/workflows/release-embedding-sdk.yml@@ -1,46 +1,103 @@+# Step 2 of the SDK release process: merging a version-bump PR (opened by+# sdk-version-bump-pr.yml, labeled `sdk-release-trigger`) publishes the version+# and dist-tag committed in package.template.json's `sdkRelease` block.+#+# workflow_dispatch publishes the same way, from the branch chosen in the ref+# picker, without a PR. It reads the same committed sdkRelease block and never+# bumps the version - so it is not how you cut a release. Use it only to publish+# a version that is already committed, when the bump PR cannot do it.+#+# To retry a failed run, re-run the failed jobs on that run rather than+# dispatching a fresh one: if publish-npm already succeeded, a fresh run would+# stop at check-git-tag on the existing tag.name: Release Metabase Embedding SDK for React-run-name: Release SDK from ${{ inputs.branch }}+run-name: Release SDK from ${{ github.event_name == 'workflow_dispatch' && github.ref_name || github.event.pull_request.base.ref }}on:workflow_dispatch:inputs:- branch:- description: "Branch we want to release the SDK from (to release from other branches use the workflow from those branches)"+ read_first:+ description: |+ ⚠️ To cut a release, use the "SDK Version Bump PR" workflow instead — it bumps the version and opens a PR; merging that PR publishes.+ This publishes the version already committed in package.template.json. It never bumps. Pick the branch in "Use workflow from" above.+ Use it only when neither the bump PR nor re-running the failed jobs will do.type: choice- required: true- default: "master"+ required: falseoptions:- - master+ - Publish the committed version from the branch picked in "Use workflow from" above+ # Step 2 of the new release process: merging a version-bump PR (opened by+ # sdk-version-bump-pr.yml, labeled `sdk-release-trigger`) triggers a release+ # of whatever branch that PR targeted. See `prepare-release` below.+ #+ # The `paths` filter keeps this from creating a run for every PR closed+ # anywhere in the repo - version-bump PRs always touch package.template.json,+ # so this is a reliable pre-filter ahead of the label/merge check below.+ pull_request:+ types: [closed]+ paths:+ - enterprise/frontend/src/embedding-sdk-package/package.template.jsonconcurrency:- # We want to ensure only one job is running at a time per branch because- # there could be a conflict when updating the readme file.- group: ${{ github.workflow }}-${{ inputs.branch }}- cancel-in-progress: true+ # One release at a time per branch; base.ref is empty on workflow_dispatch, so+ # it falls back to the ref picker's branch. Never cancel in progress - a queued+ # release that turns out stale fails loudly at check-git-tag.+ #+ # Non-release closed PRs queue here too and skip in seconds. GitHub keeps only+ # one pending run per group and cancels any earlier one, so one could in theory+ # evict a release waiting to start; that needs two same-branch releases at once.+ # `queue: max` would fix it, but actionlint cannot parse it (rhysd/actionlint#654).+ group: sdk-release-${{ github.event.pull_request.base.ref || github.ref_name }}+ cancel-in-progress: falsejobs:+ # Gates the whole workflow: either a manual workflow_dispatch, or a merged+ # PR carrying the sdk-release-trigger label. Every other job depends+ # (directly or transitively) on this one, so if it's skipped the rest of+ # the run is skipped too - no separate `if:` needed on downstream jobs.+ prepare-release:+ name: Prepare release trigger+ if: |+ github.event_name == 'workflow_dispatch' ||+ (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'sdk-release-trigger'))+ runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}+ timeout-minutes: 5+ outputs:+ branch: ${{ steps.resolve.outputs.branch }}+ steps:+ # base.ref is only set on a pull_request event; on a dispatch it is empty,+ # so this falls through to the branch picked in the ref picker.+ - name: Resolve target branch+ id: resolve+ run: echo "branch=${{ github.event.pull_request.base.ref || github.ref_name }}" >> "$GITHUB_OUTPUT"+workflow-summary:name: Log inputs+ needs: prepare-releaseruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 5steps:- name: Generate workflow summary+ env:+ BRANCH: ${{ needs.prepare-release.outputs.branch }}run: |- tee -a $GITHUB_STEP_SUMMARY << EOF+ tee -a "$GITHUB_STEP_SUMMARY" << EOF**Inputs:**- - \`branch\`: ${{ inputs.branch }}+ - \`branch\`: $BRANCH+ - \`trigger\`: ${{ github.event_name }}triggered by: @${{ github.event.sender.login }}EOF- send-slack-notification-start:- name: "Send Slack notification: SDK release started"- needs: determine-sdk-version+ # Builds release/dist/index.cjs once, for every Slack job to download. It hangs+ # off prepare-release only - not off the metadata read or anything downstream -+ # so the artifact exists even when the release fails at its very first step,+ # which is exactly when send-slack-notification-failure needs it.+ build-release-scripts:+ name: Build release scripts+ needs: prepare-releaseruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 5- outputs:- slackMessageId: ${{ steps.send-slack-message-start.outputs.result }}steps:- uses: actions/checkout@v6with:@@ -51,12 +108,28 @@ jobs:- name: Prepare release scriptsuses: ./.github/actions/prepare-release-scripts- - name: Cache build scripts+ - name: Upload release scriptsuses: actions/upload-artifact@v7with:name: build-scriptspath: release/dist/index.cjs+ send-slack-notification-start:+ name: "Send Slack notification: SDK release started"+ needs:+ - build-release-scripts+ - read-sdk-release-metadata+ runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}+ timeout-minutes: 5+ outputs:+ slackMessageId: ${{ steps.send-slack-message-start.outputs.result }}+ steps:+ - name: Retrieve release scripts+ uses: actions/download-artifact@v8+ with:+ name: build-scripts+ path: release/dist/+- name: Send build start messageid: send-slack-message-startuses: actions/github-script@v9@@ -66,7 +139,7 @@ jobs:result-encoding: stringscript: | # jsconst { mentionUserByGithubLogin, sendSlackMessage, githubRunLink } = require('${{ github.workspace }}/release/dist/index.cjs');- const sdkVersion = "${{ needs.determine-sdk-version.outputs.sdk_version }}";+ const sdkVersion = "${{ needs.read-sdk-release-metadata.outputs.sdk_version }}";const title = `:rocket: *SDK release: ${sdkVersion}* :rocket:`const runLink = githubRunLink(@@ -87,23 +160,22 @@ jobs:send-slack-notification-failure:name: "Send Slack notification: SDK release failed"needs:- [- "determine-sdk-version",- "send-slack-notification-start",- "check-git-tag",- "test",- "build-sdk",- "publish-npm",- "tag-latest",- "git-tag",- ]+ - build-release-scripts+ - read-sdk-release-metadata+ - send-slack-notification-start+ - check-git-tag+ - test+ - build-sdk+ - publish-npm+ - tag-latest+ - git-tagruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 5env:slackMessageId: ${{ needs.send-slack-notification-start.outputs.slackMessageId }}if: ${{ always() && contains(needs.*.result, 'failure') }}steps:- - name: Retrieve build scripts+ - name: Retrieve release scriptsuses: actions/download-artifact@v8with:name: build-scripts@@ -115,8 +187,9 @@ jobs:SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}with:script: | # js- const { githubRunLink, sendSlackReply } = require('${{ github.workspace }}/release/dist/index.cjs');- const sdkVersion = "${{ needs.determine-sdk-version.outputs.sdk_version }}";+ const { githubRunLink, sendSlackReply, sendSlackMessage } = require('${{ github.workspace }}/release/dist/index.cjs');+ const sdkVersion = "${{ needs.read-sdk-release-metadata.outputs.sdk_version }}";+ const messageId = "${{ env.slackMessageId }}";const runLink = githubRunLink(`:x: ${sdkVersion} Release has failed`,@@ -124,23 +197,34 @@ jobs:context.repo.owner,context.repo.repo,);- sendSlackReply({- channelName: 'team-embedding-releases',- message: runLink,- messageId: ${{ env.slackMessageId}},- broadcast: true- });++ if (messageId) {+ sendSlackReply({+ channelName: 'team-embedding-releases',+ message: runLink,+ messageId,+ broadcast: true,+ });+ } else {+ sendSlackMessage({+ channelName: 'team-embedding-releases',+ message: runLink,+ });+ }send-slack-notification-successful:name: "Send Slack notification: SDK release successful"needs:- ["determine-sdk-version", "send-slack-notification-start", "publish-npm"]+ - build-release-scripts+ - read-sdk-release-metadata+ - send-slack-notification-start+ - publish-npmruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 5env:slackMessageId: ${{ needs.send-slack-notification-start.outputs.slackMessageId }}steps:- - name: Retrieve build scripts+ - name: Retrieve release scriptsuses: actions/download-artifact@v8with:name: build-scripts@@ -153,7 +237,7 @@ jobs:with:script: | # jsconst { githubRunLink, sendSlackReply } = require('${{ github.workspace }}/release/dist/index.cjs');- const sdkVersion = "${{ needs.determine-sdk-version.outputs.sdk_version }}";+ const sdkVersion = "${{ needs.read-sdk-release-metadata.outputs.sdk_version }}";const runLink = githubRunLink(`:partydeploy: ${sdkVersion} Release is complete :partydeploy:`,@@ -164,93 +248,104 @@ jobs:sendSlackReply({channelName: 'team-embedding-releases',message: runLink,- messageId: ${{ env.slackMessageId}},+ messageId: "${{ env.slackMessageId }}",broadcast: true});- determine-sdk-version:+ # Reads the version + release metadata straight from package.template.json+ # instead of computing them (the version and sdkRelease.distTag/tagAsLatest+ # are already correct on this branch, because sdk-version-bump-pr.yml wrote+ # them there and a human reviewed them before merging).+ read-sdk-release-metadata:+ name: Read SDK release metadata+ needs: prepare-releaseruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}- timeout-minutes: 20+ timeout-minutes: 5outputs:- sdk_version: ${{ fromJson(steps.new-sdk-version.outputs.result).version }}- major_version: ${{ fromJson(steps.new-sdk-version.outputs.result).majorVersion }}- pre_release_label: ${{ fromJson(steps.new-sdk-version.outputs.result).preReleaseLabel }}+ sdk_version: ${{ steps.metadata.outputs.sdk_version }}+ major_version: ${{ steps.metadata.outputs.major_version }}+ dist_tag: ${{ steps.metadata.outputs.dist_tag }}+ tag_as_latest: ${{ steps.metadata.outputs.tag_as_latest }}steps:- name: Check out the code using the provided branchuses: actions/checkout@v6with:- ref: ${{ inputs.branch }}+ ref: ${{ needs.prepare-release.outputs.branch }}- name: Prepare release scriptsuses: ./.github/actions/prepare-release-scripts- - name: Get current SDK version- id: current-sdk-version- run: |- VERSION=$(jq -r .version ./enterprise/frontend/src/embedding-sdk-package/package.template.json)- echo "sdk_current_version=$VERSION" >> $GITHUB_OUTPUT-- - name: Get next SDK patch or pre-release version- id: new-sdk-version+ - name: Read version and sdkRelease metadata+ id: metadatauses: actions/github-script@v9with:- script: | #js- const { getNextSdkVersion } = require('${{ github.workspace }}/release/dist/index.cjs');-- const branch = "${{ inputs.branch }}";- const currentVersion = "${{ steps.current-sdk-version.outputs.sdk_current_version }}";-- const result = getNextSdkVersion(branch, currentVersion);-- return {- version: result.version,- preReleaseLabel: result.preReleaseLabel,- majorVersion: result.majorVersion- };+ script: | # js+ const { readSdkReleaseMetadata } = require('${{ github.workspace }}/release/dist/index.cjs');++ let metadata;+ try {+ metadata = readSdkReleaseMetadata({+ packageTemplatePath:+ 'enterprise/frontend/src/embedding-sdk-package/package.template.json',+ });+ } catch (error) {+ core.setFailed(error.message);+ return;+ }++ core.setOutput('sdk_version', metadata.version);+ core.setOutput('major_version', metadata.majorVersion);+ core.setOutput('dist_tag', metadata.distTag);+ core.setOutput('tag_as_latest', String(metadata.tagAsLatest));- name: Append workflow summaryrun: |- tee -a $GITHUB_STEP_SUMMARY << EOF- **Derived inputs:**+ tee -a "$GITHUB_STEP_SUMMARY" << EOF+ **SDK release metadata (from package.template.json):**- - \`current_version\`: "${{ steps.current-sdk-version.outputs.sdk_current_version }}"- - \`next_version\`: "${{ fromJson(steps.new-sdk-version.outputs.result).version }}"- - \`major_version\`: "${{ fromJson(steps.new-sdk-version.outputs.result).majorVersion }}"+ - \`version\`: "${{ steps.metadata.outputs.sdk_version }}"+ - \`major_version\`: "${{ steps.metadata.outputs.major_version }}"+ - \`distTag\`: "${{ steps.metadata.outputs.dist_tag }}"+ - \`tagAsLatest\`: "${{ steps.metadata.outputs.tag_as_latest }}"EOFcheck-git-tag:- needs: determine-sdk-version+ needs:+ - prepare-release+ - read-sdk-release-metadataruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 20env:- tag: embedding-sdk-${{ needs.determine-sdk-version.outputs.sdk_version }}+ tag: embedding-sdk-${{ needs.read-sdk-release-metadata.outputs.sdk_version }}steps:- name: Check out the code using the provided branchuses: actions/checkout@v6with:- ref: ${{ inputs.branch }}+ ref: ${{ needs.prepare-release.outputs.branch }}fetch-depth: 0fetch-tags: true- name: check tagsrun: |- if [ $(git tag -l | grep $tag$) ]+ if git tag -l | grep -q "${tag}$"then- echo "::error::Tag '${{ env.tag }}' already exists. If you expect to run this workflow with the same tag, please remove the tag first and rerun this workflow again."+ echo "::error::Tag '${{ env.tag }}' already exists. If you expect to run this workflow with the same tag, please remove the tag first and rerun this workflow."exit 1elseexit 0fitest:- needs: check-git-tag+ needs:+ - prepare-release+ - check-git-tagruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 20steps:- name: Check out the code using the provided branchuses: actions/checkout@v6with:- ref: ${{ inputs.branch }}+ ref: ${{ needs.prepare-release.outputs.branch }}- name: Prepare front-end environmentuses: ./.github/actions/prepare-frontend@@ -262,14 +357,16 @@ jobs:run: bun run embedding-sdk:test-unitbuild-sdk:- needs: [test, determine-sdk-version]+ needs:+ - prepare-release+ - testruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 20steps:- name: Check out the code using the provided branchuses: actions/checkout@v6with:- ref: ${{ inputs.branch }}+ ref: ${{ needs.prepare-release.outputs.branch }}fetch-depth: 0fetch-tags: true@@ -279,11 +376,9 @@ jobs:- name: Prepare back-end environmentuses: ./.github/actions/prepare-backend- - name: Bump published npm package version- # NOTE: this should happen before "Build SDK bundle" as we inject SDK version into the code during build step- run: |- ./bin/embedding-sdk/release_utils.bash update_package_json_template ${{ needs.determine-sdk-version.outputs.sdk_version }}-+ # No version bump here anymore: package.template.json's version is+ # already correct on this branch (bumped by sdk-version-bump-pr.yml+ # before merge), so we build with it as-is.- name: Build SDK packagerun: bun run build-embedding-sdk-package@@ -297,94 +392,22 @@ jobs:path: ./resources/embedding-sdkpublish-npm:- needs: [build-sdk, determine-sdk-version]+ needs:+ - prepare-release+ - build-sdk+ - read-sdk-release-metadataruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 20permissions:id-token: write # OIDC handshake for npm trusted publishingactions: read # actions/download-artifact reads the Actions API via GITHUB_TOKEN- pull-requests: write # gh pr review --approve step uses GITHUB_TOKEN- env:- sdk_version: ${{ needs.determine-sdk-version.outputs.sdk_version }}steps:- - name: Check out branch to prepare for a SDK version bump PR- uses: actions/checkout@v6- with:- token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}- # when we created version update PR, it would only have diff from 2 files SDK readme and SDK package.json template- ref: ${{ inputs.branch}}-- - name: Setup git user- run: |- git config --global user.email "[email protected]"- git config --global user.name "Metabase Automation"-- - name: Update readme- if: inputs.branch != 'master'- run: |- bash ./bin/embedding-sdk/release_utils.bash update_readme ${{ env.sdk_version }}-- - name: Bump published npm package version- run: |- bash ./bin/embedding-sdk/release_utils.bash update_package_json_template ${{ env.sdk_version }}-- - name: Create a PR updating readme + published version (using GitHub Metabase Automation account)- run: |- git checkout -b update-sdk-version-${{ env.sdk_version }}-- if [ "${{ inputs.branch }}" = "master" ]; then- COMMIT_MSG="chore(sdk): Update published npm version to ${{ env.sdk_version }}"- PR_TITLE="chore(sdk): Update SDK version to ${{ env.sdk_version }}"- PR_BODY="Update published npm package version to ${{ env.sdk_version }}"- else- COMMIT_MSG="docs(sdk): Update Readme version references and published npm version to ${{ env.sdk_version }}"- PR_TITLE="docs(sdk): Update SDK version to ${{ env.sdk_version }}"- PR_BODY="Update Readme version references and published npm package version to ${{ env.sdk_version }}"- fi-- git commit -a -m "$COMMIT_MSG"- git push origin HEAD- gh pr create --base "${{ inputs.branch }}" \- --assignee "${GITHUB_ACTOR}" \- --title "$PR_TITLE" \- --body "$PR_BODY"- env:- GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}-- - name: Edit PR adding useful information (using Metabase bot app)- # metabase/embedding team is added automatically as code owner of updated `package.template.json` file- run: |- gh pr edit --add-reviewer albertoperdomo --add-label no-backport- env:- GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}-- - name: Auto approve PR (using GitHub Actions account)- run: |- gh pr review --approve- env:- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}-- - name: Enable Pull request auto-merge (using GitHub Metabase Automation account)- run: |- gh pr merge --auto --squash- env:- GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}-- name: Retrieve build SDK package artifactuses: actions/download-artifact@v8with:name: metabase-sdkpath: sdk- - name: Compute master tag- id: compute-tag- run: |- if [ -n "${{ needs.determine-sdk-version.outputs.pre_release_label }}" ]; then- echo "masterTag=${{ needs.determine-sdk-version.outputs.pre_release_label }}" >> $GITHUB_OUTPUT- else- echo "masterTag=nightly" >> $GITHUB_OUTPUT- fi-# Trusted publishing requires npm >= 11.5.1 and Node >= 22.14.0.# Node 22.x line bundles npm 10.x, so pin Node 24.x which ships npm 11.x.- name: Setup Node.js for npm publish with trusted publishing@@ -396,34 +419,41 @@ jobs:- name: Publish to NPMworking-directory: sdkrun: |- TAG="${{ steps.compute-tag.outputs.masterTag }}"+ TAG="${{ needs.read-sdk-release-metadata.outputs.dist_tag }}"echo "Resolved npm tag: $TAG"npm publish --tag "$TAG"- # When a newer release branch goes gold, remove this entire job from this branch.tag-latest:name: Tag npm release as latest- # Pre-gold: remove `if: false` once this branch becomes gold.- if: false- needs: [publish-npm, determine-sdk-version]+ # Driven by package.template.json's sdkRelease.tagAsLatest instead of a+ # hardcoded `if: false` that had to be hand-edited (uncommented) once a+ # branch went gold - see sdk-version-bump-pr.yml, which is where a human+ # sets this to true when appropriate.+ if: ${{ needs.read-sdk-release-metadata.outputs.tag_as_latest == 'true' }}+ needs:+ - publish-npm+ - read-sdk-release-metadatauses: ./.github/workflows/embedding-sdk-tag-latest.ymlwith:- version: ${{ needs.determine-sdk-version.outputs.sdk_version }}+ version: ${{ needs.read-sdk-release-metadata.outputs.sdk_version }}secrets: inheritgit-tag:- needs: [publish-npm, determine-sdk-version]+ needs:+ - prepare-release+ - publish-npm+ - read-sdk-release-metadataruns-on: ${{ vars.DEFAULT_RUNNER_KEY }}timeout-minutes: 20env:- tag: embedding-sdk-${{ needs.determine-sdk-version.outputs.sdk_version }}- stable_tag: embedding-sdk-${{ needs.determine-sdk-version.outputs.major_version }}-stable+ tag: embedding-sdk-${{ needs.read-sdk-release-metadata.outputs.sdk_version }}+ stable_tag: embedding-sdk-${{ needs.read-sdk-release-metadata.outputs.major_version }}-stablesteps:- name: Check out the code using the provided branchuses: actions/checkout@v6with:token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}- ref: ${{ inputs.branch }}+ ref: ${{ needs.prepare-release.outputs.branch }}- name: Setup git userrun: |@@ -436,7 +466,7 @@ jobs:git push origin ${{ env.tag }}- name: Create and push SDK stable version tag- if: ${{ startsWith(inputs.branch, 'release-x.') }}+ if: ${{ startsWith(needs.prepare-release.outputs.branch, 'release-x.') }}run: |git tag -a -f ${{ env.stable_tag }} -m "Tagging SDK stable version ${{ env.stable_tag }}"git push origin -f ${{ env.stable_tag }}diff --git a/.github/workflows/sdk-version-bump-pr.yml b/.github/workflows/sdk-version-bump-pr.ymlnew file mode 100644index 00000000000..a91f30ac756--- /dev/null+++ b/.github/workflows/sdk-version-bump-pr.yml@@ -0,0 +1,180 @@+# Step 1 of the SDK release process: bump the version (and the sdkRelease+# metadata that controls the npm dist-tag / `latest` promotion) in+# package.template.json, then open a PR labeled `sdk-release-trigger`.+# Merging that PR is what actually triggers a release, via the+# `pull_request` trigger on release-embedding-sdk.yml.+name: SDK Version Bump PR+run-name: Bump Embedding SDK version (${{ inputs.release_type }}) on ${{ github.ref_name }}++on:+ workflow_dispatch:+ inputs:+ read_first:+ description: "Bumps the version on the branch chosen in 'Use workflow from' above."+ type: choice+ required: false+ options:+ - Pick the branch in "Use workflow from" above+ release_type:+ description: |+ Before gold:+ • beta — release branch: publish a beta++ At gold:+ • patch — release branch: graduate the beta to 0.N.0+ • preminor — master: move master to the next major++ After gold:+ • patch — release branch: ship a patch (0.N.1, 0.N.2, ...)++ Any time:+ • alpha — master: bump the development version+ • custom — one-off branch (esbuild, data-apps): publish under its own prerelease id+ type: choice+ required: true+ options:+ - alpha+ - beta+ - preminor+ - patch+ - custom+ prerelease_id:+ description: "release_type=custom only, and only on the FIRST cut of a one-off branch (e.g. data-apps). Becomes the prerelease id in the version (0.62.5-data-apps.0) and the npm dist-tag (62-data-apps). Leave empty on later bumps - the id is reused from the current version."+ type: string+ required: false++concurrency:+ # one version-bump in flight per branch at a time, to avoid racing PRs+ group: ${{ github.workflow }}-${{ github.ref_name }}+ cancel-in-progress: false++jobs:+ bump-version:+ name: Bump SDK version and open review PR+ runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}+ timeout-minutes: 10+ permissions:+ contents: write+ pull-requests: write+ env:+ package_template: enterprise/frontend/src/embedding-sdk-package/package.template.json+ steps:+ - name: Check out the code+ uses: actions/checkout@v6+ with:+ token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}++ - name: Setup git user+ run: |+ git config --global user.email "[email protected]"+ git config --global user.name "Metabase Automation"++ - name: Prepare release scripts+ uses: ./.github/actions/prepare-release-scripts++ - name: Compute version and sdkRelease metadata+ id: metadata+ uses: actions/github-script@v9+ # Pass inputs via env, not inlined `${{ }}` in the script: github-script+ # interpolates expressions into the JS source before running it, so a+ # free-form input like prerelease_id could inject code. env values are+ # read at runtime and can't escape into the code.+ env:+ BRANCH: ${{ github.ref_name }}+ RELEASE_TYPE: ${{ inputs.release_type }}+ PRERELEASE_ID: ${{ inputs.prerelease_id }}+ LATEST_MAJOR_VERSION: ${{ vars.LATEST_MAJOR_VERSION }}+ PACKAGE_TEMPLATE: ${{ env.package_template }}+ with:+ script: | # js+ const { applySdkVersionBump } = require('${{ github.workspace }}/release/dist/index.cjs');++ let result;+ try {+ result = applySdkVersionBump({+ packageTemplatePath: process.env.PACKAGE_TEMPLATE,+ branch: process.env.BRANCH,+ releaseType: process.env.RELEASE_TYPE,+ prereleaseId: process.env.PRERELEASE_ID,+ latestMajorVersion: process.env.LATEST_MAJOR_VERSION,+ });+ } catch (error) {+ core.setFailed(error.message);+ return;+ }++ core.setOutput("previous_version", result.previousVersion);+ core.setOutput("new_version", result.newVersion);+ core.setOutput("major_version", result.majorVersion);+ core.setOutput("dist_tag", result.distTag);+ core.setOutput("tag_as_latest", String(result.tagAsLatest));++ - name: Append workflow summary+ env:+ BRANCH: ${{ github.ref_name }}+ run: |+ tee -a "$GITHUB_STEP_SUMMARY" << EOF+ **SDK version bump:**++ - \`branch\`: $BRANCH+ - \`release_type\`: ${{ inputs.release_type }}+ - \`previous_version\`: ${{ steps.metadata.outputs.previous_version }}+ - \`new_version\`: ${{ steps.metadata.outputs.new_version }}+ - \`distTag\` (default, review before merging): ${{ steps.metadata.outputs.dist_tag }}+ - \`tagAsLatest\` (auto-computed from \`vars.LATEST_MAJOR_VERSION\`, review before merging): ${{ steps.metadata.outputs.tag_as_latest }}++ triggered by: @${{ github.event.sender.login }}+ EOF++ - name: Commit version bump+ env:+ BUMP_BRANCH: sdk-version-bump-${{ steps.metadata.outputs.new_version }}+ run: |+ # A leftover branch means an earlier bump to this same version was+ # abandoned. Say so, rather than pushing a near-duplicate alongside it.+ if git ls-remote --exit-code --heads origin "$BUMP_BRANCH" >/dev/null 2>&1; then+ echo "::error::'$BUMP_BRANCH' already exists on origin - an earlier bump to this version was never merged. Close its PR, delete the branch, then re-run."+ exit 1+ fi++ git checkout -b "$BUMP_BRANCH"+ git add "$package_template"+ git commit -m "chore(sdk): bump SDK version to ${{ steps.metadata.outputs.new_version }} (${{ inputs.release_type }})"+ git push origin HEAD++ - name: Open version-bump PR (using GitHub Metabase Automation account)+ id: open-pr+ env:+ BRANCH: ${{ github.ref_name }}+ GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}+ run: |+ # TODO (EMB-2095) auto-approve and auto-merge this PR once the computed+ # version/distTag/tagAsLatest have proven out over a few real releases.+ # Nothing gates on review today - merging is only manual as a seatbelt.+ #+ # --reviewer tags the team so a release is visible, not because anything+ # waits on a review. It needs the automation PAT: GITHUB_TOKEN cannot+ # resolve an org team.+ gh pr create --base "$BRANCH" \+ --assignee "${GITHUB_ACTOR}" \+ --reviewer metabase/embedding \+ --label sdk-release-trigger \+ --title "chore(sdk): bump SDK version on $BRANCH to ${{ steps.metadata.outputs.new_version }}" \+ --body "$(cat <<'BODY'+ Bumps the Embedding SDK version in `package.template.json` and updates its `sdkRelease` metadata.++ | | |+ |---|---|+ | Branch | `${{ github.ref_name }}` |+ | Release type | `${{ inputs.release_type }}` |+ | Version | `${{ steps.metadata.outputs.previous_version }}` → `${{ steps.metadata.outputs.new_version }}` |+ | npm dist-tag | `${{ steps.metadata.outputs.dist_tag }}` |+ | Tag as `latest` | `${{ steps.metadata.outputs.tag_as_latest }}` |++ `distTag` and `tagAsLatest` are computed from the branch and release type. `tagAsLatest` is `true` only when patching the current gold major (`vars.LATEST_MAJOR_VERSION`).++ Merging this PR (with the `sdk-release-trigger` label) triggers [release-embedding-sdk.yml](../actions/workflows/release-embedding-sdk.yml), which builds, publishes to npm, and tags the release.++ _Opened by the [SDK Version Bump PR workflow](../actions/workflows/sdk-version-bump-pr.yml), triggered by @${{ github.event.sender.login }}._+ BODY+ )"diff --git a/bin/embedding-sdk/generate-sdk-package-files.js b/bin/embedding-sdk/generate-sdk-package-files.jsindex e56b35c2817..bfdc69499c4 100644--- a/bin/embedding-sdk/generate-sdk-package-files.js+++ b/bin/embedding-sdk/generate-sdk-package-files.js@@ -42,10 +42,16 @@ function generateSdkPackage() {);const sdkPackageTemplateJsonContent = JSON.parse(sdkPackageTemplateJson);+ // `sdkRelease` is release-process metadata (distTag/tagAsLatest) read by+ // .github/workflows/release-embedding-sdk.yml — it must never ship inside+ // the published npm package.json.+ const { sdkRelease: _sdkRelease, ...publishableTemplateJsonContent } =+ sdkPackageTemplateJsonContent;+const todayDate = new Date().toJSON().slice(0, 10).replaceAll("-", "");const mergedContent = {- ...sdkPackageTemplateJsonContent,+ ...publishableTemplateJsonContent,version: maybeCommitHash? `${sdkPackageTemplateJsonContent.version}-${todayDate}-${maybeCommitHash}`: sdkPackageTemplateJsonContent.version,diff --git a/bin/embedding-sdk/release_utils.bash b/bin/embedding-sdk/release_utils.bashdeleted file mode 100755index 776cf857ee4..00000000000--- a/bin/embedding-sdk/release_utils.bash+++ /dev/null@@ -1,11 +0,0 @@-#!/bin/bash-function update_readme() {- sed -i -E 's|(embedding-sdk-)[0-9.]+|\1'"$1"'|' enterprise/frontend/src/embedding-sdk-package/README.md- sed -i -E 's|(http://downloads.metabase.com/sdk/v)[0-9.]+|\1'"$1"'|' enterprise/frontend/src/embedding-sdk-package/README.md-}--function update_package_json_template() {- sed -i -E 's/("version": ").*"/\1'"$1"'"/' enterprise/frontend/src/embedding-sdk-package/package.template.json-}--$1 $2diff --git a/enterprise/frontend/src/embedding-sdk-package/package.template.json b/enterprise/frontend/src/embedding-sdk-package/package.template.jsonindex 4984d488a95..e19ccbff1f8 100644--- a/enterprise/frontend/src/embedding-sdk-package/package.template.json+++ b/enterprise/frontend/src/embedding-sdk-package/package.template.json@@ -1,6 +1,10 @@{"name": "@metabase/embedding-sdk-react","version": "0.64.0-alpha",+ "sdkRelease": {+ "distTag": "alpha",+ "tagAsLatest": false+ },"description": "Metabase Embedding SDK for React","bin": "./dist/cli.js","repository": {diff --git a/release/src/embedding-sdk-release-helpers.ts b/release/src/embedding-sdk-release-helpers.tsnew file mode 100644index 00000000000..2b4cf2c7914--- /dev/null+++ b/release/src/embedding-sdk-release-helpers.ts@@ -0,0 +1,321 @@+import { readFileSync, writeFileSync } from "fs";++import semver from "semver";++import {+ getMajorVersionNumberFromReleaseBranch,+ isReleaseBranch,+} from "./version-helpers";++// Compute what the Embedding SDK release publishes for a given branch, current+// version, and release type: the next version, its npm dist-tag, and whether it+// takes the `latest` tag.++export type SdkReleaseType = "alpha" | "beta" | "preminor" | "patch" | "custom";++// alpha and beta are reserved for the master and release-branch flows.+const RESERVED_PRERELEASE_IDS = ["alpha", "beta"];++// SDK major is the second segment (0.63.0 -> 63), not semver's major (always 0).+export function getSdkMajorVersion(version: string): string {+ return version.split(".")[1];+}++// The prerelease id on a version (0.62.5-data-apps.0 -> data-apps), or "".+function getPrereleaseId(version: string): string {+ const match = /^[0-9.]*-(?<prereleaseId>[a-z][a-z0-9-]*)(?:\.[0-9]*)?$/.exec(+ version,+ );+ return match?.groups?.prereleaseId ?? "";+}++const PRERELEASE_ID_PATTERN = /^[a-z][a-z0-9-]*$/;++// Input-only checks; the version-dependent custom checks live in+// computeNextSdkVersion.+export function validateBranchReleaseType({+ branch,+ releaseType,+ prereleaseId,+}: {+ branch: string;+ releaseType: SdkReleaseType;+ prereleaseId: string;+}): void {+ if (releaseType !== "custom" && prereleaseId) {+ throw new Error(+ `prerelease_id is only used with release_type=custom (got release_type=${releaseType}). Either pick release_type=custom, or clear prerelease_id.`,+ );+ }++ if (+ branch === "master" &&+ releaseType !== "alpha" &&+ releaseType !== "preminor"+ ) {+ throw new Error(+ `Only 'alpha' or 'preminor' releases can be bumped from the 'master' branch (got release_type=${releaseType}).`,+ );+ }++ if (+ isReleaseBranch(branch) &&+ releaseType !== "beta" &&+ releaseType !== "patch"+ ) {+ throw new Error(+ `Only 'beta' or 'patch' releases can be bumped from a release branch (got release_type=${releaseType}, branch=${branch}).`,+ );+ }++ if (+ branch !== "master" &&+ !isReleaseBranch(branch) &&+ releaseType !== "custom"+ ) {+ throw new Error(+ `'${branch}' is not master or a release branch - only release_type=custom is allowed here (got release_type=${releaseType}).`,+ );+ }++ if (+ releaseType === "custom" &&+ RESERVED_PRERELEASE_IDS.includes(prereleaseId)+ ) {+ throw new Error(+ `prerelease_id '${prereleaseId}' is reserved for master/release-branch releases. Pick a distinct one-off id (e.g. data-apps, esbuild).`,+ );+ }++ if (+ releaseType === "custom" &&+ prereleaseId &&+ !PRERELEASE_ID_PATTERN.test(prereleaseId)+ ) {+ throw new Error(+ `prerelease_id '${prereleaseId}' must be lowercase, start with a letter, and contain only letters, digits and hyphens (e.g. data-apps).`,+ );+ }+}++function increment({+ version,+ release,+ prereleaseId,+}: {+ version: string;+ release: semver.ReleaseType;+ prereleaseId: string;+}): string {+ // Empty prerelease id -> 2-arg call, so semver reuses any existing one.+ const next = prereleaseId+ ? semver.inc(version, release, prereleaseId)+ : semver.inc(version, release);+ if (!next) {+ throw new Error(+ `semver could not compute a ${release} bump from '${version}'.`,+ );+ }+ return next;+}++// Assumes the inputs already passed validateBranchReleaseType.+export function computeNextSdkVersion({+ currentVersion,+ releaseType,+ prereleaseId,+}: {+ currentVersion: string;+ releaseType: SdkReleaseType;+ prereleaseId: string;+}): string {+ switch (releaseType) {+ case "alpha":+ return increment({+ version: currentVersion,+ release: "prerelease",+ prereleaseId: "alpha",+ });+ case "beta":+ return increment({+ version: currentVersion,+ release: "prerelease",+ prereleaseId: "beta",+ });+ case "preminor":+ // next major's alpha (0.63.0-alpha.5 -> 0.64.0-alpha.0); plain alpha only+ // bumps the counter, never the minor.+ return increment({+ version: currentVersion,+ release: "preminor",+ prereleaseId: "alpha",+ });+ case "patch":+ return increment({+ version: currentVersion,+ release: "patch",+ prereleaseId: "",+ });+ case "custom": {+ // A one-off branch inherits alpha (from master) or beta (from a release+ // branch); neither is a one-off id, so it's still on its first cut.+ const currentPrereleaseId = getPrereleaseId(currentVersion);+ const existingPrereleaseId = RESERVED_PRERELEASE_IDS.includes(+ currentPrereleaseId,+ )+ ? ""+ : currentPrereleaseId;++ // prerelease_id is set iff this is the first cut.+ if (existingPrereleaseId && prereleaseId) {+ throw new Error(+ `This branch already uses the prerelease id '${existingPrereleaseId}' - leave prerelease_id empty to bump it. To change the id, reset the version in package.template.json by hand.`,+ );+ }+ if (!existingPrereleaseId && !prereleaseId) {+ throw new Error(+ "prerelease_id is required when cutting a new one-off branch - it becomes the prerelease id in the version (0.62.5-<id>.0) and the npm dist-tag (<major>-<id>).",+ );+ }++ // First cut: use the given prerelease id. Later (prerelease id ""): semver+ // reuses the prerelease id in the version.+ return increment({+ version: currentVersion,+ release: "prerelease",+ prereleaseId,+ });+ }+ default:+ throw new Error(`Unsupported release_type: ${releaseType}`);+ }+}++export function computeSdkDistTag({+ newVersion,+ releaseType,+}: {+ newVersion: string;+ releaseType: SdkReleaseType;+}): string {+ const major = getSdkMajorVersion(newVersion);+ switch (releaseType) {+ case "alpha":+ case "preminor":+ return "alpha";+ case "beta":+ return `${major}-beta`;+ case "patch":+ return `${major}-stable`;+ case "custom": {+ // id read back from the computed version (0.62.5-data-apps.0 -> 62-data-apps).+ const prereleaseId = getPrereleaseId(newVersion);+ if (!prereleaseId) {+ throw new Error(+ `Could not read a prerelease id back from '${newVersion}'.`,+ );+ }+ return `${major}-${prereleaseId}`;+ }+ default:+ throw new Error(`Unsupported release_type: ${releaseType}`);+ }+}++// `latest` only when patching the release branch whose major is the current gold.+export function shouldSdkTagAsLatest({+ releaseType,+ branch,+ latestMajorVersion,+}: {+ releaseType: SdkReleaseType;+ branch: string;+ latestMajorVersion: string;+}): boolean {+ return (+ releaseType === "patch" &&+ isReleaseBranch(branch) &&+ getMajorVersionNumberFromReleaseBranch(branch) === latestMajorVersion+ );+}++type SdkVersionBumpResult = {+ previousVersion: string;+ newVersion: string;+ majorVersion: string;+ distTag: string;+ tagAsLatest: boolean;+};++// Entry point for the SDK Version Bump PR workflow: read the current version,+// compute the bump, write it back, and return the values as step outputs.+export function applySdkVersionBump({+ packageTemplatePath,+ branch,+ releaseType,+ prereleaseId = "",+ latestMajorVersion,+}: {+ packageTemplatePath: string;+ branch: string;+ releaseType: SdkReleaseType;+ prereleaseId?: string;+ latestMajorVersion: string;+}): SdkVersionBumpResult {+ const packageTemplate = JSON.parse(readFileSync(packageTemplatePath, "utf8"));+ const previousVersion: string = packageTemplate.version;++ validateBranchReleaseType({ branch, releaseType, prereleaseId });+ const newVersion = computeNextSdkVersion({+ currentVersion: previousVersion,+ releaseType,+ prereleaseId,+ });+ const majorVersion = getSdkMajorVersion(newVersion);+ const distTag = computeSdkDistTag({ newVersion, releaseType });+ const tagAsLatest = shouldSdkTagAsLatest({+ releaseType,+ branch,+ latestMajorVersion,+ });++ // Mutate only .version and .sdkRelease, preserving the rest of the file.+ packageTemplate.version = newVersion;+ packageTemplate.sdkRelease = { distTag, tagAsLatest };+ writeFileSync(+ packageTemplatePath,+ JSON.stringify(packageTemplate, null, 2) + "\n",+ );++ return { previousVersion, newVersion, majorVersion, distTag, tagAsLatest };+}++type SdkReleaseMetadata = {+ version: string;+ majorVersion: string;+ distTag: string;+ tagAsLatest: boolean;+};++// Read the version + committed sdkRelease metadata (written by the bump PR) that+// the release workflow publishes. Throws if the sdkRelease block is missing.+export function readSdkReleaseMetadata({+ packageTemplatePath,+}: {+ packageTemplatePath: string;+}): SdkReleaseMetadata {+ const packageTemplate = JSON.parse(readFileSync(packageTemplatePath, "utf8"));+ const version: string = packageTemplate.version;+ const distTag: string = packageTemplate.sdkRelease?.distTag ?? "";+ if (!distTag) {+ throw new Error(+ `${packageTemplatePath} is missing sdkRelease.distTag - add it (via sdk-version-bump-pr.yml or by hand) before releasing.`,+ );+ }+ return {+ version,+ majorVersion: getSdkMajorVersion(version),+ distTag,+ tagAsLatest: packageTemplate.sdkRelease?.tagAsLatest ?? false,+ };+}diff --git a/release/src/embedding-sdk-release-helpers.unit.spec.ts b/release/src/embedding-sdk-release-helpers.unit.spec.tsnew file mode 100644index 00000000000..f5a1d7aeb92--- /dev/null+++ b/release/src/embedding-sdk-release-helpers.unit.spec.ts@@ -0,0 +1,534 @@+import { mkdtempSync, readFileSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";++import {+ applySdkVersionBump,+ computeNextSdkVersion,+ computeSdkDistTag,+ getSdkMajorVersion,+ readSdkReleaseMetadata,+ shouldSdkTagAsLatest,+ validateBranchReleaseType,+} from "./embedding-sdk-release-helpers";++function writeJsonTemplate(content: object): string {+ const directory = mkdtempSync(join(tmpdir(), "sdk-tpl-"));+ const path = join(directory, "package.template.json");+ writeFileSync(path, JSON.stringify(content, null, 2) + "\n");+ return path;+}++describe("embedding-sdk-release-helpers", () => {+ describe("getSdkMajorVersion", () => {+ it("takes the second dot-segment", () => {+ expect(getSdkMajorVersion("0.63.0")).toBe("63");+ expect(getSdkMajorVersion("0.63.0-alpha.5")).toBe("63");+ expect(getSdkMajorVersion("0.62.5-data-apps.0")).toBe("62");+ });+ });++ describe("validateBranchReleaseType", () => {+ it("accepts the legal branch x release_type combinations", () => {+ expect(() =>+ validateBranchReleaseType({+ branch: "master",+ releaseType: "alpha",+ prereleaseId: "",+ }),+ ).not.toThrow();+ expect(() =>+ validateBranchReleaseType({+ branch: "master",+ releaseType: "preminor",+ prereleaseId: "",+ }),+ ).not.toThrow();+ expect(() =>+ validateBranchReleaseType({+ branch: "release-x.63.x",+ releaseType: "beta",+ prereleaseId: "",+ }),+ ).not.toThrow();+ expect(() =>+ validateBranchReleaseType({+ branch: "release-x.63.x",+ releaseType: "patch",+ prereleaseId: "",+ }),+ ).not.toThrow();+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "data-apps",+ }),+ ).not.toThrow();+ // follow-up release: no prerelease id, reused from the version+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "",+ }),+ ).not.toThrow();+ });++ it("rejects release types that don't belong to the branch", () => {+ expect(() =>+ validateBranchReleaseType({+ branch: "master",+ releaseType: "beta",+ prereleaseId: "",+ }),+ ).toThrow(/Only 'alpha' or 'preminor'/);+ expect(() =>+ validateBranchReleaseType({+ branch: "release-x.63.x",+ releaseType: "alpha",+ prereleaseId: "",+ }),+ ).toThrow(/Only 'beta' or 'patch'/);+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "patch",+ prereleaseId: "",+ }),+ ).toThrow(/only release_type=custom is allowed/);+ });++ it("rejects prerelease_id on a non-custom release type", () => {+ expect(() =>+ validateBranchReleaseType({+ branch: "master",+ releaseType: "alpha",+ prereleaseId: "data-apps",+ }),+ ).toThrow(/prerelease_id is only used with release_type=custom/);+ });++ it("rejects the reserved alpha/beta ids for custom", () => {+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "alpha",+ }),+ ).toThrow(/reserved for master\/release-branch/);+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "beta",+ }),+ ).toThrow(/reserved for master\/release-branch/);+ });++ it("rejects a malformed custom id", () => {+ expect(() =>+ validateBranchReleaseType({+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "Data_Apps",+ }),+ ).toThrow(/must be lowercase/);+ });+ });++ describe("computeNextSdkVersion", () => {+ it("alpha bumps the prerelease counter", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-alpha.5",+ releaseType: "alpha",+ prereleaseId: "",+ }),+ ).toBe("0.63.0-alpha.6");+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-alpha",+ releaseType: "alpha",+ prereleaseId: "",+ }),+ ).toBe("0.63.0-alpha.0");+ });++ it("beta bumps the prerelease counter", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-beta.1",+ releaseType: "beta",+ prereleaseId: "",+ }),+ ).toBe("0.63.0-beta.2");+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-beta",+ releaseType: "beta",+ prereleaseId: "",+ }),+ ).toBe("0.63.0-beta.0");+ });++ it("preminor moves master to the next major's alpha", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-alpha.5",+ releaseType: "preminor",+ prereleaseId: "",+ }),+ ).toBe("0.64.0-alpha.0");+ });++ it("patch graduates a beta and then climbs", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-beta.2",+ releaseType: "patch",+ prereleaseId: "",+ }),+ ).toBe("0.63.0");+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0",+ releaseType: "patch",+ prereleaseId: "",+ }),+ ).toBe("0.63.1");+ });++ describe("custom", () => {+ it("first cut uses the supplied id (alpha/beta on the branch is still a first cut)", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.63.0-alpha.5",+ releaseType: "custom",+ prereleaseId: "data-apps",+ }),+ ).toBe("0.63.0-data-apps.0");+ });++ it("later bump reuses the id already in the version", () => {+ expect(+ computeNextSdkVersion({+ currentVersion: "0.62.5-data-apps.0",+ releaseType: "custom",+ prereleaseId: "",+ }),+ ).toBe("0.62.5-data-apps.1");+ expect(+ computeNextSdkVersion({+ currentVersion: "0.62.5-data-apps.1",+ releaseType: "custom",+ prereleaseId: "",+ }),+ ).toBe("0.62.5-data-apps.2");+ });++ it("errors when the branch already carries an id and one is also supplied", () => {+ expect(() =>+ computeNextSdkVersion({+ currentVersion: "0.62.5-data-apps.0",+ releaseType: "custom",+ prereleaseId: "data-apps",+ }),+ ).toThrow(/already uses the prerelease id 'data-apps'/);+ });++ it("errors when neither an existing nor a supplied id is present", () => {+ // the alpha means this branch was just cut from master, so it's a first+ // cut and needs a supplied id+ expect(() =>+ computeNextSdkVersion({+ currentVersion: "0.63.0-alpha.5",+ releaseType: "custom",+ prereleaseId: "",+ }),+ ).toThrow(/prerelease_id is required when cutting a new one-off branch/);+ });+ });++ it("rejects an unsupported release type", () => {+ expect(() =>+ computeNextSdkVersion({+ currentVersion: "0.63.0",+ // @ts-expect-error - exercising the runtime guard+ releaseType: "nonsense",+ prereleaseId: "",+ }),+ ).toThrow(/Unsupported release_type/);+ });+ });++ describe("computeSdkDistTag", () => {+ it("maps each release type to its real dist-tag", () => {+ expect(+ computeSdkDistTag({ newVersion: "0.63.0-alpha.6", releaseType: "alpha" }),+ ).toBe("alpha");+ expect(+ computeSdkDistTag({+ newVersion: "0.64.0-alpha.0",+ releaseType: "preminor",+ }),+ ).toBe("alpha");+ expect(+ computeSdkDistTag({ newVersion: "0.63.0-beta.0", releaseType: "beta" }),+ ).toBe("63-beta");+ expect(+ computeSdkDistTag({ newVersion: "0.63.0", releaseType: "patch" }),+ ).toBe("63-stable");+ expect(+ computeSdkDistTag({+ newVersion: "0.62.5-data-apps.0",+ releaseType: "custom",+ }),+ ).toBe("62-data-apps");+ });++ it("errors when a custom version has no readable prerelease id", () => {+ expect(() =>+ computeSdkDistTag({ newVersion: "0.63.0", releaseType: "custom" }),+ ).toThrow(/Could not read a prerelease id/);+ });+ });++ describe("shouldSdkTagAsLatest", () => {+ it("is true only when patching the current gold major on a release branch", () => {+ expect(+ shouldSdkTagAsLatest({+ releaseType: "patch",+ branch: "release-x.63.x",+ latestMajorVersion: "63",+ }),+ ).toBe(true);+ });++ it("is false for every other combination", () => {+ // not a patch+ expect(+ shouldSdkTagAsLatest({+ releaseType: "beta",+ branch: "release-x.63.x",+ latestMajorVersion: "63",+ }),+ ).toBe(false);+ // not a release branch+ expect(+ shouldSdkTagAsLatest({+ releaseType: "patch",+ branch: "master",+ latestMajorVersion: "63",+ }),+ ).toBe(false);+ // release branch's major is not the current gold major+ expect(+ shouldSdkTagAsLatest({+ releaseType: "patch",+ branch: "release-x.62.x",+ latestMajorVersion: "63",+ }),+ ).toBe(false);+ });+ });++ describe("applySdkVersionBump", () => {+ function writeTemplate(version: string): string {+ const directory = mkdtempSync(join(tmpdir(), "sdk-bump-"));+ const path = join(directory, "package.template.json");+ writeFileSync(+ path,+ JSON.stringify(+ { name: "@metabase/embedding-sdk-react", version, description: "x" },+ null,+ 2,+ ) + "\n",+ );+ return path;+ }++ it("alpha bump on master writes the file and returns outputs", () => {+ const path = writeTemplate("0.63.0-alpha.5");++ const result = applySdkVersionBump({+ packageTemplatePath: path,+ branch: "master",+ releaseType: "alpha",+ latestMajorVersion: "63",+ });++ expect(result).toEqual({+ previousVersion: "0.63.0-alpha.5",+ newVersion: "0.63.0-alpha.6",+ majorVersion: "63",+ distTag: "alpha",+ tagAsLatest: false,+ });++ const written = JSON.parse(readFileSync(path, "utf8"));+ expect(written.version).toBe("0.63.0-alpha.6");+ expect(written.sdkRelease).toEqual({ distTag: "alpha", tagAsLatest: false });+ // other keys are preserved+ expect(written.name).toBe("@metabase/embedding-sdk-react");+ expect(written.description).toBe("x");+ });++ it("beta on a release branch", () => {+ const path = writeTemplate("0.63.0-beta.1");++ expect(+ applySdkVersionBump({+ packageTemplatePath: path,+ branch: "release-x.63.x",+ releaseType: "beta",+ latestMajorVersion: "63",+ }),+ ).toEqual({+ previousVersion: "0.63.0-beta.1",+ newVersion: "0.63.0-beta.2",+ majorVersion: "63",+ distTag: "63-beta",+ tagAsLatest: false,+ });+ });++ it("patch that graduates to gold and takes latest", () => {+ const path = writeTemplate("0.63.0-beta.2");++ const result = applySdkVersionBump({+ packageTemplatePath: path,+ branch: "release-x.63.x",+ releaseType: "patch",+ latestMajorVersion: "63",+ });++ expect(result).toEqual({+ previousVersion: "0.63.0-beta.2",+ newVersion: "0.63.0",+ majorVersion: "63",+ distTag: "63-stable",+ tagAsLatest: true,+ });+ expect(JSON.parse(readFileSync(path, "utf8")).sdkRelease).toEqual({+ distTag: "63-stable",+ tagAsLatest: true,+ });+ });++ it("patch on an older release branch does not take latest", () => {+ const path = writeTemplate("0.62.0");++ expect(+ applySdkVersionBump({+ packageTemplatePath: path,+ branch: "release-x.62.x",+ releaseType: "patch",+ latestMajorVersion: "63",+ }),+ ).toEqual({+ previousVersion: "0.62.0",+ newVersion: "0.62.1",+ majorVersion: "62",+ distTag: "62-stable",+ tagAsLatest: false,+ });+ });++ it("custom first cut on a one-off branch", () => {+ const path = writeTemplate("0.63.0-alpha.5");++ expect(+ applySdkVersionBump({+ packageTemplatePath: path,+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "data-apps",+ latestMajorVersion: "63",+ }),+ ).toEqual({+ previousVersion: "0.63.0-alpha.5",+ newVersion: "0.63.0-data-apps.0",+ majorVersion: "63",+ distTag: "63-data-apps",+ tagAsLatest: false,+ });+ });++ it("custom follow-up release reuses the id already on the branch", () => {+ const path = writeTemplate("0.63.0-data-apps.0");++ expect(+ applySdkVersionBump({+ packageTemplatePath: path,+ branch: "data-apps",+ releaseType: "custom",+ latestMajorVersion: "63",+ }),+ ).toEqual({+ previousVersion: "0.63.0-data-apps.0",+ newVersion: "0.63.0-data-apps.1",+ majorVersion: "63",+ distTag: "63-data-apps",+ tagAsLatest: false,+ });+ });++ it("propagates validation errors without writing the file", () => {+ const path = writeTemplate("0.63.0-alpha.5");++ expect(() =>+ applySdkVersionBump({+ packageTemplatePath: path,+ branch: "data-apps",+ releaseType: "custom",+ prereleaseId: "beta",+ latestMajorVersion: "63",+ }),+ ).toThrow(/reserved for master\/release-branch/);+ // the file is untouched on a validation failure+ expect(JSON.parse(readFileSync(path, "utf8")).version).toBe(+ "0.63.0-alpha.5",+ );+ });+ });++ describe("readSdkReleaseMetadata", () => {+ it("reads the committed version + sdkRelease metadata", () => {+ const path = writeJsonTemplate({+ name: "@metabase/embedding-sdk-react",+ version: "0.63.0",+ sdkRelease: { distTag: "63-stable", tagAsLatest: true },+ });++ expect(readSdkReleaseMetadata({ packageTemplatePath: path })).toEqual({+ version: "0.63.0",+ majorVersion: "63",+ distTag: "63-stable",+ tagAsLatest: true,+ });+ });++ it("defaults tagAsLatest to false when it's absent", () => {+ const path = writeJsonTemplate({+ version: "0.63.0-alpha.6",+ sdkRelease: { distTag: "alpha" },+ });++ expect(readSdkReleaseMetadata({ packageTemplatePath: path })).toEqual({+ version: "0.63.0-alpha.6",+ majorVersion: "63",+ distTag: "alpha",+ tagAsLatest: false,+ });+ });++ it("throws when the sdkRelease distTag is missing", () => {+ const path = writeJsonTemplate({ version: "0.63.0" });++ expect(() =>+ readSdkReleaseMetadata({ packageTemplatePath: path }),+ ).toThrow(/missing sdkRelease\.distTag/);+ });+ });+});diff --git a/release/src/index.ts b/release/src/index.tsindex 2375b4745b3..d8301ed8bfe 100644--- a/release/src/index.ts+++ b/release/src/index.ts@@ -7,3 +7,4 @@ export * from "./slack";export * from "./version-helpers";export * from "./version-info";export * from "./cross-version-slack";+export * from "./embedding-sdk-release-helpers";diff --git a/release/src/version-helpers.ts b/release/src/version-helpers.tsindex b50d914aff1..308c60cab63 100644--- a/release/src/version-helpers.ts+++ b/release/src/version-helpers.ts@@ -116,18 +116,6 @@ export const getMajorVersionFromRef = (ref: string) => {return getMajorVersionNumberFromReleaseBranch(ref.replace("refs/heads/", ""));};-const SDK_TAG_REGEXP = /embedding-sdk-(0\.\d+\.\d+(-\w+)?)$/;--export const getSdkVersionFromReleaseTagName = (tagName: string) => {- const match = SDK_TAG_REGEXP.exec(tagName);-- if (!match) {- throw new Error(`Invalid sdk release tag: ${tagName}`);- }-- return match[1];-};-export const getDotXs = (version: string, number: number) => {const pieces = version.replace(/-.+/, "").split("."); // ignore any -suffixesreturn pieces.slice(0, number + 1).join(".") + ".x";@@ -180,45 +168,6 @@ export const getExtraTagsForVersion = ({];};-/**- * queries the github api to get all embedding sdk version tags- */-export async function getLastEmbeddingSdkReleaseTag({- github,- owner,- repo,- majorVersion = "",-}: GithubProps & {- majorVersion?: string;-}) {- const tags = await github.paginate(github.rest.git.listMatchingRefs, {- owner,- repo,- ref: `tags/embedding-sdk-0.${majorVersion}`,- });-- const lastRelease = getLastReleaseFromTags({- tags: tags.filter(filterOutNonSupportedPrereleaseIdentifier),- });-- return lastRelease;-}--const ALLOWED_SDK_PRERELEASE_IDENTIFIERS = ["nightly"];-/**- *- * @param tag a GitHub tag object- */-export function filterOutNonSupportedPrereleaseIdentifier(tag: Tag) {- const prereleaseIdentifier = /\d+\.\d+\.\d+-(?<prerelease>\w+)$/.exec(tag.ref)- ?.groups?.prerelease;-- return (- !prereleaseIdentifier ||- ALLOWED_SDK_PRERELEASE_IDENTIFIERS.includes(prereleaseIdentifier)- );-}-export const getMajorVersionNumberFromReleaseBranch = (branch: string) => {const match = /release-x\.(\d+)\.x$/.exec(branch);@@ -497,106 +446,3 @@ export const getNextVersion = async ({? getNextPatchVersion({ github, owner, repo, majorVersion }): getNextMinorVersion({ github, owner, repo, majorVersion });};--type SdkVersionInfo = {- version: string;- preReleaseLabel: string;- majorVersion: string;-};--type PreReleaseInfo = {- label: string;- version: number | null;-};--const parsePreReleaseSuffix = (suffix: string | undefined): PreReleaseInfo => {- if (!suffix) {- return { label: "", version: null };- }-- const [label, versionStr] = suffix.split(".");- const version = versionStr ? parseInt(versionStr, 10) : null;-- return { label: label ?? "", version };-};--const getNextAlphaVersion = (- currentVersionBase: string,- preRelease: PreReleaseInfo,- majorVersion: string,-): SdkVersionInfo => {- if (preRelease.label !== "alpha") {- throw new Error(- "Only `alpha` versions can be released from the `master` branch.",- );- }-- const nextPreReleaseVersion = (preRelease.version ?? -1) + 1;-- return {- version: `${currentVersionBase}-${preRelease.label}.${nextPreReleaseVersion}`,- preReleaseLabel: preRelease.label,- majorVersion,- };-};--const getNextReleaseBranchVersion = (- versionParts: string[],- preRelease: PreReleaseInfo,- majorVersion: string,-): SdkVersionInfo => {- if (preRelease.label && preRelease.label !== "beta") {- throw new Error(- "Only `beta` versions can be released from the `release` branch.",- );- }-- const updatedVersionParts = [...versionParts];- const lastIndex = updatedVersionParts.length - 1;- const patchVersion = updatedVersionParts[lastIndex] ?? "0";-- // Handle .x placeholder versions- if (patchVersion === "x") {- updatedVersionParts[lastIndex] = "0";- } else if (!preRelease.label && preRelease.version === null) {- // Increment patch version for stable releases- const currentPatch = parseInt(patchVersion, 10) || 0;- updatedVersionParts[lastIndex] = String(currentPatch + 1);- }-- const newVersionBase = updatedVersionParts.join(".");- const nextPreReleaseVersion = (preRelease.version ?? -1) + 1;-- const versionSuffix = preRelease.label- ? `-${preRelease.label}.${nextPreReleaseVersion}`- : "";-- return {- version: `${newVersionBase}${versionSuffix}`,- preReleaseLabel: "",- majorVersion,- };-};--export const getNextSdkVersion = (- branch: string,- currentVersion: string,-): SdkVersionInfo => {- const [currentVersionBase, suffix] = currentVersion.split("-");- const versionParts = currentVersionBase.split(".");- const majorVersion = versionParts[1] ?? "";-- if (branch === "master") {- if (!suffix) {- throw new Error(- `Expected pre-release suffix on master branch, got: ${currentVersion}`,- );- }-- const preRelease = parsePreReleaseSuffix(suffix);- return getNextAlphaVersion(currentVersionBase, preRelease, majorVersion);- }-- const preRelease = parsePreReleaseSuffix(suffix);- return getNextReleaseBranchVersion(versionParts, preRelease, majorVersion);-};diff --git a/release/src/version-helpers.unit.spec.ts b/release/src/version-helpers.unit.spec.tsindex 832f49a6345..05d99fc1b45 100644--- a/release/src/version-helpers.unit.spec.ts+++ b/release/src/version-helpers.unit.spec.ts@@ -1,6 +1,5 @@import type { Tag } from "./types";import {- filterOutNonSupportedPrereleaseIdentifier,findNextMinorVersion,findNextPatchVersion,getBuildRequirements,@@ -14,11 +13,9 @@ import {getMajorVersionNumberFromReleaseBranch,getMilestoneName,getMinorVersion,- getNextSdkVersion,getNextVersions,getOSSVersion,getReleaseBranch,- getSdkVersionFromReleaseTagName,getVersionFromReleaseBranch,getVersionType,isEnterpriseVersion,@@ -729,19 +726,6 @@ describe("version-helpers", () => {});});- describe("getSdkVersionFromReleaseTagName", () => {- it("should resolve sdk package version from assigned release tag", () => {- expect(getSdkVersionFromReleaseTagName("embedding-sdk-0.51.9")).toEqual(- "0.51.9",- );- expect(- getSdkVersionFromReleaseTagName("embedding-sdk-0.52.2-nightly"),- ).toEqual("0.52.2-nightly");-- expect(() => getSdkVersionFromReleaseTagName("v0.51.5.1")).toThrow();- });- });-describe("getDotXs", () => {it("should return the correct major dot Xs", () => {expect(getDotXs("v1.75.0", 1)).toEqual("v1.75.x");@@ -896,28 +880,6 @@ describe("version-helpers", () => {});});- describe("filterOutNonSupportedPrereleaseIdentifier", () => {- function createTags(versions: string[]): Tag[] {- return versions.map(- (tag) => ({ ref: `refs/tags/embedding-sdk-${tag}` }) as Tag,- );- }-- it("should ignore prerelease labels that are not `nightly` when passing refs", () => {- const filteredTags = createTags([- "0.55.0",- "0.55.0-nightly",- "0.55.0-rc1",- "0.55.0-rc2",- "0.55.0-beta",- "0.55.0-alpha",- "0.55.5-metabot",- ]).filter(filterOutNonSupportedPrereleaseIdentifier);-- expect(filteredTags).toEqual(createTags(["0.55.0", "0.55.0-nightly"]));- });- });-describe("getMajorVersion", () => {it.each([["v0.52.3", "52"],@@ -938,78 +900,4 @@ describe("version-helpers", () => {});});- describe("getNextSdkVersion", () => {- describe("master branch (pre-release versions)", () => {- it("should increment pre-release version if suffix exists", () => {- const result = getNextSdkVersion("master", "0.57.0-alpha.1");- expect(result).toEqual({- version: "0.57.0-alpha.2",- preReleaseLabel: "alpha",- majorVersion: "57",- });- });-- it("should set next pre-release version to .1 if no numeric part in suffix", () => {- const result = getNextSdkVersion("master", "0.57.0-alpha");- expect(result).toEqual({- version: "0.57.0-alpha.0",- preReleaseLabel: "alpha",- majorVersion: "57",- });- });-- it("should throw an error if no suffix is provided on master branch", () => {- expect(() => getNextSdkVersion("master", "0.57.0")).toThrow(- "Expected pre-release suffix on master branch, got: 0.57.0",- );- });- });-- describe("release/stable branches (non-master)", () => {- it("should increment patch version when no suffix", () => {- const result = getNextSdkVersion("release-x.57.x", "0.57.0");- expect(result).toEqual({- version: "0.57.1",- preReleaseLabel: "",- majorVersion: "57",- });- });-- it("should set proper initial patch version for a next major release", () => {- const result = getNextSdkVersion("release-x.57.x", "0.57.x");- expect(result).toEqual({- version: "0.57.0",- preReleaseLabel: "",- majorVersion: "57",- });- });-- it("should set initial pre-release version when suffix is preset, but pre-release version is not", () => {- const result = getNextSdkVersion("release-x.57.x", "0.57.0-beta");- expect(result).toEqual({- version: "0.57.0-beta.0",- preReleaseLabel: "",- majorVersion: "57",- });- });-- it("should set proper initial patch version when pre-release suffix is preset", () => {- const result = getNextSdkVersion("release-x.57.x", "0.57.x-beta");- expect(result).toEqual({- version: "0.57.0-beta.0",- preReleaseLabel: "",- majorVersion: "57",- });- });-- it("should increment pre-release version", () => {- const result = getNextSdkVersion("release-x.57.x", "0.57.0-beta.0");- expect(result).toEqual({- version: "0.57.0-beta.1",- preReleaseLabel: "",- majorVersion: "57",- });- });- });- });});