Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(infra): support feature previews (#835)

teo0e862ed3993d
diff --git a/.github/workflows/cleanup-preview.yml b/.github/workflows/cleanup-preview.yml
new file mode 100644
index 0000000000..452749d5ac
--- /dev/null
+++ b/.github/workflows/cleanup-preview.yml
@@ -0,0 +1,51 @@
+# Cleanup Preview Deployment
+#
+# Removes preview files from S3 when PR is closed
+
+name: Cleanup Preview
+
+on:
+ pull_request:
+ types: [closed]
+
+env:
+ PREVIEW_BUCKET: macro-preview-assets-dev
+
+jobs:
+ cleanup:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ pull-requests: read
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Setup Bun
+ uses: oven-sh/setup-bun@v2
+
+ - name: Configure AWS Credentials
+ uses: aws-actions/configure-aws-credentials@v5
+ with:
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }}
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+ aws-region: us-east-1
+
+ - name: Get preview ID from comments
+ id: preview-id
+ working-directory: js/app
+ run: |
+ PREVIEW_ID=$(bun scripts/preview/get-or-create-id.ts \
+ --pr ${{ github.event.pull_request.number }} \
+ --repo ${{ github.repository }} \
+ --token ${{ secrets.GITHUB_TOKEN }} \
+ --branch "${{ github.head_ref }}")
+ echo "id=$PREVIEW_ID" >> $GITHUB_OUTPUT
+ echo "Preview ID: $PREVIEW_ID"
+
+ - name: Cleanup preview
+ if: steps.preview-id.outputs.id != ''
+ working-directory: js/app
+ run: |
+ bun scripts/preview/deploy.ts \
+ --preview-id ${{ steps.preview-id.outputs.id }} \
+ --cleanup
diff --git a/.github/workflows/deploy-preview.yml b/.github/workflows/deploy-preview.yml
new file mode 100644
index 0000000000..0aee2d0f37
--- /dev/null
+++ b/.github/workflows/deploy-preview.yml
@@ -0,0 +1,89 @@
+# Frontend Preview Deployments
+#
+# Deploys a preview build to <branch>-<nanoid>-preview.macro.com
+# Built identical to dev.macro.com (MODE=development, points to dev services)
+#
+# NOTE: This workflow should NOT be added to required status checks.
+# PRs should be mergeable regardless of preview deploy status.
+
+name: Deploy Preview
+
+on:
+ pull_request:
+ types: [opened, synchronize]
+ paths:
+ - 'js/app/**'
+
+concurrency:
+ group: preview-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+env:
+ PREVIEW_BUCKET: macro-preview-assets-dev
+
+jobs:
+ deploy:
+ runs-on: linux-latest-beefy
+ permissions:
+ contents: read
+ pull-requests: write
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Setup
+ uses: ./.github/actions/setup-reqs-web
+ with:
+ npm-rc-token: ${{ secrets.NPMRC_GH_TOKEN }}
+
+ # Build identical to dev.macro.com deployment
+ - name: Build
+ working-directory: js/app
+ run: bun run build:dev
+ env:
+ VITE_DD_WEB_APP_ID: ${{ secrets.DD_WEB_APP_ID }}
+ VITE_DD_WEB_APP_TOKEN: ${{ secrets.DD_WEB_APP_TOKEN }}
+ VITE_DD_HASH: ${{ github.sha }}
+ VITE_SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY_PRODUCTION }}
+
+ - name: Configure AWS Credentials
+ uses: aws-actions/configure-aws-credentials@v5
+ with:
+ aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }}
+ aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
+ aws-region: us-east-1
+
+ - name: Get or create preview ID
+ id: preview-id
+ working-directory: js/app
+ run: |
+ PREVIEW_ID=$(bun scripts/preview/get-or-create-id.ts \
+ --pr ${{ github.event.pull_request.number }} \
+ --repo ${{ github.repository }} \
+ --token ${{ secrets.GITHUB_TOKEN }} \
+ --branch "${{ github.head_ref }}")
+ echo "id=$PREVIEW_ID" >> $GITHUB_OUTPUT
+ echo "Preview ID: $PREVIEW_ID"
+
+ - name: Validate bucket name
+ run: |
+ if [[ "${{ env.PREVIEW_BUCKET }}" != "macro-preview-assets-dev" ]]; then
+ echo "ERROR: PREVIEW_BUCKET must be 'macro-preview-assets-dev'"
+ exit 1
+ fi
+
+ - name: Deploy to S3
+ working-directory: js/app
+ run: |
+ bun scripts/preview/deploy.ts \
+ --preview-id ${{ steps.preview-id.outputs.id }} \
+ --skip-build
+
+ - name: Comment on PR
+ working-directory: js/app
+ run: |
+ bun scripts/preview/post-comment.ts \
+ --pr ${{ github.event.pull_request.number }} \
+ --repo ${{ github.repository }} \
+ --token ${{ secrets.GITHUB_TOKEN }} \
+ --preview-id ${{ steps.preview-id.outputs.id }} \
+ --sha ${{ github.sha }}
diff --git a/infra/stacks/web-app-preview/Pulumi.dev.yaml b/infra/stacks/web-app-preview/Pulumi.dev.yaml
new file mode 100644
index 0000000000..9cfd7a1eb5
--- /dev/null
+++ b/infra/stacks/web-app-preview/Pulumi.dev.yaml
@@ -0,0 +1,3 @@
+config:
+ aws-native:region: us-east-1
+ aws:region: us-east-1
diff --git a/infra/stacks/web-app-preview/Pulumi.yaml b/infra/stacks/web-app-preview/Pulumi.yaml
new file mode 100644
index 0000000000..5ebe79df20
--- /dev/null
+++ b/infra/stacks/web-app-preview/Pulumi.yaml
@@ -0,0 +1,3 @@
+name: web-app-preview
+runtime: nodejs
+description: Preview deployment infrastructure for web app (S3 + CloudFront)
diff --git a/infra/stacks/web-app-preview/index.ts b/infra/stacks/web-app-preview/index.ts
new file mode 100644
index 0000000000..441751f65e
--- /dev/null
+++ b/infra/stacks/web-app-preview/index.ts
@@ -0,0 +1,269 @@
+import * as aws from '@pulumi/aws';
+import * as pulumi from '@pulumi/pulumi';
+import {
+ BASE_DOMAIN,
+ stack,
+} from '../../packages/shared/src';
+
+const BASE_NAME = 'preview-deploy';
+
+// Certificate must be in us-east-1 for CloudFront
+const usEast1Provider = new aws.Provider('us-east-1-provider', {
+ region: 'us-east-1',
+});
+
+// Create certificate for *.preview.macro.com
+const previewCert = new aws.acm.Certificate(
+ `${BASE_NAME}-cert`,
+ {
+ domainName: `*.preview.${BASE_DOMAIN}`,
+ validationMethod: 'DNS',
+ tags: {
+ environment: stack,
+ project: 'web-app-preview',
+ },
+ },
+ { provider: usEast1Provider }
+);
+
+// Get the hosted zone for DNS validation
+const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });
+
+// Create DNS validation record
+const certValidation = new aws.route53.Record(
+ `${BASE_NAME}-cert-validation`,
+ {
+ name: previewCert.domainValidationOptions[0].resourceRecordName,
+ type: previewCert.domainValidationOptions[0].resourceRecordType,
+ zoneId: zone.zoneId,
+ records: [previewCert.domainValidationOptions[0].resourceRecordValue],
+ ttl: 60,
+ }
+);
+
+// Wait for certificate validation
+const certValidated = new aws.acm.CertificateValidation(
+ `${BASE_NAME}-cert-validated`,
+ {
+ certificateArn: previewCert.arn,
+ validationRecordFqdns: [certValidation.fqdn],
+ },
+ { provider: usEast1Provider }
+);
+
+const tags = {
+ environment: stack,
+ project: 'web-app-preview',
+};
+
+// S3 bucket for preview deployments
+const previewBucket = new aws.s3.Bucket(`${BASE_NAME}-bucket`, {
+ bucket: `macro-preview-assets-${stack}`,
+ tags,
+});
+
+// Lifecycle rule to expire preview files after 7 days
+new aws.s3.BucketLifecycleConfiguration(`${BASE_NAME}-lifecycle`, {
+ bucket: previewBucket.id,
+ rules: [
+ {
+ id: 'expire-previews-after-7-days',
+ status: 'Enabled',
+ expiration: {
+ days: 7,
+ },
+ },
+ ],
+});
+
+// Block public access - CloudFront will access via OAC
+new aws.s3.BucketPublicAccessBlock(`${BASE_NAME}-public-access-block`, {
+ bucket: previewBucket.id,
+ blockPublicAcls: true,
+ blockPublicPolicy: true,
+ ignorePublicAcls: true,
+ restrictPublicBuckets: true,
+});
+
+// Origin Access Control for CloudFront to access S3
+const originAccessControl = new aws.cloudfront.OriginAccessControl(
+ `${BASE_NAME}-oac`,
+ {
+ name: `${BASE_NAME}-oac-${stack}`,
+ originAccessControlOriginType: 's3',
+ signingBehavior: 'always',
+ signingProtocol: 'sigv4',
+ }
+);
+
+// IAM role for Lambda@Edge
+const lambdaRole = new aws.iam.Role(`${BASE_NAME}-lambda-role`, {
+ assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({
+ Service: ['lambda.amazonaws.com', 'edgelambda.amazonaws.com'],
+ }),
+ tags,
+});
+
+new aws.iam.RolePolicyAttachment(`${BASE_NAME}-lambda-role-attach`, {
+ role: lambdaRole,
+ policyArn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
+});
+
+// Lambda@Edge: Viewer Request - rewrites URI based on subdomain
+const viewerRequestLambda = new aws.lambda.Function(
+ `${BASE_NAME}-origin-request`,
+ {
+ code: new pulumi.asset.FileArchive('./previewOriginRequestLambda'),
+ role: lambdaRole.arn,
+ handler: 'index.handler',
+ runtime: aws.lambda.Runtime.NodeJS20dX,
+ name: `${BASE_NAME}-origin-request-${stack}`,
+ publish: true,
+ tags,
+ },
+ {
+ // Lambda@Edge must be in us-east-1
+ provider: usEast1Provider,
+ }
+);
+
+
+const bucketRegionalDomainName = pulumi.interpolate`${previewBucket.bucket}.s3.us-east-1.amazonaws.com`;
+
+const cachePolicy = new aws.cloudfront.CachePolicy(`${BASE_NAME}-cache-policy`, {
+ name: `${BASE_NAME}-cache-policy-${stack}`,
+ defaultTtl: 60, // 1 minute default
+ minTtl: 0,
+ maxTtl: 86400, // 1 day max
+ parametersInCacheKeyAndForwardedToOrigin: {
+ cookiesConfig: {
+ cookieBehavior: 'none',
+ },
+ headersConfig: {
+ headerBehavior: 'none',
+ },
+ queryStringsConfig: {
+ queryStringBehavior: 'none',
+ },
+ },
+});
+
+const responseHeadersPolicy = new aws.cloudfront.ResponseHeadersPolicy(
+ `${BASE_NAME}-response-headers-policy`,
+ {
+ name: `${BASE_NAME}-response-headers-policy-${stack}`,
+ corsConfig: {
+ accessControlAllowOrigins: { items: ['*'] },
+ accessControlAllowHeaders: { items: ['*'] },
+ accessControlAllowMethods: { items: ['ALL'] },
+ accessControlMaxAgeSec: 300,
+ accessControlAllowCredentials: false,
+ originOverride: true,
+ },
+ securityHeadersConfig: {
+ strictTransportSecurity: {
+ accessControlMaxAgeSec: 31536000,
+ includeSubdomains: true,
+ preload: false,
+ override: false,
+ },
+ contentTypeOptions: {
+ override: true,
+ },
+ },
+ }
+);
+
+const previewAlias = `*.preview.${BASE_DOMAIN}`;
+
+const distribution = new aws.cloudfront.Distribution(
+ `${BASE_NAME}-distribution`,
+ {
+ comment: `(${stack}) Preview deployments for web app`,
+ aliases: [previewAlias],
+ viewerCertificate: {
+ cloudfrontDefaultCertificate: false,
+ acmCertificateArn: certValidated.certificateArn,
+ sslSupportMethod: 'sni-only',
+ minimumProtocolVersion: 'TLSv1.2_2021',
+ },
+ defaultCacheBehavior: {
+ allowedMethods: ['GET', 'HEAD', 'OPTIONS'],
+ cachedMethods: ['GET', 'HEAD', 'OPTIONS'],
+ compress: true,
+ targetOriginId: previewBucket.id,
+ viewerProtocolPolicy: 'redirect-to-https',
+ cachePolicyId: cachePolicy.id,
+ responseHeadersPolicyId: responseHeadersPolicy.id,
+ lambdaFunctionAssociations: [
+ {
+ eventType: 'viewer-request',
+ lambdaArn: pulumi.interpolate`${viewerRequestLambda.arn}:${viewerRequestLambda.version}`,
+ includeBody: false,
+ },
+ ],
+ },
+ enabled: true,
+ defaultRootObject: 'index.html',
+ origins: [
+ {
+ domainName: bucketRegionalDomainName,
+ originId: previewBucket.id,
+ originAccessControlId: originAccessControl.id,
+ },
+ ],
+ restrictions: {
+ geoRestriction: {
+ restrictionType: 'none',
+ },
+ },
+ httpVersion: 'http2and3',
+ tags,
+ }
+);
+
+new aws.s3.BucketPolicy(`${BASE_NAME}-bucket-policy`, {
+ bucket: previewBucket.id,
+ policy: pulumi
+ .all([previewBucket.arn, distribution.arn])
+ .apply(([bucketArn, distArn]) =>
+ JSON.stringify({
+ Version: '2012-10-17',
+ Statement: [
+ {
+ Sid: 'AllowCloudFrontServicePrincipal',
+ Effect: 'Allow',
+ Principal: {
+ Service: 'cloudfront.amazonaws.com',
+ },
+ Action: 's3:GetObject',
+ Resource: `${bucketArn}/*`,
+ Condition: {
+ StringEquals: {
+ 'AWS:SourceArn': distArn,
+ },
+ },
+ },
+ ],
+ })
+ ),
+});
+
+new aws.route53.Record(`${BASE_NAME}-dns-record`, {
+ name: `*.preview`,
+ zoneId: zone.zoneId,
+ type: 'A',
+ aliases: [
+ {
+ name: distribution.domainName,
+ zoneId: distribution.hostedZoneId,
+ evaluateTargetHealth: false,
+ },
+ ],
+});
+
+export const previewBucketName = previewBucket.bucket;
+export const previewBucketArn = previewBucket.arn;
+export const previewDistributionId = distribution.id;
+export const previewDistributionDomain = distribution.domainName;
+export const previewBaseUrl = `https://{subdomain}.preview.${BASE_DOMAIN}`;
diff --git a/js/app/package.json b/js/app/package.json
index 981ee0974f..1396c5899e 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -21,6 +21,8 @@
"build:prod": "cd packages/app && MODE=production NODE_ENV=production bun run --bun build",
"preview": "cd packages/app && bun run --bun preview:dev",
"preview:prod": "cd packages/app && MODE=production NODE_ENV=production bun preview:prod",
+ "preview:deploy": "bun scripts/preview/deploy.ts",
+ "preview:cleanup": "bun scripts/preview/deploy.ts --cleanup",
"lint": "bunx --bun biome lint --skip=nursery/noImportCycles",
"lint:staged": "bunx --bun biome lint --staged",
"lint:ci": "bunx --bun biome ci --changed",
diff --git a/js/app/scripts/preview/deploy.ts b/js/app/scripts/preview/deploy.ts
new file mode 100644
index 0000000000..4a4764dea0
--- /dev/null
+++ b/js/app/scripts/preview/deploy.ts
@@ -0,0 +1,121 @@
+#!/usr/bin/env bun
+/**
+ * Preview Deployment Script
+ *
+ * Usage:
+ * bun scripts/preview/deploy.ts --preview-id <id>
+ * bun scripts/preview/deploy.ts --preview-id my-feature-abc123
+ *
+ * Environment:
+ * AWS credentials must be configured (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, or AWS profile)
+ */
+
+import { execSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const PREVIEW_BUCKET = 'macro-preview-assets-dev';
+const DIST_PATH = resolve(import.meta.dir, '../../packages/app/dist');
+
+function parseArgs(): { previewId: string; skipBuild: boolean } {
+ const args = process.argv.slice(2);
+ let previewId = '';
+ let skipBuild = false;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--preview-id' && args[i + 1]) {
+ previewId = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--skip-build') {
+ skipBuild = true;
+ }
+ }
+
+ if (!previewId) {
+ // Generate a random preview ID for local testing
+ const branch = execSync('git branch --show-current', { encoding: 'utf-8' })
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 30);
+
+ const nanoid = Math.random().toString(36).slice(2, 8);
+ previewId = `${branch}-${nanoid}`;
+ console.log(`Generated preview ID: ${previewId}`);
+ }
+
+ return { previewId, skipBuild };
+}
+
+function validateBucket(bucket: string): void {
+ if (bucket !== 'macro-preview-assets-dev') {
+ console.error('ERROR: Can only deploy to macro-preview-assets-dev');
+ process.exit(1);
+ }
+}
+
+function build(): void {
+ console.log('\nBuilding app (same as dev.macro.com)...\n');
+ execSync('bun run build:dev', {
+ cwd: resolve(import.meta.dir, '../..'),
+ stdio: 'inherit',
+ });
+}
+
+function deploy(previewId: string): void {
+ validateBucket(PREVIEW_BUCKET);
+
+ if (!existsSync(DIST_PATH)) {
+ console.error(`ERROR: Build output not found at ${DIST_PATH}`);
+ console.error('Run with --skip-build=false or build first with: bun run build:dev');
+ process.exit(1);
+ }
+
+ console.log(`\nDeploying to s3://${PREVIEW_BUCKET}/${previewId}/app/\n`);
+
+ // Sync all files except index.html with immutable cache
+ execSync(
+ `aws s3 sync ${DIST_PATH}/ s3://${PREVIEW_BUCKET}/${previewId}/app/ ` +
+ `--delete ` +
+ `--cache-control "public, max-age=31536000, immutable" ` +
+ `--exclude "index.html"`,
+ { stdio: 'inherit' }
+ );
+
+ // Upload index.html with no-cache
+ execSync(
+ `aws s3 cp ${DIST_PATH}/index.html s3://${PREVIEW_BUCKET}/${previewId}/app/index.html ` +
+ `--cache-control "no-cache, no-store, must-revalidate"`,
+ { stdio: 'inherit' }
+ );
+
+ const previewUrl = `https://${previewId}.preview.macro.com`;
+ console.log(`\nPreview deployed: ${previewUrl}\n`);
+}
+
+function cleanup(previewId: string): void {
+ validateBucket(PREVIEW_BUCKET);
+
+ console.log(`\nCleaning up s3://${PREVIEW_BUCKET}/${previewId}/\n`);
+
+ execSync(`aws s3 rm s3://${PREVIEW_BUCKET}/${previewId}/ --recursive`, {
+ stdio: 'inherit',
+ });
+
+ console.log('\nCleanup complete\n');
+}
+
+// Main
+const { previewId, skipBuild } = parseArgs();
+
+if (process.argv.includes('--cleanup')) {
+ cleanup(previewId);
+} else {
+ if (!skipBuild) {
+ build();
+ }
+ deploy(previewId);
+}
diff --git a/js/app/scripts/preview/get-or-create-id.ts b/js/app/scripts/preview/get-or-create-id.ts
new file mode 100644
index 0000000000..3dca5502d5
--- /dev/null
+++ b/js/app/scripts/preview/get-or-create-id.ts
@@ -0,0 +1,125 @@
+#!/usr/bin/env bun
+/**
+ * Get or Create Preview ID
+ *
+ * For CI: Checks PR comments for existing preview URL, or generates new ID
+ * For local: Just generates a new ID based on branch name
+ *
+ * Usage:
+ * bun scripts/preview/get-or-create-id.ts
+ * bun scripts/preview/get-or-create-id.ts --pr 123 --repo owner/repo --token $GITHUB_TOKEN
+ *
+ * Output: Prints the preview ID to stdout
+ */
+
+import { execSync } from 'node:child_process';
+
+interface Args {
+ pr?: number;
+ repo?: string;
+ token?: string;
+ branch?: string;
+}
+
+function parseArgs(): Args {
+ const args = process.argv.slice(2);
+ const result: Args = {};
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--pr' && args[i + 1]) {
+ result.pr = parseInt(args[i + 1], 10);
+ i++;
+ }
+ if (args[i] === '--repo' && args[i + 1]) {
+ result.repo = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--token' && args[i + 1]) {
+ result.token = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--branch' && args[i + 1]) {
+ result.branch = args[i + 1];
+ i++;
+ }
+ }
+
+ return result;
+}
+
+function generatePreviewId(branchOverride?: string): string {
+ let branch = branchOverride;
+
+ if (!branch) {
+ try {
+ branch = execSync('git branch --show-current', { encoding: 'utf-8' }).trim();
+ } catch {
+ branch = '';
+ }
+ }
+
+ if (!branch) {
+ branch = 'preview';
+ }
+
+ const sanitized = branch
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 30);
+
+ const nanoid = Math.random().toString(36).slice(2, 8);
+ return `${sanitized}-${nanoid}`;
+}
+
+async function getExistingPreviewId(pr: number, repo: string, token: string): Promise<string | null> {
+ const [owner, repoName] = repo.split('/');
+
+ const response = await fetch(
+ `https://api.github.com/repos/${owner}/${repoName}/issues/${pr}/comments`,
+ {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/vnd.github.v3+json',
+ },
+ }
+ );
+
+ if (!response.ok) {
+ console.error(`Failed to fetch PR comments: ${response.status}`);
+ return null;
+ }
+
+ const comments = (await response.json()) as Array<{ body?: string; user?: { type?: string } }>;
+
+ const previewComment = comments.find(
+ (c) => c.body?.includes('.preview.macro.com') && c.user?.type === 'Bot'
+ );
+
+ if (previewComment?.body) {
+ const match = previewComment.body.match(/https:\/\/(.+)\.preview\.macro\.com/);
+ if (match?.[1]) {
+ return match[1];
+ }
+ }
+
+ return null;
+}
+
+async function main() {
+ const args = parseArgs();
+
+ // If we have PR info, try to get existing preview ID
+ if (args.pr && args.repo && args.token) {
+ const existingId = await getExistingPreviewId(args.pr, args.repo, args.token);
+ if (existingId) {
+ console.log(existingId);
+ return;
+ }
+ }
+
+ console.log(generatePreviewId(args.branch));
+}
+
+main();
diff --git a/js/app/scripts/preview/post-comment.ts b/js/app/scripts/preview/post-comment.ts
new file mode 100644
index 0000000000..bc944d2090
--- /dev/null
+++ b/js/app/scripts/preview/post-comment.ts
@@ -0,0 +1,136 @@
+#!/usr/bin/env bun
+/**
+ * Post Preview Comment to PR
+ *
+ * Usage:
+ * bun scripts/preview/post-comment.ts --pr 123 --repo owner/repo --token $GITHUB_TOKEN --preview-id my-feature-abc123 --sha abc1234
+ */
+
+interface Args {
+ pr: number;
+ repo: string;
+ token: string;
+ previewId: string;
+ sha: string;
+}
+
+function parseArgs(): Args {
+ const args = process.argv.slice(2);
+ const result: Partial<Args> = {};
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--pr' && args[i + 1]) {
+ result.pr = parseInt(args[i + 1], 10);
+ i++;
+ }
+ if (args[i] === '--repo' && args[i + 1]) {
+ result.repo = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--token' && args[i + 1]) {
+ result.token = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--preview-id' && args[i + 1]) {
+ result.previewId = args[i + 1];
+ i++;
+ }
+ if (args[i] === '--sha' && args[i + 1]) {
+ result.sha = args[i + 1];
+ i++;
+ }
+ }
+
+ if (!result.pr || !result.repo || !result.token || !result.previewId || !result.sha) {
+ console.error('Missing required arguments');
+ console.error(
+ 'Usage: bun post-comment.ts --pr 123 --repo owner/repo --token TOKEN --preview-id ID --sha SHA'
+ );
+ process.exit(1);
+ }
+
+ return result as Args;
+}
+
+async function main() {
+ const args = parseArgs();
+ const [owner, repo] = args.repo.split('/');
+ const previewUrl = `https://${args.previewId}.preview.macro.com`;
+ const shortSha = args.sha.slice(0, 7);
+
+ // Check for existing preview comment
+ const commentsResponse = await fetch(
+ `https://api.github.com/repos/${owner}/${repo}/issues/${args.pr}/comments`,
+ {
+ headers: {
+ Authorization: `Bearer ${args.token}`,
+ Accept: 'application/vnd.github.v3+json',
+ },
+ }
+ );
+
+ if (!commentsResponse.ok) {
+ console.error(`Failed to fetch comments: ${commentsResponse.status}`);
+ process.exit(1);
+ }
+
+ const comments = (await commentsResponse.json()) as Array<{
+ id: number;
+ body?: string;
+ user?: { type?: string };
+ }>;
+
+ const existingComment = comments.find(
+ (c) => c.body?.includes('.preview.macro.com') && c.user?.type === 'Bot'
+ );
+
+ const body = `**Preview:** [${previewUrl}](${previewUrl}) (${shortSha})`;
+
+ if (existingComment) {
+ // Update existing comment
+ const updateResponse = await fetch(
+ `https://api.github.com/repos/${owner}/${repo}/issues/comments/${existingComment.id}`,
+ {
+ method: 'PATCH',
+ headers: {
+ Authorization: `Bearer ${args.token}`,
+ Accept: 'application/vnd.github.v3+json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ body }),
+ }
+ );
+
+ if (!updateResponse.ok) {
+ console.error(`Failed to update comment: ${updateResponse.status}`);
+ process.exit(1);
+ }
+
+ console.log('Updated existing preview comment');
+ } else {
+ // Create new comment
+ const createResponse = await fetch(
+ `https://api.github.com/repos/${owner}/${repo}/issues/${args.pr}/comments`,
+ {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${args.token}`,
+ Accept: 'application/vnd.github.v3+json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ body }),
+ }
+ );
+
+ if (!createResponse.ok) {
+ console.error(`Failed to create comment: ${createResponse.status}`);
+ process.exit(1);
+ }
+
+ console.log('Created new preview comment');
+ }
+
+ console.log(`Preview URL: ${previewUrl}`);
+}
+
+main();