From c6ac80330f5254b165f8721385841e0d0ef84396 Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Tue, 24 Nov 2026 19:34:06 -0800 Subject: [PATCH 1/4] feat(ci): add Azure Pipelines npm release publisher Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/npm-publish.yml | 86 +++++++ scripts/ado-npm-publisher.cjs | 270 ++++++++++++++++++++ scripts/ado-npm-publisher.test.cjs | 382 +++++++++++++++++++++++++++++ 3 files changed, 738 insertions(+) create mode 100644 .azure-pipelines/npm-publish.yml create mode 100644 scripts/ado-npm-publisher.cjs create mode 100644 scripts/ado-npm-publisher.test.cjs diff --git a/.azure-pipelines/npm-publish.yml b/.azure-pipelines/npm-publish.yml new file mode 100644 index 00000000000..5b617b791b4 --- /dev/null +++ b/.azure-pipelines/npm-publish.yml @@ -0,0 +1,86 @@ +# Manual npm release publish pipeline for LogicAppsUX. +# +# Versioning and GitHub Release creation stay in .github/workflows/version-release.yml. +# Given a release version (e.g. 5.1024.0), this pipeline checks out the existing v +# tag into a clean detached worktree, builds and packs the 9 publishable packages, and +# publishes any missing packages to the Azure Artifacts npm feed. +trigger: none +pr: none +schedules: [] + +parameters: + - name: releaseVersion + displayName: Release version (e.g. 5.1024.0) + type: string + default: '' + +variables: + NpmRegistry: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' + TarballDir: '$(Agent.TempDirectory)/npm-tarballs' + PublishNpmrc: '$(Agent.TempDirectory)/npm-publish/.npmrc' + +resources: + repositories: + - repository: 1esPipelines + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release + +extends: + template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines + parameters: + pool: + name: Azure-Pipelines-1ESPT-ExDShared + image: ubuntu-latest + os: linux + sdl: + componentgovernance: + useAgentBuildDirectory: true + sourceAnalysisPool: + name: Azure-Pipelines-1ESPT-ExDShared + image: windows-latest + os: windows + stages: + - stage: Publish + displayName: Build and publish npm packages + lockBehavior: sequential + condition: and(succeeded(), or(eq(variables['Build.SourceBranch'], 'refs/heads/main'), startsWith(variables['Build.SourceBranch'], 'refs/heads/hotfix/v'))) + jobs: + - job: BuildAndPublish + displayName: Build release tag and publish to npm feed + workspace: + clean: all + steps: + - checkout: self + clean: true + fetchTags: true + fetchDepth: 0 + persistCredentials: false + - task: UseNode@1 + displayName: Use Node 24 + inputs: + version: '24.x' + - bash: node scripts/ado-npm-publisher.cjs build + displayName: Build and pack release packages + workingDirectory: '$(Build.Repository.LocalPath)' + env: + RELEASE_VERSION: ${{ parameters.releaseVersion }} + AGENT_TMP: '$(Agent.TempDirectory)' + RELEASE_SCAN_ROOT: '$(Agent.BuildDirectory)' + TARBALL_DIR: '$(TarballDir)' + NPM_REGISTRY: '$(NpmRegistry)' + PUBLISH_NPMRC: '$(PublishNpmrc)' + - task: npmAuthenticate@0 + displayName: Authenticate npm feed via WIF + inputs: + workingFile: '$(PublishNpmrc)' + workloadIdentityServiceConnection: 21d5a1d8-11d3-425c-8d3a-e7f088725481 + feedUrl: 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/' + - bash: node scripts/ado-npm-publisher.cjs publish + displayName: Publish packages to Azure Artifacts npm feed + workingDirectory: '$(Build.Repository.LocalPath)' + env: + RELEASE_VERSION: ${{ parameters.releaseVersion }} + TARBALL_DIR: '$(TarballDir)' + NPM_REGISTRY: '$(NpmRegistry)' + PUBLISH_NPMRC: '$(PublishNpmrc)' \ No newline at end of file diff --git a/scripts/ado-npm-publisher.cjs b/scripts/ado-npm-publisher.cjs new file mode 100644 index 00000000000..0e99cadb198 --- /dev/null +++ b/scripts/ado-npm-publisher.cjs @@ -0,0 +1,270 @@ +const { spawnSync } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const DEFAULT_REGISTRY = 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/'; +const PNPM_MIRROR_BASE = 'https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry'; + +// Publishable workspace libraries in dependency order (matches scripts/update-versions.js). +const PACKAGES = [ + { directory: 'libs/logic-apps-shared', name: '@microsoft/logic-apps-shared' }, + { directory: 'libs/designer-ui', name: '@microsoft/designer-ui' }, + { directory: 'libs/designer-ui-v2', name: '@microsoft/designer-ui-v2' }, + { directory: 'libs/chatbot', name: '@microsoft/logic-apps-chatbot' }, + { directory: 'libs/designer', name: '@microsoft/logic-apps-designer' }, + { directory: 'libs/designer-v2', name: '@microsoft/logic-apps-designer-v2' }, + { directory: 'libs/data-mapper', name: '@microsoft/logic-apps-data-mapper' }, + { directory: 'libs/data-mapper-v2', name: '@microsoft/logic-apps-data-mapper-v2' }, + { directory: 'libs/vscode-extension', name: '@microsoft/vscode-extension-logic-apps' }, +]; + +function parseReleaseVersion(raw) { + const value = typeof raw === 'string' ? raw.trim() : ''; + if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) { + throw new Error(`Invalid releaseVersion '${value}'. Expected a version like 5.1024.0 (without the 'v' prefix).`); + } + return value; +} + +function tarballName(packageName, version) { + return `${packageName.replace(/^@/, '').replace('/', '-')}-${version}.tgz`; +} + +function runCommand(command, args, options, run = spawnSync) { + const result = run(command, args, options); + if (result.error || result.status !== 0) { + const detail = result.error?.message ?? `exit ${result.status ?? 'unknown'}`; + const stderr = typeof result.stderr === 'string' && result.stderr.trim() ? `\n${result.stderr.trim()}` : ''; + throw new Error(`${command} ${args[0] ?? ''} failed (${detail}).${stderr}`.trim()); + } + return result; +} + +function resolveReleaseTag(repoRoot, version, run = spawnSync) { + const tag = `v${version}`; + const ref = `refs/tags/${tag}`; + const gitOptions = { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }; + + const showRef = run('git', ['show-ref', '--verify', '--hash', '--', ref], gitOptions); + if (showRef.error || showRef.status !== 0) { + throw new Error(`Release tag '${tag}' was not found in the local repository.`); + } + const tagSha = showRef.stdout.trim(); + + const revParse = run('git', ['rev-parse', '--verify', `${tagSha}^{commit}`], gitOptions); + if (revParse.error || revParse.status !== 0) { + throw new Error(`Release tag '${tag}' does not resolve to a commit.`); + } + return { tag, ref, commitSha: revParse.stdout.trim() }; +} + +// 1ES Linux network isolation blocks Corepack from reaching registry.npmjs.org, +// so download the exact pnpm version declared in package.json from the 1ES mirror. +function bootstrapPnpm(sourceRoot, pnpmHome, run = spawnSync) { + const { packageManager } = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8')); + const match = /^pnpm@(\d+\.\d+\.\d+)(?:\+sha512\.([a-f0-9]{128}))?$/.exec(packageManager ?? ''); + if (!match) { + throw new Error(`Unsupported packageManager '${packageManager ?? ''}' in package.json.`); + } + const [, pnpmVersion, expectedSha512] = match; + const archive = path.join(pnpmHome, `pnpm-${pnpmVersion}.tgz`); + const url = `${PNPM_MIRROR_BASE}/pnpm/-/pnpm-${pnpmVersion}.tgz`; + + runCommand( + 'curl', + ['--fail', '--silent', '--show-error', '--location', '--output', archive, url], + { cwd: pnpmHome, stdio: 'inherit', timeout: 120_000 }, + run + ); + + if (expectedSha512) { + const actualSha512 = createHash('sha512').update(fs.readFileSync(archive)).digest('hex'); + if (actualSha512 !== expectedSha512) { + throw new Error(`Downloaded pnpm@${pnpmVersion} archive SHA-512 does not match packageManager pin.`); + } + } + + runCommand('tar', ['-xzf', archive, '-C', pnpmHome], { cwd: pnpmHome, stdio: 'inherit', timeout: 60_000 }, run); + + const binDir = path.join(pnpmHome, 'bin'); + fs.mkdirSync(binDir, { recursive: true }); + const pnpmBin = path.join(binDir, 'pnpm'); + fs.symlinkSync(path.join(pnpmHome, 'package', 'bin', 'pnpm.cjs'), pnpmBin); + return { pnpmBin, binDir }; +} + +function buildRelease(env, { run = spawnSync, log = console.log, repoRoot = process.cwd() } = {}) { + const version = parseReleaseVersion(env.RELEASE_VERSION); + const agentTmp = env.AGENT_TMP || os.tmpdir(); + const tarballDir = env.TARBALL_DIR || path.join(agentTmp, 'npm-tarballs'); + const registry = env.NPM_REGISTRY || DEFAULT_REGISTRY; + const npmrcPath = env.PUBLISH_NPMRC; + + const { tag, commitSha } = resolveReleaseTag(repoRoot, version, run); + log(`Resolved ${tag} to ${commitSha}.`); + + // Retain the release worktree under RELEASE_SCAN_ROOT (Agent.BuildDirectory) when set + // so 1ES Component Governance scans the released tag's lockfile and node_modules. + const scanRoot = env.RELEASE_SCAN_ROOT; + const sourceRoot = path.join(scanRoot || agentTmp, 'release-source'); + fs.rmSync(sourceRoot, { recursive: true, force: true }); + run('git', ['worktree', 'prune'], { cwd: repoRoot, stdio: 'ignore' }); + runCommand('git', ['worktree', 'add', '--quiet', '--detach', sourceRoot, commitSha], { cwd: repoRoot, stdio: 'inherit' }, run); + + const pnpmHome = fs.mkdtempSync(path.join(agentTmp, 'pnpm-bootstrap-')); + let retainForScan = false; + + try { + const { pnpmBin, binDir } = bootstrapPnpm(sourceRoot, pnpmHome, run); + const buildEnv = { + ...env, + PATH: `${binDir}${path.delimiter}${env.PATH ?? process.env.PATH ?? ''}`, + HOME: pnpmHome, + CI: 'true', + HUSKY: '0', + NPM_CONFIG_USERCONFIG: '/dev/null', + }; + const execOptions = { cwd: sourceRoot, env: buildEnv, stdio: 'inherit', timeout: 1_800_000 }; + + runCommand(pnpmBin, ['install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies'], execOptions, run); + runCommand(process.execPath, ['scripts/update-versions.js', version], execOptions, run); + runCommand(pnpmBin, ['run', 'build:lib'], execOptions, run); + + fs.rmSync(tarballDir, { recursive: true, force: true }); + fs.mkdirSync(tarballDir, { recursive: true }); + + // Pack via pnpm so workspace:* references and publishConfig fields are rewritten into each tarball. + for (const pkg of PACKAGES) { + runCommand(pnpmBin, ['--dir', path.join(sourceRoot, pkg.directory), 'pack', '--pack-destination', tarballDir], execOptions, run); + const expectedTarball = path.join(tarballDir, tarballName(pkg.name, version)); + if (!fs.existsSync(expectedTarball)) { + throw new Error(`Expected packed tarball was not created: ${expectedTarball}`); + } + } + + if (npmrcPath) { + fs.mkdirSync(path.dirname(npmrcPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync(npmrcPath, `registry=${registry}\n`, { mode: 0o600 }); + } + + log(`Built and packed ${PACKAGES.length} packages for v${version} into ${tarballDir}.`); + + if (scanRoot) { + runCommand('git', ['restore', '--source', commitSha, '--staged', '--worktree', '--', '.'], { cwd: sourceRoot, stdio: 'inherit' }, run); + retainForScan = true; + } + + return { version, tag, commitSha, tarballDir }; + } finally { + fs.rmSync(pnpmHome, { recursive: true, force: true }); + if (!retainForScan) { + run('git', ['worktree', 'remove', '--force', sourceRoot], { cwd: repoRoot, stdio: 'ignore' }); + fs.rmSync(sourceRoot, { recursive: true, force: true }); + } + } +} + +function isVersionInFeed(packageName, version, { registry, npmrc, cwd, run = spawnSync }) { + const spec = `${packageName}@${version}`; + const result = run( + 'npm', + ['view', spec, 'version', '--registry', registry, '--userconfig', npmrc, '--prefer-online'], + { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 } + ); + + if (result.error) { + throw new Error(`Failed to check ${spec} in feed: ${result.error.message}`); + } + if (result.status === 0) { + // When the package exists in the feed but the requested version does not, npm view exits 0 with empty stdout. + return (result.stdout ?? '').trim() === version; + } + + const combined = `${result.stdout ?? ''}\n${result.stderr ?? ''}`; + if (/\bE404\b|404 Not Found|is not in this registry/i.test(combined)) { + return false; + } + throw new Error(`Failed to check ${spec} in feed (exit ${result.status}): ${combined.trim()}`); +} + +function publishRelease(env, { run = spawnSync, log = console.log } = {}) { + const version = parseReleaseVersion(env.RELEASE_VERSION); + const tarballDir = env.TARBALL_DIR; + const npmrc = env.PUBLISH_NPMRC; + const registry = env.NPM_REGISTRY || DEFAULT_REGISTRY; + + if (!tarballDir || !fs.existsSync(tarballDir)) { + throw new Error(`Tarball directory does not exist: ${tarballDir ?? '(unset)'}`); + } + if (!npmrc || !fs.existsSync(npmrc)) { + throw new Error(`Authenticated .npmrc file does not exist: ${npmrc ?? '(unset)'}`); + } + + let published = 0; + let skipped = 0; + + for (const pkg of PACKAGES) { + const spec = `${pkg.name}@${version}`; + const tarball = path.join(tarballDir, tarballName(pkg.name, version)); + if (!fs.existsSync(tarball)) { + throw new Error(`Missing tarball for ${spec}: ${tarball}`); + } + + if (isVersionInFeed(pkg.name, version, { registry, npmrc, cwd: tarballDir, run })) { + log(`Skipping ${spec} (already exists in feed).`); + skipped += 1; + continue; + } + + log(`Publishing ${spec}...`); + runCommand( + 'npm', + ['publish', tarball, '--tag', 'latest', '--registry', registry, '--userconfig', npmrc], + { cwd: tarballDir, stdio: 'inherit', timeout: 180_000 }, + run + ); + log(`Published ${spec}.`); + published += 1; + } + + log(`Publish complete for ${version}: ${published} published, ${skipped} skipped.`); + return { version, published, skipped }; +} + +function main([command, ...rest] = process.argv.slice(2), env = process.env, options = {}) { + if (rest.length > 0) { + throw new Error('Unexpected arguments. Usage: node scripts/ado-npm-publisher.cjs '); + } + if (command === 'build') { + return buildRelease(env, options); + } + if (command === 'publish') { + return publishRelease(env, options); + } + throw new Error(`Unknown command '${command ?? ''}'. Expected 'build' or 'publish'.`); +} + +if (require.main === module) { + try { + main(); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} + +module.exports = { + DEFAULT_REGISTRY, + PACKAGES, + PNPM_MIRROR_BASE, + bootstrapPnpm, + buildRelease, + isVersionInFeed, + main, + parseReleaseVersion, + publishRelease, + resolveReleaseTag, + tarballName, +}; diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs new file mode 100644 index 00000000000..6decf247efd --- /dev/null +++ b/scripts/ado-npm-publisher.test.cjs @@ -0,0 +1,382 @@ +const assert = require('node:assert/strict'); +const { spawnSync } = require('node:child_process'); +const { createHash, randomUUID } = require('node:crypto'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { afterEach, test } = require('node:test'); +const { + DEFAULT_REGISTRY, + PACKAGES, + PNPM_MIRROR_BASE, + bootstrapPnpm, + buildRelease, + isVersionInFeed, + main, + parseReleaseVersion, + publishRelease, + resolveReleaseTag, + tarballName, +} = require('./ado-npm-publisher.cjs'); + +const tempDirs = []; + +function createTempDir(prefix = 'ado-npm-publisher-test-') { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}${randomUUID()}-`)); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +function git(args, cwd) { + const result = spawnSync('git', args, { + cwd, + encoding: 'utf8', + env: { + ...process.env, + GIT_AUTHOR_NAME: 'Test', + GIT_AUTHOR_EMAIL: 'test@example.com', + GIT_COMMITTER_NAME: 'Test', + GIT_COMMITTER_EMAIL: 'test@example.com', + }, + }); + assert.equal(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`); + return result.stdout.trim(); +} + +function createSampleRepo({ tag, annotated = false, packageManager } = {}) { + const repoRoot = createTempDir('repo-'); + git(['init'], repoRoot); + fs.writeFileSync( + path.join(repoRoot, 'package.json'), + `${JSON.stringify({ name: '@microsoft/logicappsux', version: '0.0.0', packageManager }, null, 2)}\n` + ); + for (const pkg of PACKAGES) { + const pkgDir = path.join(repoRoot, pkg.directory); + fs.mkdirSync(pkgDir, { recursive: true }); + fs.writeFileSync(path.join(pkgDir, 'package.json'), `${JSON.stringify({ name: pkg.name, version: '0.0.0' }, null, 2)}\n`); + } + git(['add', '.'], repoRoot); + git(['commit', '-m', 'Initial commit'], repoRoot); + const commitSha = git(['rev-parse', 'HEAD'], repoRoot); + if (tag) { + if (annotated) { + git(['tag', '-a', tag, '-m', `Release ${tag}`], repoRoot); + } else { + git(['tag', tag], repoRoot); + } + } + return { repoRoot, commitSha }; +} + +test('parseReleaseVersion accepts valid semver and rejects invalid inputs', () => { + assert.equal(parseReleaseVersion('5.1024.0'), '5.1024.0'); + assert.equal(parseReleaseVersion(' 5.1024.1 '), '5.1024.1'); + for (const bad of ['', 'v5.1024.0', '5.1024', '5.1024.0-beta.1', '01.2.3', null, undefined]) { + assert.throws(() => parseReleaseVersion(bad), /Invalid releaseVersion/); + } +}); + +test('tarballName formats scoped package names as pnpm pack filenames', () => { + assert.equal(tarballName('@microsoft/logic-apps-shared', '5.1024.0'), 'microsoft-logic-apps-shared-5.1024.0.tgz'); + assert.equal(tarballName('@microsoft/designer-ui-v2', '5.1024.0'), 'microsoft-designer-ui-v2-5.1024.0.tgz'); +}); + +test('resolveReleaseTag resolves lightweight and annotated tags and fails clearly when missing', () => { + const lightweight = createSampleRepo({ tag: 'v5.1024.0', annotated: false }); + assert.deepEqual(resolveReleaseTag(lightweight.repoRoot, '5.1024.0'), { + tag: 'v5.1024.0', + ref: 'refs/tags/v5.1024.0', + commitSha: lightweight.commitSha, + }); + + const annotated = createSampleRepo({ tag: 'v5.1025.0', annotated: true }); + assert.deepEqual(resolveReleaseTag(annotated.repoRoot, '5.1025.0'), { + tag: 'v5.1025.0', + ref: 'refs/tags/v5.1025.0', + commitSha: annotated.commitSha, + }); + + assert.throws(() => resolveReleaseTag(lightweight.repoRoot, '5.9999.0'), /Release tag 'v5\.9999\.0' was not found/); +}); + +test('bootstrapPnpm downloads pnpm from the 1ES mirror and verifies optional SHA-512 pin', () => { + const archivePayload = Buffer.from('fake-pnpm-tarball'); + const sha512 = createHash('sha512').update(archivePayload).digest('hex'); + + const sourceRoot = createTempDir('src-'); + const pnpmHome = createTempDir('pnpm-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: `pnpm@9.1.3+sha512.${sha512}` })); + + const calls = []; + const run = (cmd, args) => { + calls.push([cmd, args]); + if (cmd === 'curl') { + const outputIndex = args.indexOf('--output'); + fs.writeFileSync(args[outputIndex + 1], archivePayload); + } + return { status: 0 }; + }; + + const { pnpmBin, binDir } = bootstrapPnpm(sourceRoot, pnpmHome, run); + assert.equal(calls[0][0], 'curl'); + assert.equal(calls[0][1].at(-1), `${PNPM_MIRROR_BASE}/pnpm/-/pnpm-9.1.3.tgz`); + assert.equal(calls[1][0], 'tar'); + assert.equal(pnpmBin, path.join(binDir, 'pnpm')); + assert.equal(fs.readlinkSync(pnpmBin), path.join(pnpmHome, 'package', 'bin', 'pnpm.cjs')); + + // Reject mismatched SHA-512 pin + const badHome = createTempDir('pnpm-bad-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: `pnpm@9.1.3+sha512.${'0'.repeat(128)}` })); + assert.throws(() => bootstrapPnpm(sourceRoot, badHome, run), /SHA-512 does not match/); + + // Accept version-only packageManager without a hash suffix + const noHashHome = createTempDir('pnpm-nohash-'); + fs.writeFileSync(path.join(sourceRoot, 'package.json'), JSON.stringify({ packageManager: 'pnpm@9.15.0' })); + const result = bootstrapPnpm(sourceRoot, noHashHome, run); + assert.equal(fs.readlinkSync(result.pnpmBin), path.join(noHashHome, 'package', 'bin', 'pnpm.cjs')); +}); + +test('buildRelease checks out release tag, builds, packs all 9 packages, and writes .npmrc', () => { + const archivePayload = Buffer.from('fake-pnpm-archive'); + const sha512 = createHash('sha512').update(archivePayload).digest('hex'); + const { repoRoot, commitSha } = createSampleRepo({ + tag: 'v5.1024.0', + annotated: true, + packageManager: `pnpm@9.1.3+sha512.${sha512}`, + }); + + const agentTmp = createTempDir('tmp-'); + const scanRoot = createTempDir('scan-'); + const tarballDir = path.join(agentTmp, 'tarballs'); + const publishNpmrc = path.join(agentTmp, 'npm-publish', '.npmrc'); + const commands = []; + const logs = []; + + const run = (cmd, args, options) => { + commands.push({ cmd, args, cwd: options?.cwd }); + if (cmd === 'git') { + return spawnSync(cmd, args, options); + } + if (cmd === 'curl') { + fs.writeFileSync(args[args.indexOf('--output') + 1], archivePayload); + return { status: 0 }; + } + if (cmd === 'tar') { + return { status: 0 }; + } + if (cmd === process.execPath && args[0] === 'scripts/update-versions.js') { + // Simulate version update in the detached worktree + const pkgPath = path.join(options.cwd, 'package.json'); + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); + pkg.version = args[1]; + fs.writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`); + return { status: 0 }; + } + if (cmd.endsWith(`${path.sep}pnpm`) && args[2] === 'pack') { + const pkgDir = args[1]; + const pkgJson = JSON.parse(fs.readFileSync(path.join(pkgDir, 'package.json'), 'utf8')); + const dest = args[args.indexOf('--pack-destination') + 1]; + fs.writeFileSync(path.join(dest, tarballName(pkgJson.name, '5.1024.0')), 'tgz-bytes'); + return { status: 0 }; + } + return { status: 0 }; + }; + + const result = buildRelease( + { + RELEASE_VERSION: '5.1024.0', + AGENT_TMP: agentTmp, + RELEASE_SCAN_ROOT: scanRoot, + TARBALL_DIR: tarballDir, + NPM_REGISTRY: DEFAULT_REGISTRY, + PUBLISH_NPMRC: publishNpmrc, + }, + { run, log: msg => logs.push(msg), repoRoot } + ); + + assert.equal(result.version, '5.1024.0'); + assert.equal(result.commitSha, commitSha); + + // Verify build steps ran in order + const pnpmCalls = commands.filter(c => c.cmd.endsWith(`${path.sep}pnpm`)).map(c => c.args); + assert.deepEqual(pnpmCalls[0], ['install', '--recursive', '--frozen-lockfile', '--strict-peer-dependencies']); + assert.deepEqual(pnpmCalls[1], ['run', 'build:lib']); + assert.equal(pnpmCalls.filter(a => a[2] === 'pack').length, PACKAGES.length); + + assert.ok(commands.some(c => c.cmd === process.execPath && c.args[0] === 'scripts/update-versions.js' && c.args[1] === '5.1024.0')); + + // All 9 tarballs exist and .npmrc was prepared for npmAuthenticate + for (const pkg of PACKAGES) { + assert.ok(fs.existsSync(path.join(tarballDir, tarballName(pkg.name, '5.1024.0')))); + } + assert.equal(fs.readFileSync(publishNpmrc, 'utf8'), `registry=${DEFAULT_REGISTRY}\n`); + + // Retained release-source worktree for Component Governance has tracked files restored + const retainedRoot = path.join(scanRoot, 'release-source'); + assert.ok(fs.existsSync(retainedRoot)); + assert.equal(JSON.parse(fs.readFileSync(path.join(retainedRoot, 'package.json'), 'utf8')).version, '0.0.0'); +}); + +test('isVersionInFeed handles present, empty-stdout absent, 404 absent, and unexpected errors', () => { + const baseOpts = { registry: DEFAULT_REGISTRY, npmrc: '/tmp/.npmrc', cwd: '/tmp' }; + + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 0, stdout: '5.1024.0\n', stderr: '' }), + }), + true + ); + + // Package exists in feed, target version does not -> npm view exits 0 with empty stdout + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 0, stdout: '', stderr: '' }), + }), + false + ); + + // Brand-new package not in feed -> npm view exits 1 with E404 + assert.equal( + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 1, stdout: '', stderr: 'npm error code E404\nnpm error 404 Not Found' }), + }), + false + ); + + // Auth failure must throw instead of falsely treating package as absent + assert.throws( + () => + isVersionInFeed('@microsoft/logic-apps-shared', '5.1024.0', { + ...baseOpts, + run: () => ({ status: 1, stdout: '', stderr: 'npm error code E401\nnpm error Unable to authenticate' }), + }), + /Failed to check @microsoft\/logic-apps-shared@5\.1024\.0 in feed/ + ); +}); + +test('publishRelease skips packages already in feed and publishes missing packages without post-publish readback', () => { + const version = '5.1024.0'; + const tarballDir = createTempDir('tarballs-'); + const npmrc = path.join(createTempDir('npmrc-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + + const alreadyInFeed = new Set([ + '@microsoft/logic-apps-shared', + '@microsoft/designer-ui', + '@microsoft/designer-ui-v2', + ]); + const calls = []; + const logs = []; + + const run = (cmd, args, options) => { + calls.push({ cmd, args, stdio: options?.stdio }); + if (cmd === 'npm' && args[0] === 'view') { + const pkgName = args[1].slice(0, args[1].lastIndexOf('@')); + return alreadyInFeed.has(pkgName) + ? { status: 0, stdout: `${version}\n`, stderr: '' } + : { status: 0, stdout: '', stderr: '' }; + } + if (cmd === 'npm' && args[0] === 'publish') { + return { status: 0 }; + } + throw new Error(`Unexpected command: ${cmd} ${args.join(' ')}`); + }; + + const result = publishRelease( + { + RELEASE_VERSION: version, + TARBALL_DIR: tarballDir, + PUBLISH_NPMRC: npmrc, + NPM_REGISTRY: DEFAULT_REGISTRY, + }, + { run, log: msg => logs.push(msg) } + ); + + assert.deepEqual(result, { version, published: 6, skipped: 3 }); + + const viewCalls = calls.filter(c => c.args[0] === 'view'); + const publishCalls = calls.filter(c => c.args[0] === 'publish'); + + // Exactly one pre-publish view per package (no post-publish view or pack readback) + assert.equal(viewCalls.length, PACKAGES.length); + assert.equal(publishCalls.length, PACKAGES.length - alreadyInFeed.size); + assert.equal(calls.filter(c => c.args[0] === 'pack').length, 0); + + // Every publish call uses --tag latest and normal visible stdout/stderr (stdio: 'inherit') + for (const call of publishCalls) { + assert.equal(call.stdio, 'inherit'); + assert.ok(call.args.includes('--tag')); + assert.equal(call.args[call.args.indexOf('--tag') + 1], 'latest'); + assert.equal(call.args[call.args.indexOf('--registry') + 1], DEFAULT_REGISTRY); + assert.equal(call.args[call.args.indexOf('--userconfig') + 1], npmrc); + } +}); + +test('publishRelease fails clearly when npm publish exits non-zero or files are missing', () => { + const version = '5.1024.0'; + const tarballDir = createTempDir('tarballs-fail-'); + const npmrc = path.join(createTempDir('npmrc-fail-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + // Missing tarball + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: npmrc }), + /Missing tarball/ + ); + + // Missing .npmrc + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: '/nonexistent/.npmrc' }), + /Authenticated \.npmrc file does not exist/ + ); + + // npm publish failure stops immediately + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + const run = (cmd, args) => { + if (cmd === 'npm' && args[0] === 'view') { + return { status: 0, stdout: '', stderr: '' }; + } + return { status: 1 }; + }; + assert.throws( + () => publishRelease({ RELEASE_VERSION: version, TARBALL_DIR: tarballDir, PUBLISH_NPMRC: npmrc }, { run, log: () => {} }), + /npm publish failed \(exit 1\)/ + ); +}); + +test('main validates command arguments', () => { + assert.throws(() => main(['unknown']), /Unknown command/); + assert.throws(() => main(['build', 'extra']), /Unexpected arguments/); +}); + +test('npm-publish.yml keeps 1ES Official template, WIF auth, branch gate, and single Publish stage', () => { + const yaml = fs.readFileSync(path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'), 'utf8'); + assert.match(yaml, /template:\s*v1\/1ES\.Official\.PipelineTemplate\.yml@1esPipelines/); + assert.match(yaml, /ref:\s*refs\/tags\/release/); + assert.match(yaml, /name:\s*Azure-Pipelines-1ESPT-ExDShared/); + assert.match(yaml, /useAgentBuildDirectory:\s*true/); + assert.match(yaml, /workloadIdentityServiceConnection:\s*21d5a1d8-11d3-425c-8d3a-e7f088725481/); + assert.match(yaml, /feedUrl:\s*'https:\/\/pkgs\.dev\.azure\.com\/msazure\/One\/_packaging\/microsoft-logic-apps\/npm\/registry\/'/); + assert.match( + yaml, + /and\(succeeded\(\),\s*or\(eq\(variables\['Build\.SourceBranch'\],\s*'refs\/heads\/main'\),\s*startsWith\(variables\['Build\.SourceBranch'\],\s*'refs\/heads\/hotfix\/v'\)\)\)/ + ); + assert.match(yaml, /- stage:\s*Publish/); + assert.match(yaml, /- job:\s*BuildAndPublish/); + assert.doesNotMatch(yaml, /VerifyRelease|ProductionPublishNotActivated|npm-verify-release/); +}); From 646c0c3f22a60e3af998ecd40f08d5ff3466a0f8 Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Tue, 24 Nov 2026 20:27:17 -0800 Subject: [PATCH 2/4] feat(ci): trigger ADO npm publish via Otto in version-release workflow Replace legacy direct npm publishing in version-release.yml with a publish-npm job that invokes the Otto trigger-npm-publish workflow via the E2ETesting environment secret, guard Azure login on blob upload, and add workflow invariant tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/version-release.yml | 108 ++++++++++++++++++++++++-- scripts/ado-npm-publisher.test.cjs | 63 +++++++++++++++ 2 files changed, 164 insertions(+), 7 deletions(-) diff --git a/.github/workflows/version-release.yml b/.github/workflows/version-release.yml index 2030e3b52ac..e3412f5ae6d 100644 --- a/.github/workflows/version-release.yml +++ b/.github/workflows/version-release.yml @@ -239,8 +239,9 @@ jobs: run: | gh release upload ${{ needs.create-release.outputs.tag_name }} AgentChatIFrames-${IFRAME_VERSION}.zip --clobber - # NPM Publishing + # Iframe App Azure Blob Upload - name: 'Azure login' + if: ${{ github.event.inputs.enable_blob_upload == 'true' }} uses: azure/login@v3 with: client-id: ${{ secrets.AZURE_TESTING_CLIENT_ID }} @@ -292,12 +293,105 @@ jobs: echo "Uploaded zip file and folder contents to container: $CONTAINER_NAME" - - name: 'Generate NPMRC' + publish-npm: + needs: create-release + runs-on: ubuntu-latest + environment: E2ETesting + permissions: + contents: read + steps: + - name: 'Trigger ADO npm publish via Otto' shell: bash + env: + OTTO_WORKFLOW_URL: ${{ secrets.OTTO_NPM_PUBLISH_WORKFLOW_URL }} + RELEASE_VERSION: ${{ needs.create-release.outputs.new_version }} + TAG_NAME: ${{ needs.create-release.outputs.tag_name }} + SOURCE_BRANCH: ${{ github.ref }} + REPOSITORY: ${{ github.repository }} + GITHUB_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - token=`az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 | jq -r .accessToken` - export ADO_TOKEN=$token - node ./productionNpmRCCreator.js + set -euo pipefail + + # Fail fast if the Otto webhook URL secret is not configured. + if [[ -z "${OTTO_WORKFLOW_URL:-}" ]]; then + echo "::error::OTTO_NPM_PUBLISH_WORKFLOW_URL secret is not configured in environment E2ETesting." + exit 1 + fi + + PAYLOAD=$(jq -n \ + --arg releaseVersion "$RELEASE_VERSION" \ + --arg tagName "$TAG_NAME" \ + --arg sourceBranch "$SOURCE_BRANCH" \ + --arg repository "$REPOSITORY" \ + --arg githubRunUrl "$GITHUB_RUN_URL" \ + '{ + releaseVersion: $releaseVersion, + tagName: $tagName, + sourceBranch: $sourceBranch, + repository: $repository, + githubRunUrl: $githubRunUrl, + dryRun: false + }') + + RESP_FILE=$(mktemp) + trap 'rm -f "$RESP_FILE"' EXIT + + # Invoke Otto silently without -S/-v so the signed webhook URL is never printed to logs. + CURL_EXIT=0 + HTTP_STATUS=$(curl -s \ + --connect-timeout 15 \ + --max-time 60 \ + --retry 2 \ + --retry-delay 5 \ + --retry-connrefused \ + -X POST \ + -H 'Content-Type: application/json' \ + --data "$PAYLOAD" \ + -o "$RESP_FILE" \ + -w '%{http_code}' \ + "$OTTO_WORKFLOW_URL") || CURL_EXIT=$? + + if [[ "$CURL_EXIT" -ne 0 ]]; then + echo "::error::Failed to invoke Otto npm publish workflow (curl exit code: $CURL_EXIT)." + exit "$CURL_EXIT" + fi - - name: 'Publish to NPM' - run: pnpm run publish --no-git-checks --access public --tag latest + # Otto returns 200 when a matching publish is skipped/deduplicated and 202 when queued. + if [[ "$HTTP_STATUS" != "200" && "$HTTP_STATUS" != "202" ]]; then + echo "::error::Otto npm publish workflow returned HTTP $HTTP_STATUS." + if jq -e 'type == "object"' "$RESP_FILE" >/dev/null 2>&1; then + jq 'del(.url, .webhookUrl, .sasUrl, .token, .sig, .authorization, .headers)' "$RESP_FILE" + fi + exit 1 + fi + + if ! jq -e 'type == "object"' "$RESP_FILE" >/dev/null 2>&1; then + echo "::error::Otto npm publish workflow returned HTTP $HTTP_STATUS with an empty or non-JSON response." + exit 1 + fi + + PUBLISH_STATUS=$(jq -r '.status // "unknown"' "$RESP_FILE") + BUILD_ID=$(jq -r '.buildId // .existingBuildId // empty' "$RESP_FILE") + BUILD_URL=$(jq -r '.buildUrl // .existingBuildUrl // empty' "$RESP_FILE") + + echo "Otto npm publish status: $PUBLISH_STATUS (HTTP $HTTP_STATUS)" + if [[ -n "$BUILD_ID" ]]; then + echo "ADO build ID: $BUILD_ID" + fi + if [[ -n "$BUILD_URL" ]]; then + echo "ADO build URL: $BUILD_URL" + fi + + { + echo "### ADO npm Publish" + echo "" + echo "- **Version:** \`$RELEASE_VERSION\` (\`$TAG_NAME\`)" + echo "- **Status:** \`$PUBLISH_STATUS\` (HTTP \`$HTTP_STATUS\`)" + if [[ -n "$BUILD_ID" && -n "$BUILD_URL" ]]; then + echo "- **ADO Build:** [#$BUILD_ID]($BUILD_URL)" + elif [[ -n "$BUILD_ID" ]]; then + echo "- **ADO Build ID:** \`$BUILD_ID\`" + elif [[ -n "$BUILD_URL" ]]; then + echo "- **ADO Build URL:** $BUILD_URL" + fi + } >> "$GITHUB_STEP_SUMMARY" diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index 6decf247efd..16feafdbd7b 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -380,3 +380,66 @@ test('npm-publish.yml keeps 1ES Official template, WIF auth, branch gate, and si assert.match(yaml, /- job:\s*BuildAndPublish/); assert.doesNotMatch(yaml, /VerifyRelease|ProductionPublishNotActivated|npm-verify-release/); }); + +test('version-release.yml triggers Otto ADO npm publish, guards Azure login, and removes legacy npm steps', () => { + const workflowPath = path.join(__dirname, '..', '.github', 'workflows', 'version-release.yml'); + const yaml = fs.readFileSync(workflowPath, 'utf8'); + + // Legacy npm publishing steps must be removed from build-and-publish + assert.doesNotMatch(yaml, /Generate NPMRC|Publish to NPM|productionNpmRCCreator\.js/); + assert.doesNotMatch(yaml, /# NPM Publishing/); + + // No hardcoded SAS tokens or Otto Container Apps URLs anywhere in the workflow + assert.doesNotMatch(yaml, /sig=/i); + assert.doesNotMatch(yaml, /azurecontainerapps\.io/i); + + // Azure login in build-and-publish must be gated on enable_blob_upload == 'true' + const azureLoginBlock = yaml.match(/- name:\s*'Azure login'[\s\S]*?(?=\n\s*- name:|\n [a-z-]+:|$)/); + assert.ok(azureLoginBlock, 'Expected Azure login step in version-release.yml'); + assert.match(azureLoginBlock[0], /if:\s*\$\{\{\s*github\.event\.inputs\.enable_blob_upload\s*==\s*'true'\s*\}\}/); + + // publish-npm job invariants + const publishNpmIndex = yaml.indexOf('\n publish-npm:\n'); + assert.notEqual(publishNpmIndex, -1, 'Expected publish-npm job in version-release.yml'); + const publishNpmSection = yaml.slice(publishNpmIndex); + + assert.match(publishNpmSection, /needs:\s*create-release/); + assert.match(publishNpmSection, /runs-on:\s*ubuntu-latest/); + assert.match(publishNpmSection, /environment:\s*E2ETesting/); + assert.match(publishNpmSection, /permissions:\s*\n\s*contents:\s*read/); + assert.match(publishNpmSection, /OTTO_WORKFLOW_URL:\s*\$\{\{\s*secrets\.OTTO_NPM_PUBLISH_WORKFLOW_URL\s*\}\}/); + assert.match(publishNpmSection, /dryRun:\s*false/); + + // All GitHub expressions in publish-npm must be bound via env:, never interpolated in run: + assert.match(publishNpmSection, /RELEASE_VERSION:\s*\$\{\{\s*needs\.create-release\.outputs\.new_version\s*\}\}/); + assert.match(publishNpmSection, /TAG_NAME:\s*\$\{\{\s*needs\.create-release\.outputs\.tag_name\s*\}\}/); + assert.match(publishNpmSection, /SOURCE_BRANCH:\s*\$\{\{\s*github\.ref\s*\}\}/); + assert.match(publishNpmSection, /REPOSITORY:\s*\$\{\{\s*github\.repository\s*\}\}/); + assert.match( + publishNpmSection, + /GITHUB_RUN_URL:\s*\$\{\{\s*github\.server_url\s*\}\}\/\$\{\{\s*github\.repository\s*\}\}\/actions\/runs\/\$\{\{\s*github\.run_id\s*\}\}/ + ); + + // Single step in publish-npm + const publishNpmSteps = publishNpmSection.match(/\n - name:/g) || []; + assert.equal(publishNpmSteps.length, 1, 'Expected exactly one step in publish-npm job'); + assert.match(publishNpmSection, /- name:\s*'Trigger ADO npm publish via Otto'/); + + const runBlockIndex = publishNpmSection.indexOf('\n run: |'); + assert.notEqual(runBlockIndex, -1, 'Expected run block in publish-npm job'); + const runBlock = publishNpmSection.slice(runBlockIndex); + assert.doesNotMatch(runBlock, /\$\{\{/); + assert.match(runBlock, /trap 'rm -f "\$RESP_FILE"' EXIT/); + + // curl must POST silently with retry/timeout flags and without -S/--show-error or -v/--verbose + const curlInvocation = runBlock.match(/curl[\s\S]*?"\$OTTO_WORKFLOW_URL"/); + assert.ok(curlInvocation, 'Expected curl invocation targeting "$OTTO_WORKFLOW_URL"'); + assert.match(curlInvocation[0], /(?:^|\s)-s(?:\s|$)/); + assert.match(curlInvocation[0], /-X POST/); + assert.match(curlInvocation[0], /--connect-timeout 15/); + assert.match(curlInvocation[0], /--max-time 60/); + assert.match(curlInvocation[0], /--retry 2/); + assert.match(curlInvocation[0], /--retry-delay 5/); + assert.match(curlInvocation[0], /--retry-connrefused/); + assert.doesNotMatch(curlInvocation[0], /(?:^|\s)(?:-[A-Za-z]*[Sv]|--verbose|--show-error)(?:\s|$)/); +}); From 5c31f0006a540c033dabf49dd97f484e223270ac Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Tue, 24 Nov 2026 21:32:08 -0800 Subject: [PATCH 3/4] fix(ci): protect npm latest dist-tag when publishing historical hotfixes Add compareSemver and resolvePublishDistTag in ado-npm-publisher.cjs so publishing a version lower than the feed's dist-tags.latest uses --tag hotfix instead of downgrading latest, while failing fast on non-404 feed errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/ado-npm-publisher.cjs | 87 +++++++++- scripts/ado-npm-publisher.test.cjs | 245 ++++++++++++++++++++++++++++- 2 files changed, 323 insertions(+), 9 deletions(-) diff --git a/scripts/ado-npm-publisher.cjs b/scripts/ado-npm-publisher.cjs index 0e99cadb198..c384f19288d 100644 --- a/scripts/ado-npm-publisher.cjs +++ b/scripts/ado-npm-publisher.cjs @@ -6,6 +6,18 @@ const path = require('node:path'); const DEFAULT_REGISTRY = 'https://pkgs.dev.azure.com/msazure/One/_packaging/microsoft-logic-apps/npm/registry/'; const PNPM_MIRROR_BASE = 'https://ms-feed-25.pkgs.visualstudio.com/1es-public/_packaging/npm-public/npm/registry'; +const NPM_ERROR_CODE_PATTERN = /npm (?:ERR!|error) code ([A-Z0-9_]+)/i; +const NOT_FOUND_FALLBACK_PATTERN = /\bE404\b|404 Not Found|is not in this registry/i; +const FEED_SEMVER_PATTERN = /^((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; + +// Check npm's explicit error code first so non-404 errors (e.g. E502 with "404 Not Found" in upstream text) are never misclassified as missing packages. +function isNotFoundError(combinedOutput) { + const codeMatch = NPM_ERROR_CODE_PATTERN.exec(combinedOutput); + if (codeMatch) { + return codeMatch[1].toUpperCase() === 'E404'; + } + return NOT_FOUND_FALLBACK_PATTERN.test(combinedOutput); +} // Publishable workspace libraries in dependency order (matches scripts/update-versions.js). const PACKAGES = [ @@ -28,6 +40,18 @@ function parseReleaseVersion(raw) { return value; } +// Numeric X.Y.Z semver comparison used to prevent historical hotfix releases from downgrading dist-tags.latest. +function compareSemver(a, b) { + const partsA = parseReleaseVersion(a).split('.').map(Number); + const partsB = parseReleaseVersion(b).split('.').map(Number); + for (let i = 0; i < 3; i += 1) { + if (partsA[i] !== partsB[i]) { + return partsA[i] < partsB[i] ? -1 : 1; + } + } + return 0; +} + function tarballName(packageName, version) { return `${packageName.replace(/^@/, '').replace('/', '-')}-${version}.tgz`; } @@ -170,7 +194,7 @@ function isVersionInFeed(packageName, version, { registry, npmrc, cwd, run = spa const spec = `${packageName}@${version}`; const result = run( 'npm', - ['view', spec, 'version', '--registry', registry, '--userconfig', npmrc, '--prefer-online'], + ['view', spec, 'version', '--registry', registry, '--userconfig', npmrc, '--prefer-online', '--json=false'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 } ); @@ -183,12 +207,62 @@ function isVersionInFeed(packageName, version, { registry, npmrc, cwd, run = spa } const combined = `${result.stdout ?? ''}\n${result.stderr ?? ''}`; - if (/\bE404\b|404 Not Found|is not in this registry/i.test(combined)) { + if (isNotFoundError(combined)) { return false; } throw new Error(`Failed to check ${spec} in feed (exit ${result.status}): ${combined.trim()}`); } +// Determine which dist-tag to assign on publish so historical hotfix releases never downgrade `latest`. +function resolvePublishDistTag(pkgName, version, registry, npmrc, run = spawnSync, { cwd } = {}) { + const targetVersion = parseReleaseVersion(version); + const viewOptions = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 }; + if (cwd) { + viewOptions.cwd = cwd; + } + const result = run( + 'npm', + [ + 'view', + pkgName, + 'dist-tags.latest', + '--registry', + registry, + '--userconfig', + npmrc, + '--prefer-online', + '--tag=latest', + '--json=false', + ], + viewOptions + ); + + if (result.error) { + throw new Error(`Failed to resolve dist-tags.latest for ${pkgName}: ${result.error.message}`); + } + + if (result.status !== 0) { + const combined = `${result.stdout ?? ''}\n${result.stderr ?? ''}`; + if (isNotFoundError(combined)) { + return 'latest'; + } + throw new Error(`Failed to resolve dist-tags.latest for ${pkgName} (exit ${result.status}): ${combined.trim()}`); + } + + const currentLatest = (result.stdout ?? '').trim(); + if (!currentLatest) { + return 'latest'; + } + + // Incoming release is always stable X.Y.Z; per SemVer 2.0.0, X.Y.Z >= X.Y.Z-prerelease and X.Y.Z < higherBase-prerelease. + const latestMatch = FEED_SEMVER_PATTERN.exec(currentLatest); + if (!latestMatch) { + throw new Error(`Unexpected dist-tags.latest value '${currentLatest}' for ${pkgName}.`); + } + + return compareSemver(targetVersion, latestMatch[1]) < 0 ? 'hotfix' : 'latest'; +} + function publishRelease(env, { run = spawnSync, log = console.log } = {}) { const version = parseReleaseVersion(env.RELEASE_VERSION); const tarballDir = env.TARBALL_DIR; @@ -218,14 +292,15 @@ function publishRelease(env, { run = spawnSync, log = console.log } = {}) { continue; } - log(`Publishing ${spec}...`); + const distTag = resolvePublishDistTag(pkg.name, version, registry, npmrc, run, { cwd: tarballDir }); + log(`Publishing ${spec} with dist-tag '${distTag}'...`); runCommand( 'npm', - ['publish', tarball, '--tag', 'latest', '--registry', registry, '--userconfig', npmrc], + ['publish', tarball, '--tag', distTag, '--registry', registry, '--userconfig', npmrc], { cwd: tarballDir, stdio: 'inherit', timeout: 180_000 }, run ); - log(`Published ${spec}.`); + log(`Published ${spec} with dist-tag '${distTag}'.`); published += 1; } @@ -261,10 +336,12 @@ module.exports = { PNPM_MIRROR_BASE, bootstrapPnpm, buildRelease, + compareSemver, isVersionInFeed, main, parseReleaseVersion, publishRelease, + resolvePublishDistTag, resolveReleaseTag, tarballName, }; diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index 16feafdbd7b..1af7778ac31 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -11,10 +11,12 @@ const { PNPM_MIRROR_BASE, bootstrapPnpm, buildRelease, + compareSemver, isVersionInFeed, main, parseReleaseVersion, publishRelease, + resolvePublishDistTag, resolveReleaseTag, tarballName, } = require('./ado-npm-publisher.cjs'); @@ -82,6 +84,16 @@ test('parseReleaseVersion accepts valid semver and rejects invalid inputs', () = } }); +test('compareSemver compares X.Y.Z versions numerically and rejects invalid inputs', () => { + assert.equal(compareSemver('5.1024.0', '5.1024.0'), 0); + assert.equal(compareSemver('5.1024.0', '5.999.0'), 1); + assert.equal(compareSemver('5.999.0', '5.1024.0'), -1); + assert.equal(compareSemver('2.9999.0', '5.1024.0'), -1); + assert.equal(compareSemver('5.1024.1', '5.1024.0'), 1); + assert.equal(compareSemver('5.1024.0', '5.1024.1'), -1); + assert.throws(() => compareSemver('5.1024.0', 'not-semver'), /Invalid releaseVersion/); +}); + test('tarballName formats scoped package names as pnpm pack filenames', () => { assert.equal(tarballName('@microsoft/logic-apps-shared', '5.1024.0'), 'microsoft-logic-apps-shared-5.1024.0.tgz'); assert.equal(tarballName('@microsoft/designer-ui-v2', '5.1024.0'), 'microsoft-designer-ui-v2-5.1024.0.tgz'); @@ -263,6 +275,134 @@ test('isVersionInFeed handles present, empty-stdout absent, 404 absent, and unex ); }); +test('resolvePublishDistTag selects latest or hotfix and throws on unexpected feed errors', () => { + const pkgName = '@microsoft/logic-apps-shared'; + const npmrc = '/tmp/.npmrc'; + + // version > currentLatest -> latest + const seenCalls = []; + assert.equal( + resolvePublishDistTag(pkgName, '5.1025.0', DEFAULT_REGISTRY, npmrc, (cmd, args) => { + seenCalls.push({ cmd, args }); + return { status: 0, stdout: '5.1024.0\n', stderr: '' }; + }), + 'latest' + ); + assert.equal(seenCalls[0].cmd, 'npm'); + assert.deepEqual(seenCalls[0].args, [ + 'view', + pkgName, + 'dist-tags.latest', + '--registry', + DEFAULT_REGISTRY, + '--userconfig', + npmrc, + '--prefer-online', + '--tag=latest', + '--json=false', + ]); + + // version === currentLatest -> latest + assert.equal( + resolvePublishDistTag(pkgName, '5.1024.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '5.1024.0\n', + stderr: '', + })), + 'latest' + ); + + // Prerelease tagged latest: same-base stable promotes latest, higher-base prerelease uses hotfix + assert.equal( + resolvePublishDistTag(pkgName, '5.1024.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '5.1024.0-rc.1\n', + stderr: '', + })), + 'latest' + ); + assert.equal( + resolvePublishDistTag(pkgName, '5.1024.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '5.1025.0-rc.1\n', + stderr: '', + })), + 'hotfix' + ); + + // version < currentLatest -> hotfix (never downgrade latest) + assert.equal( + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '5.1024.0\n', + stderr: '', + })), + 'hotfix' + ); + assert.equal( + resolvePublishDistTag(pkgName, '5.1023.1', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '5.1024.0\n', + stderr: '', + })), + 'hotfix' + ); + + // Package not found (404) or missing dist-tags.latest (empty stdout) -> latest + assert.equal( + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 1, + stdout: '', + stderr: 'npm error code E404\nnpm error 404 Not Found', + })), + 'latest' + ); + assert.equal( + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '', + stderr: '', + })), + 'latest' + ); + + // Non-404 feed error must throw instead of silently downgrading latest (including E502 mentioning 404 in body) + assert.throws( + () => + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 1, + stdout: '', + stderr: 'npm error code E401\nnpm error Unable to authenticate', + })), + /Failed to resolve dist-tags\.latest for @microsoft\/logic-apps-shared/ + ); + assert.throws( + () => + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 1, + stdout: '', + stderr: 'npm error code E502\nnpm error Upstream returned 404 Not Found', + })), + /Failed to resolve dist-tags\.latest for @microsoft\/logic-apps-shared/ + ); + assert.throws( + () => + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + error: new Error('ETIMEDOUT'), + })), + /Failed to resolve dist-tags\.latest for @microsoft\/logic-apps-shared: ETIMEDOUT/ + ); + assert.throws( + () => + resolvePublishDistTag(pkgName, '2.9999.0', DEFAULT_REGISTRY, npmrc, () => ({ + status: 0, + stdout: '"5.1024.0"\n', + stderr: '', + })), + /Unexpected dist-tags\.latest value/ + ); +}); + test('publishRelease skips packages already in feed and publishes missing packages without post-publish readback', () => { const version = '5.1024.0'; const tarballDir = createTempDir('tarballs-'); @@ -283,12 +423,15 @@ test('publishRelease skips packages already in feed and publishes missing packag const run = (cmd, args, options) => { calls.push({ cmd, args, stdio: options?.stdio }); - if (cmd === 'npm' && args[0] === 'view') { + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'version') { const pkgName = args[1].slice(0, args[1].lastIndexOf('@')); return alreadyInFeed.has(pkgName) ? { status: 0, stdout: `${version}\n`, stderr: '' } : { status: 0, stdout: '', stderr: '' }; } + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'dist-tags.latest') { + return { status: 0, stdout: '5.1023.0\n', stderr: '' }; + } if (cmd === 'npm' && args[0] === 'publish') { return { status: 0 }; } @@ -307,11 +450,13 @@ test('publishRelease skips packages already in feed and publishes missing packag assert.deepEqual(result, { version, published: 6, skipped: 3 }); - const viewCalls = calls.filter(c => c.args[0] === 'view'); + const versionViewCalls = calls.filter(c => c.args[0] === 'view' && c.args[2] === 'version'); + const distTagViewCalls = calls.filter(c => c.args[0] === 'view' && c.args[2] === 'dist-tags.latest'); const publishCalls = calls.filter(c => c.args[0] === 'publish'); - // Exactly one pre-publish view per package (no post-publish view or pack readback) - assert.equal(viewCalls.length, PACKAGES.length); + // Exactly one pre-publish version view per package, one dist-tag lookup per published package, and no post-publish readback + assert.equal(versionViewCalls.length, PACKAGES.length); + assert.equal(distTagViewCalls.length, PACKAGES.length - alreadyInFeed.size); assert.equal(publishCalls.length, PACKAGES.length - alreadyInFeed.size); assert.equal(calls.filter(c => c.args[0] === 'pack').length, 0); @@ -323,6 +468,98 @@ test('publishRelease skips packages already in feed and publishes missing packag assert.equal(call.args[call.args.indexOf('--registry') + 1], DEFAULT_REGISTRY); assert.equal(call.args[call.args.indexOf('--userconfig') + 1], npmrc); } + assert.ok(logs.some(line => line.includes("dist-tag 'latest'"))); +}); + +test('publishRelease uses --tag hotfix when version is older than feed latest and --tag latest on 404', () => { + const version = '2.9999.0'; + const tarballDir = createTempDir('tarballs-hotfix-'); + const npmrc = path.join(createTempDir('npmrc-hotfix-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + + const brandNewPackage = '@microsoft/vscode-extension-logic-apps'; + const publishTagsByTarball = new Map(); + const logs = []; + + const run = (cmd, args) => { + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'version') { + return { status: 0, stdout: '', stderr: '' }; + } + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'dist-tags.latest') { + if (args[1] === brandNewPackage) { + return { status: 1, stdout: '', stderr: 'npm error code E404\nnpm error 404 Not Found' }; + } + return { status: 0, stdout: '5.1024.0\n', stderr: '' }; + } + if (cmd === 'npm' && args[0] === 'publish') { + publishTagsByTarball.set(path.basename(args[1]), args[args.indexOf('--tag') + 1]); + return { status: 0 }; + } + throw new Error(`Unexpected command: ${cmd} ${args.join(' ')}`); + }; + + const result = publishRelease( + { + RELEASE_VERSION: version, + TARBALL_DIR: tarballDir, + PUBLISH_NPMRC: npmrc, + NPM_REGISTRY: DEFAULT_REGISTRY, + }, + { run, log: msg => logs.push(msg) } + ); + + assert.deepEqual(result, { version, published: PACKAGES.length, skipped: 0 }); + for (const pkg of PACKAGES) { + const expectedTag = pkg.name === brandNewPackage ? 'latest' : 'hotfix'; + assert.equal(publishTagsByTarball.get(tarballName(pkg.name, version)), expectedTag); + } + assert.ok(logs.some(line => line.includes("dist-tag 'hotfix'"))); + assert.ok(logs.some(line => line.includes("dist-tag 'latest'"))); +}); + +test('publishRelease aborts before publishing if dist-tags.latest lookup fails with a non-404 error', () => { + const version = '2.9999.0'; + const tarballDir = createTempDir('tarballs-tag-err-'); + const npmrc = path.join(createTempDir('npmrc-tag-err-'), '.npmrc'); + fs.writeFileSync(npmrc, `registry=${DEFAULT_REGISTRY}\n`); + + for (const pkg of PACKAGES) { + fs.writeFileSync(path.join(tarballDir, tarballName(pkg.name, version)), 'tgz-bytes'); + } + + let publishCalled = false; + const run = (cmd, args) => { + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'version') { + return { status: 0, stdout: '', stderr: '' }; + } + if (cmd === 'npm' && args[0] === 'view' && args[2] === 'dist-tags.latest') { + return { status: 1, stdout: '', stderr: 'npm error code E500\nnpm error Internal Server Error' }; + } + if (cmd === 'npm' && args[0] === 'publish') { + publishCalled = true; + return { status: 0 }; + } + throw new Error(`Unexpected command: ${cmd} ${args.join(' ')}`); + }; + + assert.throws( + () => + publishRelease( + { + RELEASE_VERSION: version, + TARBALL_DIR: tarballDir, + PUBLISH_NPMRC: npmrc, + NPM_REGISTRY: DEFAULT_REGISTRY, + }, + { run, log: () => {} } + ), + /Failed to resolve dist-tags\.latest/ + ); + assert.equal(publishCalled, false); }); test('publishRelease fails clearly when npm publish exits non-zero or files are missing', () => { From d1fb8ddca13bc63c25b32e5099473d8f115035a9 Mon Sep 17 00:00:00 2001 From: Krrish Mittal Date: Wed, 25 Nov 2026 06:46:41 -0800 Subject: [PATCH 4/4] ci(npm-publish): include releaseVersion in ADO pipeline run name Set top-level `name` in `.azure-pipelines/npm-publish.yml` to `${{ coalesce(trim(parameters.releaseVersion), 'unversioned') }}-$(Date:yyyyMMdd)$(Rev:.r)` so each ADO publish run captures the package version being published at queue time. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .azure-pipelines/npm-publish.yml | 1 + scripts/ado-npm-publisher.test.cjs | 1 + 2 files changed, 2 insertions(+) diff --git a/.azure-pipelines/npm-publish.yml b/.azure-pipelines/npm-publish.yml index 5b617b791b4..e6110a2bb21 100644 --- a/.azure-pipelines/npm-publish.yml +++ b/.azure-pipelines/npm-publish.yml @@ -7,6 +7,7 @@ trigger: none pr: none schedules: [] +name: ${{ coalesce(trim(parameters.releaseVersion), 'unversioned') }}-$(Date:yyyyMMdd)$(Rev:.r) parameters: - name: releaseVersion diff --git a/scripts/ado-npm-publisher.test.cjs b/scripts/ado-npm-publisher.test.cjs index 1af7778ac31..05a9024e2f4 100644 --- a/scripts/ado-npm-publisher.test.cjs +++ b/scripts/ado-npm-publisher.test.cjs @@ -603,6 +603,7 @@ test('main validates command arguments', () => { test('npm-publish.yml keeps 1ES Official template, WIF auth, branch gate, and single Publish stage', () => { const yaml = fs.readFileSync(path.join(__dirname, '..', '.azure-pipelines', 'npm-publish.yml'), 'utf8'); + assert.match(yaml, /^name:\s*\$\{\{\s*coalesce\(trim\(parameters\.releaseVersion\),\s*'unversioned'\)\s*\}\}-\$\(Date:yyyyMMdd\)\$\(Rev:\.r\)$/m); assert.match(yaml, /template:\s*v1\/1ES\.Official\.PipelineTemplate\.yml@1esPipelines/); assert.match(yaml, /ref:\s*refs\/tags\/release/); assert.match(yaml, /name:\s*Azure-Pipelines-1ESPT-ExDShared/);